• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37 
38 /*
39 ** Determine if we are dealing with WinRT, which provides only a subset of
40 ** the full Win32 API.
41 */
42 #if !defined(SQLITE_OS_WINRT)
43 # define SQLITE_OS_WINRT 0
44 #endif
45 
46 /*
47 ** Warning pragmas copied from msvc.h in the core.
48 */
49 #if defined(_MSC_VER)
50 #pragma warning(disable : 4054)
51 #pragma warning(disable : 4055)
52 #pragma warning(disable : 4100)
53 #pragma warning(disable : 4127)
54 #pragma warning(disable : 4130)
55 #pragma warning(disable : 4152)
56 #pragma warning(disable : 4189)
57 #pragma warning(disable : 4206)
58 #pragma warning(disable : 4210)
59 #pragma warning(disable : 4232)
60 #pragma warning(disable : 4244)
61 #pragma warning(disable : 4305)
62 #pragma warning(disable : 4306)
63 #pragma warning(disable : 4702)
64 #pragma warning(disable : 4706)
65 #endif /* defined(_MSC_VER) */
66 
67 /*
68 ** No support for loadable extensions in VxWorks.
69 */
70 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
71 # define SQLITE_OMIT_LOAD_EXTENSION 1
72 #endif
73 
74 /*
75 ** Enable large-file support for fopen() and friends on unix.
76 */
77 #ifndef SQLITE_DISABLE_LFS
78 # define _LARGE_FILE       1
79 # ifndef _FILE_OFFSET_BITS
80 #   define _FILE_OFFSET_BITS 64
81 # endif
82 # define _LARGEFILE_SOURCE 1
83 #endif
84 
85 #include <stdlib.h>
86 #include <string.h>
87 #include <stdio.h>
88 #include <assert.h>
89 #include "sqlite3.h"
90 typedef sqlite3_int64 i64;
91 typedef sqlite3_uint64 u64;
92 typedef unsigned char u8;
93 #if SQLITE_USER_AUTHENTICATION
94 # include "sqlite3userauth.h"
95 #endif
96 #include <ctype.h>
97 #include <stdarg.h>
98 
99 #if !defined(_WIN32) && !defined(WIN32)
100 # include <signal.h>
101 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
102 #  include <pwd.h>
103 # endif
104 #endif
105 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
106 # include <unistd.h>
107 # include <dirent.h>
108 # define GETPID getpid
109 # if defined(__MINGW32__)
110 #  define DIRENT dirent
111 #  ifndef S_ISLNK
112 #   define S_ISLNK(mode) (0)
113 #  endif
114 # endif
115 #else
116 # define GETPID (int)GetCurrentProcessId
117 #endif
118 #include <sys/types.h>
119 #include <sys/stat.h>
120 
121 #if HAVE_READLINE
122 # include <readline/readline.h>
123 # include <readline/history.h>
124 #endif
125 
126 #if HAVE_EDITLINE
127 # include <editline/readline.h>
128 #endif
129 
130 #if HAVE_EDITLINE || HAVE_READLINE
131 
132 # define shell_add_history(X) add_history(X)
133 # define shell_read_history(X) read_history(X)
134 # define shell_write_history(X) write_history(X)
135 # define shell_stifle_history(X) stifle_history(X)
136 # define shell_readline(X) readline(X)
137 
138 #elif HAVE_LINENOISE
139 
140 # include "linenoise.h"
141 # define shell_add_history(X) linenoiseHistoryAdd(X)
142 # define shell_read_history(X) linenoiseHistoryLoad(X)
143 # define shell_write_history(X) linenoiseHistorySave(X)
144 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
145 # define shell_readline(X) linenoise(X)
146 
147 #else
148 
149 # define shell_read_history(X)
150 # define shell_write_history(X)
151 # define shell_stifle_history(X)
152 
153 # define SHELL_USE_LOCAL_GETLINE 1
154 #endif
155 
156 
157 #if defined(_WIN32) || defined(WIN32)
158 # if SQLITE_OS_WINRT
159 #  define SQLITE_OMIT_POPEN 1
160 # else
161 #  include <io.h>
162 #  include <fcntl.h>
163 #  define isatty(h) _isatty(h)
164 #  ifndef access
165 #   define access(f,m) _access((f),(m))
166 #  endif
167 #  ifndef unlink
168 #   define unlink _unlink
169 #  endif
170 #  ifndef strdup
171 #   define strdup _strdup
172 #  endif
173 #  undef popen
174 #  define popen _popen
175 #  undef pclose
176 #  define pclose _pclose
177 # endif
178 #else
179  /* Make sure isatty() has a prototype. */
180  extern int isatty(int);
181 
182 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
183   /* popen and pclose are not C89 functions and so are
184   ** sometimes omitted from the <stdio.h> header */
185    extern FILE *popen(const char*,const char*);
186    extern int pclose(FILE*);
187 # else
188 #  define SQLITE_OMIT_POPEN 1
189 # endif
190 #endif
191 
192 #if defined(_WIN32_WCE)
193 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
194  * thus we always assume that we have a console. That can be
195  * overridden with the -batch command line option.
196  */
197 #define isatty(x) 1
198 #endif
199 
200 /* ctype macros that work with signed characters */
201 #define IsSpace(X)  isspace((unsigned char)X)
202 #define IsDigit(X)  isdigit((unsigned char)X)
203 #define ToLower(X)  (char)tolower((unsigned char)X)
204 
205 #if defined(_WIN32) || defined(WIN32)
206 #if SQLITE_OS_WINRT
207 #include <intrin.h>
208 #endif
209 #include <windows.h>
210 
211 /* string conversion routines only needed on Win32 */
212 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
213 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
214 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
215 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
216 #endif
217 
218 /* On Windows, we normally run with output mode of TEXT so that \n characters
219 ** are automatically translated into \r\n.  However, this behavior needs
220 ** to be disabled in some cases (ex: when generating CSV output and when
221 ** rendering quoted strings that contain \n characters).  The following
222 ** routines take care of that.
223 */
224 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
setBinaryMode(FILE * file,int isOutput)225 static void setBinaryMode(FILE *file, int isOutput){
226   if( isOutput ) fflush(file);
227   _setmode(_fileno(file), _O_BINARY);
228 }
setTextMode(FILE * file,int isOutput)229 static void setTextMode(FILE *file, int isOutput){
230   if( isOutput ) fflush(file);
231   _setmode(_fileno(file), _O_TEXT);
232 }
233 #else
234 # define setBinaryMode(X,Y)
235 # define setTextMode(X,Y)
236 #endif
237 
238 
239 /* True if the timer is enabled */
240 static int enableTimer = 0;
241 
242 /* Return the current wall-clock time */
timeOfDay(void)243 static sqlite3_int64 timeOfDay(void){
244   static sqlite3_vfs *clockVfs = 0;
245   sqlite3_int64 t;
246   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
247   if( clockVfs==0 ) return 0;  /* Never actually happens */
248   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
249     clockVfs->xCurrentTimeInt64(clockVfs, &t);
250   }else{
251     double r;
252     clockVfs->xCurrentTime(clockVfs, &r);
253     t = (sqlite3_int64)(r*86400000.0);
254   }
255   return t;
256 }
257 
258 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
259 #include <sys/time.h>
260 #include <sys/resource.h>
261 
262 /* VxWorks does not support getrusage() as far as we can determine */
263 #if defined(_WRS_KERNEL) || defined(__RTP__)
264 struct rusage {
265   struct timeval ru_utime; /* user CPU time used */
266   struct timeval ru_stime; /* system CPU time used */
267 };
268 #define getrusage(A,B) memset(B,0,sizeof(*B))
269 #endif
270 
271 /* Saved resource information for the beginning of an operation */
272 static struct rusage sBegin;  /* CPU time at start */
273 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
274 
275 /*
276 ** Begin timing an operation
277 */
beginTimer(void)278 static void beginTimer(void){
279   if( enableTimer ){
280     getrusage(RUSAGE_SELF, &sBegin);
281     iBegin = timeOfDay();
282   }
283 }
284 
285 /* Return the difference of two time_structs in seconds */
timeDiff(struct timeval * pStart,struct timeval * pEnd)286 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
287   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
288          (double)(pEnd->tv_sec - pStart->tv_sec);
289 }
290 
291 /*
292 ** Print the timing results.
293 */
endTimer(void)294 static void endTimer(void){
295   if( enableTimer ){
296     sqlite3_int64 iEnd = timeOfDay();
297     struct rusage sEnd;
298     getrusage(RUSAGE_SELF, &sEnd);
299     printf("Run Time: real %.3f user %f sys %f\n",
300        (iEnd - iBegin)*0.001,
301        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
302        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
303   }
304 }
305 
306 #define BEGIN_TIMER beginTimer()
307 #define END_TIMER endTimer()
308 #define HAS_TIMER 1
309 
310 #elif (defined(_WIN32) || defined(WIN32))
311 
312 /* Saved resource information for the beginning of an operation */
313 static HANDLE hProcess;
314 static FILETIME ftKernelBegin;
315 static FILETIME ftUserBegin;
316 static sqlite3_int64 ftWallBegin;
317 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
318                                     LPFILETIME, LPFILETIME);
319 static GETPROCTIMES getProcessTimesAddr = NULL;
320 
321 /*
322 ** Check to see if we have timer support.  Return 1 if necessary
323 ** support found (or found previously).
324 */
hasTimer(void)325 static int hasTimer(void){
326   if( getProcessTimesAddr ){
327     return 1;
328   } else {
329 #if !SQLITE_OS_WINRT
330     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
331     ** versions. See if the version we are running on has it, and if it
332     ** does, save off a pointer to it and the current process handle.
333     */
334     hProcess = GetCurrentProcess();
335     if( hProcess ){
336       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
337       if( NULL != hinstLib ){
338         getProcessTimesAddr =
339             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
340         if( NULL != getProcessTimesAddr ){
341           return 1;
342         }
343         FreeLibrary(hinstLib);
344       }
345     }
346 #endif
347   }
348   return 0;
349 }
350 
351 /*
352 ** Begin timing an operation
353 */
beginTimer(void)354 static void beginTimer(void){
355   if( enableTimer && getProcessTimesAddr ){
356     FILETIME ftCreation, ftExit;
357     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
358                         &ftKernelBegin,&ftUserBegin);
359     ftWallBegin = timeOfDay();
360   }
361 }
362 
363 /* Return the difference of two FILETIME structs in seconds */
timeDiff(FILETIME * pStart,FILETIME * pEnd)364 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
365   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
366   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
367   return (double) ((i64End - i64Start) / 10000000.0);
368 }
369 
370 /*
371 ** Print the timing results.
372 */
endTimer(void)373 static void endTimer(void){
374   if( enableTimer && getProcessTimesAddr){
375     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
376     sqlite3_int64 ftWallEnd = timeOfDay();
377     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
378     printf("Run Time: real %.3f user %f sys %f\n",
379        (ftWallEnd - ftWallBegin)*0.001,
380        timeDiff(&ftUserBegin, &ftUserEnd),
381        timeDiff(&ftKernelBegin, &ftKernelEnd));
382   }
383 }
384 
385 #define BEGIN_TIMER beginTimer()
386 #define END_TIMER endTimer()
387 #define HAS_TIMER hasTimer()
388 
389 #else
390 #define BEGIN_TIMER
391 #define END_TIMER
392 #define HAS_TIMER 0
393 #endif
394 
395 /*
396 ** Used to prevent warnings about unused parameters
397 */
398 #define UNUSED_PARAMETER(x) (void)(x)
399 
400 /*
401 ** Number of elements in an array
402 */
403 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
404 
405 /*
406 ** If the following flag is set, then command execution stops
407 ** at an error if we are not interactive.
408 */
409 static int bail_on_error = 0;
410 
411 /*
412 ** Threat stdin as an interactive input if the following variable
413 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
414 */
415 static int stdin_is_interactive = 1;
416 
417 /*
418 ** On Windows systems we have to know if standard output is a console
419 ** in order to translate UTF-8 into MBCS.  The following variable is
420 ** true if translation is required.
421 */
422 static int stdout_is_console = 1;
423 
424 /*
425 ** The following is the open SQLite database.  We make a pointer
426 ** to this database a static variable so that it can be accessed
427 ** by the SIGINT handler to interrupt database processing.
428 */
429 static sqlite3 *globalDb = 0;
430 
431 /*
432 ** True if an interrupt (Control-C) has been received.
433 */
434 static volatile int seenInterrupt = 0;
435 
436 #ifdef SQLITE_DEBUG
437 /*
438 ** Out-of-memory simulator variables
439 */
440 static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
441 static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
442 static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
443 #endif /* SQLITE_DEBUG */
444 
445 /*
446 ** This is the name of our program. It is set in main(), used
447 ** in a number of other places, mostly for error messages.
448 */
449 static char *Argv0;
450 
451 /*
452 ** Prompt strings. Initialized in main. Settable with
453 **   .prompt main continue
454 */
455 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
456 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
457 
458 /*
459 ** Render output like fprintf().  Except, if the output is going to the
460 ** console and if this is running on a Windows machine, translate the
461 ** output from UTF-8 into MBCS.
462 */
463 #if defined(_WIN32) || defined(WIN32)
utf8_printf(FILE * out,const char * zFormat,...)464 void utf8_printf(FILE *out, const char *zFormat, ...){
465   va_list ap;
466   va_start(ap, zFormat);
467   if( stdout_is_console && (out==stdout || out==stderr) ){
468     char *z1 = sqlite3_vmprintf(zFormat, ap);
469     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
470     sqlite3_free(z1);
471     fputs(z2, out);
472     sqlite3_free(z2);
473   }else{
474     vfprintf(out, zFormat, ap);
475   }
476   va_end(ap);
477 }
478 #elif !defined(utf8_printf)
479 # define utf8_printf fprintf
480 #endif
481 
482 /*
483 ** Render output like fprintf().  This should not be used on anything that
484 ** includes string formatting (e.g. "%s").
485 */
486 #if !defined(raw_printf)
487 # define raw_printf fprintf
488 #endif
489 
490 /* Indicate out-of-memory and exit. */
shell_out_of_memory(void)491 static void shell_out_of_memory(void){
492   raw_printf(stderr,"Error: out of memory\n");
493   exit(1);
494 }
495 
496 #ifdef SQLITE_DEBUG
497 /* This routine is called when a simulated OOM occurs.  It is broken
498 ** out as a separate routine to make it easy to set a breakpoint on
499 ** the OOM
500 */
shellOomFault(void)501 void shellOomFault(void){
502   if( oomRepeat>0 ){
503     oomRepeat--;
504   }else{
505     oomCounter--;
506   }
507 }
508 #endif /* SQLITE_DEBUG */
509 
510 #ifdef SQLITE_DEBUG
511 /* This routine is a replacement malloc() that is used to simulate
512 ** Out-Of-Memory (OOM) errors for testing purposes.
513 */
oomMalloc(int nByte)514 static void *oomMalloc(int nByte){
515   if( oomCounter ){
516     if( oomCounter==1 ){
517       shellOomFault();
518       return 0;
519     }else{
520       oomCounter--;
521     }
522   }
523   return defaultMalloc(nByte);
524 }
525 #endif /* SQLITE_DEBUG */
526 
527 #ifdef SQLITE_DEBUG
528 /* Register the OOM simulator.  This must occur before any memory
529 ** allocations */
registerOomSimulator(void)530 static void registerOomSimulator(void){
531   sqlite3_mem_methods mem;
532   sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
533   defaultMalloc = mem.xMalloc;
534   mem.xMalloc = oomMalloc;
535   sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
536 }
537 #endif
538 
539 /*
540 ** Write I/O traces to the following stream.
541 */
542 #ifdef SQLITE_ENABLE_IOTRACE
543 static FILE *iotrace = 0;
544 #endif
545 
546 /*
547 ** This routine works like printf in that its first argument is a
548 ** format string and subsequent arguments are values to be substituted
549 ** in place of % fields.  The result of formatting this string
550 ** is written to iotrace.
551 */
552 #ifdef SQLITE_ENABLE_IOTRACE
iotracePrintf(const char * zFormat,...)553 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
554   va_list ap;
555   char *z;
556   if( iotrace==0 ) return;
557   va_start(ap, zFormat);
558   z = sqlite3_vmprintf(zFormat, ap);
559   va_end(ap);
560   utf8_printf(iotrace, "%s", z);
561   sqlite3_free(z);
562 }
563 #endif
564 
565 /*
566 ** Output string zUtf to stream pOut as w characters.  If w is negative,
567 ** then right-justify the text.  W is the width in UTF-8 characters, not
568 ** in bytes.  This is different from the %*.*s specification in printf
569 ** since with %*.*s the width is measured in bytes, not characters.
570 */
utf8_width_print(FILE * pOut,int w,const char * zUtf)571 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
572   int i;
573   int n;
574   int aw = w<0 ? -w : w;
575   for(i=n=0; zUtf[i]; i++){
576     if( (zUtf[i]&0xc0)!=0x80 ){
577       n++;
578       if( n==aw ){
579         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
580         break;
581       }
582     }
583   }
584   if( n>=aw ){
585     utf8_printf(pOut, "%.*s", i, zUtf);
586   }else if( w<0 ){
587     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
588   }else{
589     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
590   }
591 }
592 
593 
594 /*
595 ** Determines if a string is a number of not.
596 */
isNumber(const char * z,int * realnum)597 static int isNumber(const char *z, int *realnum){
598   if( *z=='-' || *z=='+' ) z++;
599   if( !IsDigit(*z) ){
600     return 0;
601   }
602   z++;
603   if( realnum ) *realnum = 0;
604   while( IsDigit(*z) ){ z++; }
605   if( *z=='.' ){
606     z++;
607     if( !IsDigit(*z) ) return 0;
608     while( IsDigit(*z) ){ z++; }
609     if( realnum ) *realnum = 1;
610   }
611   if( *z=='e' || *z=='E' ){
612     z++;
613     if( *z=='+' || *z=='-' ) z++;
614     if( !IsDigit(*z) ) return 0;
615     while( IsDigit(*z) ){ z++; }
616     if( realnum ) *realnum = 1;
617   }
618   return *z==0;
619 }
620 
621 /*
622 ** Compute a string length that is limited to what can be stored in
623 ** lower 30 bits of a 32-bit signed integer.
624 */
strlen30(const char * z)625 static int strlen30(const char *z){
626   const char *z2 = z;
627   while( *z2 ){ z2++; }
628   return 0x3fffffff & (int)(z2 - z);
629 }
630 
631 /*
632 ** Return the length of a string in characters.  Multibyte UTF8 characters
633 ** count as a single character.
634 */
strlenChar(const char * z)635 static int strlenChar(const char *z){
636   int n = 0;
637   while( *z ){
638     if( (0xc0&*(z++))!=0x80 ) n++;
639   }
640   return n;
641 }
642 
643 /*
644 ** Return true if zFile does not exist or if it is not an ordinary file.
645 */
646 #ifdef _WIN32
647 # define notNormalFile(X) 0
648 #else
notNormalFile(const char * zFile)649 static int notNormalFile(const char *zFile){
650   struct stat x;
651   int rc;
652   memset(&x, 0, sizeof(x));
653   rc = stat(zFile, &x);
654   return rc || !S_ISREG(x.st_mode);
655 }
656 #endif
657 
658 /*
659 ** This routine reads a line of text from FILE in, stores
660 ** the text in memory obtained from malloc() and returns a pointer
661 ** to the text.  NULL is returned at end of file, or if malloc()
662 ** fails.
663 **
664 ** If zLine is not NULL then it is a malloced buffer returned from
665 ** a previous call to this routine that may be reused.
666 */
local_getline(char * zLine,FILE * in)667 static char *local_getline(char *zLine, FILE *in){
668   int nLine = zLine==0 ? 0 : 100;
669   int n = 0;
670 
671   while( 1 ){
672     if( n+100>nLine ){
673       nLine = nLine*2 + 100;
674       zLine = realloc(zLine, nLine);
675       if( zLine==0 ) shell_out_of_memory();
676     }
677     if( fgets(&zLine[n], nLine - n, in)==0 ){
678       if( n==0 ){
679         free(zLine);
680         return 0;
681       }
682       zLine[n] = 0;
683       break;
684     }
685     while( zLine[n] ) n++;
686     if( n>0 && zLine[n-1]=='\n' ){
687       n--;
688       if( n>0 && zLine[n-1]=='\r' ) n--;
689       zLine[n] = 0;
690       break;
691     }
692   }
693 #if defined(_WIN32) || defined(WIN32)
694   /* For interactive input on Windows systems, translate the
695   ** multi-byte characterset characters into UTF-8. */
696   if( stdin_is_interactive && in==stdin ){
697     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
698     if( zTrans ){
699       int nTrans = strlen30(zTrans)+1;
700       if( nTrans>nLine ){
701         zLine = realloc(zLine, nTrans);
702         if( zLine==0 ) shell_out_of_memory();
703       }
704       memcpy(zLine, zTrans, nTrans);
705       sqlite3_free(zTrans);
706     }
707   }
708 #endif /* defined(_WIN32) || defined(WIN32) */
709   return zLine;
710 }
711 
712 /*
713 ** Retrieve a single line of input text.
714 **
715 ** If in==0 then read from standard input and prompt before each line.
716 ** If isContinuation is true, then a continuation prompt is appropriate.
717 ** If isContinuation is zero, then the main prompt should be used.
718 **
719 ** If zPrior is not NULL then it is a buffer from a prior call to this
720 ** routine that can be reused.
721 **
722 ** The result is stored in space obtained from malloc() and must either
723 ** be freed by the caller or else passed back into this routine via the
724 ** zPrior argument for reuse.
725 */
one_input_line(FILE * in,char * zPrior,int isContinuation)726 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
727   char *zPrompt;
728   char *zResult;
729   if( in!=0 ){
730     zResult = local_getline(zPrior, in);
731   }else{
732     zPrompt = isContinuation ? continuePrompt : mainPrompt;
733 #if SHELL_USE_LOCAL_GETLINE
734     printf("%s", zPrompt);
735     fflush(stdout);
736     zResult = local_getline(zPrior, stdin);
737 #else
738     free(zPrior);
739     zResult = shell_readline(zPrompt);
740     if( zResult && *zResult ) shell_add_history(zResult);
741 #endif
742   }
743   return zResult;
744 }
745 
746 
747 /*
748 ** Return the value of a hexadecimal digit.  Return -1 if the input
749 ** is not a hex digit.
750 */
hexDigitValue(char c)751 static int hexDigitValue(char c){
752   if( c>='0' && c<='9' ) return c - '0';
753   if( c>='a' && c<='f' ) return c - 'a' + 10;
754   if( c>='A' && c<='F' ) return c - 'A' + 10;
755   return -1;
756 }
757 
758 /*
759 ** Interpret zArg as an integer value, possibly with suffixes.
760 */
integerValue(const char * zArg)761 static sqlite3_int64 integerValue(const char *zArg){
762   sqlite3_int64 v = 0;
763   static const struct { char *zSuffix; int iMult; } aMult[] = {
764     { "KiB", 1024 },
765     { "MiB", 1024*1024 },
766     { "GiB", 1024*1024*1024 },
767     { "KB",  1000 },
768     { "MB",  1000000 },
769     { "GB",  1000000000 },
770     { "K",   1000 },
771     { "M",   1000000 },
772     { "G",   1000000000 },
773   };
774   int i;
775   int isNeg = 0;
776   if( zArg[0]=='-' ){
777     isNeg = 1;
778     zArg++;
779   }else if( zArg[0]=='+' ){
780     zArg++;
781   }
782   if( zArg[0]=='0' && zArg[1]=='x' ){
783     int x;
784     zArg += 2;
785     while( (x = hexDigitValue(zArg[0]))>=0 ){
786       v = (v<<4) + x;
787       zArg++;
788     }
789   }else{
790     while( IsDigit(zArg[0]) ){
791       v = v*10 + zArg[0] - '0';
792       zArg++;
793     }
794   }
795   for(i=0; i<ArraySize(aMult); i++){
796     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
797       v *= aMult[i].iMult;
798       break;
799     }
800   }
801   return isNeg? -v : v;
802 }
803 
804 /*
805 ** A variable length string to which one can append text.
806 */
807 typedef struct ShellText ShellText;
808 struct ShellText {
809   char *z;
810   int n;
811   int nAlloc;
812 };
813 
814 /*
815 ** Initialize and destroy a ShellText object
816 */
initText(ShellText * p)817 static void initText(ShellText *p){
818   memset(p, 0, sizeof(*p));
819 }
freeText(ShellText * p)820 static void freeText(ShellText *p){
821   free(p->z);
822   initText(p);
823 }
824 
825 /* zIn is either a pointer to a NULL-terminated string in memory obtained
826 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
827 ** added to zIn, and the result returned in memory obtained from malloc().
828 ** zIn, if it was not NULL, is freed.
829 **
830 ** If the third argument, quote, is not '\0', then it is used as a
831 ** quote character for zAppend.
832 */
appendText(ShellText * p,char const * zAppend,char quote)833 static void appendText(ShellText *p, char const *zAppend, char quote){
834   int len;
835   int i;
836   int nAppend = strlen30(zAppend);
837 
838   len = nAppend+p->n+1;
839   if( quote ){
840     len += 2;
841     for(i=0; i<nAppend; i++){
842       if( zAppend[i]==quote ) len++;
843     }
844   }
845 
846   if( p->n+len>=p->nAlloc ){
847     p->nAlloc = p->nAlloc*2 + len + 20;
848     p->z = realloc(p->z, p->nAlloc);
849     if( p->z==0 ) shell_out_of_memory();
850   }
851 
852   if( quote ){
853     char *zCsr = p->z+p->n;
854     *zCsr++ = quote;
855     for(i=0; i<nAppend; i++){
856       *zCsr++ = zAppend[i];
857       if( zAppend[i]==quote ) *zCsr++ = quote;
858     }
859     *zCsr++ = quote;
860     p->n = (int)(zCsr - p->z);
861     *zCsr = '\0';
862   }else{
863     memcpy(p->z+p->n, zAppend, nAppend);
864     p->n += nAppend;
865     p->z[p->n] = '\0';
866   }
867 }
868 
869 /*
870 ** Attempt to determine if identifier zName needs to be quoted, either
871 ** because it contains non-alphanumeric characters, or because it is an
872 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
873 ** that quoting is required.
874 **
875 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
876 */
quoteChar(const char * zName)877 static char quoteChar(const char *zName){
878   int i;
879   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
880   for(i=0; zName[i]; i++){
881     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
882   }
883   return sqlite3_keyword_check(zName, i) ? '"' : 0;
884 }
885 
886 /*
887 ** Construct a fake object name and column list to describe the structure
888 ** of the view, virtual table, or table valued function zSchema.zName.
889 */
shellFakeSchema(sqlite3 * db,const char * zSchema,const char * zName)890 static char *shellFakeSchema(
891   sqlite3 *db,            /* The database connection containing the vtab */
892   const char *zSchema,    /* Schema of the database holding the vtab */
893   const char *zName       /* The name of the virtual table */
894 ){
895   sqlite3_stmt *pStmt = 0;
896   char *zSql;
897   ShellText s;
898   char cQuote;
899   char *zDiv = "(";
900   int nRow = 0;
901 
902   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
903                          zSchema ? zSchema : "main", zName);
904   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
905   sqlite3_free(zSql);
906   initText(&s);
907   if( zSchema ){
908     cQuote = quoteChar(zSchema);
909     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
910     appendText(&s, zSchema, cQuote);
911     appendText(&s, ".", 0);
912   }
913   cQuote = quoteChar(zName);
914   appendText(&s, zName, cQuote);
915   while( sqlite3_step(pStmt)==SQLITE_ROW ){
916     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
917     nRow++;
918     appendText(&s, zDiv, 0);
919     zDiv = ",";
920     cQuote = quoteChar(zCol);
921     appendText(&s, zCol, cQuote);
922   }
923   appendText(&s, ")", 0);
924   sqlite3_finalize(pStmt);
925   if( nRow==0 ){
926     freeText(&s);
927     s.z = 0;
928   }
929   return s.z;
930 }
931 
932 /*
933 ** SQL function:  shell_module_schema(X)
934 **
935 ** Return a fake schema for the table-valued function or eponymous virtual
936 ** table X.
937 */
shellModuleSchema(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)938 static void shellModuleSchema(
939   sqlite3_context *pCtx,
940   int nVal,
941   sqlite3_value **apVal
942 ){
943   const char *zName = (const char*)sqlite3_value_text(apVal[0]);
944   char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
945   UNUSED_PARAMETER(nVal);
946   if( zFake ){
947     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
948                         -1, sqlite3_free);
949     free(zFake);
950   }
951 }
952 
953 /*
954 ** SQL function:  shell_add_schema(S,X)
955 **
956 ** Add the schema name X to the CREATE statement in S and return the result.
957 ** Examples:
958 **
959 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
960 **
961 ** Also works on
962 **
963 **    CREATE INDEX
964 **    CREATE UNIQUE INDEX
965 **    CREATE VIEW
966 **    CREATE TRIGGER
967 **    CREATE VIRTUAL TABLE
968 **
969 ** This UDF is used by the .schema command to insert the schema name of
970 ** attached databases into the middle of the sqlite_schema.sql field.
971 */
shellAddSchemaName(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)972 static void shellAddSchemaName(
973   sqlite3_context *pCtx,
974   int nVal,
975   sqlite3_value **apVal
976 ){
977   static const char *aPrefix[] = {
978      "TABLE",
979      "INDEX",
980      "UNIQUE INDEX",
981      "VIEW",
982      "TRIGGER",
983      "VIRTUAL TABLE"
984   };
985   int i = 0;
986   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
987   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
988   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
989   sqlite3 *db = sqlite3_context_db_handle(pCtx);
990   UNUSED_PARAMETER(nVal);
991   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
992     for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
993       int n = strlen30(aPrefix[i]);
994       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
995         char *z = 0;
996         char *zFake = 0;
997         if( zSchema ){
998           char cQuote = quoteChar(zSchema);
999           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1000             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1001           }else{
1002             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1003           }
1004         }
1005         if( zName
1006          && aPrefix[i][0]=='V'
1007          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1008         ){
1009           if( z==0 ){
1010             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1011           }else{
1012             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1013           }
1014           free(zFake);
1015         }
1016         if( z ){
1017           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1018           return;
1019         }
1020       }
1021     }
1022   }
1023   sqlite3_result_value(pCtx, apVal[0]);
1024 }
1025 
1026 /*
1027 ** The source code for several run-time loadable extensions is inserted
1028 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1029 ** code, we need to override some macros to make the included program code
1030 ** work here in the middle of this regular program.
1031 */
1032 #define SQLITE_EXTENSION_INIT1
1033 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1034 
1035 #if defined(_WIN32) && defined(_MSC_VER)
1036 /************************* Begin test_windirent.h ******************/
1037 /*
1038 ** 2015 November 30
1039 **
1040 ** The author disclaims copyright to this source code.  In place of
1041 ** a legal notice, here is a blessing:
1042 **
1043 **    May you do good and not evil.
1044 **    May you find forgiveness for yourself and forgive others.
1045 **    May you share freely, never taking more than you give.
1046 **
1047 *************************************************************************
1048 ** This file contains declarations for most of the opendir() family of
1049 ** POSIX functions on Win32 using the MSVCRT.
1050 */
1051 
1052 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1053 #define SQLITE_WINDIRENT_H
1054 
1055 /*
1056 ** We need several data types from the Windows SDK header.
1057 */
1058 
1059 #ifndef WIN32_LEAN_AND_MEAN
1060 #define WIN32_LEAN_AND_MEAN
1061 #endif
1062 
1063 #include "windows.h"
1064 
1065 /*
1066 ** We need several support functions from the SQLite core.
1067 */
1068 
1069 /* #include "sqlite3.h" */
1070 
1071 /*
1072 ** We need several things from the ANSI and MSVCRT headers.
1073 */
1074 
1075 #include <stdio.h>
1076 #include <stdlib.h>
1077 #include <errno.h>
1078 #include <io.h>
1079 #include <limits.h>
1080 #include <sys/types.h>
1081 #include <sys/stat.h>
1082 
1083 /*
1084 ** We may need several defines that should have been in "sys/stat.h".
1085 */
1086 
1087 #ifndef S_ISREG
1088 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1089 #endif
1090 
1091 #ifndef S_ISDIR
1092 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1093 #endif
1094 
1095 #ifndef S_ISLNK
1096 #define S_ISLNK(mode) (0)
1097 #endif
1098 
1099 /*
1100 ** We may need to provide the "mode_t" type.
1101 */
1102 
1103 #ifndef MODE_T_DEFINED
1104   #define MODE_T_DEFINED
1105   typedef unsigned short mode_t;
1106 #endif
1107 
1108 /*
1109 ** We may need to provide the "ino_t" type.
1110 */
1111 
1112 #ifndef INO_T_DEFINED
1113   #define INO_T_DEFINED
1114   typedef unsigned short ino_t;
1115 #endif
1116 
1117 /*
1118 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1119 */
1120 
1121 #ifndef NAME_MAX
1122 #  ifdef FILENAME_MAX
1123 #    define NAME_MAX (FILENAME_MAX)
1124 #  else
1125 #    define NAME_MAX (260)
1126 #  endif
1127 #endif
1128 
1129 /*
1130 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1131 */
1132 
1133 #ifndef NULL_INTPTR_T
1134 #  define NULL_INTPTR_T ((intptr_t)(0))
1135 #endif
1136 
1137 #ifndef BAD_INTPTR_T
1138 #  define BAD_INTPTR_T ((intptr_t)(-1))
1139 #endif
1140 
1141 /*
1142 ** We need to provide the necessary structures and related types.
1143 */
1144 
1145 #ifndef DIRENT_DEFINED
1146 #define DIRENT_DEFINED
1147 typedef struct DIRENT DIRENT;
1148 typedef DIRENT *LPDIRENT;
1149 struct DIRENT {
1150   ino_t d_ino;               /* Sequence number, do not use. */
1151   unsigned d_attributes;     /* Win32 file attributes. */
1152   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1153 };
1154 #endif
1155 
1156 #ifndef DIR_DEFINED
1157 #define DIR_DEFINED
1158 typedef struct DIR DIR;
1159 typedef DIR *LPDIR;
1160 struct DIR {
1161   intptr_t d_handle; /* Value returned by "_findfirst". */
1162   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1163   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1164 };
1165 #endif
1166 
1167 /*
1168 ** Provide a macro, for use by the implementation, to determine if a
1169 ** particular directory entry should be skipped over when searching for
1170 ** the next directory entry that should be returned by the readdir() or
1171 ** readdir_r() functions.
1172 */
1173 
1174 #ifndef is_filtered
1175 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1176 #endif
1177 
1178 /*
1179 ** Provide the function prototype for the POSIX compatiable getenv()
1180 ** function.  This function is not thread-safe.
1181 */
1182 
1183 extern const char *windirent_getenv(const char *name);
1184 
1185 /*
1186 ** Finally, we can provide the function prototypes for the opendir(),
1187 ** readdir(), readdir_r(), and closedir() POSIX functions.
1188 */
1189 
1190 extern LPDIR opendir(const char *dirname);
1191 extern LPDIRENT readdir(LPDIR dirp);
1192 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1193 extern INT closedir(LPDIR dirp);
1194 
1195 #endif /* defined(WIN32) && defined(_MSC_VER) */
1196 
1197 /************************* End test_windirent.h ********************/
1198 /************************* Begin test_windirent.c ******************/
1199 /*
1200 ** 2015 November 30
1201 **
1202 ** The author disclaims copyright to this source code.  In place of
1203 ** a legal notice, here is a blessing:
1204 **
1205 **    May you do good and not evil.
1206 **    May you find forgiveness for yourself and forgive others.
1207 **    May you share freely, never taking more than you give.
1208 **
1209 *************************************************************************
1210 ** This file contains code to implement most of the opendir() family of
1211 ** POSIX functions on Win32 using the MSVCRT.
1212 */
1213 
1214 #if defined(_WIN32) && defined(_MSC_VER)
1215 /* #include "test_windirent.h" */
1216 
1217 /*
1218 ** Implementation of the POSIX getenv() function using the Win32 API.
1219 ** This function is not thread-safe.
1220 */
windirent_getenv(const char * name)1221 const char *windirent_getenv(
1222   const char *name
1223 ){
1224   static char value[32768]; /* Maximum length, per MSDN */
1225   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1226   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1227 
1228   memset(value, 0, sizeof(value));
1229   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1230   if( dwRet==0 || dwRet>dwSize ){
1231     /*
1232     ** The function call to GetEnvironmentVariableA() failed -OR-
1233     ** the buffer is not large enough.  Either way, return NULL.
1234     */
1235     return 0;
1236   }else{
1237     /*
1238     ** The function call to GetEnvironmentVariableA() succeeded
1239     ** -AND- the buffer contains the entire value.
1240     */
1241     return value;
1242   }
1243 }
1244 
1245 /*
1246 ** Implementation of the POSIX opendir() function using the MSVCRT.
1247 */
opendir(const char * dirname)1248 LPDIR opendir(
1249   const char *dirname
1250 ){
1251   struct _finddata_t data;
1252   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1253   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1254 
1255   if( dirp==NULL ) return NULL;
1256   memset(dirp, 0, sizeof(DIR));
1257 
1258   /* TODO: Remove this if Unix-style root paths are not used. */
1259   if( sqlite3_stricmp(dirname, "/")==0 ){
1260     dirname = windirent_getenv("SystemDrive");
1261   }
1262 
1263   memset(&data, 0, sizeof(struct _finddata_t));
1264   _snprintf(data.name, namesize, "%s\\*", dirname);
1265   dirp->d_handle = _findfirst(data.name, &data);
1266 
1267   if( dirp->d_handle==BAD_INTPTR_T ){
1268     closedir(dirp);
1269     return NULL;
1270   }
1271 
1272   /* TODO: Remove this block to allow hidden and/or system files. */
1273   if( is_filtered(data) ){
1274 next:
1275 
1276     memset(&data, 0, sizeof(struct _finddata_t));
1277     if( _findnext(dirp->d_handle, &data)==-1 ){
1278       closedir(dirp);
1279       return NULL;
1280     }
1281 
1282     /* TODO: Remove this block to allow hidden and/or system files. */
1283     if( is_filtered(data) ) goto next;
1284   }
1285 
1286   dirp->d_first.d_attributes = data.attrib;
1287   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1288   dirp->d_first.d_name[NAME_MAX] = '\0';
1289 
1290   return dirp;
1291 }
1292 
1293 /*
1294 ** Implementation of the POSIX readdir() function using the MSVCRT.
1295 */
readdir(LPDIR dirp)1296 LPDIRENT readdir(
1297   LPDIR dirp
1298 ){
1299   struct _finddata_t data;
1300 
1301   if( dirp==NULL ) return NULL;
1302 
1303   if( dirp->d_first.d_ino==0 ){
1304     dirp->d_first.d_ino++;
1305     dirp->d_next.d_ino++;
1306 
1307     return &dirp->d_first;
1308   }
1309 
1310 next:
1311 
1312   memset(&data, 0, sizeof(struct _finddata_t));
1313   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1314 
1315   /* TODO: Remove this block to allow hidden and/or system files. */
1316   if( is_filtered(data) ) goto next;
1317 
1318   dirp->d_next.d_ino++;
1319   dirp->d_next.d_attributes = data.attrib;
1320   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1321   dirp->d_next.d_name[NAME_MAX] = '\0';
1322 
1323   return &dirp->d_next;
1324 }
1325 
1326 /*
1327 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1328 */
readdir_r(LPDIR dirp,LPDIRENT entry,LPDIRENT * result)1329 INT readdir_r(
1330   LPDIR dirp,
1331   LPDIRENT entry,
1332   LPDIRENT *result
1333 ){
1334   struct _finddata_t data;
1335 
1336   if( dirp==NULL ) return EBADF;
1337 
1338   if( dirp->d_first.d_ino==0 ){
1339     dirp->d_first.d_ino++;
1340     dirp->d_next.d_ino++;
1341 
1342     entry->d_ino = dirp->d_first.d_ino;
1343     entry->d_attributes = dirp->d_first.d_attributes;
1344     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1345     entry->d_name[NAME_MAX] = '\0';
1346 
1347     *result = entry;
1348     return 0;
1349   }
1350 
1351 next:
1352 
1353   memset(&data, 0, sizeof(struct _finddata_t));
1354   if( _findnext(dirp->d_handle, &data)==-1 ){
1355     *result = NULL;
1356     return ENOENT;
1357   }
1358 
1359   /* TODO: Remove this block to allow hidden and/or system files. */
1360   if( is_filtered(data) ) goto next;
1361 
1362   entry->d_ino = (ino_t)-1; /* not available */
1363   entry->d_attributes = data.attrib;
1364   strncpy(entry->d_name, data.name, NAME_MAX);
1365   entry->d_name[NAME_MAX] = '\0';
1366 
1367   *result = entry;
1368   return 0;
1369 }
1370 
1371 /*
1372 ** Implementation of the POSIX closedir() function using the MSVCRT.
1373 */
closedir(LPDIR dirp)1374 INT closedir(
1375   LPDIR dirp
1376 ){
1377   INT result = 0;
1378 
1379   if( dirp==NULL ) return EINVAL;
1380 
1381   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1382     result = _findclose(dirp->d_handle);
1383   }
1384 
1385   sqlite3_free(dirp);
1386   return result;
1387 }
1388 
1389 #endif /* defined(WIN32) && defined(_MSC_VER) */
1390 
1391 /************************* End test_windirent.c ********************/
1392 #define dirent DIRENT
1393 #endif
1394 /************************* Begin ../ext/misc/shathree.c ******************/
1395 /*
1396 ** 2017-03-08
1397 **
1398 ** The author disclaims copyright to this source code.  In place of
1399 ** a legal notice, here is a blessing:
1400 **
1401 **    May you do good and not evil.
1402 **    May you find forgiveness for yourself and forgive others.
1403 **    May you share freely, never taking more than you give.
1404 **
1405 ******************************************************************************
1406 **
1407 ** This SQLite extension implements functions that compute SHA3 hashes.
1408 ** Two SQL functions are implemented:
1409 **
1410 **     sha3(X,SIZE)
1411 **     sha3_query(Y,SIZE)
1412 **
1413 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1414 ** X is NULL.
1415 **
1416 ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
1417 ** and returns a hash of their results.
1418 **
1419 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1420 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1421 ** 384, or 512, to determine SHA3 hash variant that is computed.
1422 */
1423 /* #include "sqlite3ext.h" */
1424 SQLITE_EXTENSION_INIT1
1425 #include <assert.h>
1426 #include <string.h>
1427 #include <stdarg.h>
1428 
1429 #ifndef SQLITE_AMALGAMATION
1430 /* typedef sqlite3_uint64 u64; */
1431 #endif /* SQLITE_AMALGAMATION */
1432 
1433 /******************************************************************************
1434 ** The Hash Engine
1435 */
1436 /*
1437 ** Macros to determine whether the machine is big or little endian,
1438 ** and whether or not that determination is run-time or compile-time.
1439 **
1440 ** For best performance, an attempt is made to guess at the byte-order
1441 ** using C-preprocessor macros.  If that is unsuccessful, or if
1442 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1443 ** at run-time.
1444 */
1445 #ifndef SHA3_BYTEORDER
1446 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1447      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1448      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1449      defined(__arm__)
1450 #   define SHA3_BYTEORDER    1234
1451 # elif defined(sparc)    || defined(__ppc__)
1452 #   define SHA3_BYTEORDER    4321
1453 # else
1454 #   define SHA3_BYTEORDER 0
1455 # endif
1456 #endif
1457 
1458 
1459 /*
1460 ** State structure for a SHA3 hash in progress
1461 */
1462 typedef struct SHA3Context SHA3Context;
1463 struct SHA3Context {
1464   union {
1465     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1466     unsigned char x[1600];    /* ... or 1600 bytes */
1467   } u;
1468   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1469   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1470   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1471 };
1472 
1473 /*
1474 ** A single step of the Keccak mixing function for a 1600-bit state
1475 */
KeccakF1600Step(SHA3Context * p)1476 static void KeccakF1600Step(SHA3Context *p){
1477   int i;
1478   u64 b0, b1, b2, b3, b4;
1479   u64 c0, c1, c2, c3, c4;
1480   u64 d0, d1, d2, d3, d4;
1481   static const u64 RC[] = {
1482     0x0000000000000001ULL,  0x0000000000008082ULL,
1483     0x800000000000808aULL,  0x8000000080008000ULL,
1484     0x000000000000808bULL,  0x0000000080000001ULL,
1485     0x8000000080008081ULL,  0x8000000000008009ULL,
1486     0x000000000000008aULL,  0x0000000000000088ULL,
1487     0x0000000080008009ULL,  0x000000008000000aULL,
1488     0x000000008000808bULL,  0x800000000000008bULL,
1489     0x8000000000008089ULL,  0x8000000000008003ULL,
1490     0x8000000000008002ULL,  0x8000000000000080ULL,
1491     0x000000000000800aULL,  0x800000008000000aULL,
1492     0x8000000080008081ULL,  0x8000000000008080ULL,
1493     0x0000000080000001ULL,  0x8000000080008008ULL
1494   };
1495 # define a00 (p->u.s[0])
1496 # define a01 (p->u.s[1])
1497 # define a02 (p->u.s[2])
1498 # define a03 (p->u.s[3])
1499 # define a04 (p->u.s[4])
1500 # define a10 (p->u.s[5])
1501 # define a11 (p->u.s[6])
1502 # define a12 (p->u.s[7])
1503 # define a13 (p->u.s[8])
1504 # define a14 (p->u.s[9])
1505 # define a20 (p->u.s[10])
1506 # define a21 (p->u.s[11])
1507 # define a22 (p->u.s[12])
1508 # define a23 (p->u.s[13])
1509 # define a24 (p->u.s[14])
1510 # define a30 (p->u.s[15])
1511 # define a31 (p->u.s[16])
1512 # define a32 (p->u.s[17])
1513 # define a33 (p->u.s[18])
1514 # define a34 (p->u.s[19])
1515 # define a40 (p->u.s[20])
1516 # define a41 (p->u.s[21])
1517 # define a42 (p->u.s[22])
1518 # define a43 (p->u.s[23])
1519 # define a44 (p->u.s[24])
1520 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1521 
1522   for(i=0; i<24; i+=4){
1523     c0 = a00^a10^a20^a30^a40;
1524     c1 = a01^a11^a21^a31^a41;
1525     c2 = a02^a12^a22^a32^a42;
1526     c3 = a03^a13^a23^a33^a43;
1527     c4 = a04^a14^a24^a34^a44;
1528     d0 = c4^ROL64(c1, 1);
1529     d1 = c0^ROL64(c2, 1);
1530     d2 = c1^ROL64(c3, 1);
1531     d3 = c2^ROL64(c4, 1);
1532     d4 = c3^ROL64(c0, 1);
1533 
1534     b0 = (a00^d0);
1535     b1 = ROL64((a11^d1), 44);
1536     b2 = ROL64((a22^d2), 43);
1537     b3 = ROL64((a33^d3), 21);
1538     b4 = ROL64((a44^d4), 14);
1539     a00 =   b0 ^((~b1)&  b2 );
1540     a00 ^= RC[i];
1541     a11 =   b1 ^((~b2)&  b3 );
1542     a22 =   b2 ^((~b3)&  b4 );
1543     a33 =   b3 ^((~b4)&  b0 );
1544     a44 =   b4 ^((~b0)&  b1 );
1545 
1546     b2 = ROL64((a20^d0), 3);
1547     b3 = ROL64((a31^d1), 45);
1548     b4 = ROL64((a42^d2), 61);
1549     b0 = ROL64((a03^d3), 28);
1550     b1 = ROL64((a14^d4), 20);
1551     a20 =   b0 ^((~b1)&  b2 );
1552     a31 =   b1 ^((~b2)&  b3 );
1553     a42 =   b2 ^((~b3)&  b4 );
1554     a03 =   b3 ^((~b4)&  b0 );
1555     a14 =   b4 ^((~b0)&  b1 );
1556 
1557     b4 = ROL64((a40^d0), 18);
1558     b0 = ROL64((a01^d1), 1);
1559     b1 = ROL64((a12^d2), 6);
1560     b2 = ROL64((a23^d3), 25);
1561     b3 = ROL64((a34^d4), 8);
1562     a40 =   b0 ^((~b1)&  b2 );
1563     a01 =   b1 ^((~b2)&  b3 );
1564     a12 =   b2 ^((~b3)&  b4 );
1565     a23 =   b3 ^((~b4)&  b0 );
1566     a34 =   b4 ^((~b0)&  b1 );
1567 
1568     b1 = ROL64((a10^d0), 36);
1569     b2 = ROL64((a21^d1), 10);
1570     b3 = ROL64((a32^d2), 15);
1571     b4 = ROL64((a43^d3), 56);
1572     b0 = ROL64((a04^d4), 27);
1573     a10 =   b0 ^((~b1)&  b2 );
1574     a21 =   b1 ^((~b2)&  b3 );
1575     a32 =   b2 ^((~b3)&  b4 );
1576     a43 =   b3 ^((~b4)&  b0 );
1577     a04 =   b4 ^((~b0)&  b1 );
1578 
1579     b3 = ROL64((a30^d0), 41);
1580     b4 = ROL64((a41^d1), 2);
1581     b0 = ROL64((a02^d2), 62);
1582     b1 = ROL64((a13^d3), 55);
1583     b2 = ROL64((a24^d4), 39);
1584     a30 =   b0 ^((~b1)&  b2 );
1585     a41 =   b1 ^((~b2)&  b3 );
1586     a02 =   b2 ^((~b3)&  b4 );
1587     a13 =   b3 ^((~b4)&  b0 );
1588     a24 =   b4 ^((~b0)&  b1 );
1589 
1590     c0 = a00^a20^a40^a10^a30;
1591     c1 = a11^a31^a01^a21^a41;
1592     c2 = a22^a42^a12^a32^a02;
1593     c3 = a33^a03^a23^a43^a13;
1594     c4 = a44^a14^a34^a04^a24;
1595     d0 = c4^ROL64(c1, 1);
1596     d1 = c0^ROL64(c2, 1);
1597     d2 = c1^ROL64(c3, 1);
1598     d3 = c2^ROL64(c4, 1);
1599     d4 = c3^ROL64(c0, 1);
1600 
1601     b0 = (a00^d0);
1602     b1 = ROL64((a31^d1), 44);
1603     b2 = ROL64((a12^d2), 43);
1604     b3 = ROL64((a43^d3), 21);
1605     b4 = ROL64((a24^d4), 14);
1606     a00 =   b0 ^((~b1)&  b2 );
1607     a00 ^= RC[i+1];
1608     a31 =   b1 ^((~b2)&  b3 );
1609     a12 =   b2 ^((~b3)&  b4 );
1610     a43 =   b3 ^((~b4)&  b0 );
1611     a24 =   b4 ^((~b0)&  b1 );
1612 
1613     b2 = ROL64((a40^d0), 3);
1614     b3 = ROL64((a21^d1), 45);
1615     b4 = ROL64((a02^d2), 61);
1616     b0 = ROL64((a33^d3), 28);
1617     b1 = ROL64((a14^d4), 20);
1618     a40 =   b0 ^((~b1)&  b2 );
1619     a21 =   b1 ^((~b2)&  b3 );
1620     a02 =   b2 ^((~b3)&  b4 );
1621     a33 =   b3 ^((~b4)&  b0 );
1622     a14 =   b4 ^((~b0)&  b1 );
1623 
1624     b4 = ROL64((a30^d0), 18);
1625     b0 = ROL64((a11^d1), 1);
1626     b1 = ROL64((a42^d2), 6);
1627     b2 = ROL64((a23^d3), 25);
1628     b3 = ROL64((a04^d4), 8);
1629     a30 =   b0 ^((~b1)&  b2 );
1630     a11 =   b1 ^((~b2)&  b3 );
1631     a42 =   b2 ^((~b3)&  b4 );
1632     a23 =   b3 ^((~b4)&  b0 );
1633     a04 =   b4 ^((~b0)&  b1 );
1634 
1635     b1 = ROL64((a20^d0), 36);
1636     b2 = ROL64((a01^d1), 10);
1637     b3 = ROL64((a32^d2), 15);
1638     b4 = ROL64((a13^d3), 56);
1639     b0 = ROL64((a44^d4), 27);
1640     a20 =   b0 ^((~b1)&  b2 );
1641     a01 =   b1 ^((~b2)&  b3 );
1642     a32 =   b2 ^((~b3)&  b4 );
1643     a13 =   b3 ^((~b4)&  b0 );
1644     a44 =   b4 ^((~b0)&  b1 );
1645 
1646     b3 = ROL64((a10^d0), 41);
1647     b4 = ROL64((a41^d1), 2);
1648     b0 = ROL64((a22^d2), 62);
1649     b1 = ROL64((a03^d3), 55);
1650     b2 = ROL64((a34^d4), 39);
1651     a10 =   b0 ^((~b1)&  b2 );
1652     a41 =   b1 ^((~b2)&  b3 );
1653     a22 =   b2 ^((~b3)&  b4 );
1654     a03 =   b3 ^((~b4)&  b0 );
1655     a34 =   b4 ^((~b0)&  b1 );
1656 
1657     c0 = a00^a40^a30^a20^a10;
1658     c1 = a31^a21^a11^a01^a41;
1659     c2 = a12^a02^a42^a32^a22;
1660     c3 = a43^a33^a23^a13^a03;
1661     c4 = a24^a14^a04^a44^a34;
1662     d0 = c4^ROL64(c1, 1);
1663     d1 = c0^ROL64(c2, 1);
1664     d2 = c1^ROL64(c3, 1);
1665     d3 = c2^ROL64(c4, 1);
1666     d4 = c3^ROL64(c0, 1);
1667 
1668     b0 = (a00^d0);
1669     b1 = ROL64((a21^d1), 44);
1670     b2 = ROL64((a42^d2), 43);
1671     b3 = ROL64((a13^d3), 21);
1672     b4 = ROL64((a34^d4), 14);
1673     a00 =   b0 ^((~b1)&  b2 );
1674     a00 ^= RC[i+2];
1675     a21 =   b1 ^((~b2)&  b3 );
1676     a42 =   b2 ^((~b3)&  b4 );
1677     a13 =   b3 ^((~b4)&  b0 );
1678     a34 =   b4 ^((~b0)&  b1 );
1679 
1680     b2 = ROL64((a30^d0), 3);
1681     b3 = ROL64((a01^d1), 45);
1682     b4 = ROL64((a22^d2), 61);
1683     b0 = ROL64((a43^d3), 28);
1684     b1 = ROL64((a14^d4), 20);
1685     a30 =   b0 ^((~b1)&  b2 );
1686     a01 =   b1 ^((~b2)&  b3 );
1687     a22 =   b2 ^((~b3)&  b4 );
1688     a43 =   b3 ^((~b4)&  b0 );
1689     a14 =   b4 ^((~b0)&  b1 );
1690 
1691     b4 = ROL64((a10^d0), 18);
1692     b0 = ROL64((a31^d1), 1);
1693     b1 = ROL64((a02^d2), 6);
1694     b2 = ROL64((a23^d3), 25);
1695     b3 = ROL64((a44^d4), 8);
1696     a10 =   b0 ^((~b1)&  b2 );
1697     a31 =   b1 ^((~b2)&  b3 );
1698     a02 =   b2 ^((~b3)&  b4 );
1699     a23 =   b3 ^((~b4)&  b0 );
1700     a44 =   b4 ^((~b0)&  b1 );
1701 
1702     b1 = ROL64((a40^d0), 36);
1703     b2 = ROL64((a11^d1), 10);
1704     b3 = ROL64((a32^d2), 15);
1705     b4 = ROL64((a03^d3), 56);
1706     b0 = ROL64((a24^d4), 27);
1707     a40 =   b0 ^((~b1)&  b2 );
1708     a11 =   b1 ^((~b2)&  b3 );
1709     a32 =   b2 ^((~b3)&  b4 );
1710     a03 =   b3 ^((~b4)&  b0 );
1711     a24 =   b4 ^((~b0)&  b1 );
1712 
1713     b3 = ROL64((a20^d0), 41);
1714     b4 = ROL64((a41^d1), 2);
1715     b0 = ROL64((a12^d2), 62);
1716     b1 = ROL64((a33^d3), 55);
1717     b2 = ROL64((a04^d4), 39);
1718     a20 =   b0 ^((~b1)&  b2 );
1719     a41 =   b1 ^((~b2)&  b3 );
1720     a12 =   b2 ^((~b3)&  b4 );
1721     a33 =   b3 ^((~b4)&  b0 );
1722     a04 =   b4 ^((~b0)&  b1 );
1723 
1724     c0 = a00^a30^a10^a40^a20;
1725     c1 = a21^a01^a31^a11^a41;
1726     c2 = a42^a22^a02^a32^a12;
1727     c3 = a13^a43^a23^a03^a33;
1728     c4 = a34^a14^a44^a24^a04;
1729     d0 = c4^ROL64(c1, 1);
1730     d1 = c0^ROL64(c2, 1);
1731     d2 = c1^ROL64(c3, 1);
1732     d3 = c2^ROL64(c4, 1);
1733     d4 = c3^ROL64(c0, 1);
1734 
1735     b0 = (a00^d0);
1736     b1 = ROL64((a01^d1), 44);
1737     b2 = ROL64((a02^d2), 43);
1738     b3 = ROL64((a03^d3), 21);
1739     b4 = ROL64((a04^d4), 14);
1740     a00 =   b0 ^((~b1)&  b2 );
1741     a00 ^= RC[i+3];
1742     a01 =   b1 ^((~b2)&  b3 );
1743     a02 =   b2 ^((~b3)&  b4 );
1744     a03 =   b3 ^((~b4)&  b0 );
1745     a04 =   b4 ^((~b0)&  b1 );
1746 
1747     b2 = ROL64((a10^d0), 3);
1748     b3 = ROL64((a11^d1), 45);
1749     b4 = ROL64((a12^d2), 61);
1750     b0 = ROL64((a13^d3), 28);
1751     b1 = ROL64((a14^d4), 20);
1752     a10 =   b0 ^((~b1)&  b2 );
1753     a11 =   b1 ^((~b2)&  b3 );
1754     a12 =   b2 ^((~b3)&  b4 );
1755     a13 =   b3 ^((~b4)&  b0 );
1756     a14 =   b4 ^((~b0)&  b1 );
1757 
1758     b4 = ROL64((a20^d0), 18);
1759     b0 = ROL64((a21^d1), 1);
1760     b1 = ROL64((a22^d2), 6);
1761     b2 = ROL64((a23^d3), 25);
1762     b3 = ROL64((a24^d4), 8);
1763     a20 =   b0 ^((~b1)&  b2 );
1764     a21 =   b1 ^((~b2)&  b3 );
1765     a22 =   b2 ^((~b3)&  b4 );
1766     a23 =   b3 ^((~b4)&  b0 );
1767     a24 =   b4 ^((~b0)&  b1 );
1768 
1769     b1 = ROL64((a30^d0), 36);
1770     b2 = ROL64((a31^d1), 10);
1771     b3 = ROL64((a32^d2), 15);
1772     b4 = ROL64((a33^d3), 56);
1773     b0 = ROL64((a34^d4), 27);
1774     a30 =   b0 ^((~b1)&  b2 );
1775     a31 =   b1 ^((~b2)&  b3 );
1776     a32 =   b2 ^((~b3)&  b4 );
1777     a33 =   b3 ^((~b4)&  b0 );
1778     a34 =   b4 ^((~b0)&  b1 );
1779 
1780     b3 = ROL64((a40^d0), 41);
1781     b4 = ROL64((a41^d1), 2);
1782     b0 = ROL64((a42^d2), 62);
1783     b1 = ROL64((a43^d3), 55);
1784     b2 = ROL64((a44^d4), 39);
1785     a40 =   b0 ^((~b1)&  b2 );
1786     a41 =   b1 ^((~b2)&  b3 );
1787     a42 =   b2 ^((~b3)&  b4 );
1788     a43 =   b3 ^((~b4)&  b0 );
1789     a44 =   b4 ^((~b0)&  b1 );
1790   }
1791 }
1792 
1793 /*
1794 ** Initialize a new hash.  iSize determines the size of the hash
1795 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1796 ** can be zero to use the default hash size of 256 bits.
1797 */
SHA3Init(SHA3Context * p,int iSize)1798 static void SHA3Init(SHA3Context *p, int iSize){
1799   memset(p, 0, sizeof(*p));
1800   if( iSize>=128 && iSize<=512 ){
1801     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1802   }else{
1803     p->nRate = (1600 - 2*256)/8;
1804   }
1805 #if SHA3_BYTEORDER==1234
1806   /* Known to be little-endian at compile-time. No-op */
1807 #elif SHA3_BYTEORDER==4321
1808   p->ixMask = 7;  /* Big-endian */
1809 #else
1810   {
1811     static unsigned int one = 1;
1812     if( 1==*(unsigned char*)&one ){
1813       /* Little endian.  No byte swapping. */
1814       p->ixMask = 0;
1815     }else{
1816       /* Big endian.  Byte swap. */
1817       p->ixMask = 7;
1818     }
1819   }
1820 #endif
1821 }
1822 
1823 /*
1824 ** Make consecutive calls to the SHA3Update function to add new content
1825 ** to the hash
1826 */
SHA3Update(SHA3Context * p,const unsigned char * aData,unsigned int nData)1827 static void SHA3Update(
1828   SHA3Context *p,
1829   const unsigned char *aData,
1830   unsigned int nData
1831 ){
1832   unsigned int i = 0;
1833 #if SHA3_BYTEORDER==1234
1834   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1835     for(; i+7<nData; i+=8){
1836       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1837       p->nLoaded += 8;
1838       if( p->nLoaded>=p->nRate ){
1839         KeccakF1600Step(p);
1840         p->nLoaded = 0;
1841       }
1842     }
1843   }
1844 #endif
1845   for(; i<nData; i++){
1846 #if SHA3_BYTEORDER==1234
1847     p->u.x[p->nLoaded] ^= aData[i];
1848 #elif SHA3_BYTEORDER==4321
1849     p->u.x[p->nLoaded^0x07] ^= aData[i];
1850 #else
1851     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1852 #endif
1853     p->nLoaded++;
1854     if( p->nLoaded==p->nRate ){
1855       KeccakF1600Step(p);
1856       p->nLoaded = 0;
1857     }
1858   }
1859 }
1860 
1861 /*
1862 ** After all content has been added, invoke SHA3Final() to compute
1863 ** the final hash.  The function returns a pointer to the binary
1864 ** hash value.
1865 */
SHA3Final(SHA3Context * p)1866 static unsigned char *SHA3Final(SHA3Context *p){
1867   unsigned int i;
1868   if( p->nLoaded==p->nRate-1 ){
1869     const unsigned char c1 = 0x86;
1870     SHA3Update(p, &c1, 1);
1871   }else{
1872     const unsigned char c2 = 0x06;
1873     const unsigned char c3 = 0x80;
1874     SHA3Update(p, &c2, 1);
1875     p->nLoaded = p->nRate - 1;
1876     SHA3Update(p, &c3, 1);
1877   }
1878   for(i=0; i<p->nRate; i++){
1879     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1880   }
1881   return &p->u.x[p->nRate];
1882 }
1883 /* End of the hashing logic
1884 *****************************************************************************/
1885 
1886 /*
1887 ** Implementation of the sha3(X,SIZE) function.
1888 **
1889 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
1890 ** size is 256.  If X is a BLOB, it is hashed as is.
1891 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1892 ** and the string is hashed without the trailing 0x00 terminator.  The hash
1893 ** of a NULL value is NULL.
1894 */
sha3Func(sqlite3_context * context,int argc,sqlite3_value ** argv)1895 static void sha3Func(
1896   sqlite3_context *context,
1897   int argc,
1898   sqlite3_value **argv
1899 ){
1900   SHA3Context cx;
1901   int eType = sqlite3_value_type(argv[0]);
1902   int nByte = sqlite3_value_bytes(argv[0]);
1903   int iSize;
1904   if( argc==1 ){
1905     iSize = 256;
1906   }else{
1907     iSize = sqlite3_value_int(argv[1]);
1908     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1909       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1910                                     "384 512", -1);
1911       return;
1912     }
1913   }
1914   if( eType==SQLITE_NULL ) return;
1915   SHA3Init(&cx, iSize);
1916   if( eType==SQLITE_BLOB ){
1917     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1918   }else{
1919     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1920   }
1921   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1922 }
1923 
1924 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1925 ** of 50 bytes and add it to the hash.
1926 */
hash_step_vformat(SHA3Context * p,const char * zFormat,...)1927 static void hash_step_vformat(
1928   SHA3Context *p,                 /* Add content to this context */
1929   const char *zFormat,
1930   ...
1931 ){
1932   va_list ap;
1933   int n;
1934   char zBuf[50];
1935   va_start(ap, zFormat);
1936   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1937   va_end(ap);
1938   n = (int)strlen(zBuf);
1939   SHA3Update(p, (unsigned char*)zBuf, n);
1940 }
1941 
1942 /*
1943 ** Implementation of the sha3_query(SQL,SIZE) function.
1944 **
1945 ** This function compiles and runs the SQL statement(s) given in the
1946 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
1947 ** size is 256.
1948 **
1949 ** The format of the byte stream that is hashed is summarized as follows:
1950 **
1951 **       S<n>:<sql>
1952 **       R
1953 **       N
1954 **       I<int>
1955 **       F<ieee-float>
1956 **       B<size>:<bytes>
1957 **       T<size>:<text>
1958 **
1959 ** <sql> is the original SQL text for each statement run and <n> is
1960 ** the size of that text.  The SQL text is UTF-8.  A single R character
1961 ** occurs before the start of each row.  N means a NULL value.
1962 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
1963 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1964 ** B means blobs of <size> bytes.  T means text rendered as <size>
1965 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
1966 ** text integers.
1967 **
1968 ** For each SQL statement in the X input, there is one S segment.  Each
1969 ** S segment is followed by zero or more R segments, one for each row in the
1970 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
1971 ** one for each column in the result set.  Segments are concatentated directly
1972 ** with no delimiters of any kind.
1973 */
sha3QueryFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1974 static void sha3QueryFunc(
1975   sqlite3_context *context,
1976   int argc,
1977   sqlite3_value **argv
1978 ){
1979   sqlite3 *db = sqlite3_context_db_handle(context);
1980   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1981   sqlite3_stmt *pStmt = 0;
1982   int nCol;                   /* Number of columns in the result set */
1983   int i;                      /* Loop counter */
1984   int rc;
1985   int n;
1986   const char *z;
1987   SHA3Context cx;
1988   int iSize;
1989 
1990   if( argc==1 ){
1991     iSize = 256;
1992   }else{
1993     iSize = sqlite3_value_int(argv[1]);
1994     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1995       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1996                                     "384 512", -1);
1997       return;
1998     }
1999   }
2000   if( zSql==0 ) return;
2001   SHA3Init(&cx, iSize);
2002   while( zSql[0] ){
2003     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2004     if( rc ){
2005       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2006                                    zSql, sqlite3_errmsg(db));
2007       sqlite3_finalize(pStmt);
2008       sqlite3_result_error(context, zMsg, -1);
2009       sqlite3_free(zMsg);
2010       return;
2011     }
2012     if( !sqlite3_stmt_readonly(pStmt) ){
2013       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2014       sqlite3_finalize(pStmt);
2015       sqlite3_result_error(context, zMsg, -1);
2016       sqlite3_free(zMsg);
2017       return;
2018     }
2019     nCol = sqlite3_column_count(pStmt);
2020     z = sqlite3_sql(pStmt);
2021     if( z ){
2022       n = (int)strlen(z);
2023       hash_step_vformat(&cx,"S%d:",n);
2024       SHA3Update(&cx,(unsigned char*)z,n);
2025     }
2026 
2027     /* Compute a hash over the result of the query */
2028     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2029       SHA3Update(&cx,(const unsigned char*)"R",1);
2030       for(i=0; i<nCol; i++){
2031         switch( sqlite3_column_type(pStmt,i) ){
2032           case SQLITE_NULL: {
2033             SHA3Update(&cx, (const unsigned char*)"N",1);
2034             break;
2035           }
2036           case SQLITE_INTEGER: {
2037             sqlite3_uint64 u;
2038             int j;
2039             unsigned char x[9];
2040             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2041             memcpy(&u, &v, 8);
2042             for(j=8; j>=1; j--){
2043               x[j] = u & 0xff;
2044               u >>= 8;
2045             }
2046             x[0] = 'I';
2047             SHA3Update(&cx, x, 9);
2048             break;
2049           }
2050           case SQLITE_FLOAT: {
2051             sqlite3_uint64 u;
2052             int j;
2053             unsigned char x[9];
2054             double r = sqlite3_column_double(pStmt,i);
2055             memcpy(&u, &r, 8);
2056             for(j=8; j>=1; j--){
2057               x[j] = u & 0xff;
2058               u >>= 8;
2059             }
2060             x[0] = 'F';
2061             SHA3Update(&cx,x,9);
2062             break;
2063           }
2064           case SQLITE_TEXT: {
2065             int n2 = sqlite3_column_bytes(pStmt, i);
2066             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2067             hash_step_vformat(&cx,"T%d:",n2);
2068             SHA3Update(&cx, z2, n2);
2069             break;
2070           }
2071           case SQLITE_BLOB: {
2072             int n2 = sqlite3_column_bytes(pStmt, i);
2073             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2074             hash_step_vformat(&cx,"B%d:",n2);
2075             SHA3Update(&cx, z2, n2);
2076             break;
2077           }
2078         }
2079       }
2080     }
2081     sqlite3_finalize(pStmt);
2082   }
2083   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2084 }
2085 
2086 
2087 #ifdef _WIN32
2088 
2089 #endif
sqlite3_shathree_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)2090 int sqlite3_shathree_init(
2091   sqlite3 *db,
2092   char **pzErrMsg,
2093   const sqlite3_api_routines *pApi
2094 ){
2095   int rc = SQLITE_OK;
2096   SQLITE_EXTENSION_INIT2(pApi);
2097   (void)pzErrMsg;  /* Unused parameter */
2098   rc = sqlite3_create_function(db, "sha3", 1,
2099                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2100                       0, sha3Func, 0, 0);
2101   if( rc==SQLITE_OK ){
2102     rc = sqlite3_create_function(db, "sha3", 2,
2103                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2104                       0, sha3Func, 0, 0);
2105   }
2106   if( rc==SQLITE_OK ){
2107     rc = sqlite3_create_function(db, "sha3_query", 1,
2108                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2109                       0, sha3QueryFunc, 0, 0);
2110   }
2111   if( rc==SQLITE_OK ){
2112     rc = sqlite3_create_function(db, "sha3_query", 2,
2113                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2114                       0, sha3QueryFunc, 0, 0);
2115   }
2116   return rc;
2117 }
2118 
2119 /************************* End ../ext/misc/shathree.c ********************/
2120 /************************* Begin ../ext/misc/fileio.c ******************/
2121 /*
2122 ** 2014-06-13
2123 **
2124 ** The author disclaims copyright to this source code.  In place of
2125 ** a legal notice, here is a blessing:
2126 **
2127 **    May you do good and not evil.
2128 **    May you find forgiveness for yourself and forgive others.
2129 **    May you share freely, never taking more than you give.
2130 **
2131 ******************************************************************************
2132 **
2133 ** This SQLite extension implements SQL functions readfile() and
2134 ** writefile(), and eponymous virtual type "fsdir".
2135 **
2136 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
2137 **
2138 **   If neither of the optional arguments is present, then this UDF
2139 **   function writes blob DATA to file FILE. If successful, the number
2140 **   of bytes written is returned. If an error occurs, NULL is returned.
2141 **
2142 **   If the first option argument - MODE - is present, then it must
2143 **   be passed an integer value that corresponds to a POSIX mode
2144 **   value (file type + permissions, as returned in the stat.st_mode
2145 **   field by the stat() system call). Three types of files may
2146 **   be written/created:
2147 **
2148 **     regular files:  (mode & 0170000)==0100000
2149 **     symbolic links: (mode & 0170000)==0120000
2150 **     directories:    (mode & 0170000)==0040000
2151 **
2152 **   For a directory, the DATA is ignored. For a symbolic link, it is
2153 **   interpreted as text and used as the target of the link. For a
2154 **   regular file, it is interpreted as a blob and written into the
2155 **   named file. Regardless of the type of file, its permissions are
2156 **   set to (mode & 0777) before returning.
2157 **
2158 **   If the optional MTIME argument is present, then it is interpreted
2159 **   as an integer - the number of seconds since the unix epoch. The
2160 **   modification-time of the target file is set to this value before
2161 **   returning.
2162 **
2163 **   If three or more arguments are passed to this function and an
2164 **   error is encountered, an exception is raised.
2165 **
2166 ** READFILE(FILE):
2167 **
2168 **   Read and return the contents of file FILE (type blob) from disk.
2169 **
2170 ** FSDIR:
2171 **
2172 **   Used as follows:
2173 **
2174 **     SELECT * FROM fsdir($path [, $dir]);
2175 **
2176 **   Parameter $path is an absolute or relative pathname. If the file that it
2177 **   refers to does not exist, it is an error. If the path refers to a regular
2178 **   file or symbolic link, it returns a single row. Or, if the path refers
2179 **   to a directory, it returns one row for the directory, and one row for each
2180 **   file within the hierarchy rooted at $path.
2181 **
2182 **   Each row has the following columns:
2183 **
2184 **     name:  Path to file or directory (text value).
2185 **     mode:  Value of stat.st_mode for directory entry (an integer).
2186 **     mtime: Value of stat.st_mtime for directory entry (an integer).
2187 **     data:  For a regular file, a blob containing the file data. For a
2188 **            symlink, a text value containing the text of the link. For a
2189 **            directory, NULL.
2190 **
2191 **   If a non-NULL value is specified for the optional $dir parameter and
2192 **   $path is a relative path, then $path is interpreted relative to $dir.
2193 **   And the paths returned in the "name" column of the table are also
2194 **   relative to directory $dir.
2195 */
2196 /* #include "sqlite3ext.h" */
2197 SQLITE_EXTENSION_INIT1
2198 #include <stdio.h>
2199 #include <string.h>
2200 #include <assert.h>
2201 
2202 #include <sys/types.h>
2203 #include <sys/stat.h>
2204 #include <fcntl.h>
2205 #if !defined(_WIN32) && !defined(WIN32)
2206 #  include <unistd.h>
2207 #  include <dirent.h>
2208 #  include <utime.h>
2209 #  include <sys/time.h>
2210 #else
2211 #  include "windows.h"
2212 #  include <io.h>
2213 #  include <direct.h>
2214 /* #  include "test_windirent.h" */
2215 #  define dirent DIRENT
2216 #  ifndef chmod
2217 #    define chmod _chmod
2218 #  endif
2219 #  ifndef stat
2220 #    define stat _stat
2221 #  endif
2222 #  define mkdir(path,mode) _mkdir(path)
2223 #  define lstat(path,buf) stat(path,buf)
2224 #endif
2225 #include <time.h>
2226 #include <errno.h>
2227 
2228 
2229 /*
2230 ** Structure of the fsdir() table-valued function
2231 */
2232                  /*    0    1    2     3    4           5             */
2233 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2234 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
2235 #define FSDIR_COLUMN_MODE     1     /* Access mode */
2236 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
2237 #define FSDIR_COLUMN_DATA     3     /* File content */
2238 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
2239 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
2240 
2241 
2242 /*
2243 ** Set the result stored by context ctx to a blob containing the
2244 ** contents of file zName.  Or, leave the result unchanged (NULL)
2245 ** if the file does not exist or is unreadable.
2246 **
2247 ** If the file exceeds the SQLite blob size limit, through an
2248 ** SQLITE_TOOBIG error.
2249 **
2250 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
2251 ** off of disk.
2252 */
readFileContents(sqlite3_context * ctx,const char * zName)2253 static void readFileContents(sqlite3_context *ctx, const char *zName){
2254   FILE *in;
2255   sqlite3_int64 nIn;
2256   void *pBuf;
2257   sqlite3 *db;
2258   int mxBlob;
2259 
2260   in = fopen(zName, "rb");
2261   if( in==0 ){
2262     /* File does not exist or is unreadable. Leave the result set to NULL. */
2263     return;
2264   }
2265   fseek(in, 0, SEEK_END);
2266   nIn = ftell(in);
2267   rewind(in);
2268   db = sqlite3_context_db_handle(ctx);
2269   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
2270   if( nIn>mxBlob ){
2271     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
2272     fclose(in);
2273     return;
2274   }
2275   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
2276   if( pBuf==0 ){
2277     sqlite3_result_error_nomem(ctx);
2278     fclose(in);
2279     return;
2280   }
2281   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
2282     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
2283   }else{
2284     sqlite3_result_error_code(ctx, SQLITE_IOERR);
2285     sqlite3_free(pBuf);
2286   }
2287   fclose(in);
2288 }
2289 
2290 /*
2291 ** Implementation of the "readfile(X)" SQL function.  The entire content
2292 ** of the file named X is read and returned as a BLOB.  NULL is returned
2293 ** if the file does not exist or is unreadable.
2294 */
readfileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)2295 static void readfileFunc(
2296   sqlite3_context *context,
2297   int argc,
2298   sqlite3_value **argv
2299 ){
2300   const char *zName;
2301   (void)(argc);  /* Unused parameter */
2302   zName = (const char*)sqlite3_value_text(argv[0]);
2303   if( zName==0 ) return;
2304   readFileContents(context, zName);
2305 }
2306 
2307 /*
2308 ** Set the error message contained in context ctx to the results of
2309 ** vprintf(zFmt, ...).
2310 */
ctxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)2311 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
2312   char *zMsg = 0;
2313   va_list ap;
2314   va_start(ap, zFmt);
2315   zMsg = sqlite3_vmprintf(zFmt, ap);
2316   sqlite3_result_error(ctx, zMsg, -1);
2317   sqlite3_free(zMsg);
2318   va_end(ap);
2319 }
2320 
2321 #if defined(_WIN32)
2322 /*
2323 ** This function is designed to convert a Win32 FILETIME structure into the
2324 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
2325 */
fileTimeToUnixTime(LPFILETIME pFileTime)2326 static sqlite3_uint64 fileTimeToUnixTime(
2327   LPFILETIME pFileTime
2328 ){
2329   SYSTEMTIME epochSystemTime;
2330   ULARGE_INTEGER epochIntervals;
2331   FILETIME epochFileTime;
2332   ULARGE_INTEGER fileIntervals;
2333 
2334   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
2335   epochSystemTime.wYear = 1970;
2336   epochSystemTime.wMonth = 1;
2337   epochSystemTime.wDay = 1;
2338   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2339   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2340   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2341 
2342   fileIntervals.LowPart = pFileTime->dwLowDateTime;
2343   fileIntervals.HighPart = pFileTime->dwHighDateTime;
2344 
2345   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2346 }
2347 
2348 /*
2349 ** This function attempts to normalize the time values found in the stat()
2350 ** buffer to UTC.  This is necessary on Win32, where the runtime library
2351 ** appears to return these values as local times.
2352 */
statTimesToUtc(const char * zPath,struct stat * pStatBuf)2353 static void statTimesToUtc(
2354   const char *zPath,
2355   struct stat *pStatBuf
2356 ){
2357   HANDLE hFindFile;
2358   WIN32_FIND_DATAW fd;
2359   LPWSTR zUnicodeName;
2360   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2361   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2362   if( zUnicodeName ){
2363     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
2364     hFindFile = FindFirstFileW(zUnicodeName, &fd);
2365     if( hFindFile!=NULL ){
2366       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2367       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2368       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2369       FindClose(hFindFile);
2370     }
2371     sqlite3_free(zUnicodeName);
2372   }
2373 }
2374 #endif
2375 
2376 /*
2377 ** This function is used in place of stat().  On Windows, special handling
2378 ** is required in order for the included time to be returned as UTC.  On all
2379 ** other systems, this function simply calls stat().
2380 */
fileStat(const char * zPath,struct stat * pStatBuf)2381 static int fileStat(
2382   const char *zPath,
2383   struct stat *pStatBuf
2384 ){
2385 #if defined(_WIN32)
2386   int rc = stat(zPath, pStatBuf);
2387   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2388   return rc;
2389 #else
2390   return stat(zPath, pStatBuf);
2391 #endif
2392 }
2393 
2394 /*
2395 ** This function is used in place of lstat().  On Windows, special handling
2396 ** is required in order for the included time to be returned as UTC.  On all
2397 ** other systems, this function simply calls lstat().
2398 */
fileLinkStat(const char * zPath,struct stat * pStatBuf)2399 static int fileLinkStat(
2400   const char *zPath,
2401   struct stat *pStatBuf
2402 ){
2403 #if defined(_WIN32)
2404   int rc = lstat(zPath, pStatBuf);
2405   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2406   return rc;
2407 #else
2408   return lstat(zPath, pStatBuf);
2409 #endif
2410 }
2411 
2412 /*
2413 ** Argument zFile is the name of a file that will be created and/or written
2414 ** by SQL function writefile(). This function ensures that the directory
2415 ** zFile will be written to exists, creating it if required. The permissions
2416 ** for any path components created by this function are set in accordance
2417 ** with the current umask.
2418 **
2419 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
2420 ** SQLITE_OK is returned if the directory is successfully created, or
2421 ** SQLITE_ERROR otherwise.
2422 */
makeDirectory(const char * zFile)2423 static int makeDirectory(
2424   const char *zFile
2425 ){
2426   char *zCopy = sqlite3_mprintf("%s", zFile);
2427   int rc = SQLITE_OK;
2428 
2429   if( zCopy==0 ){
2430     rc = SQLITE_NOMEM;
2431   }else{
2432     int nCopy = (int)strlen(zCopy);
2433     int i = 1;
2434 
2435     while( rc==SQLITE_OK ){
2436       struct stat sStat;
2437       int rc2;
2438 
2439       for(; zCopy[i]!='/' && i<nCopy; i++);
2440       if( i==nCopy ) break;
2441       zCopy[i] = '\0';
2442 
2443       rc2 = fileStat(zCopy, &sStat);
2444       if( rc2!=0 ){
2445         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
2446       }else{
2447         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
2448       }
2449       zCopy[i] = '/';
2450       i++;
2451     }
2452 
2453     sqlite3_free(zCopy);
2454   }
2455 
2456   return rc;
2457 }
2458 
2459 /*
2460 ** This function does the work for the writefile() UDF. Refer to
2461 ** header comments at the top of this file for details.
2462 */
writeFile(sqlite3_context * pCtx,const char * zFile,sqlite3_value * pData,mode_t mode,sqlite3_int64 mtime)2463 static int writeFile(
2464   sqlite3_context *pCtx,          /* Context to return bytes written in */
2465   const char *zFile,              /* File to write */
2466   sqlite3_value *pData,           /* Data to write */
2467   mode_t mode,                    /* MODE parameter passed to writefile() */
2468   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
2469 ){
2470 #if !defined(_WIN32) && !defined(WIN32)
2471   if( S_ISLNK(mode) ){
2472     const char *zTo = (const char*)sqlite3_value_text(pData);
2473     if( symlink(zTo, zFile)<0 ) return 1;
2474   }else
2475 #endif
2476   {
2477     if( S_ISDIR(mode) ){
2478       if( mkdir(zFile, mode) ){
2479         /* The mkdir() call to create the directory failed. This might not
2480         ** be an error though - if there is already a directory at the same
2481         ** path and either the permissions already match or can be changed
2482         ** to do so using chmod(), it is not an error.  */
2483         struct stat sStat;
2484         if( errno!=EEXIST
2485          || 0!=fileStat(zFile, &sStat)
2486          || !S_ISDIR(sStat.st_mode)
2487          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2488         ){
2489           return 1;
2490         }
2491       }
2492     }else{
2493       sqlite3_int64 nWrite = 0;
2494       const char *z;
2495       int rc = 0;
2496       FILE *out = fopen(zFile, "wb");
2497       if( out==0 ) return 1;
2498       z = (const char*)sqlite3_value_blob(pData);
2499       if( z ){
2500         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
2501         nWrite = sqlite3_value_bytes(pData);
2502         if( nWrite!=n ){
2503           rc = 1;
2504         }
2505       }
2506       fclose(out);
2507       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2508         rc = 1;
2509       }
2510       if( rc ) return 2;
2511       sqlite3_result_int64(pCtx, nWrite);
2512     }
2513   }
2514 
2515   if( mtime>=0 ){
2516 #if defined(_WIN32)
2517 #if !SQLITE_OS_WINRT
2518     /* Windows */
2519     FILETIME lastAccess;
2520     FILETIME lastWrite;
2521     SYSTEMTIME currentTime;
2522     LONGLONG intervals;
2523     HANDLE hFile;
2524     LPWSTR zUnicodeName;
2525     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2526 
2527     GetSystemTime(&currentTime);
2528     SystemTimeToFileTime(&currentTime, &lastAccess);
2529     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2530     lastWrite.dwLowDateTime = (DWORD)intervals;
2531     lastWrite.dwHighDateTime = intervals >> 32;
2532     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2533     if( zUnicodeName==0 ){
2534       return 1;
2535     }
2536     hFile = CreateFileW(
2537       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
2538       FILE_FLAG_BACKUP_SEMANTICS, NULL
2539     );
2540     sqlite3_free(zUnicodeName);
2541     if( hFile!=INVALID_HANDLE_VALUE ){
2542       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
2543       CloseHandle(hFile);
2544       return !bResult;
2545     }else{
2546       return 1;
2547     }
2548 #endif
2549 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
2550     /* Recent unix */
2551     struct timespec times[2];
2552     times[0].tv_nsec = times[1].tv_nsec = 0;
2553     times[0].tv_sec = time(0);
2554     times[1].tv_sec = mtime;
2555     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2556       return 1;
2557     }
2558 #else
2559     /* Legacy unix */
2560     struct timeval times[2];
2561     times[0].tv_usec = times[1].tv_usec = 0;
2562     times[0].tv_sec = time(0);
2563     times[1].tv_sec = mtime;
2564     if( utimes(zFile, times) ){
2565       return 1;
2566     }
2567 #endif
2568   }
2569 
2570   return 0;
2571 }
2572 
2573 /*
2574 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
2575 ** Refer to header comments at the top of this file for details.
2576 */
writefileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)2577 static void writefileFunc(
2578   sqlite3_context *context,
2579   int argc,
2580   sqlite3_value **argv
2581 ){
2582   const char *zFile;
2583   mode_t mode = 0;
2584   int res;
2585   sqlite3_int64 mtime = -1;
2586 
2587   if( argc<2 || argc>4 ){
2588     sqlite3_result_error(context,
2589         "wrong number of arguments to function writefile()", -1
2590     );
2591     return;
2592   }
2593 
2594   zFile = (const char*)sqlite3_value_text(argv[0]);
2595   if( zFile==0 ) return;
2596   if( argc>=3 ){
2597     mode = (mode_t)sqlite3_value_int(argv[2]);
2598   }
2599   if( argc==4 ){
2600     mtime = sqlite3_value_int64(argv[3]);
2601   }
2602 
2603   res = writeFile(context, zFile, argv[1], mode, mtime);
2604   if( res==1 && errno==ENOENT ){
2605     if( makeDirectory(zFile)==SQLITE_OK ){
2606       res = writeFile(context, zFile, argv[1], mode, mtime);
2607     }
2608   }
2609 
2610   if( argc>2 && res!=0 ){
2611     if( S_ISLNK(mode) ){
2612       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
2613     }else if( S_ISDIR(mode) ){
2614       ctxErrorMsg(context, "failed to create directory: %s", zFile);
2615     }else{
2616       ctxErrorMsg(context, "failed to write file: %s", zFile);
2617     }
2618   }
2619 }
2620 
2621 /*
2622 ** SQL function:   lsmode(MODE)
2623 **
2624 ** Given a numberic st_mode from stat(), convert it into a human-readable
2625 ** text string in the style of "ls -l".
2626 */
lsModeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)2627 static void lsModeFunc(
2628   sqlite3_context *context,
2629   int argc,
2630   sqlite3_value **argv
2631 ){
2632   int i;
2633   int iMode = sqlite3_value_int(argv[0]);
2634   char z[16];
2635   (void)argc;
2636   if( S_ISLNK(iMode) ){
2637     z[0] = 'l';
2638   }else if( S_ISREG(iMode) ){
2639     z[0] = '-';
2640   }else if( S_ISDIR(iMode) ){
2641     z[0] = 'd';
2642   }else{
2643     z[0] = '?';
2644   }
2645   for(i=0; i<3; i++){
2646     int m = (iMode >> ((2-i)*3));
2647     char *a = &z[1 + i*3];
2648     a[0] = (m & 0x4) ? 'r' : '-';
2649     a[1] = (m & 0x2) ? 'w' : '-';
2650     a[2] = (m & 0x1) ? 'x' : '-';
2651   }
2652   z[10] = '\0';
2653   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2654 }
2655 
2656 #ifndef SQLITE_OMIT_VIRTUALTABLE
2657 
2658 /*
2659 ** Cursor type for recursively iterating through a directory structure.
2660 */
2661 typedef struct fsdir_cursor fsdir_cursor;
2662 typedef struct FsdirLevel FsdirLevel;
2663 
2664 struct FsdirLevel {
2665   DIR *pDir;                 /* From opendir() */
2666   char *zDir;                /* Name of directory (nul-terminated) */
2667 };
2668 
2669 struct fsdir_cursor {
2670   sqlite3_vtab_cursor base;  /* Base class - must be first */
2671 
2672   int nLvl;                  /* Number of entries in aLvl[] array */
2673   int iLvl;                  /* Index of current entry */
2674   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
2675 
2676   const char *zBase;
2677   int nBase;
2678 
2679   struct stat sStat;         /* Current lstat() results */
2680   char *zPath;               /* Path to current entry */
2681   sqlite3_int64 iRowid;      /* Current rowid */
2682 };
2683 
2684 typedef struct fsdir_tab fsdir_tab;
2685 struct fsdir_tab {
2686   sqlite3_vtab base;         /* Base class - must be first */
2687 };
2688 
2689 /*
2690 ** Construct a new fsdir virtual table object.
2691 */
fsdirConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)2692 static int fsdirConnect(
2693   sqlite3 *db,
2694   void *pAux,
2695   int argc, const char *const*argv,
2696   sqlite3_vtab **ppVtab,
2697   char **pzErr
2698 ){
2699   fsdir_tab *pNew = 0;
2700   int rc;
2701   (void)pAux;
2702   (void)argc;
2703   (void)argv;
2704   (void)pzErr;
2705   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
2706   if( rc==SQLITE_OK ){
2707     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
2708     if( pNew==0 ) return SQLITE_NOMEM;
2709     memset(pNew, 0, sizeof(*pNew));
2710     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
2711   }
2712   *ppVtab = (sqlite3_vtab*)pNew;
2713   return rc;
2714 }
2715 
2716 /*
2717 ** This method is the destructor for fsdir vtab objects.
2718 */
fsdirDisconnect(sqlite3_vtab * pVtab)2719 static int fsdirDisconnect(sqlite3_vtab *pVtab){
2720   sqlite3_free(pVtab);
2721   return SQLITE_OK;
2722 }
2723 
2724 /*
2725 ** Constructor for a new fsdir_cursor object.
2726 */
fsdirOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)2727 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2728   fsdir_cursor *pCur;
2729   (void)p;
2730   pCur = sqlite3_malloc( sizeof(*pCur) );
2731   if( pCur==0 ) return SQLITE_NOMEM;
2732   memset(pCur, 0, sizeof(*pCur));
2733   pCur->iLvl = -1;
2734   *ppCursor = &pCur->base;
2735   return SQLITE_OK;
2736 }
2737 
2738 /*
2739 ** Reset a cursor back to the state it was in when first returned
2740 ** by fsdirOpen().
2741 */
fsdirResetCursor(fsdir_cursor * pCur)2742 static void fsdirResetCursor(fsdir_cursor *pCur){
2743   int i;
2744   for(i=0; i<=pCur->iLvl; i++){
2745     FsdirLevel *pLvl = &pCur->aLvl[i];
2746     if( pLvl->pDir ) closedir(pLvl->pDir);
2747     sqlite3_free(pLvl->zDir);
2748   }
2749   sqlite3_free(pCur->zPath);
2750   sqlite3_free(pCur->aLvl);
2751   pCur->aLvl = 0;
2752   pCur->zPath = 0;
2753   pCur->zBase = 0;
2754   pCur->nBase = 0;
2755   pCur->nLvl = 0;
2756   pCur->iLvl = -1;
2757   pCur->iRowid = 1;
2758 }
2759 
2760 /*
2761 ** Destructor for an fsdir_cursor.
2762 */
fsdirClose(sqlite3_vtab_cursor * cur)2763 static int fsdirClose(sqlite3_vtab_cursor *cur){
2764   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2765 
2766   fsdirResetCursor(pCur);
2767   sqlite3_free(pCur);
2768   return SQLITE_OK;
2769 }
2770 
2771 /*
2772 ** Set the error message for the virtual table associated with cursor
2773 ** pCur to the results of vprintf(zFmt, ...).
2774 */
fsdirSetErrmsg(fsdir_cursor * pCur,const char * zFmt,...)2775 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
2776   va_list ap;
2777   va_start(ap, zFmt);
2778   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
2779   va_end(ap);
2780 }
2781 
2782 
2783 /*
2784 ** Advance an fsdir_cursor to its next row of output.
2785 */
fsdirNext(sqlite3_vtab_cursor * cur)2786 static int fsdirNext(sqlite3_vtab_cursor *cur){
2787   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2788   mode_t m = pCur->sStat.st_mode;
2789 
2790   pCur->iRowid++;
2791   if( S_ISDIR(m) ){
2792     /* Descend into this directory */
2793     int iNew = pCur->iLvl + 1;
2794     FsdirLevel *pLvl;
2795     if( iNew>=pCur->nLvl ){
2796       int nNew = iNew+1;
2797       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
2798       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
2799       if( aNew==0 ) return SQLITE_NOMEM;
2800       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
2801       pCur->aLvl = aNew;
2802       pCur->nLvl = nNew;
2803     }
2804     pCur->iLvl = iNew;
2805     pLvl = &pCur->aLvl[iNew];
2806 
2807     pLvl->zDir = pCur->zPath;
2808     pCur->zPath = 0;
2809     pLvl->pDir = opendir(pLvl->zDir);
2810     if( pLvl->pDir==0 ){
2811       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
2812       return SQLITE_ERROR;
2813     }
2814   }
2815 
2816   while( pCur->iLvl>=0 ){
2817     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
2818     struct dirent *pEntry = readdir(pLvl->pDir);
2819     if( pEntry ){
2820       if( pEntry->d_name[0]=='.' ){
2821        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
2822        if( pEntry->d_name[1]=='\0' ) continue;
2823       }
2824       sqlite3_free(pCur->zPath);
2825       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
2826       if( pCur->zPath==0 ) return SQLITE_NOMEM;
2827       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2828         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2829         return SQLITE_ERROR;
2830       }
2831       return SQLITE_OK;
2832     }
2833     closedir(pLvl->pDir);
2834     sqlite3_free(pLvl->zDir);
2835     pLvl->pDir = 0;
2836     pLvl->zDir = 0;
2837     pCur->iLvl--;
2838   }
2839 
2840   /* EOF */
2841   sqlite3_free(pCur->zPath);
2842   pCur->zPath = 0;
2843   return SQLITE_OK;
2844 }
2845 
2846 /*
2847 ** Return values of columns for the row at which the series_cursor
2848 ** is currently pointing.
2849 */
fsdirColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)2850 static int fsdirColumn(
2851   sqlite3_vtab_cursor *cur,   /* The cursor */
2852   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
2853   int i                       /* Which column to return */
2854 ){
2855   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2856   switch( i ){
2857     case FSDIR_COLUMN_NAME: {
2858       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
2859       break;
2860     }
2861 
2862     case FSDIR_COLUMN_MODE:
2863       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
2864       break;
2865 
2866     case FSDIR_COLUMN_MTIME:
2867       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
2868       break;
2869 
2870     case FSDIR_COLUMN_DATA: {
2871       mode_t m = pCur->sStat.st_mode;
2872       if( S_ISDIR(m) ){
2873         sqlite3_result_null(ctx);
2874 #if !defined(_WIN32) && !defined(WIN32)
2875       }else if( S_ISLNK(m) ){
2876         char aStatic[64];
2877         char *aBuf = aStatic;
2878         sqlite3_int64 nBuf = 64;
2879         int n;
2880 
2881         while( 1 ){
2882           n = readlink(pCur->zPath, aBuf, nBuf);
2883           if( n<nBuf ) break;
2884           if( aBuf!=aStatic ) sqlite3_free(aBuf);
2885           nBuf = nBuf*2;
2886           aBuf = sqlite3_malloc64(nBuf);
2887           if( aBuf==0 ){
2888             sqlite3_result_error_nomem(ctx);
2889             return SQLITE_NOMEM;
2890           }
2891         }
2892 
2893         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
2894         if( aBuf!=aStatic ) sqlite3_free(aBuf);
2895 #endif
2896       }else{
2897         readFileContents(ctx, pCur->zPath);
2898       }
2899     }
2900     case FSDIR_COLUMN_PATH:
2901     default: {
2902       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
2903       ** always return their values as NULL */
2904       break;
2905     }
2906   }
2907   return SQLITE_OK;
2908 }
2909 
2910 /*
2911 ** Return the rowid for the current row. In this implementation, the
2912 ** first row returned is assigned rowid value 1, and each subsequent
2913 ** row a value 1 more than that of the previous.
2914 */
fsdirRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)2915 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2916   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2917   *pRowid = pCur->iRowid;
2918   return SQLITE_OK;
2919 }
2920 
2921 /*
2922 ** Return TRUE if the cursor has been moved off of the last
2923 ** row of output.
2924 */
fsdirEof(sqlite3_vtab_cursor * cur)2925 static int fsdirEof(sqlite3_vtab_cursor *cur){
2926   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2927   return (pCur->zPath==0);
2928 }
2929 
2930 /*
2931 ** xFilter callback.
2932 **
2933 ** idxNum==1   PATH parameter only
2934 ** idxNum==2   Both PATH and DIR supplied
2935 */
fsdirFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)2936 static int fsdirFilter(
2937   sqlite3_vtab_cursor *cur,
2938   int idxNum, const char *idxStr,
2939   int argc, sqlite3_value **argv
2940 ){
2941   const char *zDir = 0;
2942   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2943   (void)idxStr;
2944   fsdirResetCursor(pCur);
2945 
2946   if( idxNum==0 ){
2947     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
2948     return SQLITE_ERROR;
2949   }
2950 
2951   assert( argc==idxNum && (argc==1 || argc==2) );
2952   zDir = (const char*)sqlite3_value_text(argv[0]);
2953   if( zDir==0 ){
2954     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
2955     return SQLITE_ERROR;
2956   }
2957   if( argc==2 ){
2958     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
2959   }
2960   if( pCur->zBase ){
2961     pCur->nBase = (int)strlen(pCur->zBase)+1;
2962     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
2963   }else{
2964     pCur->zPath = sqlite3_mprintf("%s", zDir);
2965   }
2966 
2967   if( pCur->zPath==0 ){
2968     return SQLITE_NOMEM;
2969   }
2970   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2971     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2972     return SQLITE_ERROR;
2973   }
2974 
2975   return SQLITE_OK;
2976 }
2977 
2978 /*
2979 ** SQLite will invoke this method one or more times while planning a query
2980 ** that uses the generate_series virtual table.  This routine needs to create
2981 ** a query plan for each invocation and compute an estimated cost for that
2982 ** plan.
2983 **
2984 ** In this implementation idxNum is used to represent the
2985 ** query plan.  idxStr is unused.
2986 **
2987 ** The query plan is represented by values of idxNum:
2988 **
2989 **  (1)  The path value is supplied by argv[0]
2990 **  (2)  Path is in argv[0] and dir is in argv[1]
2991 */
fsdirBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)2992 static int fsdirBestIndex(
2993   sqlite3_vtab *tab,
2994   sqlite3_index_info *pIdxInfo
2995 ){
2996   int i;                 /* Loop over constraints */
2997   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
2998   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
2999   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
3000   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
3001   const struct sqlite3_index_constraint *pConstraint;
3002 
3003   (void)tab;
3004   pConstraint = pIdxInfo->aConstraint;
3005   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3006     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3007     switch( pConstraint->iColumn ){
3008       case FSDIR_COLUMN_PATH: {
3009         if( pConstraint->usable ){
3010           idxPath = i;
3011           seenPath = 0;
3012         }else if( idxPath<0 ){
3013           seenPath = 1;
3014         }
3015         break;
3016       }
3017       case FSDIR_COLUMN_DIR: {
3018         if( pConstraint->usable ){
3019           idxDir = i;
3020           seenDir = 0;
3021         }else if( idxDir<0 ){
3022           seenDir = 1;
3023         }
3024         break;
3025       }
3026     }
3027   }
3028   if( seenPath || seenDir ){
3029     /* If input parameters are unusable, disallow this plan */
3030     return SQLITE_CONSTRAINT;
3031   }
3032 
3033   if( idxPath<0 ){
3034     pIdxInfo->idxNum = 0;
3035     /* The pIdxInfo->estimatedCost should have been initialized to a huge
3036     ** number.  Leave it unchanged. */
3037     pIdxInfo->estimatedRows = 0x7fffffff;
3038   }else{
3039     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
3040     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
3041     if( idxDir>=0 ){
3042       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
3043       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
3044       pIdxInfo->idxNum = 2;
3045       pIdxInfo->estimatedCost = 10.0;
3046     }else{
3047       pIdxInfo->idxNum = 1;
3048       pIdxInfo->estimatedCost = 100.0;
3049     }
3050   }
3051 
3052   return SQLITE_OK;
3053 }
3054 
3055 /*
3056 ** Register the "fsdir" virtual table.
3057 */
fsdirRegister(sqlite3 * db)3058 static int fsdirRegister(sqlite3 *db){
3059   static sqlite3_module fsdirModule = {
3060     0,                         /* iVersion */
3061     0,                         /* xCreate */
3062     fsdirConnect,              /* xConnect */
3063     fsdirBestIndex,            /* xBestIndex */
3064     fsdirDisconnect,           /* xDisconnect */
3065     0,                         /* xDestroy */
3066     fsdirOpen,                 /* xOpen - open a cursor */
3067     fsdirClose,                /* xClose - close a cursor */
3068     fsdirFilter,               /* xFilter - configure scan constraints */
3069     fsdirNext,                 /* xNext - advance a cursor */
3070     fsdirEof,                  /* xEof - check for end of scan */
3071     fsdirColumn,               /* xColumn - read data */
3072     fsdirRowid,                /* xRowid - read data */
3073     0,                         /* xUpdate */
3074     0,                         /* xBegin */
3075     0,                         /* xSync */
3076     0,                         /* xCommit */
3077     0,                         /* xRollback */
3078     0,                         /* xFindMethod */
3079     0,                         /* xRename */
3080     0,                         /* xSavepoint */
3081     0,                         /* xRelease */
3082     0,                         /* xRollbackTo */
3083     0,                         /* xShadowName */
3084   };
3085 
3086   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
3087   return rc;
3088 }
3089 #else         /* SQLITE_OMIT_VIRTUALTABLE */
3090 # define fsdirRegister(x) SQLITE_OK
3091 #endif
3092 
3093 #ifdef _WIN32
3094 
3095 #endif
sqlite3_fileio_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3096 int sqlite3_fileio_init(
3097   sqlite3 *db,
3098   char **pzErrMsg,
3099   const sqlite3_api_routines *pApi
3100 ){
3101   int rc = SQLITE_OK;
3102   SQLITE_EXTENSION_INIT2(pApi);
3103   (void)pzErrMsg;  /* Unused parameter */
3104   rc = sqlite3_create_function(db, "readfile", 1,
3105                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3106                                readfileFunc, 0, 0);
3107   if( rc==SQLITE_OK ){
3108     rc = sqlite3_create_function(db, "writefile", -1,
3109                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3110                                  writefileFunc, 0, 0);
3111   }
3112   if( rc==SQLITE_OK ){
3113     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
3114                                  lsModeFunc, 0, 0);
3115   }
3116   if( rc==SQLITE_OK ){
3117     rc = fsdirRegister(db);
3118   }
3119   return rc;
3120 }
3121 
3122 /************************* End ../ext/misc/fileio.c ********************/
3123 /************************* Begin ../ext/misc/completion.c ******************/
3124 /*
3125 ** 2017-07-10
3126 **
3127 ** The author disclaims copyright to this source code.  In place of
3128 ** a legal notice, here is a blessing:
3129 **
3130 **    May you do good and not evil.
3131 **    May you find forgiveness for yourself and forgive others.
3132 **    May you share freely, never taking more than you give.
3133 **
3134 *************************************************************************
3135 **
3136 ** This file implements an eponymous virtual table that returns suggested
3137 ** completions for a partial SQL input.
3138 **
3139 ** Suggested usage:
3140 **
3141 **     SELECT DISTINCT candidate COLLATE nocase
3142 **       FROM completion($prefix,$wholeline)
3143 **      ORDER BY 1;
3144 **
3145 ** The two query parameters are optional.  $prefix is the text of the
3146 ** current word being typed and that is to be completed.  $wholeline is
3147 ** the complete input line, used for context.
3148 **
3149 ** The raw completion() table might return the same candidate multiple
3150 ** times, for example if the same column name is used to two or more
3151 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
3152 ** the DISTINCT and ORDER BY are recommended.
3153 **
3154 ** This virtual table operates at the speed of human typing, and so there
3155 ** is no attempt to make it fast.  Even a slow implementation will be much
3156 ** faster than any human can type.
3157 **
3158 */
3159 /* #include "sqlite3ext.h" */
3160 SQLITE_EXTENSION_INIT1
3161 #include <assert.h>
3162 #include <string.h>
3163 #include <ctype.h>
3164 
3165 #ifndef SQLITE_OMIT_VIRTUALTABLE
3166 
3167 /* completion_vtab is a subclass of sqlite3_vtab which will
3168 ** serve as the underlying representation of a completion virtual table
3169 */
3170 typedef struct completion_vtab completion_vtab;
3171 struct completion_vtab {
3172   sqlite3_vtab base;  /* Base class - must be first */
3173   sqlite3 *db;        /* Database connection for this completion vtab */
3174 };
3175 
3176 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
3177 ** serve as the underlying representation of a cursor that scans
3178 ** over rows of the result
3179 */
3180 typedef struct completion_cursor completion_cursor;
3181 struct completion_cursor {
3182   sqlite3_vtab_cursor base;  /* Base class - must be first */
3183   sqlite3 *db;               /* Database connection for this cursor */
3184   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
3185   char *zPrefix;             /* The prefix for the word we want to complete */
3186   char *zLine;               /* The whole that we want to complete */
3187   const char *zCurrentRow;   /* Current output row */
3188   int szRow;                 /* Length of the zCurrentRow string */
3189   sqlite3_stmt *pStmt;       /* Current statement */
3190   sqlite3_int64 iRowid;      /* The rowid */
3191   int ePhase;                /* Current phase */
3192   int j;                     /* inter-phase counter */
3193 };
3194 
3195 /* Values for ePhase:
3196 */
3197 #define COMPLETION_FIRST_PHASE   1
3198 #define COMPLETION_KEYWORDS      1
3199 #define COMPLETION_PRAGMAS       2
3200 #define COMPLETION_FUNCTIONS     3
3201 #define COMPLETION_COLLATIONS    4
3202 #define COMPLETION_INDEXES       5
3203 #define COMPLETION_TRIGGERS      6
3204 #define COMPLETION_DATABASES     7
3205 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
3206 #define COMPLETION_COLUMNS       9
3207 #define COMPLETION_MODULES       10
3208 #define COMPLETION_EOF           11
3209 
3210 /*
3211 ** The completionConnect() method is invoked to create a new
3212 ** completion_vtab that describes the completion virtual table.
3213 **
3214 ** Think of this routine as the constructor for completion_vtab objects.
3215 **
3216 ** All this routine needs to do is:
3217 **
3218 **    (1) Allocate the completion_vtab object and initialize all fields.
3219 **
3220 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3221 **        result set of queries against completion will look like.
3222 */
completionConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)3223 static int completionConnect(
3224   sqlite3 *db,
3225   void *pAux,
3226   int argc, const char *const*argv,
3227   sqlite3_vtab **ppVtab,
3228   char **pzErr
3229 ){
3230   completion_vtab *pNew;
3231   int rc;
3232 
3233   (void)(pAux);    /* Unused parameter */
3234   (void)(argc);    /* Unused parameter */
3235   (void)(argv);    /* Unused parameter */
3236   (void)(pzErr);   /* Unused parameter */
3237 
3238 /* Column numbers */
3239 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
3240 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
3241 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
3242 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
3243 
3244   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
3245   rc = sqlite3_declare_vtab(db,
3246       "CREATE TABLE x("
3247       "  candidate TEXT,"
3248       "  prefix TEXT HIDDEN,"
3249       "  wholeline TEXT HIDDEN,"
3250       "  phase INT HIDDEN"        /* Used for debugging only */
3251       ")");
3252   if( rc==SQLITE_OK ){
3253     pNew = sqlite3_malloc( sizeof(*pNew) );
3254     *ppVtab = (sqlite3_vtab*)pNew;
3255     if( pNew==0 ) return SQLITE_NOMEM;
3256     memset(pNew, 0, sizeof(*pNew));
3257     pNew->db = db;
3258   }
3259   return rc;
3260 }
3261 
3262 /*
3263 ** This method is the destructor for completion_cursor objects.
3264 */
completionDisconnect(sqlite3_vtab * pVtab)3265 static int completionDisconnect(sqlite3_vtab *pVtab){
3266   sqlite3_free(pVtab);
3267   return SQLITE_OK;
3268 }
3269 
3270 /*
3271 ** Constructor for a new completion_cursor object.
3272 */
completionOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)3273 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
3274   completion_cursor *pCur;
3275   pCur = sqlite3_malloc( sizeof(*pCur) );
3276   if( pCur==0 ) return SQLITE_NOMEM;
3277   memset(pCur, 0, sizeof(*pCur));
3278   pCur->db = ((completion_vtab*)p)->db;
3279   *ppCursor = &pCur->base;
3280   return SQLITE_OK;
3281 }
3282 
3283 /*
3284 ** Reset the completion_cursor.
3285 */
completionCursorReset(completion_cursor * pCur)3286 static void completionCursorReset(completion_cursor *pCur){
3287   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
3288   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
3289   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
3290   pCur->j = 0;
3291 }
3292 
3293 /*
3294 ** Destructor for a completion_cursor.
3295 */
completionClose(sqlite3_vtab_cursor * cur)3296 static int completionClose(sqlite3_vtab_cursor *cur){
3297   completionCursorReset((completion_cursor*)cur);
3298   sqlite3_free(cur);
3299   return SQLITE_OK;
3300 }
3301 
3302 /*
3303 ** Advance a completion_cursor to its next row of output.
3304 **
3305 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
3306 ** record the current state of the scan.  This routine sets ->zCurrentRow
3307 ** to the current row of output and then returns.  If no more rows remain,
3308 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
3309 ** table that has reached the end of its scan.
3310 **
3311 ** The current implementation just lists potential identifiers and
3312 ** keywords and filters them by zPrefix.  Future enhancements should
3313 ** take zLine into account to try to restrict the set of identifiers and
3314 ** keywords based on what would be legal at the current point of input.
3315 */
completionNext(sqlite3_vtab_cursor * cur)3316 static int completionNext(sqlite3_vtab_cursor *cur){
3317   completion_cursor *pCur = (completion_cursor*)cur;
3318   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
3319   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
3320   pCur->iRowid++;
3321   while( pCur->ePhase!=COMPLETION_EOF ){
3322     switch( pCur->ePhase ){
3323       case COMPLETION_KEYWORDS: {
3324         if( pCur->j >= sqlite3_keyword_count() ){
3325           pCur->zCurrentRow = 0;
3326           pCur->ePhase = COMPLETION_DATABASES;
3327         }else{
3328           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
3329         }
3330         iCol = -1;
3331         break;
3332       }
3333       case COMPLETION_DATABASES: {
3334         if( pCur->pStmt==0 ){
3335           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
3336                              &pCur->pStmt, 0);
3337         }
3338         iCol = 1;
3339         eNextPhase = COMPLETION_TABLES;
3340         break;
3341       }
3342       case COMPLETION_TABLES: {
3343         if( pCur->pStmt==0 ){
3344           sqlite3_stmt *pS2;
3345           char *zSql = 0;
3346           const char *zSep = "";
3347           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3348           while( sqlite3_step(pS2)==SQLITE_ROW ){
3349             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3350             zSql = sqlite3_mprintf(
3351                "%z%s"
3352                "SELECT name FROM \"%w\".sqlite_schema",
3353                zSql, zSep, zDb
3354             );
3355             if( zSql==0 ) return SQLITE_NOMEM;
3356             zSep = " UNION ";
3357           }
3358           sqlite3_finalize(pS2);
3359           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3360           sqlite3_free(zSql);
3361         }
3362         iCol = 0;
3363         eNextPhase = COMPLETION_COLUMNS;
3364         break;
3365       }
3366       case COMPLETION_COLUMNS: {
3367         if( pCur->pStmt==0 ){
3368           sqlite3_stmt *pS2;
3369           char *zSql = 0;
3370           const char *zSep = "";
3371           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3372           while( sqlite3_step(pS2)==SQLITE_ROW ){
3373             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3374             zSql = sqlite3_mprintf(
3375                "%z%s"
3376                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
3377                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
3378                " WHERE sm.type='table'",
3379                zSql, zSep, zDb, zDb
3380             );
3381             if( zSql==0 ) return SQLITE_NOMEM;
3382             zSep = " UNION ";
3383           }
3384           sqlite3_finalize(pS2);
3385           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3386           sqlite3_free(zSql);
3387         }
3388         iCol = 0;
3389         eNextPhase = COMPLETION_EOF;
3390         break;
3391       }
3392     }
3393     if( iCol<0 ){
3394       /* This case is when the phase presets zCurrentRow */
3395       if( pCur->zCurrentRow==0 ) continue;
3396     }else{
3397       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
3398         /* Extract the next row of content */
3399         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
3400         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
3401       }else{
3402         /* When all rows are finished, advance to the next phase */
3403         sqlite3_finalize(pCur->pStmt);
3404         pCur->pStmt = 0;
3405         pCur->ePhase = eNextPhase;
3406         continue;
3407       }
3408     }
3409     if( pCur->nPrefix==0 ) break;
3410     if( pCur->nPrefix<=pCur->szRow
3411      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
3412     ){
3413       break;
3414     }
3415   }
3416 
3417   return SQLITE_OK;
3418 }
3419 
3420 /*
3421 ** Return values of columns for the row at which the completion_cursor
3422 ** is currently pointing.
3423 */
completionColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)3424 static int completionColumn(
3425   sqlite3_vtab_cursor *cur,   /* The cursor */
3426   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
3427   int i                       /* Which column to return */
3428 ){
3429   completion_cursor *pCur = (completion_cursor*)cur;
3430   switch( i ){
3431     case COMPLETION_COLUMN_CANDIDATE: {
3432       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
3433       break;
3434     }
3435     case COMPLETION_COLUMN_PREFIX: {
3436       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
3437       break;
3438     }
3439     case COMPLETION_COLUMN_WHOLELINE: {
3440       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
3441       break;
3442     }
3443     case COMPLETION_COLUMN_PHASE: {
3444       sqlite3_result_int(ctx, pCur->ePhase);
3445       break;
3446     }
3447   }
3448   return SQLITE_OK;
3449 }
3450 
3451 /*
3452 ** Return the rowid for the current row.  In this implementation, the
3453 ** rowid is the same as the output value.
3454 */
completionRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)3455 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3456   completion_cursor *pCur = (completion_cursor*)cur;
3457   *pRowid = pCur->iRowid;
3458   return SQLITE_OK;
3459 }
3460 
3461 /*
3462 ** Return TRUE if the cursor has been moved off of the last
3463 ** row of output.
3464 */
completionEof(sqlite3_vtab_cursor * cur)3465 static int completionEof(sqlite3_vtab_cursor *cur){
3466   completion_cursor *pCur = (completion_cursor*)cur;
3467   return pCur->ePhase >= COMPLETION_EOF;
3468 }
3469 
3470 /*
3471 ** This method is called to "rewind" the completion_cursor object back
3472 ** to the first row of output.  This method is always called at least
3473 ** once prior to any call to completionColumn() or completionRowid() or
3474 ** completionEof().
3475 */
completionFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)3476 static int completionFilter(
3477   sqlite3_vtab_cursor *pVtabCursor,
3478   int idxNum, const char *idxStr,
3479   int argc, sqlite3_value **argv
3480 ){
3481   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
3482   int iArg = 0;
3483   (void)(idxStr);   /* Unused parameter */
3484   (void)(argc);     /* Unused parameter */
3485   completionCursorReset(pCur);
3486   if( idxNum & 1 ){
3487     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
3488     if( pCur->nPrefix>0 ){
3489       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3490       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3491     }
3492     iArg = 1;
3493   }
3494   if( idxNum & 2 ){
3495     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
3496     if( pCur->nLine>0 ){
3497       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3498       if( pCur->zLine==0 ) return SQLITE_NOMEM;
3499     }
3500   }
3501   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
3502     int i = pCur->nLine;
3503     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
3504       i--;
3505     }
3506     pCur->nPrefix = pCur->nLine - i;
3507     if( pCur->nPrefix>0 ){
3508       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
3509       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3510     }
3511   }
3512   pCur->iRowid = 0;
3513   pCur->ePhase = COMPLETION_FIRST_PHASE;
3514   return completionNext(pVtabCursor);
3515 }
3516 
3517 /*
3518 ** SQLite will invoke this method one or more times while planning a query
3519 ** that uses the completion virtual table.  This routine needs to create
3520 ** a query plan for each invocation and compute an estimated cost for that
3521 ** plan.
3522 **
3523 ** There are two hidden parameters that act as arguments to the table-valued
3524 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
3525 ** is available and bit 1 is set if "wholeline" is available.
3526 */
completionBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)3527 static int completionBestIndex(
3528   sqlite3_vtab *tab,
3529   sqlite3_index_info *pIdxInfo
3530 ){
3531   int i;                 /* Loop over constraints */
3532   int idxNum = 0;        /* The query plan bitmask */
3533   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
3534   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
3535   int nArg = 0;          /* Number of arguments that completeFilter() expects */
3536   const struct sqlite3_index_constraint *pConstraint;
3537 
3538   (void)(tab);    /* Unused parameter */
3539   pConstraint = pIdxInfo->aConstraint;
3540   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3541     if( pConstraint->usable==0 ) continue;
3542     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3543     switch( pConstraint->iColumn ){
3544       case COMPLETION_COLUMN_PREFIX:
3545         prefixIdx = i;
3546         idxNum |= 1;
3547         break;
3548       case COMPLETION_COLUMN_WHOLELINE:
3549         wholelineIdx = i;
3550         idxNum |= 2;
3551         break;
3552     }
3553   }
3554   if( prefixIdx>=0 ){
3555     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
3556     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
3557   }
3558   if( wholelineIdx>=0 ){
3559     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
3560     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
3561   }
3562   pIdxInfo->idxNum = idxNum;
3563   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
3564   pIdxInfo->estimatedRows = 500 - 100*nArg;
3565   return SQLITE_OK;
3566 }
3567 
3568 /*
3569 ** This following structure defines all the methods for the
3570 ** completion virtual table.
3571 */
3572 static sqlite3_module completionModule = {
3573   0,                         /* iVersion */
3574   0,                         /* xCreate */
3575   completionConnect,         /* xConnect */
3576   completionBestIndex,       /* xBestIndex */
3577   completionDisconnect,      /* xDisconnect */
3578   0,                         /* xDestroy */
3579   completionOpen,            /* xOpen - open a cursor */
3580   completionClose,           /* xClose - close a cursor */
3581   completionFilter,          /* xFilter - configure scan constraints */
3582   completionNext,            /* xNext - advance a cursor */
3583   completionEof,             /* xEof - check for end of scan */
3584   completionColumn,          /* xColumn - read data */
3585   completionRowid,           /* xRowid - read data */
3586   0,                         /* xUpdate */
3587   0,                         /* xBegin */
3588   0,                         /* xSync */
3589   0,                         /* xCommit */
3590   0,                         /* xRollback */
3591   0,                         /* xFindMethod */
3592   0,                         /* xRename */
3593   0,                         /* xSavepoint */
3594   0,                         /* xRelease */
3595   0,                         /* xRollbackTo */
3596   0                          /* xShadowName */
3597 };
3598 
3599 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3600 
sqlite3CompletionVtabInit(sqlite3 * db)3601 int sqlite3CompletionVtabInit(sqlite3 *db){
3602   int rc = SQLITE_OK;
3603 #ifndef SQLITE_OMIT_VIRTUALTABLE
3604   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
3605 #endif
3606   return rc;
3607 }
3608 
3609 #ifdef _WIN32
3610 
3611 #endif
sqlite3_completion_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3612 int sqlite3_completion_init(
3613   sqlite3 *db,
3614   char **pzErrMsg,
3615   const sqlite3_api_routines *pApi
3616 ){
3617   int rc = SQLITE_OK;
3618   SQLITE_EXTENSION_INIT2(pApi);
3619   (void)(pzErrMsg);  /* Unused parameter */
3620 #ifndef SQLITE_OMIT_VIRTUALTABLE
3621   rc = sqlite3CompletionVtabInit(db);
3622 #endif
3623   return rc;
3624 }
3625 
3626 /************************* End ../ext/misc/completion.c ********************/
3627 /************************* Begin ../ext/misc/appendvfs.c ******************/
3628 /*
3629 ** 2017-10-20
3630 **
3631 ** The author disclaims copyright to this source code.  In place of
3632 ** a legal notice, here is a blessing:
3633 **
3634 **    May you do good and not evil.
3635 **    May you find forgiveness for yourself and forgive others.
3636 **    May you share freely, never taking more than you give.
3637 **
3638 ******************************************************************************
3639 **
3640 ** This file implements a VFS shim that allows an SQLite database to be
3641 ** appended onto the end of some other file, such as an executable.
3642 **
3643 ** A special record must appear at the end of the file that identifies the
3644 ** file as an appended database and provides the offset to the first page
3645 ** of the exposed content. (Or, it is the length of the content prefix.)
3646 ** For best performance page 1 should be located at a disk page boundary,
3647 ** though that is not required.
3648 **
3649 ** When opening a database using this VFS, the connection might treat
3650 ** the file as an ordinary SQLite database, or it might treat it as a
3651 ** database appended onto some other file.  The decision is made by
3652 ** applying the following rules in order:
3653 **
3654 **  (1)  An empty file is an ordinary database.
3655 **
3656 **  (2)  If the file ends with the appendvfs trailer string
3657 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
3658 **
3659 **  (3)  If the file begins with the standard SQLite prefix string
3660 **       "SQLite format 3", that file is an ordinary database.
3661 **
3662 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
3663 **       set, then a new database is appended to the already existing file.
3664 **
3665 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
3666 **
3667 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
3668 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
3669 ** This VFS will not read or write past the 1GiB mark.  This restriction
3670 ** might be lifted in future versions.  For now, if you need a larger
3671 ** database, then keep it in a separate file.
3672 **
3673 ** If the file being opened is a plain database (not an appended one), then
3674 ** this shim is a pass-through into the default underlying VFS. (rule 3)
3675 **/
3676 /* #include "sqlite3ext.h" */
3677 SQLITE_EXTENSION_INIT1
3678 #include <string.h>
3679 #include <assert.h>
3680 
3681 /* The append mark at the end of the database is:
3682 **
3683 **     Start-Of-SQLite3-NNNNNNNN
3684 **     123456789 123456789 12345
3685 **
3686 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
3687 ** the offset to page 1, and also the length of the prefix content.
3688 */
3689 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
3690 #define APND_MARK_PREFIX_SZ  17
3691 #define APND_MARK_FOS_SZ      8
3692 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
3693 
3694 /*
3695 ** Maximum size of the combined prefix + database + append-mark.  This
3696 ** must be less than 0x40000000 to avoid locking issues on Windows.
3697 */
3698 #define APND_MAX_SIZE  (0x40000000)
3699 
3700 /*
3701 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
3702 */
3703 #ifndef APND_ROUNDUP
3704 #define APND_ROUNDUP 4096
3705 #endif
3706 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
3707 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
3708 
3709 /*
3710 ** Forward declaration of objects used by this utility
3711 */
3712 typedef struct sqlite3_vfs ApndVfs;
3713 typedef struct ApndFile ApndFile;
3714 
3715 /* Access to a lower-level VFS that (might) implement dynamic loading,
3716 ** access to randomness, etc.
3717 */
3718 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
3719 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
3720 
3721 /* An open appendvfs file
3722 **
3723 ** An instance of this structure describes the appended database file.
3724 ** A separate sqlite3_file object is always appended. The appended
3725 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
3726 ** the entire file, including the prefix, the database, and the
3727 ** append-mark.
3728 **
3729 ** The structure of an AppendVFS database is like this:
3730 **
3731 **   +-------------+---------+----------+-------------+
3732 **   | prefix-file | padding | database | append-mark |
3733 **   +-------------+---------+----------+-------------+
3734 **                           ^          ^
3735 **                           |          |
3736 **                         iPgOne      iMark
3737 **
3738 **
3739 ** "prefix file" -  file onto which the database has been appended.
3740 ** "padding"     -  zero or more bytes inserted so that "database"
3741 **                  starts on an APND_ROUNDUP boundary
3742 ** "database"    -  The SQLite database file
3743 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
3744 **                  the offset from the start of prefix-file to the start
3745 **                  of "database".
3746 **
3747 ** The size of the database is iMark - iPgOne.
3748 **
3749 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
3750 ** of iPgOne stored as a big-ending 64-bit integer.
3751 **
3752 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
3753 ** Or, iMark is -1 to indicate that it has not yet been written.
3754 */
3755 struct ApndFile {
3756   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
3757   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
3758   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
3759   /* Always followed by another sqlite3_file that describes the whole file */
3760 };
3761 
3762 /*
3763 ** Methods for ApndFile
3764 */
3765 static int apndClose(sqlite3_file*);
3766 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
3767 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
3768 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
3769 static int apndSync(sqlite3_file*, int flags);
3770 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
3771 static int apndLock(sqlite3_file*, int);
3772 static int apndUnlock(sqlite3_file*, int);
3773 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
3774 static int apndFileControl(sqlite3_file*, int op, void *pArg);
3775 static int apndSectorSize(sqlite3_file*);
3776 static int apndDeviceCharacteristics(sqlite3_file*);
3777 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
3778 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
3779 static void apndShmBarrier(sqlite3_file*);
3780 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
3781 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
3782 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
3783 
3784 /*
3785 ** Methods for ApndVfs
3786 */
3787 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
3788 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
3789 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
3790 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
3791 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
3792 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
3793 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
3794 static void apndDlClose(sqlite3_vfs*, void*);
3795 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
3796 static int apndSleep(sqlite3_vfs*, int microseconds);
3797 static int apndCurrentTime(sqlite3_vfs*, double*);
3798 static int apndGetLastError(sqlite3_vfs*, int, char *);
3799 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
3800 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
3801 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
3802 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
3803 
3804 static sqlite3_vfs apnd_vfs = {
3805   3,                            /* iVersion (set when registered) */
3806   0,                            /* szOsFile (set when registered) */
3807   1024,                         /* mxPathname */
3808   0,                            /* pNext */
3809   "apndvfs",                    /* zName */
3810   0,                            /* pAppData (set when registered) */
3811   apndOpen,                     /* xOpen */
3812   apndDelete,                   /* xDelete */
3813   apndAccess,                   /* xAccess */
3814   apndFullPathname,             /* xFullPathname */
3815   apndDlOpen,                   /* xDlOpen */
3816   apndDlError,                  /* xDlError */
3817   apndDlSym,                    /* xDlSym */
3818   apndDlClose,                  /* xDlClose */
3819   apndRandomness,               /* xRandomness */
3820   apndSleep,                    /* xSleep */
3821   apndCurrentTime,              /* xCurrentTime */
3822   apndGetLastError,             /* xGetLastError */
3823   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
3824   apndSetSystemCall,            /* xSetSystemCall */
3825   apndGetSystemCall,            /* xGetSystemCall */
3826   apndNextSystemCall            /* xNextSystemCall */
3827 };
3828 
3829 static const sqlite3_io_methods apnd_io_methods = {
3830   3,                              /* iVersion */
3831   apndClose,                      /* xClose */
3832   apndRead,                       /* xRead */
3833   apndWrite,                      /* xWrite */
3834   apndTruncate,                   /* xTruncate */
3835   apndSync,                       /* xSync */
3836   apndFileSize,                   /* xFileSize */
3837   apndLock,                       /* xLock */
3838   apndUnlock,                     /* xUnlock */
3839   apndCheckReservedLock,          /* xCheckReservedLock */
3840   apndFileControl,                /* xFileControl */
3841   apndSectorSize,                 /* xSectorSize */
3842   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
3843   apndShmMap,                     /* xShmMap */
3844   apndShmLock,                    /* xShmLock */
3845   apndShmBarrier,                 /* xShmBarrier */
3846   apndShmUnmap,                   /* xShmUnmap */
3847   apndFetch,                      /* xFetch */
3848   apndUnfetch                     /* xUnfetch */
3849 };
3850 
3851 /*
3852 ** Close an apnd-file.
3853 */
apndClose(sqlite3_file * pFile)3854 static int apndClose(sqlite3_file *pFile){
3855   pFile = ORIGFILE(pFile);
3856   return pFile->pMethods->xClose(pFile);
3857 }
3858 
3859 /*
3860 ** Read data from an apnd-file.
3861 */
apndRead(sqlite3_file * pFile,void * zBuf,int iAmt,sqlite_int64 iOfst)3862 static int apndRead(
3863   sqlite3_file *pFile,
3864   void *zBuf,
3865   int iAmt,
3866   sqlite_int64 iOfst
3867 ){
3868   ApndFile *paf = (ApndFile *)pFile;
3869   pFile = ORIGFILE(pFile);
3870   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
3871 }
3872 
3873 /*
3874 ** Add the append-mark onto what should become the end of the file.
3875 *  If and only if this succeeds, internal ApndFile.iMark is updated.
3876 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
3877 */
apndWriteMark(ApndFile * paf,sqlite3_file * pFile,sqlite_int64 iWriteEnd)3878 static int apndWriteMark(
3879   ApndFile *paf,
3880   sqlite3_file *pFile,
3881   sqlite_int64 iWriteEnd
3882 ){
3883   sqlite_int64 iPgOne = paf->iPgOne;
3884   unsigned char a[APND_MARK_SIZE];
3885   int i = APND_MARK_FOS_SZ;
3886   int rc;
3887   assert(pFile == ORIGFILE(paf));
3888   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
3889   while( --i >= 0 ){
3890     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
3891     iPgOne >>= 8;
3892   }
3893   iWriteEnd += paf->iPgOne;
3894   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
3895                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
3896     paf->iMark = iWriteEnd;
3897   }
3898   return rc;
3899 }
3900 
3901 /*
3902 ** Write data to an apnd-file.
3903 */
apndWrite(sqlite3_file * pFile,const void * zBuf,int iAmt,sqlite_int64 iOfst)3904 static int apndWrite(
3905   sqlite3_file *pFile,
3906   const void *zBuf,
3907   int iAmt,
3908   sqlite_int64 iOfst
3909 ){
3910   ApndFile *paf = (ApndFile *)pFile;
3911   sqlite_int64 iWriteEnd = iOfst + iAmt;
3912   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
3913   pFile = ORIGFILE(pFile);
3914   /* If append-mark is absent or will be overwritten, write it. */
3915   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
3916     int rc = apndWriteMark(paf, pFile, iWriteEnd);
3917     if( SQLITE_OK!=rc ) return rc;
3918   }
3919   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
3920 }
3921 
3922 /*
3923 ** Truncate an apnd-file.
3924 */
apndTruncate(sqlite3_file * pFile,sqlite_int64 size)3925 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
3926   ApndFile *paf = (ApndFile *)pFile;
3927   pFile = ORIGFILE(pFile);
3928   /* The append mark goes out first so truncate failure does not lose it. */
3929   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
3930   /* Truncate underlying file just past append mark */
3931   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
3932 }
3933 
3934 /*
3935 ** Sync an apnd-file.
3936 */
apndSync(sqlite3_file * pFile,int flags)3937 static int apndSync(sqlite3_file *pFile, int flags){
3938   pFile = ORIGFILE(pFile);
3939   return pFile->pMethods->xSync(pFile, flags);
3940 }
3941 
3942 /*
3943 ** Return the current file-size of an apnd-file.
3944 ** If the append mark is not yet there, the file-size is 0.
3945 */
apndFileSize(sqlite3_file * pFile,sqlite_int64 * pSize)3946 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
3947   ApndFile *paf = (ApndFile *)pFile;
3948   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
3949   return SQLITE_OK;
3950 }
3951 
3952 /*
3953 ** Lock an apnd-file.
3954 */
apndLock(sqlite3_file * pFile,int eLock)3955 static int apndLock(sqlite3_file *pFile, int eLock){
3956   pFile = ORIGFILE(pFile);
3957   return pFile->pMethods->xLock(pFile, eLock);
3958 }
3959 
3960 /*
3961 ** Unlock an apnd-file.
3962 */
apndUnlock(sqlite3_file * pFile,int eLock)3963 static int apndUnlock(sqlite3_file *pFile, int eLock){
3964   pFile = ORIGFILE(pFile);
3965   return pFile->pMethods->xUnlock(pFile, eLock);
3966 }
3967 
3968 /*
3969 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
3970 */
apndCheckReservedLock(sqlite3_file * pFile,int * pResOut)3971 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
3972   pFile = ORIGFILE(pFile);
3973   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
3974 }
3975 
3976 /*
3977 ** File control method. For custom operations on an apnd-file.
3978 */
apndFileControl(sqlite3_file * pFile,int op,void * pArg)3979 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
3980   ApndFile *paf = (ApndFile *)pFile;
3981   int rc;
3982   pFile = ORIGFILE(pFile);
3983   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
3984   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
3985   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
3986     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
3987   }
3988   return rc;
3989 }
3990 
3991 /*
3992 ** Return the sector-size in bytes for an apnd-file.
3993 */
apndSectorSize(sqlite3_file * pFile)3994 static int apndSectorSize(sqlite3_file *pFile){
3995   pFile = ORIGFILE(pFile);
3996   return pFile->pMethods->xSectorSize(pFile);
3997 }
3998 
3999 /*
4000 ** Return the device characteristic flags supported by an apnd-file.
4001 */
apndDeviceCharacteristics(sqlite3_file * pFile)4002 static int apndDeviceCharacteristics(sqlite3_file *pFile){
4003   pFile = ORIGFILE(pFile);
4004   return pFile->pMethods->xDeviceCharacteristics(pFile);
4005 }
4006 
4007 /* Create a shared memory file mapping */
apndShmMap(sqlite3_file * pFile,int iPg,int pgsz,int bExtend,void volatile ** pp)4008 static int apndShmMap(
4009   sqlite3_file *pFile,
4010   int iPg,
4011   int pgsz,
4012   int bExtend,
4013   void volatile **pp
4014 ){
4015   pFile = ORIGFILE(pFile);
4016   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
4017 }
4018 
4019 /* Perform locking on a shared-memory segment */
apndShmLock(sqlite3_file * pFile,int offset,int n,int flags)4020 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
4021   pFile = ORIGFILE(pFile);
4022   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
4023 }
4024 
4025 /* Memory barrier operation on shared memory */
apndShmBarrier(sqlite3_file * pFile)4026 static void apndShmBarrier(sqlite3_file *pFile){
4027   pFile = ORIGFILE(pFile);
4028   pFile->pMethods->xShmBarrier(pFile);
4029 }
4030 
4031 /* Unmap a shared memory segment */
apndShmUnmap(sqlite3_file * pFile,int deleteFlag)4032 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
4033   pFile = ORIGFILE(pFile);
4034   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
4035 }
4036 
4037 /* Fetch a page of a memory-mapped file */
apndFetch(sqlite3_file * pFile,sqlite3_int64 iOfst,int iAmt,void ** pp)4038 static int apndFetch(
4039   sqlite3_file *pFile,
4040   sqlite3_int64 iOfst,
4041   int iAmt,
4042   void **pp
4043 ){
4044   ApndFile *p = (ApndFile *)pFile;
4045   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
4046     return SQLITE_IOERR; /* Cannot read what is not yet there. */
4047   }
4048   pFile = ORIGFILE(pFile);
4049   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
4050 }
4051 
4052 /* Release a memory-mapped page */
apndUnfetch(sqlite3_file * pFile,sqlite3_int64 iOfst,void * pPage)4053 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
4054   ApndFile *p = (ApndFile *)pFile;
4055   pFile = ORIGFILE(pFile);
4056   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
4057 }
4058 
4059 /*
4060 ** Try to read the append-mark off the end of a file.  Return the
4061 ** start of the appended database if the append-mark is present.
4062 ** If there is no valid append-mark, return -1;
4063 **
4064 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
4065 ** indicates that the appended database contains at least one page.  The
4066 ** start-of-database value must be a multiple of 512.
4067 */
apndReadMark(sqlite3_int64 sz,sqlite3_file * pFile)4068 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
4069   int rc, i;
4070   sqlite3_int64 iMark;
4071   int msbs = 8 * (APND_MARK_FOS_SZ-1);
4072   unsigned char a[APND_MARK_SIZE];
4073 
4074   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
4075   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
4076   if( rc ) return -1;
4077   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
4078   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
4079   for(i=1; i<8; i++){
4080     msbs -= 8;
4081     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
4082   }
4083   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
4084   if( iMark & 0x1ff ) return -1;
4085   return iMark;
4086 }
4087 
4088 static const char apvfsSqliteHdr[] = "SQLite format 3";
4089 /*
4090 ** Check to see if the file is an appendvfs SQLite database file.
4091 ** Return true iff it is such. Parameter sz is the file's size.
4092 */
apndIsAppendvfsDatabase(sqlite3_int64 sz,sqlite3_file * pFile)4093 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
4094   int rc;
4095   char zHdr[16];
4096   sqlite3_int64 iMark = apndReadMark(sz, pFile);
4097   if( iMark>=0 ){
4098     /* If file has the correct end-marker, the expected odd size, and the
4099     ** SQLite DB type marker where the end-marker puts it, then it
4100     ** is an appendvfs database.
4101     */
4102     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
4103     if( SQLITE_OK==rc
4104      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
4105      && (sz & 0x1ff) == APND_MARK_SIZE
4106      && sz>=512+APND_MARK_SIZE
4107     ){
4108       return 1; /* It's an appendvfs database */
4109     }
4110   }
4111   return 0;
4112 }
4113 
4114 /*
4115 ** Check to see if the file is an ordinary SQLite database file.
4116 ** Return true iff so. Parameter sz is the file's size.
4117 */
apndIsOrdinaryDatabaseFile(sqlite3_int64 sz,sqlite3_file * pFile)4118 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
4119   char zHdr[16];
4120   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
4121    || (sz & 0x1ff) != 0
4122    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
4123    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
4124   ){
4125     return 0;
4126   }else{
4127     return 1;
4128   }
4129 }
4130 
4131 /*
4132 ** Open an apnd file handle.
4133 */
apndOpen(sqlite3_vfs * pApndVfs,const char * zName,sqlite3_file * pFile,int flags,int * pOutFlags)4134 static int apndOpen(
4135   sqlite3_vfs *pApndVfs,
4136   const char *zName,
4137   sqlite3_file *pFile,
4138   int flags,
4139   int *pOutFlags
4140 ){
4141   ApndFile *pApndFile = (ApndFile*)pFile;
4142   sqlite3_file *pBaseFile = ORIGFILE(pFile);
4143   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
4144   int rc;
4145   sqlite3_int64 sz = 0;
4146   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
4147     /* The appendvfs is not to be used for transient or temporary databases.
4148     ** Just use the base VFS open to initialize the given file object and
4149     ** open the underlying file. (Appendvfs is then unused for this file.)
4150     */
4151     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
4152   }
4153   memset(pApndFile, 0, sizeof(ApndFile));
4154   pFile->pMethods = &apnd_io_methods;
4155   pApndFile->iMark = -1;    /* Append mark not yet written */
4156 
4157   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
4158   if( rc==SQLITE_OK ){
4159     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
4160     if( rc ){
4161       pBaseFile->pMethods->xClose(pBaseFile);
4162     }
4163   }
4164   if( rc ){
4165     pFile->pMethods = 0;
4166     return rc;
4167   }
4168   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
4169     /* The file being opened appears to be just an ordinary DB. Copy
4170     ** the base dispatch-table so this instance mimics the base VFS.
4171     */
4172     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
4173     return SQLITE_OK;
4174   }
4175   pApndFile->iPgOne = apndReadMark(sz, pFile);
4176   if( pApndFile->iPgOne>=0 ){
4177     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
4178     return SQLITE_OK;
4179   }
4180   if( (flags & SQLITE_OPEN_CREATE)==0 ){
4181     pBaseFile->pMethods->xClose(pBaseFile);
4182     rc = SQLITE_CANTOPEN;
4183     pFile->pMethods = 0;
4184   }else{
4185     /* Round newly added appendvfs location to #define'd page boundary.
4186     ** Note that nothing has yet been written to the underlying file.
4187     ** The append mark will be written along with first content write.
4188     ** Until then, paf->iMark value indicates it is not yet written.
4189     */
4190     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
4191   }
4192   return rc;
4193 }
4194 
4195 /*
4196 ** Delete an apnd file.
4197 ** For an appendvfs, this could mean delete the appendvfs portion,
4198 ** leaving the appendee as it was before it gained an appendvfs.
4199 ** For now, this code deletes the underlying file too.
4200 */
apndDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)4201 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
4202   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
4203 }
4204 
4205 /*
4206 ** All other VFS methods are pass-thrus.
4207 */
apndAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)4208 static int apndAccess(
4209   sqlite3_vfs *pVfs,
4210   const char *zPath,
4211   int flags,
4212   int *pResOut
4213 ){
4214   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
4215 }
apndFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nOut,char * zOut)4216 static int apndFullPathname(
4217   sqlite3_vfs *pVfs,
4218   const char *zPath,
4219   int nOut,
4220   char *zOut
4221 ){
4222   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
4223 }
apndDlOpen(sqlite3_vfs * pVfs,const char * zPath)4224 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
4225   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
4226 }
apndDlError(sqlite3_vfs * pVfs,int nByte,char * zErrMsg)4227 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
4228   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
4229 }
apndDlSym(sqlite3_vfs * pVfs,void * p,const char * zSym)4230 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
4231   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
4232 }
apndDlClose(sqlite3_vfs * pVfs,void * pHandle)4233 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
4234   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
4235 }
apndRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)4236 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
4237   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
4238 }
apndSleep(sqlite3_vfs * pVfs,int nMicro)4239 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
4240   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
4241 }
apndCurrentTime(sqlite3_vfs * pVfs,double * pTimeOut)4242 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
4243   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
4244 }
apndGetLastError(sqlite3_vfs * pVfs,int a,char * b)4245 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
4246   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
4247 }
apndCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * p)4248 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
4249   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
4250 }
apndSetSystemCall(sqlite3_vfs * pVfs,const char * zName,sqlite3_syscall_ptr pCall)4251 static int apndSetSystemCall(
4252   sqlite3_vfs *pVfs,
4253   const char *zName,
4254   sqlite3_syscall_ptr pCall
4255 ){
4256   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
4257 }
apndGetSystemCall(sqlite3_vfs * pVfs,const char * zName)4258 static sqlite3_syscall_ptr apndGetSystemCall(
4259   sqlite3_vfs *pVfs,
4260   const char *zName
4261 ){
4262   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
4263 }
apndNextSystemCall(sqlite3_vfs * pVfs,const char * zName)4264 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
4265   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
4266 }
4267 
4268 
4269 #ifdef _WIN32
4270 
4271 #endif
4272 /*
4273 ** This routine is called when the extension is loaded.
4274 ** Register the new VFS.
4275 */
sqlite3_appendvfs_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)4276 int sqlite3_appendvfs_init(
4277   sqlite3 *db,
4278   char **pzErrMsg,
4279   const sqlite3_api_routines *pApi
4280 ){
4281   int rc = SQLITE_OK;
4282   sqlite3_vfs *pOrig;
4283   SQLITE_EXTENSION_INIT2(pApi);
4284   (void)pzErrMsg;
4285   (void)db;
4286   pOrig = sqlite3_vfs_find(0);
4287   if( pOrig==0 ) return SQLITE_ERROR;
4288   apnd_vfs.iVersion = pOrig->iVersion;
4289   apnd_vfs.pAppData = pOrig;
4290   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
4291   rc = sqlite3_vfs_register(&apnd_vfs, 0);
4292 #ifdef APPENDVFS_TEST
4293   if( rc==SQLITE_OK ){
4294     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
4295   }
4296 #endif
4297   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
4298   return rc;
4299 }
4300 
4301 /************************* End ../ext/misc/appendvfs.c ********************/
4302 /************************* Begin ../ext/misc/memtrace.c ******************/
4303 /*
4304 ** 2019-01-21
4305 **
4306 ** The author disclaims copyright to this source code.  In place of
4307 ** a legal notice, here is a blessing:
4308 **
4309 **    May you do good and not evil.
4310 **    May you find forgiveness for yourself and forgive others.
4311 **    May you share freely, never taking more than you give.
4312 **
4313 *************************************************************************
4314 **
4315 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
4316 ** mechanism to add a tracing layer on top of SQLite.  If this extension
4317 ** is registered prior to sqlite3_initialize(), it will cause all memory
4318 ** allocation activities to be logged on standard output, or to some other
4319 ** FILE specified by the initializer.
4320 **
4321 ** This file needs to be compiled into the application that uses it.
4322 **
4323 ** This extension is used to implement the --memtrace option of the
4324 ** command-line shell.
4325 */
4326 #include <assert.h>
4327 #include <string.h>
4328 #include <stdio.h>
4329 
4330 /* The original memory allocation routines */
4331 static sqlite3_mem_methods memtraceBase;
4332 static FILE *memtraceOut;
4333 
4334 /* Methods that trace memory allocations */
memtraceMalloc(int n)4335 static void *memtraceMalloc(int n){
4336   if( memtraceOut ){
4337     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
4338             memtraceBase.xRoundup(n));
4339   }
4340   return memtraceBase.xMalloc(n);
4341 }
memtraceFree(void * p)4342 static void memtraceFree(void *p){
4343   if( p==0 ) return;
4344   if( memtraceOut ){
4345     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
4346   }
4347   memtraceBase.xFree(p);
4348 }
memtraceRealloc(void * p,int n)4349 static void *memtraceRealloc(void *p, int n){
4350   if( p==0 ) return memtraceMalloc(n);
4351   if( n==0 ){
4352     memtraceFree(p);
4353     return 0;
4354   }
4355   if( memtraceOut ){
4356     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
4357             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
4358   }
4359   return memtraceBase.xRealloc(p, n);
4360 }
memtraceSize(void * p)4361 static int memtraceSize(void *p){
4362   return memtraceBase.xSize(p);
4363 }
memtraceRoundup(int n)4364 static int memtraceRoundup(int n){
4365   return memtraceBase.xRoundup(n);
4366 }
memtraceInit(void * p)4367 static int memtraceInit(void *p){
4368   return memtraceBase.xInit(p);
4369 }
memtraceShutdown(void * p)4370 static void memtraceShutdown(void *p){
4371   memtraceBase.xShutdown(p);
4372 }
4373 
4374 /* The substitute memory allocator */
4375 static sqlite3_mem_methods ersaztMethods = {
4376   memtraceMalloc,
4377   memtraceFree,
4378   memtraceRealloc,
4379   memtraceSize,
4380   memtraceRoundup,
4381   memtraceInit,
4382   memtraceShutdown,
4383   0
4384 };
4385 
4386 /* Begin tracing memory allocations to out. */
sqlite3MemTraceActivate(FILE * out)4387 int sqlite3MemTraceActivate(FILE *out){
4388   int rc = SQLITE_OK;
4389   if( memtraceBase.xMalloc==0 ){
4390     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
4391     if( rc==SQLITE_OK ){
4392       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
4393     }
4394   }
4395   memtraceOut = out;
4396   return rc;
4397 }
4398 
4399 /* Deactivate memory tracing */
sqlite3MemTraceDeactivate(void)4400 int sqlite3MemTraceDeactivate(void){
4401   int rc = SQLITE_OK;
4402   if( memtraceBase.xMalloc!=0 ){
4403     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
4404     if( rc==SQLITE_OK ){
4405       memset(&memtraceBase, 0, sizeof(memtraceBase));
4406     }
4407   }
4408   memtraceOut = 0;
4409   return rc;
4410 }
4411 
4412 /************************* End ../ext/misc/memtrace.c ********************/
4413 /************************* Begin ../ext/misc/uint.c ******************/
4414 /*
4415 ** 2020-04-14
4416 **
4417 ** The author disclaims copyright to this source code.  In place of
4418 ** a legal notice, here is a blessing:
4419 **
4420 **    May you do good and not evil.
4421 **    May you find forgiveness for yourself and forgive others.
4422 **    May you share freely, never taking more than you give.
4423 **
4424 ******************************************************************************
4425 **
4426 ** This SQLite extension implements the UINT collating sequence.
4427 **
4428 ** UINT works like BINARY for text, except that embedded strings
4429 ** of digits compare in numeric order.
4430 **
4431 **     *   Leading zeros are handled properly, in the sense that
4432 **         they do not mess of the maginitude comparison of embedded
4433 **         strings of digits.  "x00123y" is equal to "x123y".
4434 **
4435 **     *   Only unsigned integers are recognized.  Plus and minus
4436 **         signs are ignored.  Decimal points and exponential notation
4437 **         are ignored.
4438 **
4439 **     *   Embedded integers can be of arbitrary length.  Comparison
4440 **         is *not* limited integers that can be expressed as a
4441 **         64-bit machine integer.
4442 */
4443 /* #include "sqlite3ext.h" */
4444 SQLITE_EXTENSION_INIT1
4445 #include <assert.h>
4446 #include <string.h>
4447 #include <ctype.h>
4448 
4449 /*
4450 ** Compare text in lexicographic order, except strings of digits
4451 ** compare in numeric order.
4452 */
uintCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)4453 static int uintCollFunc(
4454   void *notUsed,
4455   int nKey1, const void *pKey1,
4456   int nKey2, const void *pKey2
4457 ){
4458   const unsigned char *zA = (const unsigned char*)pKey1;
4459   const unsigned char *zB = (const unsigned char*)pKey2;
4460   int i=0, j=0, x;
4461   (void)notUsed;
4462   while( i<nKey1 && j<nKey2 ){
4463     x = zA[i] - zB[j];
4464     if( isdigit(zA[i]) ){
4465       int k;
4466       if( !isdigit(zB[j]) ) return x;
4467       while( i<nKey1 && zA[i]=='0' ){ i++; }
4468       while( j<nKey2 && zB[j]=='0' ){ j++; }
4469       k = 0;
4470       while( i+k<nKey1 && isdigit(zA[i+k])
4471              && j+k<nKey2 && isdigit(zB[j+k]) ){
4472         k++;
4473       }
4474       if( i+k<nKey1 && isdigit(zA[i+k]) ){
4475         return +1;
4476       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
4477         return -1;
4478       }else{
4479         x = memcmp(zA+i, zB+j, k);
4480         if( x ) return x;
4481         i += k;
4482         j += k;
4483       }
4484     }else if( x ){
4485       return x;
4486     }else{
4487       i++;
4488       j++;
4489     }
4490   }
4491   return (nKey1 - i) - (nKey2 - j);
4492 }
4493 
4494 #ifdef _WIN32
4495 
4496 #endif
sqlite3_uint_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)4497 int sqlite3_uint_init(
4498   sqlite3 *db,
4499   char **pzErrMsg,
4500   const sqlite3_api_routines *pApi
4501 ){
4502   SQLITE_EXTENSION_INIT2(pApi);
4503   (void)pzErrMsg;  /* Unused parameter */
4504   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
4505 }
4506 
4507 /************************* End ../ext/misc/uint.c ********************/
4508 /************************* Begin ../ext/misc/decimal.c ******************/
4509 /*
4510 ** 2020-06-22
4511 **
4512 ** The author disclaims copyright to this source code.  In place of
4513 ** a legal notice, here is a blessing:
4514 **
4515 **    May you do good and not evil.
4516 **    May you find forgiveness for yourself and forgive others.
4517 **    May you share freely, never taking more than you give.
4518 **
4519 ******************************************************************************
4520 **
4521 ** Routines to implement arbitrary-precision decimal math.
4522 **
4523 ** The focus here is on simplicity and correctness, not performance.
4524 */
4525 /* #include "sqlite3ext.h" */
4526 SQLITE_EXTENSION_INIT1
4527 #include <assert.h>
4528 #include <string.h>
4529 #include <ctype.h>
4530 #include <stdlib.h>
4531 
4532 /* Mark a function parameter as unused, to suppress nuisance compiler
4533 ** warnings. */
4534 #ifndef UNUSED_PARAMETER
4535 # define UNUSED_PARAMETER(X)  (void)(X)
4536 #endif
4537 
4538 
4539 /* A decimal object */
4540 typedef struct Decimal Decimal;
4541 struct Decimal {
4542   char sign;        /* 0 for positive, 1 for negative */
4543   char oom;         /* True if an OOM is encountered */
4544   char isNull;      /* True if holds a NULL rather than a number */
4545   char isInit;      /* True upon initialization */
4546   int nDigit;       /* Total number of digits */
4547   int nFrac;        /* Number of digits to the right of the decimal point */
4548   signed char *a;   /* Array of digits.  Most significant first. */
4549 };
4550 
4551 /*
4552 ** Release memory held by a Decimal, but do not free the object itself.
4553 */
decimal_clear(Decimal * p)4554 static void decimal_clear(Decimal *p){
4555   sqlite3_free(p->a);
4556 }
4557 
4558 /*
4559 ** Destroy a Decimal object
4560 */
decimal_free(Decimal * p)4561 static void decimal_free(Decimal *p){
4562   if( p ){
4563     decimal_clear(p);
4564     sqlite3_free(p);
4565   }
4566 }
4567 
4568 /*
4569 ** Allocate a new Decimal object.  Initialize it to the number given
4570 ** by the input string.
4571 */
decimal_new(sqlite3_context * pCtx,sqlite3_value * pIn,int nAlt,const unsigned char * zAlt)4572 static Decimal *decimal_new(
4573   sqlite3_context *pCtx,
4574   sqlite3_value *pIn,
4575   int nAlt,
4576   const unsigned char *zAlt
4577 ){
4578   Decimal *p;
4579   int n, i;
4580   const unsigned char *zIn;
4581   int iExp = 0;
4582   p = sqlite3_malloc( sizeof(*p) );
4583   if( p==0 ) goto new_no_mem;
4584   p->sign = 0;
4585   p->oom = 0;
4586   p->isInit = 1;
4587   p->isNull = 0;
4588   p->nDigit = 0;
4589   p->nFrac = 0;
4590   if( zAlt ){
4591     n = nAlt,
4592     zIn = zAlt;
4593   }else{
4594     if( sqlite3_value_type(pIn)==SQLITE_NULL ){
4595       p->a = 0;
4596       p->isNull = 1;
4597       return p;
4598     }
4599     n = sqlite3_value_bytes(pIn);
4600     zIn = sqlite3_value_text(pIn);
4601   }
4602   p->a = sqlite3_malloc64( n+1 );
4603   if( p->a==0 ) goto new_no_mem;
4604   for(i=0; isspace(zIn[i]); i++){}
4605   if( zIn[i]=='-' ){
4606     p->sign = 1;
4607     i++;
4608   }else if( zIn[i]=='+' ){
4609     i++;
4610   }
4611   while( i<n && zIn[i]=='0' ) i++;
4612   while( i<n ){
4613     char c = zIn[i];
4614     if( c>='0' && c<='9' ){
4615       p->a[p->nDigit++] = c - '0';
4616     }else if( c=='.' ){
4617       p->nFrac = p->nDigit + 1;
4618     }else if( c=='e' || c=='E' ){
4619       int j = i+1;
4620       int neg = 0;
4621       if( j>=n ) break;
4622       if( zIn[j]=='-' ){
4623         neg = 1;
4624         j++;
4625       }else if( zIn[j]=='+' ){
4626         j++;
4627       }
4628       while( j<n && iExp<1000000 ){
4629         if( zIn[j]>='0' && zIn[j]<='9' ){
4630           iExp = iExp*10 + zIn[j] - '0';
4631         }
4632         j++;
4633       }
4634       if( neg ) iExp = -iExp;
4635       break;
4636     }
4637     i++;
4638   }
4639   if( p->nFrac ){
4640     p->nFrac = p->nDigit - (p->nFrac - 1);
4641   }
4642   if( iExp>0 ){
4643     if( p->nFrac>0 ){
4644       if( iExp<=p->nFrac ){
4645         p->nFrac -= iExp;
4646         iExp = 0;
4647       }else{
4648         iExp -= p->nFrac;
4649         p->nFrac = 0;
4650       }
4651     }
4652     if( iExp>0 ){
4653       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
4654       if( p->a==0 ) goto new_no_mem;
4655       memset(p->a+p->nDigit, 0, iExp);
4656       p->nDigit += iExp;
4657     }
4658   }else if( iExp<0 ){
4659     int nExtra;
4660     iExp = -iExp;
4661     nExtra = p->nDigit - p->nFrac - 1;
4662     if( nExtra ){
4663       if( nExtra>=iExp ){
4664         p->nFrac += iExp;
4665         iExp  = 0;
4666       }else{
4667         iExp -= nExtra;
4668         p->nFrac = p->nDigit - 1;
4669       }
4670     }
4671     if( iExp>0 ){
4672       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
4673       if( p->a==0 ) goto new_no_mem;
4674       memmove(p->a+iExp, p->a, p->nDigit);
4675       memset(p->a, 0, iExp);
4676       p->nDigit += iExp;
4677       p->nFrac += iExp;
4678     }
4679   }
4680   return p;
4681 
4682 new_no_mem:
4683   if( pCtx ) sqlite3_result_error_nomem(pCtx);
4684   sqlite3_free(p);
4685   return 0;
4686 }
4687 
4688 /*
4689 ** Make the given Decimal the result.
4690 */
decimal_result(sqlite3_context * pCtx,Decimal * p)4691 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
4692   char *z;
4693   int i, j;
4694   int n;
4695   if( p==0 || p->oom ){
4696     sqlite3_result_error_nomem(pCtx);
4697     return;
4698   }
4699   if( p->isNull ){
4700     sqlite3_result_null(pCtx);
4701     return;
4702   }
4703   z = sqlite3_malloc( p->nDigit+4 );
4704   if( z==0 ){
4705     sqlite3_result_error_nomem(pCtx);
4706     return;
4707   }
4708   i = 0;
4709   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
4710     p->sign = 0;
4711   }
4712   if( p->sign ){
4713     z[0] = '-';
4714     i = 1;
4715   }
4716   n = p->nDigit - p->nFrac;
4717   if( n<=0 ){
4718     z[i++] = '0';
4719   }
4720   j = 0;
4721   while( n>1 && p->a[j]==0 ){
4722     j++;
4723     n--;
4724   }
4725   while( n>0  ){
4726     z[i++] = p->a[j] + '0';
4727     j++;
4728     n--;
4729   }
4730   if( p->nFrac ){
4731     z[i++] = '.';
4732     do{
4733       z[i++] = p->a[j] + '0';
4734       j++;
4735     }while( j<p->nDigit );
4736   }
4737   z[i] = 0;
4738   sqlite3_result_text(pCtx, z, i, sqlite3_free);
4739 }
4740 
4741 /*
4742 ** SQL Function:   decimal(X)
4743 **
4744 ** Convert input X into decimal and then back into text
4745 */
decimalFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4746 static void decimalFunc(
4747   sqlite3_context *context,
4748   int argc,
4749   sqlite3_value **argv
4750 ){
4751   Decimal *p = decimal_new(context, argv[0], 0, 0);
4752   UNUSED_PARAMETER(argc);
4753   decimal_result(context, p);
4754   decimal_free(p);
4755 }
4756 
4757 /*
4758 ** Compare to Decimal objects.  Return negative, 0, or positive if the
4759 ** first object is less than, equal to, or greater than the second.
4760 **
4761 ** Preconditions for this routine:
4762 **
4763 **    pA!=0
4764 **    pA->isNull==0
4765 **    pB!=0
4766 **    pB->isNull==0
4767 */
decimal_cmp(const Decimal * pA,const Decimal * pB)4768 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4769   int nASig, nBSig, rc, n;
4770   if( pA->sign!=pB->sign ){
4771     return pA->sign ? -1 : +1;
4772   }
4773   if( pA->sign ){
4774     const Decimal *pTemp = pA;
4775     pA = pB;
4776     pB = pTemp;
4777   }
4778   nASig = pA->nDigit - pA->nFrac;
4779   nBSig = pB->nDigit - pB->nFrac;
4780   if( nASig!=nBSig ){
4781     return nASig - nBSig;
4782   }
4783   n = pA->nDigit;
4784   if( n>pB->nDigit ) n = pB->nDigit;
4785   rc = memcmp(pA->a, pB->a, n);
4786   if( rc==0 ){
4787     rc = pA->nDigit - pB->nDigit;
4788   }
4789   return rc;
4790 }
4791 
4792 /*
4793 ** SQL Function:   decimal_cmp(X, Y)
4794 **
4795 ** Return negative, zero, or positive if X is less then, equal to, or
4796 ** greater than Y.
4797 */
decimalCmpFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4798 static void decimalCmpFunc(
4799   sqlite3_context *context,
4800   int argc,
4801   sqlite3_value **argv
4802 ){
4803   Decimal *pA = 0, *pB = 0;
4804   int rc;
4805 
4806   UNUSED_PARAMETER(argc);
4807   pA = decimal_new(context, argv[0], 0, 0);
4808   if( pA==0 || pA->isNull ) goto cmp_done;
4809   pB = decimal_new(context, argv[1], 0, 0);
4810   if( pB==0 || pB->isNull ) goto cmp_done;
4811   rc = decimal_cmp(pA, pB);
4812   if( rc<0 ) rc = -1;
4813   else if( rc>0 ) rc = +1;
4814   sqlite3_result_int(context, rc);
4815 cmp_done:
4816   decimal_free(pA);
4817   decimal_free(pB);
4818 }
4819 
4820 /*
4821 ** Expand the Decimal so that it has a least nDigit digits and nFrac
4822 ** digits to the right of the decimal point.
4823 */
decimal_expand(Decimal * p,int nDigit,int nFrac)4824 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4825   int nAddSig;
4826   int nAddFrac;
4827   if( p==0 ) return;
4828   nAddFrac = nFrac - p->nFrac;
4829   nAddSig = (nDigit - p->nDigit) - nAddFrac;
4830   if( nAddFrac==0 && nAddSig==0 ) return;
4831   p->a = sqlite3_realloc64(p->a, nDigit+1);
4832   if( p->a==0 ){
4833     p->oom = 1;
4834     return;
4835   }
4836   if( nAddSig ){
4837     memmove(p->a+nAddSig, p->a, p->nDigit);
4838     memset(p->a, 0, nAddSig);
4839     p->nDigit += nAddSig;
4840   }
4841   if( nAddFrac ){
4842     memset(p->a+p->nDigit, 0, nAddFrac);
4843     p->nDigit += nAddFrac;
4844     p->nFrac += nAddFrac;
4845   }
4846 }
4847 
4848 /*
4849 ** Add the value pB into pA.
4850 **
4851 ** Both pA and pB might become denormalized by this routine.
4852 */
decimal_add(Decimal * pA,Decimal * pB)4853 static void decimal_add(Decimal *pA, Decimal *pB){
4854   int nSig, nFrac, nDigit;
4855   int i, rc;
4856   if( pA==0 ){
4857     return;
4858   }
4859   if( pA->oom || pB==0 || pB->oom ){
4860     pA->oom = 1;
4861     return;
4862   }
4863   if( pA->isNull || pB->isNull ){
4864     pA->isNull = 1;
4865     return;
4866   }
4867   nSig = pA->nDigit - pA->nFrac;
4868   if( nSig && pA->a[0]==0 ) nSig--;
4869   if( nSig<pB->nDigit-pB->nFrac ){
4870     nSig = pB->nDigit - pB->nFrac;
4871   }
4872   nFrac = pA->nFrac;
4873   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4874   nDigit = nSig + nFrac + 1;
4875   decimal_expand(pA, nDigit, nFrac);
4876   decimal_expand(pB, nDigit, nFrac);
4877   if( pA->oom || pB->oom ){
4878     pA->oom = 1;
4879   }else{
4880     if( pA->sign==pB->sign ){
4881       int carry = 0;
4882       for(i=nDigit-1; i>=0; i--){
4883         int x = pA->a[i] + pB->a[i] + carry;
4884         if( x>=10 ){
4885           carry = 1;
4886           pA->a[i] = x - 10;
4887         }else{
4888           carry = 0;
4889           pA->a[i] = x;
4890         }
4891       }
4892     }else{
4893       signed char *aA, *aB;
4894       int borrow = 0;
4895       rc = memcmp(pA->a, pB->a, nDigit);
4896       if( rc<0 ){
4897         aA = pB->a;
4898         aB = pA->a;
4899         pA->sign = !pA->sign;
4900       }else{
4901         aA = pA->a;
4902         aB = pB->a;
4903       }
4904       for(i=nDigit-1; i>=0; i--){
4905         int x = aA[i] - aB[i] - borrow;
4906         if( x<0 ){
4907           pA->a[i] = x+10;
4908           borrow = 1;
4909         }else{
4910           pA->a[i] = x;
4911           borrow = 0;
4912         }
4913       }
4914     }
4915   }
4916 }
4917 
4918 /*
4919 ** Compare text in decimal order.
4920 */
decimalCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)4921 static int decimalCollFunc(
4922   void *notUsed,
4923   int nKey1, const void *pKey1,
4924   int nKey2, const void *pKey2
4925 ){
4926   const unsigned char *zA = (const unsigned char*)pKey1;
4927   const unsigned char *zB = (const unsigned char*)pKey2;
4928   Decimal *pA = decimal_new(0, 0, nKey1, zA);
4929   Decimal *pB = decimal_new(0, 0, nKey2, zB);
4930   int rc;
4931   UNUSED_PARAMETER(notUsed);
4932   if( pA==0 || pB==0 ){
4933     rc = 0;
4934   }else{
4935     rc = decimal_cmp(pA, pB);
4936   }
4937   decimal_free(pA);
4938   decimal_free(pB);
4939   return rc;
4940 }
4941 
4942 
4943 /*
4944 ** SQL Function:   decimal_add(X, Y)
4945 **                 decimal_sub(X, Y)
4946 **
4947 ** Return the sum or difference of X and Y.
4948 */
decimalAddFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4949 static void decimalAddFunc(
4950   sqlite3_context *context,
4951   int argc,
4952   sqlite3_value **argv
4953 ){
4954   Decimal *pA = decimal_new(context, argv[0], 0, 0);
4955   Decimal *pB = decimal_new(context, argv[1], 0, 0);
4956   UNUSED_PARAMETER(argc);
4957   decimal_add(pA, pB);
4958   decimal_result(context, pA);
4959   decimal_free(pA);
4960   decimal_free(pB);
4961 }
decimalSubFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4962 static void decimalSubFunc(
4963   sqlite3_context *context,
4964   int argc,
4965   sqlite3_value **argv
4966 ){
4967   Decimal *pA = decimal_new(context, argv[0], 0, 0);
4968   Decimal *pB = decimal_new(context, argv[1], 0, 0);
4969   UNUSED_PARAMETER(argc);
4970   if( pB ){
4971     pB->sign = !pB->sign;
4972     decimal_add(pA, pB);
4973     decimal_result(context, pA);
4974   }
4975   decimal_free(pA);
4976   decimal_free(pB);
4977 }
4978 
4979 /* Aggregate funcion:   decimal_sum(X)
4980 **
4981 ** Works like sum() except that it uses decimal arithmetic for unlimited
4982 ** precision.
4983 */
decimalSumStep(sqlite3_context * context,int argc,sqlite3_value ** argv)4984 static void decimalSumStep(
4985   sqlite3_context *context,
4986   int argc,
4987   sqlite3_value **argv
4988 ){
4989   Decimal *p;
4990   Decimal *pArg;
4991   UNUSED_PARAMETER(argc);
4992   p = sqlite3_aggregate_context(context, sizeof(*p));
4993   if( p==0 ) return;
4994   if( !p->isInit ){
4995     p->isInit = 1;
4996     p->a = sqlite3_malloc(2);
4997     if( p->a==0 ){
4998       p->oom = 1;
4999     }else{
5000       p->a[0] = 0;
5001     }
5002     p->nDigit = 1;
5003     p->nFrac = 0;
5004   }
5005   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
5006   pArg = decimal_new(context, argv[0], 0, 0);
5007   decimal_add(p, pArg);
5008   decimal_free(pArg);
5009 }
decimalSumInverse(sqlite3_context * context,int argc,sqlite3_value ** argv)5010 static void decimalSumInverse(
5011   sqlite3_context *context,
5012   int argc,
5013   sqlite3_value **argv
5014 ){
5015   Decimal *p;
5016   Decimal *pArg;
5017   UNUSED_PARAMETER(argc);
5018   p = sqlite3_aggregate_context(context, sizeof(*p));
5019   if( p==0 ) return;
5020   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
5021   pArg = decimal_new(context, argv[0], 0, 0);
5022   if( pArg ) pArg->sign = !pArg->sign;
5023   decimal_add(p, pArg);
5024   decimal_free(pArg);
5025 }
decimalSumValue(sqlite3_context * context)5026 static void decimalSumValue(sqlite3_context *context){
5027   Decimal *p = sqlite3_aggregate_context(context, 0);
5028   if( p==0 ) return;
5029   decimal_result(context, p);
5030 }
decimalSumFinalize(sqlite3_context * context)5031 static void decimalSumFinalize(sqlite3_context *context){
5032   Decimal *p = sqlite3_aggregate_context(context, 0);
5033   if( p==0 ) return;
5034   decimal_result(context, p);
5035   decimal_clear(p);
5036 }
5037 
5038 /*
5039 ** SQL Function:   decimal_mul(X, Y)
5040 **
5041 ** Return the product of X and Y.
5042 **
5043 ** All significant digits after the decimal point are retained.
5044 ** Trailing zeros after the decimal point are omitted as long as
5045 ** the number of digits after the decimal point is no less than
5046 ** either the number of digits in either input.
5047 */
decimalMulFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)5048 static void decimalMulFunc(
5049   sqlite3_context *context,
5050   int argc,
5051   sqlite3_value **argv
5052 ){
5053   Decimal *pA = decimal_new(context, argv[0], 0, 0);
5054   Decimal *pB = decimal_new(context, argv[1], 0, 0);
5055   signed char *acc = 0;
5056   int i, j, k;
5057   int minFrac;
5058   UNUSED_PARAMETER(argc);
5059   if( pA==0 || pA->oom || pA->isNull
5060    || pB==0 || pB->oom || pB->isNull
5061   ){
5062     goto mul_end;
5063   }
5064   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
5065   if( acc==0 ){
5066     sqlite3_result_error_nomem(context);
5067     goto mul_end;
5068   }
5069   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
5070   minFrac = pA->nFrac;
5071   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
5072   for(i=pA->nDigit-1; i>=0; i--){
5073     signed char f = pA->a[i];
5074     int carry = 0, x;
5075     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
5076       x = acc[k] + f*pB->a[j] + carry;
5077       acc[k] = x%10;
5078       carry = x/10;
5079     }
5080     x = acc[k] + carry;
5081     acc[k] = x%10;
5082     acc[k-1] += x/10;
5083   }
5084   sqlite3_free(pA->a);
5085   pA->a = acc;
5086   acc = 0;
5087   pA->nDigit += pB->nDigit + 2;
5088   pA->nFrac += pB->nFrac;
5089   pA->sign ^= pB->sign;
5090   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
5091     pA->nFrac--;
5092     pA->nDigit--;
5093   }
5094   decimal_result(context, pA);
5095 
5096 mul_end:
5097   sqlite3_free(acc);
5098   decimal_free(pA);
5099   decimal_free(pB);
5100 }
5101 
5102 #ifdef _WIN32
5103 
5104 #endif
sqlite3_decimal_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)5105 int sqlite3_decimal_init(
5106   sqlite3 *db,
5107   char **pzErrMsg,
5108   const sqlite3_api_routines *pApi
5109 ){
5110   int rc = SQLITE_OK;
5111   static const struct {
5112     const char *zFuncName;
5113     int nArg;
5114     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5115   } aFunc[] = {
5116     { "decimal",       1,   decimalFunc        },
5117     { "decimal_cmp",   2,   decimalCmpFunc     },
5118     { "decimal_add",   2,   decimalAddFunc     },
5119     { "decimal_sub",   2,   decimalSubFunc     },
5120     { "decimal_mul",   2,   decimalMulFunc     },
5121   };
5122   unsigned int i;
5123   (void)pzErrMsg;  /* Unused parameter */
5124 
5125   SQLITE_EXTENSION_INIT2(pApi);
5126 
5127   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5128     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
5129                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5130                    0, aFunc[i].xFunc, 0, 0);
5131   }
5132   if( rc==SQLITE_OK ){
5133     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
5134                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
5135                    decimalSumStep, decimalSumFinalize,
5136                    decimalSumValue, decimalSumInverse, 0);
5137   }
5138   if( rc==SQLITE_OK ){
5139     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
5140                                   0, decimalCollFunc);
5141   }
5142   return rc;
5143 }
5144 
5145 /************************* End ../ext/misc/decimal.c ********************/
5146 /************************* Begin ../ext/misc/ieee754.c ******************/
5147 /*
5148 ** 2013-04-17
5149 **
5150 ** The author disclaims copyright to this source code.  In place of
5151 ** a legal notice, here is a blessing:
5152 **
5153 **    May you do good and not evil.
5154 **    May you find forgiveness for yourself and forgive others.
5155 **    May you share freely, never taking more than you give.
5156 **
5157 ******************************************************************************
5158 **
5159 ** This SQLite extension implements functions for the exact display
5160 ** and input of IEEE754 Binary64 floating-point numbers.
5161 **
5162 **   ieee754(X)
5163 **   ieee754(Y,Z)
5164 **
5165 ** In the first form, the value X should be a floating-point number.
5166 ** The function will return a string of the form 'ieee754(Y,Z)' where
5167 ** Y and Z are integers such that X==Y*pow(2,Z).
5168 **
5169 ** In the second form, Y and Z are integers which are the mantissa and
5170 ** base-2 exponent of a new floating point number.  The function returns
5171 ** a floating-point value equal to Y*pow(2,Z).
5172 **
5173 ** Examples:
5174 **
5175 **     ieee754(2.0)             ->     'ieee754(2,0)'
5176 **     ieee754(45.25)           ->     'ieee754(181,-2)'
5177 **     ieee754(2, 0)            ->     2.0
5178 **     ieee754(181, -2)         ->     45.25
5179 **
5180 ** Two additional functions break apart the one-argument ieee754()
5181 ** result into separate integer values:
5182 **
5183 **     ieee754_mantissa(45.25)  ->     181
5184 **     ieee754_exponent(45.25)  ->     -2
5185 **
5186 ** These functions convert binary64 numbers into blobs and back again.
5187 **
5188 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5189 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5190 **
5191 ** In all single-argument functions, if the argument is an 8-byte blob
5192 ** then that blob is interpreted as a big-endian binary64 value.
5193 **
5194 **
5195 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5196 ** -----------------------------------------------
5197 **
5198 ** This extension in combination with the separate 'decimal' extension
5199 ** can be used to compute the exact decimal representation of binary64
5200 ** values.  To begin, first compute a table of exponent values:
5201 **
5202 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5203 **    WITH RECURSIVE c(x,v) AS (
5204 **      VALUES(0,'1')
5205 **      UNION ALL
5206 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5207 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5208 **    WITH RECURSIVE c(x,v) AS (
5209 **      VALUES(-1,'0.5')
5210 **      UNION ALL
5211 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5212 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5213 **
5214 ** Then, to compute the exact decimal representation of a floating
5215 ** point value (the value 47.49 is used in the example) do:
5216 **
5217 **    WITH c(n) AS (VALUES(47.49))
5218 **          ---------------^^^^^---- Replace with whatever you want
5219 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5220 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5221 **
5222 ** Here is a query to show various boundry values for the binary64
5223 ** number format:
5224 **
5225 **    WITH c(name,bin) AS (VALUES
5226 **       ('minimum positive value',        x'0000000000000001'),
5227 **       ('maximum subnormal value',       x'000fffffffffffff'),
5228 **       ('mininum positive nornal value', x'0010000000000000'),
5229 **       ('maximum value',                 x'7fefffffffffffff'))
5230 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5231 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5232 **
5233 */
5234 /* #include "sqlite3ext.h" */
5235 SQLITE_EXTENSION_INIT1
5236 #include <assert.h>
5237 #include <string.h>
5238 
5239 /* Mark a function parameter as unused, to suppress nuisance compiler
5240 ** warnings. */
5241 #ifndef UNUSED_PARAMETER
5242 # define UNUSED_PARAMETER(X)  (void)(X)
5243 #endif
5244 
5245 /*
5246 ** Implementation of the ieee754() function
5247 */
ieee754func(sqlite3_context * context,int argc,sqlite3_value ** argv)5248 static void ieee754func(
5249   sqlite3_context *context,
5250   int argc,
5251   sqlite3_value **argv
5252 ){
5253   if( argc==1 ){
5254     sqlite3_int64 m, a;
5255     double r;
5256     int e;
5257     int isNeg;
5258     char zResult[100];
5259     assert( sizeof(m)==sizeof(r) );
5260     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5261      && sqlite3_value_bytes(argv[0])==sizeof(r)
5262     ){
5263       const unsigned char *x = sqlite3_value_blob(argv[0]);
5264       unsigned int i;
5265       sqlite3_uint64 v = 0;
5266       for(i=0; i<sizeof(r); i++){
5267         v = (v<<8) | x[i];
5268       }
5269       memcpy(&r, &v, sizeof(r));
5270     }else{
5271       r = sqlite3_value_double(argv[0]);
5272     }
5273     if( r<0.0 ){
5274       isNeg = 1;
5275       r = -r;
5276     }else{
5277       isNeg = 0;
5278     }
5279     memcpy(&a,&r,sizeof(a));
5280     if( a==0 ){
5281       e = 0;
5282       m = 0;
5283     }else{
5284       e = a>>52;
5285       m = a & ((((sqlite3_int64)1)<<52)-1);
5286       if( e==0 ){
5287         m <<= 1;
5288       }else{
5289         m |= ((sqlite3_int64)1)<<52;
5290       }
5291       while( e<1075 && m>0 && (m&1)==0 ){
5292         m >>= 1;
5293         e++;
5294       }
5295       if( isNeg ) m = -m;
5296     }
5297     switch( *(int*)sqlite3_user_data(context) ){
5298       case 0:
5299         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5300                          m, e-1075);
5301         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5302         break;
5303       case 1:
5304         sqlite3_result_int64(context, m);
5305         break;
5306       case 2:
5307         sqlite3_result_int(context, e-1075);
5308         break;
5309     }
5310   }else{
5311     sqlite3_int64 m, e, a;
5312     double r;
5313     int isNeg = 0;
5314     m = sqlite3_value_int64(argv[0]);
5315     e = sqlite3_value_int64(argv[1]);
5316 
5317     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
5318     if( e>10000 ){
5319       e = 10000;
5320     }else if( e<-10000 ){
5321       e = -10000;
5322     }
5323 
5324     if( m<0 ){
5325       isNeg = 1;
5326       m = -m;
5327       if( m<0 ) return;
5328     }else if( m==0 && e>-1000 && e<1000 ){
5329       sqlite3_result_double(context, 0.0);
5330       return;
5331     }
5332     while( (m>>32)&0xffe00000 ){
5333       m >>= 1;
5334       e++;
5335     }
5336     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5337       m <<= 1;
5338       e--;
5339     }
5340     e += 1075;
5341     if( e<=0 ){
5342       /* Subnormal */
5343       m >>= 1-e;
5344       e = 0;
5345     }else if( e>0x7ff ){
5346       e = 0x7ff;
5347     }
5348     a = m & ((((sqlite3_int64)1)<<52)-1);
5349     a |= e<<52;
5350     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5351     memcpy(&r, &a, sizeof(r));
5352     sqlite3_result_double(context, r);
5353   }
5354 }
5355 
5356 /*
5357 ** Functions to convert between blobs and floats.
5358 */
ieee754func_from_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5359 static void ieee754func_from_blob(
5360   sqlite3_context *context,
5361   int argc,
5362   sqlite3_value **argv
5363 ){
5364   UNUSED_PARAMETER(argc);
5365   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5366    && sqlite3_value_bytes(argv[0])==sizeof(double)
5367   ){
5368     double r;
5369     const unsigned char *x = sqlite3_value_blob(argv[0]);
5370     unsigned int i;
5371     sqlite3_uint64 v = 0;
5372     for(i=0; i<sizeof(r); i++){
5373       v = (v<<8) | x[i];
5374     }
5375     memcpy(&r, &v, sizeof(r));
5376     sqlite3_result_double(context, r);
5377   }
5378 }
ieee754func_to_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5379 static void ieee754func_to_blob(
5380   sqlite3_context *context,
5381   int argc,
5382   sqlite3_value **argv
5383 ){
5384   UNUSED_PARAMETER(argc);
5385   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5386    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5387   ){
5388     double r = sqlite3_value_double(argv[0]);
5389     sqlite3_uint64 v;
5390     unsigned char a[sizeof(r)];
5391     unsigned int i;
5392     memcpy(&v, &r, sizeof(r));
5393     for(i=1; i<=sizeof(r); i++){
5394       a[sizeof(r)-i] = v&0xff;
5395       v >>= 8;
5396     }
5397     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5398   }
5399 }
5400 
5401 
5402 #ifdef _WIN32
5403 
5404 #endif
sqlite3_ieee_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)5405 int sqlite3_ieee_init(
5406   sqlite3 *db,
5407   char **pzErrMsg,
5408   const sqlite3_api_routines *pApi
5409 ){
5410   static const struct {
5411     char *zFName;
5412     int nArg;
5413     int iAux;
5414     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5415   } aFunc[] = {
5416     { "ieee754",           1,   0, ieee754func },
5417     { "ieee754",           2,   0, ieee754func },
5418     { "ieee754_mantissa",  1,   1, ieee754func },
5419     { "ieee754_exponent",  1,   2, ieee754func },
5420     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5421     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5422 
5423   };
5424   unsigned int i;
5425   int rc = SQLITE_OK;
5426   SQLITE_EXTENSION_INIT2(pApi);
5427   (void)pzErrMsg;  /* Unused parameter */
5428   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5429     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
5430                                SQLITE_UTF8|SQLITE_INNOCUOUS,
5431                                (void*)&aFunc[i].iAux,
5432                                aFunc[i].xFunc, 0, 0);
5433   }
5434   return rc;
5435 }
5436 
5437 /************************* End ../ext/misc/ieee754.c ********************/
5438 /************************* Begin ../ext/misc/series.c ******************/
5439 /*
5440 ** 2015-08-18
5441 **
5442 ** The author disclaims copyright to this source code.  In place of
5443 ** a legal notice, here is a blessing:
5444 **
5445 **    May you do good and not evil.
5446 **    May you find forgiveness for yourself and forgive others.
5447 **    May you share freely, never taking more than you give.
5448 **
5449 *************************************************************************
5450 **
5451 ** This file demonstrates how to create a table-valued-function using
5452 ** a virtual table.  This demo implements the generate_series() function
5453 ** which gives similar results to the eponymous function in PostgreSQL.
5454 ** Examples:
5455 **
5456 **      SELECT * FROM generate_series(0,100,5);
5457 **
5458 ** The query above returns integers from 0 through 100 counting by steps
5459 ** of 5.
5460 **
5461 **      SELECT * FROM generate_series(0,100);
5462 **
5463 ** Integers from 0 through 100 with a step size of 1.
5464 **
5465 **      SELECT * FROM generate_series(20) LIMIT 10;
5466 **
5467 ** Integers 20 through 29.
5468 **
5469 ** HOW IT WORKS
5470 **
5471 ** The generate_series "function" is really a virtual table with the
5472 ** following schema:
5473 **
5474 **     CREATE TABLE generate_series(
5475 **       value,
5476 **       start HIDDEN,
5477 **       stop HIDDEN,
5478 **       step HIDDEN
5479 **     );
5480 **
5481 ** Function arguments in queries against this virtual table are translated
5482 ** into equality constraints against successive hidden columns.  In other
5483 ** words, the following pairs of queries are equivalent to each other:
5484 **
5485 **    SELECT * FROM generate_series(0,100,5);
5486 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5487 **
5488 **    SELECT * FROM generate_series(0,100);
5489 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5490 **
5491 **    SELECT * FROM generate_series(20) LIMIT 10;
5492 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5493 **
5494 ** The generate_series virtual table implementation leaves the xCreate method
5495 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5496 ** TABLE command with "generate_series" as the USING argument.  Instead, there
5497 ** is a single generate_series virtual table that is always available without
5498 ** having to be created first.
5499 **
5500 ** The xBestIndex method looks for equality constraints against the hidden
5501 ** start, stop, and step columns, and if present, it uses those constraints
5502 ** to bound the sequence of generated values.  If the equality constraints
5503 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5504 ** xBestIndex returns a small cost when both start and stop are available,
5505 ** and a very large cost if either start or stop are unavailable.  This
5506 ** encourages the query planner to order joins such that the bounds of the
5507 ** series are well-defined.
5508 */
5509 /* #include "sqlite3ext.h" */
5510 SQLITE_EXTENSION_INIT1
5511 #include <assert.h>
5512 #include <string.h>
5513 
5514 #ifndef SQLITE_OMIT_VIRTUALTABLE
5515 
5516 
5517 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
5518 ** serve as the underlying representation of a cursor that scans
5519 ** over rows of the result
5520 */
5521 typedef struct series_cursor series_cursor;
5522 struct series_cursor {
5523   sqlite3_vtab_cursor base;  /* Base class - must be first */
5524   int isDesc;                /* True to count down rather than up */
5525   sqlite3_int64 iRowid;      /* The rowid */
5526   sqlite3_int64 iValue;      /* Current value ("value") */
5527   sqlite3_int64 mnValue;     /* Mimimum value ("start") */
5528   sqlite3_int64 mxValue;     /* Maximum value ("stop") */
5529   sqlite3_int64 iStep;       /* Increment ("step") */
5530 };
5531 
5532 /*
5533 ** The seriesConnect() method is invoked to create a new
5534 ** series_vtab that describes the generate_series virtual table.
5535 **
5536 ** Think of this routine as the constructor for series_vtab objects.
5537 **
5538 ** All this routine needs to do is:
5539 **
5540 **    (1) Allocate the series_vtab object and initialize all fields.
5541 **
5542 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5543 **        result set of queries against generate_series will look like.
5544 */
seriesConnect(sqlite3 * db,void * pUnused,int argcUnused,const char * const * argvUnused,sqlite3_vtab ** ppVtab,char ** pzErrUnused)5545 static int seriesConnect(
5546   sqlite3 *db,
5547   void *pUnused,
5548   int argcUnused, const char *const*argvUnused,
5549   sqlite3_vtab **ppVtab,
5550   char **pzErrUnused
5551 ){
5552   sqlite3_vtab *pNew;
5553   int rc;
5554 
5555 /* Column numbers */
5556 #define SERIES_COLUMN_VALUE 0
5557 #define SERIES_COLUMN_START 1
5558 #define SERIES_COLUMN_STOP  2
5559 #define SERIES_COLUMN_STEP  3
5560 
5561   (void)pUnused;
5562   (void)argcUnused;
5563   (void)argvUnused;
5564   (void)pzErrUnused;
5565   rc = sqlite3_declare_vtab(db,
5566      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5567   if( rc==SQLITE_OK ){
5568     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5569     if( pNew==0 ) return SQLITE_NOMEM;
5570     memset(pNew, 0, sizeof(*pNew));
5571     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5572   }
5573   return rc;
5574 }
5575 
5576 /*
5577 ** This method is the destructor for series_cursor objects.
5578 */
seriesDisconnect(sqlite3_vtab * pVtab)5579 static int seriesDisconnect(sqlite3_vtab *pVtab){
5580   sqlite3_free(pVtab);
5581   return SQLITE_OK;
5582 }
5583 
5584 /*
5585 ** Constructor for a new series_cursor object.
5586 */
seriesOpen(sqlite3_vtab * pUnused,sqlite3_vtab_cursor ** ppCursor)5587 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5588   series_cursor *pCur;
5589   (void)pUnused;
5590   pCur = sqlite3_malloc( sizeof(*pCur) );
5591   if( pCur==0 ) return SQLITE_NOMEM;
5592   memset(pCur, 0, sizeof(*pCur));
5593   *ppCursor = &pCur->base;
5594   return SQLITE_OK;
5595 }
5596 
5597 /*
5598 ** Destructor for a series_cursor.
5599 */
seriesClose(sqlite3_vtab_cursor * cur)5600 static int seriesClose(sqlite3_vtab_cursor *cur){
5601   sqlite3_free(cur);
5602   return SQLITE_OK;
5603 }
5604 
5605 
5606 /*
5607 ** Advance a series_cursor to its next row of output.
5608 */
seriesNext(sqlite3_vtab_cursor * cur)5609 static int seriesNext(sqlite3_vtab_cursor *cur){
5610   series_cursor *pCur = (series_cursor*)cur;
5611   if( pCur->isDesc ){
5612     pCur->iValue -= pCur->iStep;
5613   }else{
5614     pCur->iValue += pCur->iStep;
5615   }
5616   pCur->iRowid++;
5617   return SQLITE_OK;
5618 }
5619 
5620 /*
5621 ** Return values of columns for the row at which the series_cursor
5622 ** is currently pointing.
5623 */
seriesColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)5624 static int seriesColumn(
5625   sqlite3_vtab_cursor *cur,   /* The cursor */
5626   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5627   int i                       /* Which column to return */
5628 ){
5629   series_cursor *pCur = (series_cursor*)cur;
5630   sqlite3_int64 x = 0;
5631   switch( i ){
5632     case SERIES_COLUMN_START:  x = pCur->mnValue; break;
5633     case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
5634     case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
5635     default:                   x = pCur->iValue;  break;
5636   }
5637   sqlite3_result_int64(ctx, x);
5638   return SQLITE_OK;
5639 }
5640 
5641 /*
5642 ** Return the rowid for the current row. In this implementation, the
5643 ** first row returned is assigned rowid value 1, and each subsequent
5644 ** row a value 1 more than that of the previous.
5645 */
seriesRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)5646 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5647   series_cursor *pCur = (series_cursor*)cur;
5648   *pRowid = pCur->iRowid;
5649   return SQLITE_OK;
5650 }
5651 
5652 /*
5653 ** Return TRUE if the cursor has been moved off of the last
5654 ** row of output.
5655 */
seriesEof(sqlite3_vtab_cursor * cur)5656 static int seriesEof(sqlite3_vtab_cursor *cur){
5657   series_cursor *pCur = (series_cursor*)cur;
5658   if( pCur->isDesc ){
5659     return pCur->iValue < pCur->mnValue;
5660   }else{
5661     return pCur->iValue > pCur->mxValue;
5662   }
5663 }
5664 
5665 /* True to cause run-time checking of the start=, stop=, and/or step=
5666 ** parameters.  The only reason to do this is for testing the
5667 ** constraint checking logic for virtual tables in the SQLite core.
5668 */
5669 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5670 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5671 #endif
5672 
5673 /*
5674 ** This method is called to "rewind" the series_cursor object back
5675 ** to the first row of output.  This method is always called at least
5676 ** once prior to any call to seriesColumn() or seriesRowid() or
5677 ** seriesEof().
5678 **
5679 ** The query plan selected by seriesBestIndex is passed in the idxNum
5680 ** parameter.  (idxStr is not used in this implementation.)  idxNum
5681 ** is a bitmask showing which constraints are available:
5682 **
5683 **    1:    start=VALUE
5684 **    2:    stop=VALUE
5685 **    4:    step=VALUE
5686 **
5687 ** Also, if bit 8 is set, that means that the series should be output
5688 ** in descending order rather than in ascending order.  If bit 16 is
5689 ** set, then output must appear in ascending order.
5690 **
5691 ** This routine should initialize the cursor and position it so that it
5692 ** is pointing at the first row, or pointing off the end of the table
5693 ** (so that seriesEof() will return true) if the table is empty.
5694 */
seriesFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStrUnused,int argc,sqlite3_value ** argv)5695 static int seriesFilter(
5696   sqlite3_vtab_cursor *pVtabCursor,
5697   int idxNum, const char *idxStrUnused,
5698   int argc, sqlite3_value **argv
5699 ){
5700   series_cursor *pCur = (series_cursor *)pVtabCursor;
5701   int i = 0;
5702   (void)idxStrUnused;
5703   if( idxNum & 1 ){
5704     pCur->mnValue = sqlite3_value_int64(argv[i++]);
5705   }else{
5706     pCur->mnValue = 0;
5707   }
5708   if( idxNum & 2 ){
5709     pCur->mxValue = sqlite3_value_int64(argv[i++]);
5710   }else{
5711     pCur->mxValue = 0xffffffff;
5712   }
5713   if( idxNum & 4 ){
5714     pCur->iStep = sqlite3_value_int64(argv[i++]);
5715     if( pCur->iStep==0 ){
5716       pCur->iStep = 1;
5717     }else if( pCur->iStep<0 ){
5718       pCur->iStep = -pCur->iStep;
5719       if( (idxNum & 16)==0 ) idxNum |= 8;
5720     }
5721   }else{
5722     pCur->iStep = 1;
5723   }
5724   for(i=0; i<argc; i++){
5725     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
5726       /* If any of the constraints have a NULL value, then return no rows.
5727       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
5728       pCur->mnValue = 1;
5729       pCur->mxValue = 0;
5730       break;
5731     }
5732   }
5733   if( idxNum & 8 ){
5734     pCur->isDesc = 1;
5735     pCur->iValue = pCur->mxValue;
5736     if( pCur->iStep>0 ){
5737       pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
5738     }
5739   }else{
5740     pCur->isDesc = 0;
5741     pCur->iValue = pCur->mnValue;
5742   }
5743   pCur->iRowid = 1;
5744   return SQLITE_OK;
5745 }
5746 
5747 /*
5748 ** SQLite will invoke this method one or more times while planning a query
5749 ** that uses the generate_series virtual table.  This routine needs to create
5750 ** a query plan for each invocation and compute an estimated cost for that
5751 ** plan.
5752 **
5753 ** In this implementation idxNum is used to represent the
5754 ** query plan.  idxStr is unused.
5755 **
5756 ** The query plan is represented by bits in idxNum:
5757 **
5758 **  (1)  start = $value  -- constraint exists
5759 **  (2)  stop = $value   -- constraint exists
5760 **  (4)  step = $value   -- constraint exists
5761 **  (8)  output in descending order
5762 */
seriesBestIndex(sqlite3_vtab * tabUnused,sqlite3_index_info * pIdxInfo)5763 static int seriesBestIndex(
5764   sqlite3_vtab *tabUnused,
5765   sqlite3_index_info *pIdxInfo
5766 ){
5767   int i, j;              /* Loop over constraints */
5768   int idxNum = 0;        /* The query plan bitmask */
5769   int unusableMask = 0;  /* Mask of unusable constraints */
5770   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
5771   int aIdx[3];           /* Constraints on start, stop, and step */
5772   const struct sqlite3_index_constraint *pConstraint;
5773 
5774   /* This implementation assumes that the start, stop, and step columns
5775   ** are the last three columns in the virtual table. */
5776   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
5777   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
5778   (void)tabUnused;
5779   aIdx[0] = aIdx[1] = aIdx[2] = -1;
5780   pConstraint = pIdxInfo->aConstraint;
5781   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
5782     int iCol;    /* 0 for start, 1 for stop, 2 for step */
5783     int iMask;   /* bitmask for those column */
5784     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
5785     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
5786     assert( iCol>=0 && iCol<=2 );
5787     iMask = 1 << iCol;
5788     if( pConstraint->usable==0 ){
5789       unusableMask |=  iMask;
5790       continue;
5791     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
5792       idxNum |= iMask;
5793       aIdx[iCol] = i;
5794     }
5795   }
5796   for(i=0; i<3; i++){
5797     if( (j = aIdx[i])>=0 ){
5798       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
5799       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
5800     }
5801   }
5802   if( (unusableMask & ~idxNum)!=0 ){
5803     /* The start, stop, and step columns are inputs.  Therefore if there
5804     ** are unusable constraints on any of start, stop, or step then
5805     ** this plan is unusable */
5806     return SQLITE_CONSTRAINT;
5807   }
5808   if( (idxNum & 3)==3 ){
5809     /* Both start= and stop= boundaries are available.  This is the
5810     ** the preferred case */
5811     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
5812     pIdxInfo->estimatedRows = 1000;
5813     if( pIdxInfo->nOrderBy==1 ){
5814       if( pIdxInfo->aOrderBy[0].desc ){
5815         idxNum |= 8;
5816       }else{
5817         idxNum |= 16;
5818       }
5819       pIdxInfo->orderByConsumed = 1;
5820     }
5821   }else{
5822     /* If either boundary is missing, we have to generate a huge span
5823     ** of numbers.  Make this case very expensive so that the query
5824     ** planner will work hard to avoid it. */
5825     pIdxInfo->estimatedRows = 2147483647;
5826   }
5827   pIdxInfo->idxNum = idxNum;
5828   return SQLITE_OK;
5829 }
5830 
5831 /*
5832 ** This following structure defines all the methods for the
5833 ** generate_series virtual table.
5834 */
5835 static sqlite3_module seriesModule = {
5836   0,                         /* iVersion */
5837   0,                         /* xCreate */
5838   seriesConnect,             /* xConnect */
5839   seriesBestIndex,           /* xBestIndex */
5840   seriesDisconnect,          /* xDisconnect */
5841   0,                         /* xDestroy */
5842   seriesOpen,                /* xOpen - open a cursor */
5843   seriesClose,               /* xClose - close a cursor */
5844   seriesFilter,              /* xFilter - configure scan constraints */
5845   seriesNext,                /* xNext - advance a cursor */
5846   seriesEof,                 /* xEof - check for end of scan */
5847   seriesColumn,              /* xColumn - read data */
5848   seriesRowid,               /* xRowid - read data */
5849   0,                         /* xUpdate */
5850   0,                         /* xBegin */
5851   0,                         /* xSync */
5852   0,                         /* xCommit */
5853   0,                         /* xRollback */
5854   0,                         /* xFindMethod */
5855   0,                         /* xRename */
5856   0,                         /* xSavepoint */
5857   0,                         /* xRelease */
5858   0,                         /* xRollbackTo */
5859   0                          /* xShadowName */
5860 };
5861 
5862 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5863 
5864 #ifdef _WIN32
5865 
5866 #endif
sqlite3_series_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)5867 int sqlite3_series_init(
5868   sqlite3 *db,
5869   char **pzErrMsg,
5870   const sqlite3_api_routines *pApi
5871 ){
5872   int rc = SQLITE_OK;
5873   SQLITE_EXTENSION_INIT2(pApi);
5874 #ifndef SQLITE_OMIT_VIRTUALTABLE
5875   if( sqlite3_libversion_number()<3008012 ){
5876     *pzErrMsg = sqlite3_mprintf(
5877         "generate_series() requires SQLite 3.8.12 or later");
5878     return SQLITE_ERROR;
5879   }
5880   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
5881 #endif
5882   return rc;
5883 }
5884 
5885 /************************* End ../ext/misc/series.c ********************/
5886 /************************* Begin ../ext/misc/regexp.c ******************/
5887 /*
5888 ** 2012-11-13
5889 **
5890 ** The author disclaims copyright to this source code.  In place of
5891 ** a legal notice, here is a blessing:
5892 **
5893 **    May you do good and not evil.
5894 **    May you find forgiveness for yourself and forgive others.
5895 **    May you share freely, never taking more than you give.
5896 **
5897 ******************************************************************************
5898 **
5899 ** The code in this file implements a compact but reasonably
5900 ** efficient regular-expression matcher for posix extended regular
5901 ** expressions against UTF8 text.
5902 **
5903 ** This file is an SQLite extension.  It registers a single function
5904 ** named "regexp(A,B)" where A is the regular expression and B is the
5905 ** string to be matched.  By registering this function, SQLite will also
5906 ** then implement the "B regexp A" operator.  Note that with the function
5907 ** the regular expression comes first, but with the operator it comes
5908 ** second.
5909 **
5910 **  The following regular expression syntax is supported:
5911 **
5912 **     X*      zero or more occurrences of X
5913 **     X+      one or more occurrences of X
5914 **     X?      zero or one occurrences of X
5915 **     X{p,q}  between p and q occurrences of X
5916 **     (X)     match X
5917 **     X|Y     X or Y
5918 **     ^X      X occurring at the beginning of the string
5919 **     X$      X occurring at the end of the string
5920 **     .       Match any single character
5921 **     \c      Character c where c is one of \{}()[]|*+?.
5922 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
5923 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
5924 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
5925 **     [abc]   Any single character from the set abc
5926 **     [^abc]  Any single character not in the set abc
5927 **     [a-z]   Any single character in the range a-z
5928 **     [^a-z]  Any single character not in the range a-z
5929 **     \b      Word boundary
5930 **     \w      Word character.  [A-Za-z0-9_]
5931 **     \W      Non-word character
5932 **     \d      Digit
5933 **     \D      Non-digit
5934 **     \s      Whitespace character
5935 **     \S      Non-whitespace character
5936 **
5937 ** A nondeterministic finite automaton (NFA) is used for matching, so the
5938 ** performance is bounded by O(N*M) where N is the size of the regular
5939 ** expression and M is the size of the input string.  The matcher never
5940 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
5941 ** to p copies of X following by q-p copies of X? and that the size of the
5942 ** regular expression in the O(N*M) performance bound is computed after
5943 ** this expansion.
5944 */
5945 #include <string.h>
5946 #include <stdlib.h>
5947 /* #include "sqlite3ext.h" */
5948 SQLITE_EXTENSION_INIT1
5949 
5950 /*
5951 ** The following #defines change the names of some functions implemented in
5952 ** this file to prevent name collisions with C-library functions of the
5953 ** same name.
5954 */
5955 #define re_match   sqlite3re_match
5956 #define re_compile sqlite3re_compile
5957 #define re_free    sqlite3re_free
5958 
5959 /* The end-of-input character */
5960 #define RE_EOF            0    /* End of input */
5961 
5962 /* The NFA is implemented as sequence of opcodes taken from the following
5963 ** set.  Each opcode has a single integer argument.
5964 */
5965 #define RE_OP_MATCH       1    /* Match the one character in the argument */
5966 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
5967 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
5968 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
5969 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
5970 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
5971 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
5972 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
5973 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
5974 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
5975 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
5976 #define RE_OP_NOTWORD    12    /* Not a perl word character */
5977 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
5978 #define RE_OP_NOTDIGIT   14    /* Not a digit */
5979 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
5980 #define RE_OP_NOTSPACE   16    /* Not a digit */
5981 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
5982 
5983 /* Each opcode is a "state" in the NFA */
5984 typedef unsigned short ReStateNumber;
5985 
5986 /* Because this is an NFA and not a DFA, multiple states can be active at
5987 ** once.  An instance of the following object records all active states in
5988 ** the NFA.  The implementation is optimized for the common case where the
5989 ** number of actives states is small.
5990 */
5991 typedef struct ReStateSet {
5992   unsigned nState;            /* Number of current states */
5993   ReStateNumber *aState;      /* Current states */
5994 } ReStateSet;
5995 
5996 /* An input string read one character at a time.
5997 */
5998 typedef struct ReInput ReInput;
5999 struct ReInput {
6000   const unsigned char *z;  /* All text */
6001   int i;                   /* Next byte to read */
6002   int mx;                  /* EOF when i>=mx */
6003 };
6004 
6005 /* A compiled NFA (or an NFA that is in the process of being compiled) is
6006 ** an instance of the following object.
6007 */
6008 typedef struct ReCompiled ReCompiled;
6009 struct ReCompiled {
6010   ReInput sIn;                /* Regular expression text */
6011   const char *zErr;           /* Error message to return */
6012   char *aOp;                  /* Operators for the virtual machine */
6013   int *aArg;                  /* Arguments to each operator */
6014   unsigned (*xNextChar)(ReInput*);  /* Next character function */
6015   unsigned char zInit[12];    /* Initial text to match */
6016   int nInit;                  /* Number of characters in zInit */
6017   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
6018   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
6019 };
6020 
6021 /* Add a state to the given state set if it is not already there */
re_add_state(ReStateSet * pSet,int newState)6022 static void re_add_state(ReStateSet *pSet, int newState){
6023   unsigned i;
6024   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
6025   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
6026 }
6027 
6028 /* Extract the next unicode character from *pzIn and return it.  Advance
6029 ** *pzIn to the first byte past the end of the character returned.  To
6030 ** be clear:  this routine converts utf8 to unicode.  This routine is
6031 ** optimized for the common case where the next character is a single byte.
6032 */
re_next_char(ReInput * p)6033 static unsigned re_next_char(ReInput *p){
6034   unsigned c;
6035   if( p->i>=p->mx ) return 0;
6036   c = p->z[p->i++];
6037   if( c>=0x80 ){
6038     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
6039       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
6040       if( c<0x80 ) c = 0xfffd;
6041     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
6042            && (p->z[p->i+1]&0xc0)==0x80 ){
6043       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
6044       p->i += 2;
6045       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
6046     }else if( (c&0xf8)==0xf0 && p->i+3<p->mx && (p->z[p->i]&0xc0)==0x80
6047            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
6048       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
6049                        | (p->z[p->i+2]&0x3f);
6050       p->i += 3;
6051       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
6052     }else{
6053       c = 0xfffd;
6054     }
6055   }
6056   return c;
6057 }
re_next_char_nocase(ReInput * p)6058 static unsigned re_next_char_nocase(ReInput *p){
6059   unsigned c = re_next_char(p);
6060   if( c>='A' && c<='Z' ) c += 'a' - 'A';
6061   return c;
6062 }
6063 
6064 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
re_word_char(int c)6065 static int re_word_char(int c){
6066   return (c>='0' && c<='9') || (c>='a' && c<='z')
6067       || (c>='A' && c<='Z') || c=='_';
6068 }
6069 
6070 /* Return true if c is a "digit" character:  [0-9] */
re_digit_char(int c)6071 static int re_digit_char(int c){
6072   return (c>='0' && c<='9');
6073 }
6074 
6075 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
re_space_char(int c)6076 static int re_space_char(int c){
6077   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
6078 }
6079 
6080 /* Run a compiled regular expression on the zero-terminated input
6081 ** string zIn[].  Return true on a match and false if there is no match.
6082 */
re_match(ReCompiled * pRe,const unsigned char * zIn,int nIn)6083 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
6084   ReStateSet aStateSet[2], *pThis, *pNext;
6085   ReStateNumber aSpace[100];
6086   ReStateNumber *pToFree;
6087   unsigned int i = 0;
6088   unsigned int iSwap = 0;
6089   int c = RE_EOF+1;
6090   int cPrev = 0;
6091   int rc = 0;
6092   ReInput in;
6093 
6094   in.z = zIn;
6095   in.i = 0;
6096   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
6097 
6098   /* Look for the initial prefix match, if there is one. */
6099   if( pRe->nInit ){
6100     unsigned char x = pRe->zInit[0];
6101     while( in.i+pRe->nInit<=in.mx
6102      && (zIn[in.i]!=x ||
6103          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
6104     ){
6105       in.i++;
6106     }
6107     if( in.i+pRe->nInit>in.mx ) return 0;
6108   }
6109 
6110   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
6111     pToFree = 0;
6112     aStateSet[0].aState = aSpace;
6113   }else{
6114     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
6115     if( pToFree==0 ) return -1;
6116     aStateSet[0].aState = pToFree;
6117   }
6118   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
6119   pNext = &aStateSet[1];
6120   pNext->nState = 0;
6121   re_add_state(pNext, 0);
6122   while( c!=RE_EOF && pNext->nState>0 ){
6123     cPrev = c;
6124     c = pRe->xNextChar(&in);
6125     pThis = pNext;
6126     pNext = &aStateSet[iSwap];
6127     iSwap = 1 - iSwap;
6128     pNext->nState = 0;
6129     for(i=0; i<pThis->nState; i++){
6130       int x = pThis->aState[i];
6131       switch( pRe->aOp[x] ){
6132         case RE_OP_MATCH: {
6133           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
6134           break;
6135         }
6136         case RE_OP_ANY: {
6137           if( c!=0 ) re_add_state(pNext, x+1);
6138           break;
6139         }
6140         case RE_OP_WORD: {
6141           if( re_word_char(c) ) re_add_state(pNext, x+1);
6142           break;
6143         }
6144         case RE_OP_NOTWORD: {
6145           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
6146           break;
6147         }
6148         case RE_OP_DIGIT: {
6149           if( re_digit_char(c) ) re_add_state(pNext, x+1);
6150           break;
6151         }
6152         case RE_OP_NOTDIGIT: {
6153           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
6154           break;
6155         }
6156         case RE_OP_SPACE: {
6157           if( re_space_char(c) ) re_add_state(pNext, x+1);
6158           break;
6159         }
6160         case RE_OP_NOTSPACE: {
6161           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
6162           break;
6163         }
6164         case RE_OP_BOUNDARY: {
6165           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
6166           break;
6167         }
6168         case RE_OP_ANYSTAR: {
6169           re_add_state(pNext, x);
6170           re_add_state(pThis, x+1);
6171           break;
6172         }
6173         case RE_OP_FORK: {
6174           re_add_state(pThis, x+pRe->aArg[x]);
6175           re_add_state(pThis, x+1);
6176           break;
6177         }
6178         case RE_OP_GOTO: {
6179           re_add_state(pThis, x+pRe->aArg[x]);
6180           break;
6181         }
6182         case RE_OP_ACCEPT: {
6183           rc = 1;
6184           goto re_match_end;
6185         }
6186         case RE_OP_CC_EXC: {
6187           if( c==0 ) break;
6188           /* fall-through */
6189         }
6190         case RE_OP_CC_INC: {
6191           int j = 1;
6192           int n = pRe->aArg[x];
6193           int hit = 0;
6194           for(j=1; j>0 && j<n; j++){
6195             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
6196               if( pRe->aArg[x+j]==c ){
6197                 hit = 1;
6198                 j = -1;
6199               }
6200             }else{
6201               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
6202                 hit = 1;
6203                 j = -1;
6204               }else{
6205                 j++;
6206               }
6207             }
6208           }
6209           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
6210           if( hit ) re_add_state(pNext, x+n);
6211           break;
6212         }
6213       }
6214     }
6215   }
6216   for(i=0; i<pNext->nState; i++){
6217     if( pRe->aOp[pNext->aState[i]]==RE_OP_ACCEPT ){ rc = 1; break; }
6218   }
6219 re_match_end:
6220   sqlite3_free(pToFree);
6221   return rc;
6222 }
6223 
6224 /* Resize the opcode and argument arrays for an RE under construction.
6225 */
re_resize(ReCompiled * p,int N)6226 static int re_resize(ReCompiled *p, int N){
6227   char *aOp;
6228   int *aArg;
6229   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
6230   if( aOp==0 ) return 1;
6231   p->aOp = aOp;
6232   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
6233   if( aArg==0 ) return 1;
6234   p->aArg = aArg;
6235   p->nAlloc = N;
6236   return 0;
6237 }
6238 
6239 /* Insert a new opcode and argument into an RE under construction.  The
6240 ** insertion point is just prior to existing opcode iBefore.
6241 */
re_insert(ReCompiled * p,int iBefore,int op,int arg)6242 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
6243   int i;
6244   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
6245   for(i=p->nState; i>iBefore; i--){
6246     p->aOp[i] = p->aOp[i-1];
6247     p->aArg[i] = p->aArg[i-1];
6248   }
6249   p->nState++;
6250   p->aOp[iBefore] = (char)op;
6251   p->aArg[iBefore] = arg;
6252   return iBefore;
6253 }
6254 
6255 /* Append a new opcode and argument to the end of the RE under construction.
6256 */
re_append(ReCompiled * p,int op,int arg)6257 static int re_append(ReCompiled *p, int op, int arg){
6258   return re_insert(p, p->nState, op, arg);
6259 }
6260 
6261 /* Make a copy of N opcodes starting at iStart onto the end of the RE
6262 ** under construction.
6263 */
re_copy(ReCompiled * p,int iStart,int N)6264 static void re_copy(ReCompiled *p, int iStart, int N){
6265   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
6266   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
6267   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
6268   p->nState += N;
6269 }
6270 
6271 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
6272 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
6273 ** c is not a hex digit *pV is unchanged.
6274 */
re_hex(int c,int * pV)6275 static int re_hex(int c, int *pV){
6276   if( c>='0' && c<='9' ){
6277     c -= '0';
6278   }else if( c>='a' && c<='f' ){
6279     c -= 'a' - 10;
6280   }else if( c>='A' && c<='F' ){
6281     c -= 'A' - 10;
6282   }else{
6283     return 0;
6284   }
6285   *pV = (*pV)*16 + (c & 0xff);
6286   return 1;
6287 }
6288 
6289 /* A backslash character has been seen, read the next character and
6290 ** return its interpretation.
6291 */
re_esc_char(ReCompiled * p)6292 static unsigned re_esc_char(ReCompiled *p){
6293   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
6294   static const char zTrans[] = "\a\f\n\r\t\v";
6295   int i, v = 0;
6296   char c;
6297   if( p->sIn.i>=p->sIn.mx ) return 0;
6298   c = p->sIn.z[p->sIn.i];
6299   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
6300     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6301     if( re_hex(zIn[1],&v)
6302      && re_hex(zIn[2],&v)
6303      && re_hex(zIn[3],&v)
6304      && re_hex(zIn[4],&v)
6305     ){
6306       p->sIn.i += 5;
6307       return v;
6308     }
6309   }
6310   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
6311     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6312     if( re_hex(zIn[1],&v)
6313      && re_hex(zIn[2],&v)
6314     ){
6315       p->sIn.i += 3;
6316       return v;
6317     }
6318   }
6319   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
6320   if( zEsc[i] ){
6321     if( i<6 ) c = zTrans[i];
6322     p->sIn.i++;
6323   }else{
6324     p->zErr = "unknown \\ escape";
6325   }
6326   return c;
6327 }
6328 
6329 /* Forward declaration */
6330 static const char *re_subcompile_string(ReCompiled*);
6331 
6332 /* Peek at the next byte of input */
rePeek(ReCompiled * p)6333 static unsigned char rePeek(ReCompiled *p){
6334   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
6335 }
6336 
6337 /* Compile RE text into a sequence of opcodes.  Continue up to the
6338 ** first unmatched ")" character, then return.  If an error is found,
6339 ** return a pointer to the error message string.
6340 */
re_subcompile_re(ReCompiled * p)6341 static const char *re_subcompile_re(ReCompiled *p){
6342   const char *zErr;
6343   int iStart, iEnd, iGoto;
6344   iStart = p->nState;
6345   zErr = re_subcompile_string(p);
6346   if( zErr ) return zErr;
6347   while( rePeek(p)=='|' ){
6348     iEnd = p->nState;
6349     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
6350     iGoto = re_append(p, RE_OP_GOTO, 0);
6351     p->sIn.i++;
6352     zErr = re_subcompile_string(p);
6353     if( zErr ) return zErr;
6354     p->aArg[iGoto] = p->nState - iGoto;
6355   }
6356   return 0;
6357 }
6358 
6359 /* Compile an element of regular expression text (anything that can be
6360 ** an operand to the "|" operator).  Return NULL on success or a pointer
6361 ** to the error message if there is a problem.
6362 */
re_subcompile_string(ReCompiled * p)6363 static const char *re_subcompile_string(ReCompiled *p){
6364   int iPrev = -1;
6365   int iStart;
6366   unsigned c;
6367   const char *zErr;
6368   while( (c = p->xNextChar(&p->sIn))!=0 ){
6369     iStart = p->nState;
6370     switch( c ){
6371       case '|':
6372       case '$':
6373       case ')': {
6374         p->sIn.i--;
6375         return 0;
6376       }
6377       case '(': {
6378         zErr = re_subcompile_re(p);
6379         if( zErr ) return zErr;
6380         if( rePeek(p)!=')' ) return "unmatched '('";
6381         p->sIn.i++;
6382         break;
6383       }
6384       case '.': {
6385         if( rePeek(p)=='*' ){
6386           re_append(p, RE_OP_ANYSTAR, 0);
6387           p->sIn.i++;
6388         }else{
6389           re_append(p, RE_OP_ANY, 0);
6390         }
6391         break;
6392       }
6393       case '*': {
6394         if( iPrev<0 ) return "'*' without operand";
6395         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
6396         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
6397         break;
6398       }
6399       case '+': {
6400         if( iPrev<0 ) return "'+' without operand";
6401         re_append(p, RE_OP_FORK, iPrev - p->nState);
6402         break;
6403       }
6404       case '?': {
6405         if( iPrev<0 ) return "'?' without operand";
6406         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
6407         break;
6408       }
6409       case '{': {
6410         int m = 0, n = 0;
6411         int sz, j;
6412         if( iPrev<0 ) return "'{m,n}' without operand";
6413         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
6414         n = m;
6415         if( c==',' ){
6416           p->sIn.i++;
6417           n = 0;
6418           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
6419         }
6420         if( c!='}' ) return "unmatched '{'";
6421         if( n>0 && n<m ) return "n less than m in '{m,n}'";
6422         p->sIn.i++;
6423         sz = p->nState - iPrev;
6424         if( m==0 ){
6425           if( n==0 ) return "both m and n are zero in '{m,n}'";
6426           re_insert(p, iPrev, RE_OP_FORK, sz+1);
6427           n--;
6428         }else{
6429           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
6430         }
6431         for(j=m; j<n; j++){
6432           re_append(p, RE_OP_FORK, sz+1);
6433           re_copy(p, iPrev, sz);
6434         }
6435         if( n==0 && m>0 ){
6436           re_append(p, RE_OP_FORK, -sz);
6437         }
6438         break;
6439       }
6440       case '[': {
6441         int iFirst = p->nState;
6442         if( rePeek(p)=='^' ){
6443           re_append(p, RE_OP_CC_EXC, 0);
6444           p->sIn.i++;
6445         }else{
6446           re_append(p, RE_OP_CC_INC, 0);
6447         }
6448         while( (c = p->xNextChar(&p->sIn))!=0 ){
6449           if( c=='[' && rePeek(p)==':' ){
6450             return "POSIX character classes not supported";
6451           }
6452           if( c=='\\' ) c = re_esc_char(p);
6453           if( rePeek(p)=='-' ){
6454             re_append(p, RE_OP_CC_RANGE, c);
6455             p->sIn.i++;
6456             c = p->xNextChar(&p->sIn);
6457             if( c=='\\' ) c = re_esc_char(p);
6458             re_append(p, RE_OP_CC_RANGE, c);
6459           }else{
6460             re_append(p, RE_OP_CC_VALUE, c);
6461           }
6462           if( rePeek(p)==']' ){ p->sIn.i++; break; }
6463         }
6464         if( c==0 ) return "unclosed '['";
6465         p->aArg[iFirst] = p->nState - iFirst;
6466         break;
6467       }
6468       case '\\': {
6469         int specialOp = 0;
6470         switch( rePeek(p) ){
6471           case 'b': specialOp = RE_OP_BOUNDARY;   break;
6472           case 'd': specialOp = RE_OP_DIGIT;      break;
6473           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
6474           case 's': specialOp = RE_OP_SPACE;      break;
6475           case 'S': specialOp = RE_OP_NOTSPACE;   break;
6476           case 'w': specialOp = RE_OP_WORD;       break;
6477           case 'W': specialOp = RE_OP_NOTWORD;    break;
6478         }
6479         if( specialOp ){
6480           p->sIn.i++;
6481           re_append(p, specialOp, 0);
6482         }else{
6483           c = re_esc_char(p);
6484           re_append(p, RE_OP_MATCH, c);
6485         }
6486         break;
6487       }
6488       default: {
6489         re_append(p, RE_OP_MATCH, c);
6490         break;
6491       }
6492     }
6493     iPrev = iStart;
6494   }
6495   return 0;
6496 }
6497 
6498 /* Free and reclaim all the memory used by a previously compiled
6499 ** regular expression.  Applications should invoke this routine once
6500 ** for every call to re_compile() to avoid memory leaks.
6501 */
re_free(ReCompiled * pRe)6502 static void re_free(ReCompiled *pRe){
6503   if( pRe ){
6504     sqlite3_free(pRe->aOp);
6505     sqlite3_free(pRe->aArg);
6506     sqlite3_free(pRe);
6507   }
6508 }
6509 
6510 /*
6511 ** Compile a textual regular expression in zIn[] into a compiled regular
6512 ** expression suitable for us by re_match() and return a pointer to the
6513 ** compiled regular expression in *ppRe.  Return NULL on success or an
6514 ** error message if something goes wrong.
6515 */
re_compile(ReCompiled ** ppRe,const char * zIn,int noCase)6516 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
6517   ReCompiled *pRe;
6518   const char *zErr;
6519   int i, j;
6520 
6521   *ppRe = 0;
6522   pRe = sqlite3_malloc( sizeof(*pRe) );
6523   if( pRe==0 ){
6524     return "out of memory";
6525   }
6526   memset(pRe, 0, sizeof(*pRe));
6527   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
6528   if( re_resize(pRe, 30) ){
6529     re_free(pRe);
6530     return "out of memory";
6531   }
6532   if( zIn[0]=='^' ){
6533     zIn++;
6534   }else{
6535     re_append(pRe, RE_OP_ANYSTAR, 0);
6536   }
6537   pRe->sIn.z = (unsigned char*)zIn;
6538   pRe->sIn.i = 0;
6539   pRe->sIn.mx = (int)strlen(zIn);
6540   zErr = re_subcompile_re(pRe);
6541   if( zErr ){
6542     re_free(pRe);
6543     return zErr;
6544   }
6545   if( rePeek(pRe)=='$' && pRe->sIn.i+1>=pRe->sIn.mx ){
6546     re_append(pRe, RE_OP_MATCH, RE_EOF);
6547     re_append(pRe, RE_OP_ACCEPT, 0);
6548     *ppRe = pRe;
6549   }else if( pRe->sIn.i>=pRe->sIn.mx ){
6550     re_append(pRe, RE_OP_ACCEPT, 0);
6551     *ppRe = pRe;
6552   }else{
6553     re_free(pRe);
6554     return "unrecognized character";
6555   }
6556 
6557   /* The following is a performance optimization.  If the regex begins with
6558   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
6559   ** one or more matching characters, enter those matching characters into
6560   ** zInit[].  The re_match() routine can then search ahead in the input
6561   ** string looking for the initial match without having to run the whole
6562   ** regex engine over the string.  Do not worry able trying to match
6563   ** unicode characters beyond plane 0 - those are very rare and this is
6564   ** just an optimization. */
6565   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
6566     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
6567       unsigned x = pRe->aArg[i];
6568       if( x<=127 ){
6569         pRe->zInit[j++] = (unsigned char)x;
6570       }else if( x<=0xfff ){
6571         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
6572         pRe->zInit[j++] = 0x80 | (x&0x3f);
6573       }else if( x<=0xffff ){
6574         pRe->zInit[j++] = (unsigned char)(0xd0 | (x>>12));
6575         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
6576         pRe->zInit[j++] = 0x80 | (x&0x3f);
6577       }else{
6578         break;
6579       }
6580     }
6581     if( j>0 && pRe->zInit[j-1]==0 ) j--;
6582     pRe->nInit = j;
6583   }
6584   return pRe->zErr;
6585 }
6586 
6587 /*
6588 ** Implementation of the regexp() SQL function.  This function implements
6589 ** the build-in REGEXP operator.  The first argument to the function is the
6590 ** pattern and the second argument is the string.  So, the SQL statements:
6591 **
6592 **       A REGEXP B
6593 **
6594 ** is implemented as regexp(B,A).
6595 */
re_sql_func(sqlite3_context * context,int argc,sqlite3_value ** argv)6596 static void re_sql_func(
6597   sqlite3_context *context,
6598   int argc,
6599   sqlite3_value **argv
6600 ){
6601   ReCompiled *pRe;          /* Compiled regular expression */
6602   const char *zPattern;     /* The regular expression */
6603   const unsigned char *zStr;/* String being searched */
6604   const char *zErr;         /* Compile error message */
6605   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
6606 
6607   (void)argc;  /* Unused */
6608   pRe = sqlite3_get_auxdata(context, 0);
6609   if( pRe==0 ){
6610     zPattern = (const char*)sqlite3_value_text(argv[0]);
6611     if( zPattern==0 ) return;
6612     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
6613     if( zErr ){
6614       re_free(pRe);
6615       sqlite3_result_error(context, zErr, -1);
6616       return;
6617     }
6618     if( pRe==0 ){
6619       sqlite3_result_error_nomem(context);
6620       return;
6621     }
6622     setAux = 1;
6623   }
6624   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
6625   if( zStr!=0 ){
6626     sqlite3_result_int(context, re_match(pRe, zStr, -1));
6627   }
6628   if( setAux ){
6629     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
6630   }
6631 }
6632 
6633 /*
6634 ** Invoke this routine to register the regexp() function with the
6635 ** SQLite database connection.
6636 */
6637 #ifdef _WIN32
6638 
6639 #endif
sqlite3_regexp_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)6640 int sqlite3_regexp_init(
6641   sqlite3 *db,
6642   char **pzErrMsg,
6643   const sqlite3_api_routines *pApi
6644 ){
6645   int rc = SQLITE_OK;
6646   SQLITE_EXTENSION_INIT2(pApi);
6647   (void)pzErrMsg;  /* Unused */
6648   rc = sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8|SQLITE_INNOCUOUS,
6649                                0, re_sql_func, 0, 0);
6650   if( rc==SQLITE_OK ){
6651     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
6652     ** of regexp(PATTERN,STRING). */
6653     rc = sqlite3_create_function(db, "regexpi", 2, SQLITE_UTF8|SQLITE_INNOCUOUS,
6654                                  (void*)db, re_sql_func, 0, 0);
6655   }
6656   return rc;
6657 }
6658 
6659 /************************* End ../ext/misc/regexp.c ********************/
6660 #ifdef SQLITE_HAVE_ZLIB
6661 /************************* Begin ../ext/misc/zipfile.c ******************/
6662 /*
6663 ** 2017-12-26
6664 **
6665 ** The author disclaims copyright to this source code.  In place of
6666 ** a legal notice, here is a blessing:
6667 **
6668 **    May you do good and not evil.
6669 **    May you find forgiveness for yourself and forgive others.
6670 **    May you share freely, never taking more than you give.
6671 **
6672 ******************************************************************************
6673 **
6674 ** This file implements a virtual table for reading and writing ZIP archive
6675 ** files.
6676 **
6677 ** Usage example:
6678 **
6679 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
6680 **
6681 ** Current limitations:
6682 **
6683 **    *  No support for encryption
6684 **    *  No support for ZIP archives spanning multiple files
6685 **    *  No support for zip64 extensions
6686 **    *  Only the "inflate/deflate" (zlib) compression method is supported
6687 */
6688 /* #include "sqlite3ext.h" */
6689 SQLITE_EXTENSION_INIT1
6690 #include <stdio.h>
6691 #include <string.h>
6692 #include <assert.h>
6693 
6694 #include <zlib.h>
6695 
6696 #ifndef SQLITE_OMIT_VIRTUALTABLE
6697 
6698 #ifndef SQLITE_AMALGAMATION
6699 
6700 #ifndef UINT32_TYPE
6701 # ifdef HAVE_UINT32_T
6702 #  define UINT32_TYPE uint32_t
6703 # else
6704 #  define UINT32_TYPE unsigned int
6705 # endif
6706 #endif
6707 #ifndef UINT16_TYPE
6708 # ifdef HAVE_UINT16_T
6709 #  define UINT16_TYPE uint16_t
6710 # else
6711 #  define UINT16_TYPE unsigned short int
6712 # endif
6713 #endif
6714 /* typedef sqlite3_int64 i64; */
6715 /* typedef unsigned char u8; */
6716 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6717 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6718 #define MIN(a,b) ((a)<(b) ? (a) : (b))
6719 
6720 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
6721 # define ALWAYS(X)      (1)
6722 # define NEVER(X)       (0)
6723 #elif !defined(NDEBUG)
6724 # define ALWAYS(X)      ((X)?1:(assert(0),0))
6725 # define NEVER(X)       ((X)?(assert(0),1):0)
6726 #else
6727 # define ALWAYS(X)      (X)
6728 # define NEVER(X)       (X)
6729 #endif
6730 
6731 #endif   /* SQLITE_AMALGAMATION */
6732 
6733 /*
6734 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
6735 **
6736 ** In some ways it would be better to obtain these values from system
6737 ** header files. But, the dependency is undesirable and (a) these
6738 ** have been stable for decades, (b) the values are part of POSIX and
6739 ** are also made explicit in [man stat], and (c) are part of the
6740 ** file format for zip archives.
6741 */
6742 #ifndef S_IFDIR
6743 # define S_IFDIR 0040000
6744 #endif
6745 #ifndef S_IFREG
6746 # define S_IFREG 0100000
6747 #endif
6748 #ifndef S_IFLNK
6749 # define S_IFLNK 0120000
6750 #endif
6751 
6752 static const char ZIPFILE_SCHEMA[] =
6753   "CREATE TABLE y("
6754     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
6755     "mode,"              /* 1: POSIX mode for file */
6756     "mtime,"             /* 2: Last modification time (secs since 1970)*/
6757     "sz,"                /* 3: Size of object */
6758     "rawdata,"           /* 4: Raw data */
6759     "data,"              /* 5: Uncompressed data */
6760     "method,"            /* 6: Compression method (integer) */
6761     "z HIDDEN"           /* 7: Name of zip file */
6762   ") WITHOUT ROWID;";
6763 
6764 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
6765 #define ZIPFILE_BUFFER_SIZE (64*1024)
6766 
6767 
6768 /*
6769 ** Magic numbers used to read and write zip files.
6770 **
6771 ** ZIPFILE_NEWENTRY_MADEBY:
6772 **   Use this value for the "version-made-by" field in new zip file
6773 **   entries. The upper byte indicates "unix", and the lower byte
6774 **   indicates that the zip file matches pkzip specification 3.0.
6775 **   This is what info-zip seems to do.
6776 **
6777 ** ZIPFILE_NEWENTRY_REQUIRED:
6778 **   Value for "version-required-to-extract" field of new entries.
6779 **   Version 2.0 is required to support folders and deflate compression.
6780 **
6781 ** ZIPFILE_NEWENTRY_FLAGS:
6782 **   Value for "general-purpose-bit-flags" field of new entries. Bit
6783 **   11 means "utf-8 filename and comment".
6784 **
6785 ** ZIPFILE_SIGNATURE_CDS:
6786 **   First 4 bytes of a valid CDS record.
6787 **
6788 ** ZIPFILE_SIGNATURE_LFH:
6789 **   First 4 bytes of a valid LFH record.
6790 **
6791 ** ZIPFILE_SIGNATURE_EOCD
6792 **   First 4 bytes of a valid EOCD record.
6793 */
6794 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
6795 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
6796 #define ZIPFILE_NEWENTRY_REQUIRED 20
6797 #define ZIPFILE_NEWENTRY_FLAGS    0x800
6798 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
6799 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
6800 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
6801 
6802 /*
6803 ** The sizes of the fixed-size part of each of the three main data
6804 ** structures in a zip archive.
6805 */
6806 #define ZIPFILE_LFH_FIXED_SZ      30
6807 #define ZIPFILE_EOCD_FIXED_SZ     22
6808 #define ZIPFILE_CDS_FIXED_SZ      46
6809 
6810 /*
6811 *** 4.3.16  End of central directory record:
6812 ***
6813 ***   end of central dir signature    4 bytes  (0x06054b50)
6814 ***   number of this disk             2 bytes
6815 ***   number of the disk with the
6816 ***   start of the central directory  2 bytes
6817 ***   total number of entries in the
6818 ***   central directory on this disk  2 bytes
6819 ***   total number of entries in
6820 ***   the central directory           2 bytes
6821 ***   size of the central directory   4 bytes
6822 ***   offset of start of central
6823 ***   directory with respect to
6824 ***   the starting disk number        4 bytes
6825 ***   .ZIP file comment length        2 bytes
6826 ***   .ZIP file comment       (variable size)
6827 */
6828 typedef struct ZipfileEOCD ZipfileEOCD;
6829 struct ZipfileEOCD {
6830   u16 iDisk;
6831   u16 iFirstDisk;
6832   u16 nEntry;
6833   u16 nEntryTotal;
6834   u32 nSize;
6835   u32 iOffset;
6836 };
6837 
6838 /*
6839 *** 4.3.12  Central directory structure:
6840 ***
6841 *** ...
6842 ***
6843 ***   central file header signature   4 bytes  (0x02014b50)
6844 ***   version made by                 2 bytes
6845 ***   version needed to extract       2 bytes
6846 ***   general purpose bit flag        2 bytes
6847 ***   compression method              2 bytes
6848 ***   last mod file time              2 bytes
6849 ***   last mod file date              2 bytes
6850 ***   crc-32                          4 bytes
6851 ***   compressed size                 4 bytes
6852 ***   uncompressed size               4 bytes
6853 ***   file name length                2 bytes
6854 ***   extra field length              2 bytes
6855 ***   file comment length             2 bytes
6856 ***   disk number start               2 bytes
6857 ***   internal file attributes        2 bytes
6858 ***   external file attributes        4 bytes
6859 ***   relative offset of local header 4 bytes
6860 */
6861 typedef struct ZipfileCDS ZipfileCDS;
6862 struct ZipfileCDS {
6863   u16 iVersionMadeBy;
6864   u16 iVersionExtract;
6865   u16 flags;
6866   u16 iCompression;
6867   u16 mTime;
6868   u16 mDate;
6869   u32 crc32;
6870   u32 szCompressed;
6871   u32 szUncompressed;
6872   u16 nFile;
6873   u16 nExtra;
6874   u16 nComment;
6875   u16 iDiskStart;
6876   u16 iInternalAttr;
6877   u32 iExternalAttr;
6878   u32 iOffset;
6879   char *zFile;                    /* Filename (sqlite3_malloc()) */
6880 };
6881 
6882 /*
6883 *** 4.3.7  Local file header:
6884 ***
6885 ***   local file header signature     4 bytes  (0x04034b50)
6886 ***   version needed to extract       2 bytes
6887 ***   general purpose bit flag        2 bytes
6888 ***   compression method              2 bytes
6889 ***   last mod file time              2 bytes
6890 ***   last mod file date              2 bytes
6891 ***   crc-32                          4 bytes
6892 ***   compressed size                 4 bytes
6893 ***   uncompressed size               4 bytes
6894 ***   file name length                2 bytes
6895 ***   extra field length              2 bytes
6896 ***
6897 */
6898 typedef struct ZipfileLFH ZipfileLFH;
6899 struct ZipfileLFH {
6900   u16 iVersionExtract;
6901   u16 flags;
6902   u16 iCompression;
6903   u16 mTime;
6904   u16 mDate;
6905   u32 crc32;
6906   u32 szCompressed;
6907   u32 szUncompressed;
6908   u16 nFile;
6909   u16 nExtra;
6910 };
6911 
6912 typedef struct ZipfileEntry ZipfileEntry;
6913 struct ZipfileEntry {
6914   ZipfileCDS cds;            /* Parsed CDS record */
6915   u32 mUnixTime;             /* Modification time, in UNIX format */
6916   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
6917   i64 iDataOff;              /* Offset to data in file (if aData==0) */
6918   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
6919   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
6920 };
6921 
6922 /*
6923 ** Cursor type for zipfile tables.
6924 */
6925 typedef struct ZipfileCsr ZipfileCsr;
6926 struct ZipfileCsr {
6927   sqlite3_vtab_cursor base;  /* Base class - must be first */
6928   i64 iId;                   /* Cursor ID */
6929   u8 bEof;                   /* True when at EOF */
6930   u8 bNoop;                  /* If next xNext() call is no-op */
6931 
6932   /* Used outside of write transactions */
6933   FILE *pFile;               /* Zip file */
6934   i64 iNextOff;              /* Offset of next record in central directory */
6935   ZipfileEOCD eocd;          /* Parse of central directory record */
6936 
6937   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
6938   ZipfileEntry *pCurrent;    /* Current entry */
6939   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
6940 };
6941 
6942 typedef struct ZipfileTab ZipfileTab;
6943 struct ZipfileTab {
6944   sqlite3_vtab base;         /* Base class - must be first */
6945   char *zFile;               /* Zip file this table accesses (may be NULL) */
6946   sqlite3 *db;               /* Host database connection */
6947   u8 *aBuffer;               /* Temporary buffer used for various tasks */
6948 
6949   ZipfileCsr *pCsrList;      /* List of cursors */
6950   i64 iNextCsrid;
6951 
6952   /* The following are used by write transactions only */
6953   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
6954   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
6955   FILE *pWriteFd;            /* File handle open on zip archive */
6956   i64 szCurrent;             /* Current size of zip archive */
6957   i64 szOrig;                /* Size of archive at start of transaction */
6958 };
6959 
6960 /*
6961 ** Set the error message contained in context ctx to the results of
6962 ** vprintf(zFmt, ...).
6963 */
zipfileCtxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)6964 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
6965   char *zMsg = 0;
6966   va_list ap;
6967   va_start(ap, zFmt);
6968   zMsg = sqlite3_vmprintf(zFmt, ap);
6969   sqlite3_result_error(ctx, zMsg, -1);
6970   sqlite3_free(zMsg);
6971   va_end(ap);
6972 }
6973 
6974 /*
6975 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
6976 ** is not quoted, do nothing.
6977 */
zipfileDequote(char * zIn)6978 static void zipfileDequote(char *zIn){
6979   char q = zIn[0];
6980   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
6981     int iIn = 1;
6982     int iOut = 0;
6983     if( q=='[' ) q = ']';
6984     while( ALWAYS(zIn[iIn]) ){
6985       char c = zIn[iIn++];
6986       if( c==q && zIn[iIn++]!=q ) break;
6987       zIn[iOut++] = c;
6988     }
6989     zIn[iOut] = '\0';
6990   }
6991 }
6992 
6993 /*
6994 ** Construct a new ZipfileTab virtual table object.
6995 **
6996 **   argv[0]   -> module name  ("zipfile")
6997 **   argv[1]   -> database name
6998 **   argv[2]   -> table name
6999 **   argv[...] -> "column name" and other module argument fields.
7000 */
zipfileConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)7001 static int zipfileConnect(
7002   sqlite3 *db,
7003   void *pAux,
7004   int argc, const char *const*argv,
7005   sqlite3_vtab **ppVtab,
7006   char **pzErr
7007 ){
7008   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
7009   int nFile = 0;
7010   const char *zFile = 0;
7011   ZipfileTab *pNew = 0;
7012   int rc;
7013 
7014   /* If the table name is not "zipfile", require that the argument be
7015   ** specified. This stops zipfile tables from being created as:
7016   **
7017   **   CREATE VIRTUAL TABLE zzz USING zipfile();
7018   **
7019   ** It does not prevent:
7020   **
7021   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
7022   */
7023   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
7024   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
7025     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
7026     return SQLITE_ERROR;
7027   }
7028 
7029   if( argc>3 ){
7030     zFile = argv[3];
7031     nFile = (int)strlen(zFile)+1;
7032   }
7033 
7034   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
7035   if( rc==SQLITE_OK ){
7036     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
7037     if( pNew==0 ) return SQLITE_NOMEM;
7038     memset(pNew, 0, nByte+nFile);
7039     pNew->db = db;
7040     pNew->aBuffer = (u8*)&pNew[1];
7041     if( zFile ){
7042       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
7043       memcpy(pNew->zFile, zFile, nFile);
7044       zipfileDequote(pNew->zFile);
7045     }
7046   }
7047   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
7048   *ppVtab = (sqlite3_vtab*)pNew;
7049   return rc;
7050 }
7051 
7052 /*
7053 ** Free the ZipfileEntry structure indicated by the only argument.
7054 */
zipfileEntryFree(ZipfileEntry * p)7055 static void zipfileEntryFree(ZipfileEntry *p){
7056   if( p ){
7057     sqlite3_free(p->cds.zFile);
7058     sqlite3_free(p);
7059   }
7060 }
7061 
7062 /*
7063 ** Release resources that should be freed at the end of a write
7064 ** transaction.
7065 */
zipfileCleanupTransaction(ZipfileTab * pTab)7066 static void zipfileCleanupTransaction(ZipfileTab *pTab){
7067   ZipfileEntry *pEntry;
7068   ZipfileEntry *pNext;
7069 
7070   if( pTab->pWriteFd ){
7071     fclose(pTab->pWriteFd);
7072     pTab->pWriteFd = 0;
7073   }
7074   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
7075     pNext = pEntry->pNext;
7076     zipfileEntryFree(pEntry);
7077   }
7078   pTab->pFirstEntry = 0;
7079   pTab->pLastEntry = 0;
7080   pTab->szCurrent = 0;
7081   pTab->szOrig = 0;
7082 }
7083 
7084 /*
7085 ** This method is the destructor for zipfile vtab objects.
7086 */
zipfileDisconnect(sqlite3_vtab * pVtab)7087 static int zipfileDisconnect(sqlite3_vtab *pVtab){
7088   zipfileCleanupTransaction((ZipfileTab*)pVtab);
7089   sqlite3_free(pVtab);
7090   return SQLITE_OK;
7091 }
7092 
7093 /*
7094 ** Constructor for a new ZipfileCsr object.
7095 */
zipfileOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCsr)7096 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
7097   ZipfileTab *pTab = (ZipfileTab*)p;
7098   ZipfileCsr *pCsr;
7099   pCsr = sqlite3_malloc(sizeof(*pCsr));
7100   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
7101   if( pCsr==0 ){
7102     return SQLITE_NOMEM;
7103   }
7104   memset(pCsr, 0, sizeof(*pCsr));
7105   pCsr->iId = ++pTab->iNextCsrid;
7106   pCsr->pCsrNext = pTab->pCsrList;
7107   pTab->pCsrList = pCsr;
7108   return SQLITE_OK;
7109 }
7110 
7111 /*
7112 ** Reset a cursor back to the state it was in when first returned
7113 ** by zipfileOpen().
7114 */
zipfileResetCursor(ZipfileCsr * pCsr)7115 static void zipfileResetCursor(ZipfileCsr *pCsr){
7116   ZipfileEntry *p;
7117   ZipfileEntry *pNext;
7118 
7119   pCsr->bEof = 0;
7120   if( pCsr->pFile ){
7121     fclose(pCsr->pFile);
7122     pCsr->pFile = 0;
7123     zipfileEntryFree(pCsr->pCurrent);
7124     pCsr->pCurrent = 0;
7125   }
7126 
7127   for(p=pCsr->pFreeEntry; p; p=pNext){
7128     pNext = p->pNext;
7129     zipfileEntryFree(p);
7130   }
7131 }
7132 
7133 /*
7134 ** Destructor for an ZipfileCsr.
7135 */
zipfileClose(sqlite3_vtab_cursor * cur)7136 static int zipfileClose(sqlite3_vtab_cursor *cur){
7137   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7138   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
7139   ZipfileCsr **pp;
7140   zipfileResetCursor(pCsr);
7141 
7142   /* Remove this cursor from the ZipfileTab.pCsrList list. */
7143   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
7144   *pp = pCsr->pCsrNext;
7145 
7146   sqlite3_free(pCsr);
7147   return SQLITE_OK;
7148 }
7149 
7150 /*
7151 ** Set the error message for the virtual table associated with cursor
7152 ** pCsr to the results of vprintf(zFmt, ...).
7153 */
zipfileTableErr(ZipfileTab * pTab,const char * zFmt,...)7154 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
7155   va_list ap;
7156   va_start(ap, zFmt);
7157   sqlite3_free(pTab->base.zErrMsg);
7158   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
7159   va_end(ap);
7160 }
zipfileCursorErr(ZipfileCsr * pCsr,const char * zFmt,...)7161 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
7162   va_list ap;
7163   va_start(ap, zFmt);
7164   sqlite3_free(pCsr->base.pVtab->zErrMsg);
7165   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7166   va_end(ap);
7167 }
7168 
7169 /*
7170 ** Read nRead bytes of data from offset iOff of file pFile into buffer
7171 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
7172 ** otherwise.
7173 **
7174 ** If an error does occur, output variable (*pzErrmsg) may be set to point
7175 ** to an English language error message. It is the responsibility of the
7176 ** caller to eventually free this buffer using
7177 ** sqlite3_free().
7178 */
zipfileReadData(FILE * pFile,u8 * aRead,int nRead,i64 iOff,char ** pzErrmsg)7179 static int zipfileReadData(
7180   FILE *pFile,                    /* Read from this file */
7181   u8 *aRead,                      /* Read into this buffer */
7182   int nRead,                      /* Number of bytes to read */
7183   i64 iOff,                       /* Offset to read from */
7184   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
7185 ){
7186   size_t n;
7187   fseek(pFile, (long)iOff, SEEK_SET);
7188   n = fread(aRead, 1, nRead, pFile);
7189   if( (int)n!=nRead ){
7190     *pzErrmsg = sqlite3_mprintf("error in fread()");
7191     return SQLITE_ERROR;
7192   }
7193   return SQLITE_OK;
7194 }
7195 
zipfileAppendData(ZipfileTab * pTab,const u8 * aWrite,int nWrite)7196 static int zipfileAppendData(
7197   ZipfileTab *pTab,
7198   const u8 *aWrite,
7199   int nWrite
7200 ){
7201   if( nWrite>0 ){
7202     size_t n = nWrite;
7203     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
7204     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
7205     if( (int)n!=nWrite ){
7206       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
7207       return SQLITE_ERROR;
7208     }
7209     pTab->szCurrent += nWrite;
7210   }
7211   return SQLITE_OK;
7212 }
7213 
7214 /*
7215 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
7216 */
zipfileGetU16(const u8 * aBuf)7217 static u16 zipfileGetU16(const u8 *aBuf){
7218   return (aBuf[1] << 8) + aBuf[0];
7219 }
7220 
7221 /*
7222 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
7223 */
zipfileGetU32(const u8 * aBuf)7224 static u32 zipfileGetU32(const u8 *aBuf){
7225   return ((u32)(aBuf[3]) << 24)
7226        + ((u32)(aBuf[2]) << 16)
7227        + ((u32)(aBuf[1]) <<  8)
7228        + ((u32)(aBuf[0]) <<  0);
7229 }
7230 
7231 /*
7232 ** Write a 16-bit little endiate integer into buffer aBuf.
7233 */
zipfilePutU16(u8 * aBuf,u16 val)7234 static void zipfilePutU16(u8 *aBuf, u16 val){
7235   aBuf[0] = val & 0xFF;
7236   aBuf[1] = (val>>8) & 0xFF;
7237 }
7238 
7239 /*
7240 ** Write a 32-bit little endiate integer into buffer aBuf.
7241 */
zipfilePutU32(u8 * aBuf,u32 val)7242 static void zipfilePutU32(u8 *aBuf, u32 val){
7243   aBuf[0] = val & 0xFF;
7244   aBuf[1] = (val>>8) & 0xFF;
7245   aBuf[2] = (val>>16) & 0xFF;
7246   aBuf[3] = (val>>24) & 0xFF;
7247 }
7248 
7249 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
7250 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
7251 
7252 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
7253 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
7254 
7255 /*
7256 ** Magic numbers used to read CDS records.
7257 */
7258 #define ZIPFILE_CDS_NFILE_OFF        28
7259 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
7260 
7261 /*
7262 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
7263 ** if the record is not well-formed, or SQLITE_OK otherwise.
7264 */
zipfileReadCDS(u8 * aBuf,ZipfileCDS * pCDS)7265 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
7266   u8 *aRead = aBuf;
7267   u32 sig = zipfileRead32(aRead);
7268   int rc = SQLITE_OK;
7269   if( sig!=ZIPFILE_SIGNATURE_CDS ){
7270     rc = SQLITE_ERROR;
7271   }else{
7272     pCDS->iVersionMadeBy = zipfileRead16(aRead);
7273     pCDS->iVersionExtract = zipfileRead16(aRead);
7274     pCDS->flags = zipfileRead16(aRead);
7275     pCDS->iCompression = zipfileRead16(aRead);
7276     pCDS->mTime = zipfileRead16(aRead);
7277     pCDS->mDate = zipfileRead16(aRead);
7278     pCDS->crc32 = zipfileRead32(aRead);
7279     pCDS->szCompressed = zipfileRead32(aRead);
7280     pCDS->szUncompressed = zipfileRead32(aRead);
7281     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
7282     pCDS->nFile = zipfileRead16(aRead);
7283     pCDS->nExtra = zipfileRead16(aRead);
7284     pCDS->nComment = zipfileRead16(aRead);
7285     pCDS->iDiskStart = zipfileRead16(aRead);
7286     pCDS->iInternalAttr = zipfileRead16(aRead);
7287     pCDS->iExternalAttr = zipfileRead32(aRead);
7288     pCDS->iOffset = zipfileRead32(aRead);
7289     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
7290   }
7291 
7292   return rc;
7293 }
7294 
7295 /*
7296 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
7297 ** if the record is not well-formed, or SQLITE_OK otherwise.
7298 */
zipfileReadLFH(u8 * aBuffer,ZipfileLFH * pLFH)7299 static int zipfileReadLFH(
7300   u8 *aBuffer,
7301   ZipfileLFH *pLFH
7302 ){
7303   u8 *aRead = aBuffer;
7304   int rc = SQLITE_OK;
7305 
7306   u32 sig = zipfileRead32(aRead);
7307   if( sig!=ZIPFILE_SIGNATURE_LFH ){
7308     rc = SQLITE_ERROR;
7309   }else{
7310     pLFH->iVersionExtract = zipfileRead16(aRead);
7311     pLFH->flags = zipfileRead16(aRead);
7312     pLFH->iCompression = zipfileRead16(aRead);
7313     pLFH->mTime = zipfileRead16(aRead);
7314     pLFH->mDate = zipfileRead16(aRead);
7315     pLFH->crc32 = zipfileRead32(aRead);
7316     pLFH->szCompressed = zipfileRead32(aRead);
7317     pLFH->szUncompressed = zipfileRead32(aRead);
7318     pLFH->nFile = zipfileRead16(aRead);
7319     pLFH->nExtra = zipfileRead16(aRead);
7320   }
7321   return rc;
7322 }
7323 
7324 
7325 /*
7326 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
7327 ** Scan through this buffer to find an "extra-timestamp" field. If one
7328 ** exists, extract the 32-bit modification-timestamp from it and store
7329 ** the value in output parameter *pmTime.
7330 **
7331 ** Zero is returned if no extra-timestamp record could be found (and so
7332 ** *pmTime is left unchanged), or non-zero otherwise.
7333 **
7334 ** The general format of an extra field is:
7335 **
7336 **   Header ID    2 bytes
7337 **   Data Size    2 bytes
7338 **   Data         N bytes
7339 */
zipfileScanExtra(u8 * aExtra,int nExtra,u32 * pmTime)7340 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
7341   int ret = 0;
7342   u8 *p = aExtra;
7343   u8 *pEnd = &aExtra[nExtra];
7344 
7345   while( p<pEnd ){
7346     u16 id = zipfileRead16(p);
7347     u16 nByte = zipfileRead16(p);
7348 
7349     switch( id ){
7350       case ZIPFILE_EXTRA_TIMESTAMP: {
7351         u8 b = p[0];
7352         if( b & 0x01 ){     /* 0x01 -> modtime is present */
7353           *pmTime = zipfileGetU32(&p[1]);
7354           ret = 1;
7355         }
7356         break;
7357       }
7358     }
7359 
7360     p += nByte;
7361   }
7362   return ret;
7363 }
7364 
7365 /*
7366 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
7367 ** fields of the CDS structure passed as the only argument to a 32-bit
7368 ** UNIX seconds-since-the-epoch timestamp. Return the result.
7369 **
7370 ** "Standard" MS-DOS time format:
7371 **
7372 **   File modification time:
7373 **     Bits 00-04: seconds divided by 2
7374 **     Bits 05-10: minute
7375 **     Bits 11-15: hour
7376 **   File modification date:
7377 **     Bits 00-04: day
7378 **     Bits 05-08: month (1-12)
7379 **     Bits 09-15: years from 1980
7380 **
7381 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
7382 */
zipfileMtime(ZipfileCDS * pCDS)7383 static u32 zipfileMtime(ZipfileCDS *pCDS){
7384   int Y,M,D,X1,X2,A,B,sec,min,hr;
7385   i64 JDsec;
7386   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
7387   M = ((pCDS->mDate >> 5) & 0x0F);
7388   D = (pCDS->mDate & 0x1F);
7389   sec = (pCDS->mTime & 0x1F)*2;
7390   min = (pCDS->mTime >> 5) & 0x3F;
7391   hr = (pCDS->mTime >> 11) & 0x1F;
7392   if( M<=2 ){
7393     Y--;
7394     M += 12;
7395   }
7396   X1 = 36525*(Y+4716)/100;
7397   X2 = 306001*(M+1)/10000;
7398   A = Y/100;
7399   B = 2 - A + (A/4);
7400   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
7401   return (u32)(JDsec - (i64)24405875*(i64)8640);
7402 }
7403 
7404 /*
7405 ** The opposite of zipfileMtime(). This function populates the mTime and
7406 ** mDate fields of the CDS structure passed as the first argument according
7407 ** to the UNIX timestamp value passed as the second.
7408 */
zipfileMtimeToDos(ZipfileCDS * pCds,u32 mUnixTime)7409 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
7410   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
7411   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
7412 
7413   int A, B, C, D, E;
7414   int yr, mon, day;
7415   int hr, min, sec;
7416 
7417   A = (int)((JD - 1867216.25)/36524.25);
7418   A = (int)(JD + 1 + A - (A/4));
7419   B = A + 1524;
7420   C = (int)((B - 122.1)/365.25);
7421   D = (36525*(C&32767))/100;
7422   E = (int)((B-D)/30.6001);
7423 
7424   day = B - D - (int)(30.6001*E);
7425   mon = (E<14 ? E-1 : E-13);
7426   yr = mon>2 ? C-4716 : C-4715;
7427 
7428   hr = (mUnixTime % (24*60*60)) / (60*60);
7429   min = (mUnixTime % (60*60)) / 60;
7430   sec = (mUnixTime % 60);
7431 
7432   if( yr>=1980 ){
7433     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
7434     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
7435   }else{
7436     pCds->mDate = pCds->mTime = 0;
7437   }
7438 
7439   assert( mUnixTime<315507600
7440        || mUnixTime==zipfileMtime(pCds)
7441        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
7442        /* || (mUnixTime % 2) */
7443   );
7444 }
7445 
7446 /*
7447 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
7448 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
7449 ** then pFile is a file-handle open on a zip file. In either case, this
7450 ** function creates a ZipfileEntry object based on the zip archive entry
7451 ** for which the CDS record is at offset iOff.
7452 **
7453 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
7454 ** the new object. Otherwise, an SQLite error code is returned and the
7455 ** final value of (*ppEntry) undefined.
7456 */
zipfileGetEntry(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,i64 iOff,ZipfileEntry ** ppEntry)7457 static int zipfileGetEntry(
7458   ZipfileTab *pTab,               /* Store any error message here */
7459   const u8 *aBlob,                /* Pointer to in-memory file image */
7460   int nBlob,                      /* Size of aBlob[] in bytes */
7461   FILE *pFile,                    /* If aBlob==0, read from this file */
7462   i64 iOff,                       /* Offset of CDS record */
7463   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
7464 ){
7465   u8 *aRead;
7466   char **pzErr = &pTab->base.zErrMsg;
7467   int rc = SQLITE_OK;
7468 
7469   if( aBlob==0 ){
7470     aRead = pTab->aBuffer;
7471     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
7472   }else{
7473     aRead = (u8*)&aBlob[iOff];
7474   }
7475 
7476   if( rc==SQLITE_OK ){
7477     sqlite3_int64 nAlloc;
7478     ZipfileEntry *pNew;
7479 
7480     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
7481     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
7482     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
7483 
7484     nAlloc = sizeof(ZipfileEntry) + nExtra;
7485     if( aBlob ){
7486       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
7487     }
7488 
7489     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
7490     if( pNew==0 ){
7491       rc = SQLITE_NOMEM;
7492     }else{
7493       memset(pNew, 0, sizeof(ZipfileEntry));
7494       rc = zipfileReadCDS(aRead, &pNew->cds);
7495       if( rc!=SQLITE_OK ){
7496         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
7497       }else if( aBlob==0 ){
7498         rc = zipfileReadData(
7499             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
7500         );
7501       }else{
7502         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
7503       }
7504     }
7505 
7506     if( rc==SQLITE_OK ){
7507       u32 *pt = &pNew->mUnixTime;
7508       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
7509       pNew->aExtra = (u8*)&pNew[1];
7510       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
7511       if( pNew->cds.zFile==0 ){
7512         rc = SQLITE_NOMEM;
7513       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
7514         pNew->mUnixTime = zipfileMtime(&pNew->cds);
7515       }
7516     }
7517 
7518     if( rc==SQLITE_OK ){
7519       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
7520       ZipfileLFH lfh;
7521       if( pFile ){
7522         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
7523       }else{
7524         aRead = (u8*)&aBlob[pNew->cds.iOffset];
7525       }
7526 
7527       rc = zipfileReadLFH(aRead, &lfh);
7528       if( rc==SQLITE_OK ){
7529         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
7530         pNew->iDataOff += lfh.nFile + lfh.nExtra;
7531         if( aBlob && pNew->cds.szCompressed ){
7532           pNew->aData = &pNew->aExtra[nExtra];
7533           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
7534         }
7535       }else{
7536         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
7537             (int)pNew->cds.iOffset
7538         );
7539       }
7540     }
7541 
7542     if( rc!=SQLITE_OK ){
7543       zipfileEntryFree(pNew);
7544     }else{
7545       *ppEntry = pNew;
7546     }
7547   }
7548 
7549   return rc;
7550 }
7551 
7552 /*
7553 ** Advance an ZipfileCsr to its next row of output.
7554 */
zipfileNext(sqlite3_vtab_cursor * cur)7555 static int zipfileNext(sqlite3_vtab_cursor *cur){
7556   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7557   int rc = SQLITE_OK;
7558 
7559   if( pCsr->pFile ){
7560     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
7561     zipfileEntryFree(pCsr->pCurrent);
7562     pCsr->pCurrent = 0;
7563     if( pCsr->iNextOff>=iEof ){
7564       pCsr->bEof = 1;
7565     }else{
7566       ZipfileEntry *p = 0;
7567       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
7568       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
7569       if( rc==SQLITE_OK ){
7570         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
7571         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
7572       }
7573       pCsr->pCurrent = p;
7574     }
7575   }else{
7576     if( !pCsr->bNoop ){
7577       pCsr->pCurrent = pCsr->pCurrent->pNext;
7578     }
7579     if( pCsr->pCurrent==0 ){
7580       pCsr->bEof = 1;
7581     }
7582   }
7583 
7584   pCsr->bNoop = 0;
7585   return rc;
7586 }
7587 
zipfileFree(void * p)7588 static void zipfileFree(void *p) {
7589   sqlite3_free(p);
7590 }
7591 
7592 /*
7593 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
7594 ** size is nOut bytes. This function uncompresses the data and sets the
7595 ** return value in context pCtx to the result (a blob).
7596 **
7597 ** If an error occurs, an error code is left in pCtx instead.
7598 */
zipfileInflate(sqlite3_context * pCtx,const u8 * aIn,int nIn,int nOut)7599 static void zipfileInflate(
7600   sqlite3_context *pCtx,          /* Store result here */
7601   const u8 *aIn,                  /* Compressed data */
7602   int nIn,                        /* Size of buffer aIn[] in bytes */
7603   int nOut                        /* Expected output size */
7604 ){
7605   u8 *aRes = sqlite3_malloc(nOut);
7606   if( aRes==0 ){
7607     sqlite3_result_error_nomem(pCtx);
7608   }else{
7609     int err;
7610     z_stream str;
7611     memset(&str, 0, sizeof(str));
7612 
7613     str.next_in = (Byte*)aIn;
7614     str.avail_in = nIn;
7615     str.next_out = (Byte*)aRes;
7616     str.avail_out = nOut;
7617 
7618     err = inflateInit2(&str, -15);
7619     if( err!=Z_OK ){
7620       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
7621     }else{
7622       err = inflate(&str, Z_NO_FLUSH);
7623       if( err!=Z_STREAM_END ){
7624         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
7625       }else{
7626         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
7627         aRes = 0;
7628       }
7629     }
7630     sqlite3_free(aRes);
7631     inflateEnd(&str);
7632   }
7633 }
7634 
7635 /*
7636 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
7637 ** compresses it and sets (*ppOut) to point to a buffer containing the
7638 ** compressed data. The caller is responsible for eventually calling
7639 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
7640 ** is set to the size of buffer (*ppOut) in bytes.
7641 **
7642 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
7643 ** code is returned and an error message left in virtual-table handle
7644 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
7645 ** case.
7646 */
zipfileDeflate(const u8 * aIn,int nIn,u8 ** ppOut,int * pnOut,char ** pzErr)7647 static int zipfileDeflate(
7648   const u8 *aIn, int nIn,         /* Input */
7649   u8 **ppOut, int *pnOut,         /* Output */
7650   char **pzErr                    /* OUT: Error message */
7651 ){
7652   int rc = SQLITE_OK;
7653   sqlite3_int64 nAlloc;
7654   z_stream str;
7655   u8 *aOut;
7656 
7657   memset(&str, 0, sizeof(str));
7658   str.next_in = (Bytef*)aIn;
7659   str.avail_in = nIn;
7660   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
7661 
7662   nAlloc = deflateBound(&str, nIn);
7663   aOut = (u8*)sqlite3_malloc64(nAlloc);
7664   if( aOut==0 ){
7665     rc = SQLITE_NOMEM;
7666   }else{
7667     int res;
7668     str.next_out = aOut;
7669     str.avail_out = nAlloc;
7670     res = deflate(&str, Z_FINISH);
7671     if( res==Z_STREAM_END ){
7672       *ppOut = aOut;
7673       *pnOut = (int)str.total_out;
7674     }else{
7675       sqlite3_free(aOut);
7676       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
7677       rc = SQLITE_ERROR;
7678     }
7679     deflateEnd(&str);
7680   }
7681 
7682   return rc;
7683 }
7684 
7685 
7686 /*
7687 ** Return values of columns for the row at which the series_cursor
7688 ** is currently pointing.
7689 */
zipfileColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)7690 static int zipfileColumn(
7691   sqlite3_vtab_cursor *cur,   /* The cursor */
7692   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7693   int i                       /* Which column to return */
7694 ){
7695   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7696   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
7697   int rc = SQLITE_OK;
7698   switch( i ){
7699     case 0:   /* name */
7700       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
7701       break;
7702     case 1:   /* mode */
7703       /* TODO: Whether or not the following is correct surely depends on
7704       ** the platform on which the archive was created.  */
7705       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
7706       break;
7707     case 2: { /* mtime */
7708       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
7709       break;
7710     }
7711     case 3: { /* sz */
7712       if( sqlite3_vtab_nochange(ctx)==0 ){
7713         sqlite3_result_int64(ctx, pCDS->szUncompressed);
7714       }
7715       break;
7716     }
7717     case 4:   /* rawdata */
7718       if( sqlite3_vtab_nochange(ctx) ) break;
7719     case 5: { /* data */
7720       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
7721         int sz = pCDS->szCompressed;
7722         int szFinal = pCDS->szUncompressed;
7723         if( szFinal>0 ){
7724           u8 *aBuf;
7725           u8 *aFree = 0;
7726           if( pCsr->pCurrent->aData ){
7727             aBuf = pCsr->pCurrent->aData;
7728           }else{
7729             aBuf = aFree = sqlite3_malloc64(sz);
7730             if( aBuf==0 ){
7731               rc = SQLITE_NOMEM;
7732             }else{
7733               FILE *pFile = pCsr->pFile;
7734               if( pFile==0 ){
7735                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
7736               }
7737               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
7738                   &pCsr->base.pVtab->zErrMsg
7739               );
7740             }
7741           }
7742           if( rc==SQLITE_OK ){
7743             if( i==5 && pCDS->iCompression ){
7744               zipfileInflate(ctx, aBuf, sz, szFinal);
7745             }else{
7746               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
7747             }
7748           }
7749           sqlite3_free(aFree);
7750         }else{
7751           /* Figure out if this is a directory or a zero-sized file. Consider
7752           ** it to be a directory either if the mode suggests so, or if
7753           ** the final character in the name is '/'.  */
7754           u32 mode = pCDS->iExternalAttr >> 16;
7755           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
7756             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
7757           }
7758         }
7759       }
7760       break;
7761     }
7762     case 6:   /* method */
7763       sqlite3_result_int(ctx, pCDS->iCompression);
7764       break;
7765     default:  /* z */
7766       assert( i==7 );
7767       sqlite3_result_int64(ctx, pCsr->iId);
7768       break;
7769   }
7770 
7771   return rc;
7772 }
7773 
7774 /*
7775 ** Return TRUE if the cursor is at EOF.
7776 */
zipfileEof(sqlite3_vtab_cursor * cur)7777 static int zipfileEof(sqlite3_vtab_cursor *cur){
7778   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7779   return pCsr->bEof;
7780 }
7781 
7782 /*
7783 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
7784 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
7785 ** is guaranteed to be a file-handle open on a zip file.
7786 **
7787 ** This function attempts to locate the EOCD record within the zip archive
7788 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
7789 ** returned if successful. Otherwise, an SQLite error code is returned and
7790 ** an English language error message may be left in virtual-table pTab.
7791 */
zipfileReadEOCD(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,ZipfileEOCD * pEOCD)7792 static int zipfileReadEOCD(
7793   ZipfileTab *pTab,               /* Return errors here */
7794   const u8 *aBlob,                /* Pointer to in-memory file image */
7795   int nBlob,                      /* Size of aBlob[] in bytes */
7796   FILE *pFile,                    /* Read from this file if aBlob==0 */
7797   ZipfileEOCD *pEOCD              /* Object to populate */
7798 ){
7799   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
7800   int nRead;                      /* Bytes to read from file */
7801   int rc = SQLITE_OK;
7802 
7803   if( aBlob==0 ){
7804     i64 iOff;                     /* Offset to read from */
7805     i64 szFile;                   /* Total size of file in bytes */
7806     fseek(pFile, 0, SEEK_END);
7807     szFile = (i64)ftell(pFile);
7808     if( szFile==0 ){
7809       memset(pEOCD, 0, sizeof(ZipfileEOCD));
7810       return SQLITE_OK;
7811     }
7812     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
7813     iOff = szFile - nRead;
7814     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
7815   }else{
7816     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
7817     aRead = (u8*)&aBlob[nBlob-nRead];
7818   }
7819 
7820   if( rc==SQLITE_OK ){
7821     int i;
7822 
7823     /* Scan backwards looking for the signature bytes */
7824     for(i=nRead-20; i>=0; i--){
7825       if( aRead[i]==0x50 && aRead[i+1]==0x4b
7826        && aRead[i+2]==0x05 && aRead[i+3]==0x06
7827       ){
7828         break;
7829       }
7830     }
7831     if( i<0 ){
7832       pTab->base.zErrMsg = sqlite3_mprintf(
7833           "cannot find end of central directory record"
7834       );
7835       return SQLITE_ERROR;
7836     }
7837 
7838     aRead += i+4;
7839     pEOCD->iDisk = zipfileRead16(aRead);
7840     pEOCD->iFirstDisk = zipfileRead16(aRead);
7841     pEOCD->nEntry = zipfileRead16(aRead);
7842     pEOCD->nEntryTotal = zipfileRead16(aRead);
7843     pEOCD->nSize = zipfileRead32(aRead);
7844     pEOCD->iOffset = zipfileRead32(aRead);
7845   }
7846 
7847   return rc;
7848 }
7849 
7850 /*
7851 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
7852 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
7853 ** to the end of the list. Otherwise, it is added to the list immediately
7854 ** before pBefore (which is guaranteed to be a part of said list).
7855 */
zipfileAddEntry(ZipfileTab * pTab,ZipfileEntry * pBefore,ZipfileEntry * pNew)7856 static void zipfileAddEntry(
7857   ZipfileTab *pTab,
7858   ZipfileEntry *pBefore,
7859   ZipfileEntry *pNew
7860 ){
7861   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
7862   assert( pNew->pNext==0 );
7863   if( pBefore==0 ){
7864     if( pTab->pFirstEntry==0 ){
7865       pTab->pFirstEntry = pTab->pLastEntry = pNew;
7866     }else{
7867       assert( pTab->pLastEntry->pNext==0 );
7868       pTab->pLastEntry->pNext = pNew;
7869       pTab->pLastEntry = pNew;
7870     }
7871   }else{
7872     ZipfileEntry **pp;
7873     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
7874     pNew->pNext = pBefore;
7875     *pp = pNew;
7876   }
7877 }
7878 
zipfileLoadDirectory(ZipfileTab * pTab,const u8 * aBlob,int nBlob)7879 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
7880   ZipfileEOCD eocd;
7881   int rc;
7882   int i;
7883   i64 iOff;
7884 
7885   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
7886   iOff = eocd.iOffset;
7887   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
7888     ZipfileEntry *pNew = 0;
7889     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
7890 
7891     if( rc==SQLITE_OK ){
7892       zipfileAddEntry(pTab, 0, pNew);
7893       iOff += ZIPFILE_CDS_FIXED_SZ;
7894       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
7895     }
7896   }
7897   return rc;
7898 }
7899 
7900 /*
7901 ** xFilter callback.
7902 */
zipfileFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)7903 static int zipfileFilter(
7904   sqlite3_vtab_cursor *cur,
7905   int idxNum, const char *idxStr,
7906   int argc, sqlite3_value **argv
7907 ){
7908   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
7909   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7910   const char *zFile = 0;          /* Zip file to scan */
7911   int rc = SQLITE_OK;             /* Return Code */
7912   int bInMemory = 0;              /* True for an in-memory zipfile */
7913 
7914   zipfileResetCursor(pCsr);
7915 
7916   if( pTab->zFile ){
7917     zFile = pTab->zFile;
7918   }else if( idxNum==0 ){
7919     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
7920     return SQLITE_ERROR;
7921   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
7922     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
7923     int nBlob = sqlite3_value_bytes(argv[0]);
7924     assert( pTab->pFirstEntry==0 );
7925     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
7926     pCsr->pFreeEntry = pTab->pFirstEntry;
7927     pTab->pFirstEntry = pTab->pLastEntry = 0;
7928     if( rc!=SQLITE_OK ) return rc;
7929     bInMemory = 1;
7930   }else{
7931     zFile = (const char*)sqlite3_value_text(argv[0]);
7932   }
7933 
7934   if( 0==pTab->pWriteFd && 0==bInMemory ){
7935     pCsr->pFile = fopen(zFile, "rb");
7936     if( pCsr->pFile==0 ){
7937       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
7938       rc = SQLITE_ERROR;
7939     }else{
7940       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
7941       if( rc==SQLITE_OK ){
7942         if( pCsr->eocd.nEntry==0 ){
7943           pCsr->bEof = 1;
7944         }else{
7945           pCsr->iNextOff = pCsr->eocd.iOffset;
7946           rc = zipfileNext(cur);
7947         }
7948       }
7949     }
7950   }else{
7951     pCsr->bNoop = 1;
7952     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
7953     rc = zipfileNext(cur);
7954   }
7955 
7956   return rc;
7957 }
7958 
7959 /*
7960 ** xBestIndex callback.
7961 */
zipfileBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)7962 static int zipfileBestIndex(
7963   sqlite3_vtab *tab,
7964   sqlite3_index_info *pIdxInfo
7965 ){
7966   int i;
7967   int idx = -1;
7968   int unusable = 0;
7969 
7970   for(i=0; i<pIdxInfo->nConstraint; i++){
7971     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
7972     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
7973     if( pCons->usable==0 ){
7974       unusable = 1;
7975     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
7976       idx = i;
7977     }
7978   }
7979   pIdxInfo->estimatedCost = 1000.0;
7980   if( idx>=0 ){
7981     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
7982     pIdxInfo->aConstraintUsage[idx].omit = 1;
7983     pIdxInfo->idxNum = 1;
7984   }else if( unusable ){
7985     return SQLITE_CONSTRAINT;
7986   }
7987   return SQLITE_OK;
7988 }
7989 
zipfileNewEntry(const char * zPath)7990 static ZipfileEntry *zipfileNewEntry(const char *zPath){
7991   ZipfileEntry *pNew;
7992   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
7993   if( pNew ){
7994     memset(pNew, 0, sizeof(ZipfileEntry));
7995     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
7996     if( pNew->cds.zFile==0 ){
7997       sqlite3_free(pNew);
7998       pNew = 0;
7999     }
8000   }
8001   return pNew;
8002 }
8003 
zipfileSerializeLFH(ZipfileEntry * pEntry,u8 * aBuf)8004 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
8005   ZipfileCDS *pCds = &pEntry->cds;
8006   u8 *a = aBuf;
8007 
8008   pCds->nExtra = 9;
8009 
8010   /* Write the LFH itself */
8011   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
8012   zipfileWrite16(a, pCds->iVersionExtract);
8013   zipfileWrite16(a, pCds->flags);
8014   zipfileWrite16(a, pCds->iCompression);
8015   zipfileWrite16(a, pCds->mTime);
8016   zipfileWrite16(a, pCds->mDate);
8017   zipfileWrite32(a, pCds->crc32);
8018   zipfileWrite32(a, pCds->szCompressed);
8019   zipfileWrite32(a, pCds->szUncompressed);
8020   zipfileWrite16(a, (u16)pCds->nFile);
8021   zipfileWrite16(a, pCds->nExtra);
8022   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
8023 
8024   /* Add the file name */
8025   memcpy(a, pCds->zFile, (int)pCds->nFile);
8026   a += (int)pCds->nFile;
8027 
8028   /* The "extra" data */
8029   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
8030   zipfileWrite16(a, 5);
8031   *a++ = 0x01;
8032   zipfileWrite32(a, pEntry->mUnixTime);
8033 
8034   return a-aBuf;
8035 }
8036 
zipfileAppendEntry(ZipfileTab * pTab,ZipfileEntry * pEntry,const u8 * pData,int nData)8037 static int zipfileAppendEntry(
8038   ZipfileTab *pTab,
8039   ZipfileEntry *pEntry,
8040   const u8 *pData,
8041   int nData
8042 ){
8043   u8 *aBuf = pTab->aBuffer;
8044   int nBuf;
8045   int rc;
8046 
8047   nBuf = zipfileSerializeLFH(pEntry, aBuf);
8048   rc = zipfileAppendData(pTab, aBuf, nBuf);
8049   if( rc==SQLITE_OK ){
8050     pEntry->iDataOff = pTab->szCurrent;
8051     rc = zipfileAppendData(pTab, pData, nData);
8052   }
8053 
8054   return rc;
8055 }
8056 
zipfileGetMode(sqlite3_value * pVal,int bIsDir,u32 * pMode,char ** pzErr)8057 static int zipfileGetMode(
8058   sqlite3_value *pVal,
8059   int bIsDir,                     /* If true, default to directory */
8060   u32 *pMode,                     /* OUT: Mode value */
8061   char **pzErr                    /* OUT: Error message */
8062 ){
8063   const char *z = (const char*)sqlite3_value_text(pVal);
8064   u32 mode = 0;
8065   if( z==0 ){
8066     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
8067   }else if( z[0]>='0' && z[0]<='9' ){
8068     mode = (unsigned int)sqlite3_value_int(pVal);
8069   }else{
8070     const char zTemplate[11] = "-rwxrwxrwx";
8071     int i;
8072     if( strlen(z)!=10 ) goto parse_error;
8073     switch( z[0] ){
8074       case '-': mode |= S_IFREG; break;
8075       case 'd': mode |= S_IFDIR; break;
8076       case 'l': mode |= S_IFLNK; break;
8077       default: goto parse_error;
8078     }
8079     for(i=1; i<10; i++){
8080       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
8081       else if( z[i]!='-' ) goto parse_error;
8082     }
8083   }
8084   if( ((mode & S_IFDIR)==0)==bIsDir ){
8085     /* The "mode" attribute is a directory, but data has been specified.
8086     ** Or vice-versa - no data but "mode" is a file or symlink.  */
8087     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
8088     return SQLITE_CONSTRAINT;
8089   }
8090   *pMode = mode;
8091   return SQLITE_OK;
8092 
8093  parse_error:
8094   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
8095   return SQLITE_ERROR;
8096 }
8097 
8098 /*
8099 ** Both (const char*) arguments point to nul-terminated strings. Argument
8100 ** nB is the value of strlen(zB). This function returns 0 if the strings are
8101 ** identical, ignoring any trailing '/' character in either path.  */
zipfileComparePath(const char * zA,const char * zB,int nB)8102 static int zipfileComparePath(const char *zA, const char *zB, int nB){
8103   int nA = (int)strlen(zA);
8104   if( nA>0 && zA[nA-1]=='/' ) nA--;
8105   if( nB>0 && zB[nB-1]=='/' ) nB--;
8106   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
8107   return 1;
8108 }
8109 
zipfileBegin(sqlite3_vtab * pVtab)8110 static int zipfileBegin(sqlite3_vtab *pVtab){
8111   ZipfileTab *pTab = (ZipfileTab*)pVtab;
8112   int rc = SQLITE_OK;
8113 
8114   assert( pTab->pWriteFd==0 );
8115   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
8116     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
8117     return SQLITE_ERROR;
8118   }
8119 
8120   /* Open a write fd on the file. Also load the entire central directory
8121   ** structure into memory. During the transaction any new file data is
8122   ** appended to the archive file, but the central directory is accumulated
8123   ** in main-memory until the transaction is committed.  */
8124   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
8125   if( pTab->pWriteFd==0 ){
8126     pTab->base.zErrMsg = sqlite3_mprintf(
8127         "zipfile: failed to open file %s for writing", pTab->zFile
8128         );
8129     rc = SQLITE_ERROR;
8130   }else{
8131     fseek(pTab->pWriteFd, 0, SEEK_END);
8132     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
8133     rc = zipfileLoadDirectory(pTab, 0, 0);
8134   }
8135 
8136   if( rc!=SQLITE_OK ){
8137     zipfileCleanupTransaction(pTab);
8138   }
8139 
8140   return rc;
8141 }
8142 
8143 /*
8144 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
8145 ** time(2)).
8146 */
zipfileTime(void)8147 static u32 zipfileTime(void){
8148   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
8149   u32 ret;
8150   if( pVfs==0 ) return 0;
8151   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
8152     i64 ms;
8153     pVfs->xCurrentTimeInt64(pVfs, &ms);
8154     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
8155   }else{
8156     double day;
8157     pVfs->xCurrentTime(pVfs, &day);
8158     ret = (u32)((day - 2440587.5) * 86400);
8159   }
8160   return ret;
8161 }
8162 
8163 /*
8164 ** Return a 32-bit timestamp in UNIX epoch format.
8165 **
8166 ** If the value passed as the only argument is either NULL or an SQL NULL,
8167 ** return the current time. Otherwise, return the value stored in (*pVal)
8168 ** cast to a 32-bit unsigned integer.
8169 */
zipfileGetTime(sqlite3_value * pVal)8170 static u32 zipfileGetTime(sqlite3_value *pVal){
8171   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
8172     return zipfileTime();
8173   }
8174   return (u32)sqlite3_value_int64(pVal);
8175 }
8176 
8177 /*
8178 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
8179 ** linked list.  Remove it from the list and free the object.
8180 */
zipfileRemoveEntryFromList(ZipfileTab * pTab,ZipfileEntry * pOld)8181 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
8182   if( pOld ){
8183     ZipfileEntry **pp;
8184     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
8185     *pp = (*pp)->pNext;
8186     zipfileEntryFree(pOld);
8187   }
8188 }
8189 
8190 /*
8191 ** xUpdate method.
8192 */
zipfileUpdate(sqlite3_vtab * pVtab,int nVal,sqlite3_value ** apVal,sqlite_int64 * pRowid)8193 static int zipfileUpdate(
8194   sqlite3_vtab *pVtab,
8195   int nVal,
8196   sqlite3_value **apVal,
8197   sqlite_int64 *pRowid
8198 ){
8199   ZipfileTab *pTab = (ZipfileTab*)pVtab;
8200   int rc = SQLITE_OK;             /* Return Code */
8201   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
8202 
8203   u32 mode = 0;                   /* Mode for new entry */
8204   u32 mTime = 0;                  /* Modification time for new entry */
8205   i64 sz = 0;                     /* Uncompressed size */
8206   const char *zPath = 0;          /* Path for new entry */
8207   int nPath = 0;                  /* strlen(zPath) */
8208   const u8 *pData = 0;            /* Pointer to buffer containing content */
8209   int nData = 0;                  /* Size of pData buffer in bytes */
8210   int iMethod = 0;                /* Compression method for new entry */
8211   u8 *pFree = 0;                  /* Free this */
8212   char *zFree = 0;                /* Also free this */
8213   ZipfileEntry *pOld = 0;
8214   ZipfileEntry *pOld2 = 0;
8215   int bUpdate = 0;                /* True for an update that modifies "name" */
8216   int bIsDir = 0;
8217   u32 iCrc32 = 0;
8218 
8219   if( pTab->pWriteFd==0 ){
8220     rc = zipfileBegin(pVtab);
8221     if( rc!=SQLITE_OK ) return rc;
8222   }
8223 
8224   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
8225   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
8226     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
8227     int nDelete = (int)strlen(zDelete);
8228     if( nVal>1 ){
8229       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
8230       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
8231         bUpdate = 1;
8232       }
8233     }
8234     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
8235       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
8236         break;
8237       }
8238       assert( pOld->pNext );
8239     }
8240   }
8241 
8242   if( nVal>1 ){
8243     /* Check that "sz" and "rawdata" are both NULL: */
8244     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
8245       zipfileTableErr(pTab, "sz must be NULL");
8246       rc = SQLITE_CONSTRAINT;
8247     }
8248     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
8249       zipfileTableErr(pTab, "rawdata must be NULL");
8250       rc = SQLITE_CONSTRAINT;
8251     }
8252 
8253     if( rc==SQLITE_OK ){
8254       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
8255         /* data=NULL. A directory */
8256         bIsDir = 1;
8257       }else{
8258         /* Value specified for "data", and possibly "method". This must be
8259         ** a regular file or a symlink. */
8260         const u8 *aIn = sqlite3_value_blob(apVal[7]);
8261         int nIn = sqlite3_value_bytes(apVal[7]);
8262         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
8263 
8264         iMethod = sqlite3_value_int(apVal[8]);
8265         sz = nIn;
8266         pData = aIn;
8267         nData = nIn;
8268         if( iMethod!=0 && iMethod!=8 ){
8269           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
8270           rc = SQLITE_CONSTRAINT;
8271         }else{
8272           if( bAuto || iMethod ){
8273             int nCmp;
8274             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
8275             if( rc==SQLITE_OK ){
8276               if( iMethod || nCmp<nIn ){
8277                 iMethod = 8;
8278                 pData = pFree;
8279                 nData = nCmp;
8280               }
8281             }
8282           }
8283           iCrc32 = crc32(0, aIn, nIn);
8284         }
8285       }
8286     }
8287 
8288     if( rc==SQLITE_OK ){
8289       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
8290     }
8291 
8292     if( rc==SQLITE_OK ){
8293       zPath = (const char*)sqlite3_value_text(apVal[2]);
8294       if( zPath==0 ) zPath = "";
8295       nPath = (int)strlen(zPath);
8296       mTime = zipfileGetTime(apVal[4]);
8297     }
8298 
8299     if( rc==SQLITE_OK && bIsDir ){
8300       /* For a directory, check that the last character in the path is a
8301       ** '/'. This appears to be required for compatibility with info-zip
8302       ** (the unzip command on unix). It does not create directories
8303       ** otherwise.  */
8304       if( nPath<=0 || zPath[nPath-1]!='/' ){
8305         zFree = sqlite3_mprintf("%s/", zPath);
8306         zPath = (const char*)zFree;
8307         if( zFree==0 ){
8308           rc = SQLITE_NOMEM;
8309           nPath = 0;
8310         }else{
8311           nPath = (int)strlen(zPath);
8312         }
8313       }
8314     }
8315 
8316     /* Check that we're not inserting a duplicate entry -OR- updating an
8317     ** entry with a path, thereby making it into a duplicate. */
8318     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
8319       ZipfileEntry *p;
8320       for(p=pTab->pFirstEntry; p; p=p->pNext){
8321         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
8322           switch( sqlite3_vtab_on_conflict(pTab->db) ){
8323             case SQLITE_IGNORE: {
8324               goto zipfile_update_done;
8325             }
8326             case SQLITE_REPLACE: {
8327               pOld2 = p;
8328               break;
8329             }
8330             default: {
8331               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
8332               rc = SQLITE_CONSTRAINT;
8333               break;
8334             }
8335           }
8336           break;
8337         }
8338       }
8339     }
8340 
8341     if( rc==SQLITE_OK ){
8342       /* Create the new CDS record. */
8343       pNew = zipfileNewEntry(zPath);
8344       if( pNew==0 ){
8345         rc = SQLITE_NOMEM;
8346       }else{
8347         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
8348         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
8349         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
8350         pNew->cds.iCompression = (u16)iMethod;
8351         zipfileMtimeToDos(&pNew->cds, mTime);
8352         pNew->cds.crc32 = iCrc32;
8353         pNew->cds.szCompressed = nData;
8354         pNew->cds.szUncompressed = (u32)sz;
8355         pNew->cds.iExternalAttr = (mode<<16);
8356         pNew->cds.iOffset = (u32)pTab->szCurrent;
8357         pNew->cds.nFile = (u16)nPath;
8358         pNew->mUnixTime = (u32)mTime;
8359         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
8360         zipfileAddEntry(pTab, pOld, pNew);
8361       }
8362     }
8363   }
8364 
8365   if( rc==SQLITE_OK && (pOld || pOld2) ){
8366     ZipfileCsr *pCsr;
8367     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
8368       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
8369         pCsr->pCurrent = pCsr->pCurrent->pNext;
8370         pCsr->bNoop = 1;
8371       }
8372     }
8373 
8374     zipfileRemoveEntryFromList(pTab, pOld);
8375     zipfileRemoveEntryFromList(pTab, pOld2);
8376   }
8377 
8378 zipfile_update_done:
8379   sqlite3_free(pFree);
8380   sqlite3_free(zFree);
8381   return rc;
8382 }
8383 
zipfileSerializeEOCD(ZipfileEOCD * p,u8 * aBuf)8384 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
8385   u8 *a = aBuf;
8386   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
8387   zipfileWrite16(a, p->iDisk);
8388   zipfileWrite16(a, p->iFirstDisk);
8389   zipfileWrite16(a, p->nEntry);
8390   zipfileWrite16(a, p->nEntryTotal);
8391   zipfileWrite32(a, p->nSize);
8392   zipfileWrite32(a, p->iOffset);
8393   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
8394 
8395   return a-aBuf;
8396 }
8397 
zipfileAppendEOCD(ZipfileTab * pTab,ZipfileEOCD * p)8398 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
8399   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
8400   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
8401   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
8402 }
8403 
8404 /*
8405 ** Serialize the CDS structure into buffer aBuf[]. Return the number
8406 ** of bytes written.
8407 */
zipfileSerializeCDS(ZipfileEntry * pEntry,u8 * aBuf)8408 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
8409   u8 *a = aBuf;
8410   ZipfileCDS *pCDS = &pEntry->cds;
8411 
8412   if( pEntry->aExtra==0 ){
8413     pCDS->nExtra = 9;
8414   }
8415 
8416   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
8417   zipfileWrite16(a, pCDS->iVersionMadeBy);
8418   zipfileWrite16(a, pCDS->iVersionExtract);
8419   zipfileWrite16(a, pCDS->flags);
8420   zipfileWrite16(a, pCDS->iCompression);
8421   zipfileWrite16(a, pCDS->mTime);
8422   zipfileWrite16(a, pCDS->mDate);
8423   zipfileWrite32(a, pCDS->crc32);
8424   zipfileWrite32(a, pCDS->szCompressed);
8425   zipfileWrite32(a, pCDS->szUncompressed);
8426   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
8427   zipfileWrite16(a, pCDS->nFile);
8428   zipfileWrite16(a, pCDS->nExtra);
8429   zipfileWrite16(a, pCDS->nComment);
8430   zipfileWrite16(a, pCDS->iDiskStart);
8431   zipfileWrite16(a, pCDS->iInternalAttr);
8432   zipfileWrite32(a, pCDS->iExternalAttr);
8433   zipfileWrite32(a, pCDS->iOffset);
8434 
8435   memcpy(a, pCDS->zFile, pCDS->nFile);
8436   a += pCDS->nFile;
8437 
8438   if( pEntry->aExtra ){
8439     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
8440     memcpy(a, pEntry->aExtra, n);
8441     a += n;
8442   }else{
8443     assert( pCDS->nExtra==9 );
8444     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
8445     zipfileWrite16(a, 5);
8446     *a++ = 0x01;
8447     zipfileWrite32(a, pEntry->mUnixTime);
8448   }
8449 
8450   return a-aBuf;
8451 }
8452 
zipfileCommit(sqlite3_vtab * pVtab)8453 static int zipfileCommit(sqlite3_vtab *pVtab){
8454   ZipfileTab *pTab = (ZipfileTab*)pVtab;
8455   int rc = SQLITE_OK;
8456   if( pTab->pWriteFd ){
8457     i64 iOffset = pTab->szCurrent;
8458     ZipfileEntry *p;
8459     ZipfileEOCD eocd;
8460     int nEntry = 0;
8461 
8462     /* Write out all entries */
8463     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
8464       int n = zipfileSerializeCDS(p, pTab->aBuffer);
8465       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
8466       nEntry++;
8467     }
8468 
8469     /* Write out the EOCD record */
8470     eocd.iDisk = 0;
8471     eocd.iFirstDisk = 0;
8472     eocd.nEntry = (u16)nEntry;
8473     eocd.nEntryTotal = (u16)nEntry;
8474     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
8475     eocd.iOffset = (u32)iOffset;
8476     rc = zipfileAppendEOCD(pTab, &eocd);
8477 
8478     zipfileCleanupTransaction(pTab);
8479   }
8480   return rc;
8481 }
8482 
zipfileRollback(sqlite3_vtab * pVtab)8483 static int zipfileRollback(sqlite3_vtab *pVtab){
8484   return zipfileCommit(pVtab);
8485 }
8486 
zipfileFindCursor(ZipfileTab * pTab,i64 iId)8487 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
8488   ZipfileCsr *pCsr;
8489   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
8490     if( iId==pCsr->iId ) break;
8491   }
8492   return pCsr;
8493 }
8494 
zipfileFunctionCds(sqlite3_context * context,int argc,sqlite3_value ** argv)8495 static void zipfileFunctionCds(
8496   sqlite3_context *context,
8497   int argc,
8498   sqlite3_value **argv
8499 ){
8500   ZipfileCsr *pCsr;
8501   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
8502   assert( argc>0 );
8503 
8504   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
8505   if( pCsr ){
8506     ZipfileCDS *p = &pCsr->pCurrent->cds;
8507     char *zRes = sqlite3_mprintf("{"
8508         "\"version-made-by\" : %u, "
8509         "\"version-to-extract\" : %u, "
8510         "\"flags\" : %u, "
8511         "\"compression\" : %u, "
8512         "\"time\" : %u, "
8513         "\"date\" : %u, "
8514         "\"crc32\" : %u, "
8515         "\"compressed-size\" : %u, "
8516         "\"uncompressed-size\" : %u, "
8517         "\"file-name-length\" : %u, "
8518         "\"extra-field-length\" : %u, "
8519         "\"file-comment-length\" : %u, "
8520         "\"disk-number-start\" : %u, "
8521         "\"internal-attr\" : %u, "
8522         "\"external-attr\" : %u, "
8523         "\"offset\" : %u }",
8524         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
8525         (u32)p->flags, (u32)p->iCompression,
8526         (u32)p->mTime, (u32)p->mDate,
8527         (u32)p->crc32, (u32)p->szCompressed,
8528         (u32)p->szUncompressed, (u32)p->nFile,
8529         (u32)p->nExtra, (u32)p->nComment,
8530         (u32)p->iDiskStart, (u32)p->iInternalAttr,
8531         (u32)p->iExternalAttr, (u32)p->iOffset
8532     );
8533 
8534     if( zRes==0 ){
8535       sqlite3_result_error_nomem(context);
8536     }else{
8537       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
8538       sqlite3_free(zRes);
8539     }
8540   }
8541 }
8542 
8543 /*
8544 ** xFindFunction method.
8545 */
zipfileFindFunction(sqlite3_vtab * pVtab,int nArg,const char * zName,void (** pxFunc)(sqlite3_context *,int,sqlite3_value **),void ** ppArg)8546 static int zipfileFindFunction(
8547   sqlite3_vtab *pVtab,            /* Virtual table handle */
8548   int nArg,                       /* Number of SQL function arguments */
8549   const char *zName,              /* Name of SQL function */
8550   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
8551   void **ppArg                    /* OUT: User data for *pxFunc */
8552 ){
8553   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
8554     *pxFunc = zipfileFunctionCds;
8555     *ppArg = (void*)pVtab;
8556     return 1;
8557   }
8558   return 0;
8559 }
8560 
8561 typedef struct ZipfileBuffer ZipfileBuffer;
8562 struct ZipfileBuffer {
8563   u8 *a;                          /* Pointer to buffer */
8564   int n;                          /* Size of buffer in bytes */
8565   int nAlloc;                     /* Byte allocated at a[] */
8566 };
8567 
8568 typedef struct ZipfileCtx ZipfileCtx;
8569 struct ZipfileCtx {
8570   int nEntry;
8571   ZipfileBuffer body;
8572   ZipfileBuffer cds;
8573 };
8574 
zipfileBufferGrow(ZipfileBuffer * pBuf,int nByte)8575 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
8576   if( pBuf->n+nByte>pBuf->nAlloc ){
8577     u8 *aNew;
8578     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
8579     int nReq = pBuf->n + nByte;
8580 
8581     while( nNew<nReq ) nNew = nNew*2;
8582     aNew = sqlite3_realloc64(pBuf->a, nNew);
8583     if( aNew==0 ) return SQLITE_NOMEM;
8584     pBuf->a = aNew;
8585     pBuf->nAlloc = (int)nNew;
8586   }
8587   return SQLITE_OK;
8588 }
8589 
8590 /*
8591 ** xStep() callback for the zipfile() aggregate. This can be called in
8592 ** any of the following ways:
8593 **
8594 **   SELECT zipfile(name,data) ...
8595 **   SELECT zipfile(name,mode,mtime,data) ...
8596 **   SELECT zipfile(name,mode,mtime,data,method) ...
8597 */
zipfileStep(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)8598 void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
8599   ZipfileCtx *p;                  /* Aggregate function context */
8600   ZipfileEntry e;                 /* New entry to add to zip archive */
8601 
8602   sqlite3_value *pName = 0;
8603   sqlite3_value *pMode = 0;
8604   sqlite3_value *pMtime = 0;
8605   sqlite3_value *pData = 0;
8606   sqlite3_value *pMethod = 0;
8607 
8608   int bIsDir = 0;
8609   u32 mode;
8610   int rc = SQLITE_OK;
8611   char *zErr = 0;
8612 
8613   int iMethod = -1;               /* Compression method to use (0 or 8) */
8614 
8615   const u8 *aData = 0;            /* Possibly compressed data for new entry */
8616   int nData = 0;                  /* Size of aData[] in bytes */
8617   int szUncompressed = 0;         /* Size of data before compression */
8618   u8 *aFree = 0;                  /* Free this before returning */
8619   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
8620 
8621   char *zName = 0;                /* Path (name) of new entry */
8622   int nName = 0;                  /* Size of zName in bytes */
8623   char *zFree = 0;                /* Free this before returning */
8624   int nByte;
8625 
8626   memset(&e, 0, sizeof(e));
8627   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
8628   if( p==0 ) return;
8629 
8630   /* Martial the arguments into stack variables */
8631   if( nVal!=2 && nVal!=4 && nVal!=5 ){
8632     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
8633     rc = SQLITE_ERROR;
8634     goto zipfile_step_out;
8635   }
8636   pName = apVal[0];
8637   if( nVal==2 ){
8638     pData = apVal[1];
8639   }else{
8640     pMode = apVal[1];
8641     pMtime = apVal[2];
8642     pData = apVal[3];
8643     if( nVal==5 ){
8644       pMethod = apVal[4];
8645     }
8646   }
8647 
8648   /* Check that the 'name' parameter looks ok. */
8649   zName = (char*)sqlite3_value_text(pName);
8650   nName = sqlite3_value_bytes(pName);
8651   if( zName==0 ){
8652     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
8653     rc = SQLITE_ERROR;
8654     goto zipfile_step_out;
8655   }
8656 
8657   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
8658   ** deflate compression) or NULL (choose automatically).  */
8659   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
8660     iMethod = (int)sqlite3_value_int64(pMethod);
8661     if( iMethod!=0 && iMethod!=8 ){
8662       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
8663       rc = SQLITE_ERROR;
8664       goto zipfile_step_out;
8665     }
8666   }
8667 
8668   /* Now inspect the data. If this is NULL, then the new entry must be a
8669   ** directory.  Otherwise, figure out whether or not the data should
8670   ** be deflated or simply stored in the zip archive. */
8671   if( sqlite3_value_type(pData)==SQLITE_NULL ){
8672     bIsDir = 1;
8673     iMethod = 0;
8674   }else{
8675     aData = sqlite3_value_blob(pData);
8676     szUncompressed = nData = sqlite3_value_bytes(pData);
8677     iCrc32 = crc32(0, aData, nData);
8678     if( iMethod<0 || iMethod==8 ){
8679       int nOut = 0;
8680       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
8681       if( rc!=SQLITE_OK ){
8682         goto zipfile_step_out;
8683       }
8684       if( iMethod==8 || nOut<nData ){
8685         aData = aFree;
8686         nData = nOut;
8687         iMethod = 8;
8688       }else{
8689         iMethod = 0;
8690       }
8691     }
8692   }
8693 
8694   /* Decode the "mode" argument. */
8695   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
8696   if( rc ) goto zipfile_step_out;
8697 
8698   /* Decode the "mtime" argument. */
8699   e.mUnixTime = zipfileGetTime(pMtime);
8700 
8701   /* If this is a directory entry, ensure that there is exactly one '/'
8702   ** at the end of the path. Or, if this is not a directory and the path
8703   ** ends in '/' it is an error. */
8704   if( bIsDir==0 ){
8705     if( nName>0 && zName[nName-1]=='/' ){
8706       zErr = sqlite3_mprintf("non-directory name must not end with /");
8707       rc = SQLITE_ERROR;
8708       goto zipfile_step_out;
8709     }
8710   }else{
8711     if( nName==0 || zName[nName-1]!='/' ){
8712       zName = zFree = sqlite3_mprintf("%s/", zName);
8713       if( zName==0 ){
8714         rc = SQLITE_NOMEM;
8715         goto zipfile_step_out;
8716       }
8717       nName = (int)strlen(zName);
8718     }else{
8719       while( nName>1 && zName[nName-2]=='/' ) nName--;
8720     }
8721   }
8722 
8723   /* Assemble the ZipfileEntry object for the new zip archive entry */
8724   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
8725   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
8726   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
8727   e.cds.iCompression = (u16)iMethod;
8728   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
8729   e.cds.crc32 = iCrc32;
8730   e.cds.szCompressed = nData;
8731   e.cds.szUncompressed = szUncompressed;
8732   e.cds.iExternalAttr = (mode<<16);
8733   e.cds.iOffset = p->body.n;
8734   e.cds.nFile = (u16)nName;
8735   e.cds.zFile = zName;
8736 
8737   /* Append the LFH to the body of the new archive */
8738   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
8739   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
8740   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
8741 
8742   /* Append the data to the body of the new archive */
8743   if( nData>0 ){
8744     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
8745     memcpy(&p->body.a[p->body.n], aData, nData);
8746     p->body.n += nData;
8747   }
8748 
8749   /* Append the CDS record to the directory of the new archive */
8750   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
8751   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
8752   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
8753 
8754   /* Increment the count of entries in the archive */
8755   p->nEntry++;
8756 
8757  zipfile_step_out:
8758   sqlite3_free(aFree);
8759   sqlite3_free(zFree);
8760   if( rc ){
8761     if( zErr ){
8762       sqlite3_result_error(pCtx, zErr, -1);
8763     }else{
8764       sqlite3_result_error_code(pCtx, rc);
8765     }
8766   }
8767   sqlite3_free(zErr);
8768 }
8769 
8770 /*
8771 ** xFinalize() callback for zipfile aggregate function.
8772 */
zipfileFinal(sqlite3_context * pCtx)8773 void zipfileFinal(sqlite3_context *pCtx){
8774   ZipfileCtx *p;
8775   ZipfileEOCD eocd;
8776   sqlite3_int64 nZip;
8777   u8 *aZip;
8778 
8779   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
8780   if( p==0 ) return;
8781   if( p->nEntry>0 ){
8782     memset(&eocd, 0, sizeof(eocd));
8783     eocd.nEntry = (u16)p->nEntry;
8784     eocd.nEntryTotal = (u16)p->nEntry;
8785     eocd.nSize = p->cds.n;
8786     eocd.iOffset = p->body.n;
8787 
8788     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
8789     aZip = (u8*)sqlite3_malloc64(nZip);
8790     if( aZip==0 ){
8791       sqlite3_result_error_nomem(pCtx);
8792     }else{
8793       memcpy(aZip, p->body.a, p->body.n);
8794       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
8795       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
8796       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
8797     }
8798   }
8799 
8800   sqlite3_free(p->body.a);
8801   sqlite3_free(p->cds.a);
8802 }
8803 
8804 
8805 /*
8806 ** Register the "zipfile" virtual table.
8807 */
zipfileRegister(sqlite3 * db)8808 static int zipfileRegister(sqlite3 *db){
8809   static sqlite3_module zipfileModule = {
8810     1,                         /* iVersion */
8811     zipfileConnect,            /* xCreate */
8812     zipfileConnect,            /* xConnect */
8813     zipfileBestIndex,          /* xBestIndex */
8814     zipfileDisconnect,         /* xDisconnect */
8815     zipfileDisconnect,         /* xDestroy */
8816     zipfileOpen,               /* xOpen - open a cursor */
8817     zipfileClose,              /* xClose - close a cursor */
8818     zipfileFilter,             /* xFilter - configure scan constraints */
8819     zipfileNext,               /* xNext - advance a cursor */
8820     zipfileEof,                /* xEof - check for end of scan */
8821     zipfileColumn,             /* xColumn - read data */
8822     0,                         /* xRowid - read data */
8823     zipfileUpdate,             /* xUpdate */
8824     zipfileBegin,              /* xBegin */
8825     0,                         /* xSync */
8826     zipfileCommit,             /* xCommit */
8827     zipfileRollback,           /* xRollback */
8828     zipfileFindFunction,       /* xFindMethod */
8829     0,                         /* xRename */
8830   };
8831 
8832   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
8833   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
8834   if( rc==SQLITE_OK ){
8835     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
8836         zipfileStep, zipfileFinal
8837     );
8838   }
8839   assert( sizeof(i64)==8 );
8840   assert( sizeof(u32)==4 );
8841   assert( sizeof(u16)==2 );
8842   assert( sizeof(u8)==1 );
8843   return rc;
8844 }
8845 #else         /* SQLITE_OMIT_VIRTUALTABLE */
8846 # define zipfileRegister(x) SQLITE_OK
8847 #endif
8848 
8849 #ifdef _WIN32
8850 
8851 #endif
sqlite3_zipfile_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8852 int sqlite3_zipfile_init(
8853   sqlite3 *db,
8854   char **pzErrMsg,
8855   const sqlite3_api_routines *pApi
8856 ){
8857   SQLITE_EXTENSION_INIT2(pApi);
8858   (void)pzErrMsg;  /* Unused parameter */
8859   return zipfileRegister(db);
8860 }
8861 
8862 /************************* End ../ext/misc/zipfile.c ********************/
8863 /************************* Begin ../ext/misc/sqlar.c ******************/
8864 /*
8865 ** 2017-12-17
8866 **
8867 ** The author disclaims copyright to this source code.  In place of
8868 ** a legal notice, here is a blessing:
8869 **
8870 **    May you do good and not evil.
8871 **    May you find forgiveness for yourself and forgive others.
8872 **    May you share freely, never taking more than you give.
8873 **
8874 ******************************************************************************
8875 **
8876 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
8877 ** for working with sqlar archives and used by the shell tool's built-in
8878 ** sqlar support.
8879 */
8880 /* #include "sqlite3ext.h" */
8881 SQLITE_EXTENSION_INIT1
8882 #include <zlib.h>
8883 #include <assert.h>
8884 
8885 /*
8886 ** Implementation of the "sqlar_compress(X)" SQL function.
8887 **
8888 ** If the type of X is SQLITE_BLOB, and compressing that blob using
8889 ** zlib utility function compress() yields a smaller blob, return the
8890 ** compressed blob. Otherwise, return a copy of X.
8891 **
8892 ** SQLar uses the "zlib format" for compressed content.  The zlib format
8893 ** contains a two-byte identification header and a four-byte checksum at
8894 ** the end.  This is different from ZIP which uses the raw deflate format.
8895 **
8896 ** Future enhancements to SQLar might add support for new compression formats.
8897 ** If so, those new formats will be identified by alternative headers in the
8898 ** compressed data.
8899 */
sqlarCompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)8900 static void sqlarCompressFunc(
8901   sqlite3_context *context,
8902   int argc,
8903   sqlite3_value **argv
8904 ){
8905   assert( argc==1 );
8906   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
8907     const Bytef *pData = sqlite3_value_blob(argv[0]);
8908     uLong nData = sqlite3_value_bytes(argv[0]);
8909     uLongf nOut = compressBound(nData);
8910     Bytef *pOut;
8911 
8912     pOut = (Bytef*)sqlite3_malloc(nOut);
8913     if( pOut==0 ){
8914       sqlite3_result_error_nomem(context);
8915       return;
8916     }else{
8917       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
8918         sqlite3_result_error(context, "error in compress()", -1);
8919       }else if( nOut<nData ){
8920         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
8921       }else{
8922         sqlite3_result_value(context, argv[0]);
8923       }
8924       sqlite3_free(pOut);
8925     }
8926   }else{
8927     sqlite3_result_value(context, argv[0]);
8928   }
8929 }
8930 
8931 /*
8932 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
8933 **
8934 ** Parameter SZ is interpreted as an integer. If it is less than or
8935 ** equal to zero, then this function returns a copy of X. Or, if
8936 ** SZ is equal to the size of X when interpreted as a blob, also
8937 ** return a copy of X. Otherwise, decompress blob X using zlib
8938 ** utility function uncompress() and return the results (another
8939 ** blob).
8940 */
sqlarUncompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)8941 static void sqlarUncompressFunc(
8942   sqlite3_context *context,
8943   int argc,
8944   sqlite3_value **argv
8945 ){
8946   uLong nData;
8947   uLongf sz;
8948 
8949   assert( argc==2 );
8950   sz = sqlite3_value_int(argv[1]);
8951 
8952   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
8953     sqlite3_result_value(context, argv[0]);
8954   }else{
8955     const Bytef *pData= sqlite3_value_blob(argv[0]);
8956     Bytef *pOut = sqlite3_malloc(sz);
8957     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
8958       sqlite3_result_error(context, "error in uncompress()", -1);
8959     }else{
8960       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
8961     }
8962     sqlite3_free(pOut);
8963   }
8964 }
8965 
8966 
8967 #ifdef _WIN32
8968 
8969 #endif
sqlite3_sqlar_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8970 int sqlite3_sqlar_init(
8971   sqlite3 *db,
8972   char **pzErrMsg,
8973   const sqlite3_api_routines *pApi
8974 ){
8975   int rc = SQLITE_OK;
8976   SQLITE_EXTENSION_INIT2(pApi);
8977   (void)pzErrMsg;  /* Unused parameter */
8978   rc = sqlite3_create_function(db, "sqlar_compress", 1,
8979                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
8980                                sqlarCompressFunc, 0, 0);
8981   if( rc==SQLITE_OK ){
8982     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
8983                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
8984                                  sqlarUncompressFunc, 0, 0);
8985   }
8986   return rc;
8987 }
8988 
8989 /************************* End ../ext/misc/sqlar.c ********************/
8990 #endif
8991 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
8992 /*
8993 ** 2017 April 07
8994 **
8995 ** The author disclaims copyright to this source code.  In place of
8996 ** a legal notice, here is a blessing:
8997 **
8998 **    May you do good and not evil.
8999 **    May you find forgiveness for yourself and forgive others.
9000 **    May you share freely, never taking more than you give.
9001 **
9002 *************************************************************************
9003 */
9004 #if !defined(SQLITEEXPERT_H)
9005 #define SQLITEEXPERT_H 1
9006 /* #include "sqlite3.h" */
9007 
9008 typedef struct sqlite3expert sqlite3expert;
9009 
9010 /*
9011 ** Create a new sqlite3expert object.
9012 **
9013 ** If successful, a pointer to the new object is returned and (*pzErr) set
9014 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
9015 ** an English-language error message. In this case it is the responsibility
9016 ** of the caller to eventually free the error message buffer using
9017 ** sqlite3_free().
9018 */
9019 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
9020 
9021 /*
9022 ** Configure an sqlite3expert object.
9023 **
9024 ** EXPERT_CONFIG_SAMPLE:
9025 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
9026 **   each candidate index. This involves scanning and sorting the entire
9027 **   contents of each user database table once for each candidate index
9028 **   associated with the table. For large databases, this can be
9029 **   prohibitively slow. This option allows the sqlite3expert object to
9030 **   be configured so that sqlite_stat1 data is instead generated based on a
9031 **   subset of each table, or so that no sqlite_stat1 data is used at all.
9032 **
9033 **   A single integer argument is passed to this option. If the value is less
9034 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
9035 **   the analysis - indexes are recommended based on the database schema only.
9036 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
9037 **   generated for each candidate index (this is the default). Finally, if the
9038 **   value falls between 0 and 100, then it represents the percentage of user
9039 **   table rows that should be considered when generating sqlite_stat1 data.
9040 **
9041 **   Examples:
9042 **
9043 **     // Do not generate any sqlite_stat1 data
9044 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
9045 **
9046 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
9047 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
9048 */
9049 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
9050 
9051 #define EXPERT_CONFIG_SAMPLE 1    /* int */
9052 
9053 /*
9054 ** Specify zero or more SQL statements to be included in the analysis.
9055 **
9056 ** Buffer zSql must contain zero or more complete SQL statements. This
9057 ** function parses all statements contained in the buffer and adds them
9058 ** to the internal list of statements to analyze. If successful, SQLITE_OK
9059 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
9060 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
9061 ** may be set to point to an English language error message. In this case
9062 ** the caller is responsible for eventually freeing the error message buffer
9063 ** using sqlite3_free().
9064 **
9065 ** If an error does occur while processing one of the statements in the
9066 ** buffer passed as the second argument, none of the statements in the
9067 ** buffer are added to the analysis.
9068 **
9069 ** This function must be called before sqlite3_expert_analyze(). If a call
9070 ** to this function is made on an sqlite3expert object that has already
9071 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
9072 ** immediately and no statements are added to the analysis.
9073 */
9074 int sqlite3_expert_sql(
9075   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
9076   const char *zSql,               /* SQL statement(s) to add */
9077   char **pzErr                    /* OUT: Error message (if any) */
9078 );
9079 
9080 
9081 /*
9082 ** This function is called after the sqlite3expert object has been configured
9083 ** with all SQL statements using sqlite3_expert_sql() to actually perform
9084 ** the analysis. Once this function has been called, it is not possible to
9085 ** add further SQL statements to the analysis.
9086 **
9087 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
9088 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
9089 ** point to a buffer containing an English language error message. In this
9090 ** case it is the responsibility of the caller to eventually free the buffer
9091 ** using sqlite3_free().
9092 **
9093 ** If an error does occur within this function, the sqlite3expert object
9094 ** is no longer useful for any purpose. At that point it is no longer
9095 ** possible to add further SQL statements to the object or to re-attempt
9096 ** the analysis. The sqlite3expert object must still be freed using a call
9097 ** sqlite3_expert_destroy().
9098 */
9099 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
9100 
9101 /*
9102 ** Return the total number of statements loaded using sqlite3_expert_sql().
9103 ** The total number of SQL statements may be different from the total number
9104 ** to calls to sqlite3_expert_sql().
9105 */
9106 int sqlite3_expert_count(sqlite3expert*);
9107 
9108 /*
9109 ** Return a component of the report.
9110 **
9111 ** This function is called after sqlite3_expert_analyze() to extract the
9112 ** results of the analysis. Each call to this function returns either a
9113 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
9114 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
9115 ** #define constants defined below.
9116 **
9117 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
9118 ** information relating to a specific SQL statement. In these cases that
9119 ** SQL statement is identified by the value passed as the second argument.
9120 ** SQL statements are numbered from 0 in the order in which they are parsed.
9121 ** If an out-of-range value (less than zero or equal to or greater than the
9122 ** value returned by sqlite3_expert_count()) is passed as the second argument
9123 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
9124 **
9125 ** EXPERT_REPORT_SQL:
9126 **   Return the text of SQL statement iStmt.
9127 **
9128 ** EXPERT_REPORT_INDEXES:
9129 **   Return a buffer containing the CREATE INDEX statements for all recommended
9130 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
9131 **   is returned.
9132 **
9133 ** EXPERT_REPORT_PLAN:
9134 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
9135 **   iStmt after the proposed indexes have been added to the database schema.
9136 **
9137 ** EXPERT_REPORT_CANDIDATES:
9138 **   Return a pointer to a buffer containing the CREATE INDEX statements
9139 **   for all indexes that were tested (for all SQL statements). The iStmt
9140 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
9141 */
9142 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
9143 
9144 /*
9145 ** Values for the third argument passed to sqlite3_expert_report().
9146 */
9147 #define EXPERT_REPORT_SQL        1
9148 #define EXPERT_REPORT_INDEXES    2
9149 #define EXPERT_REPORT_PLAN       3
9150 #define EXPERT_REPORT_CANDIDATES 4
9151 
9152 /*
9153 ** Free an (sqlite3expert*) handle and all associated resources. There
9154 ** should be one call to this function for each successful call to
9155 ** sqlite3-expert_new().
9156 */
9157 void sqlite3_expert_destroy(sqlite3expert*);
9158 
9159 #endif  /* !defined(SQLITEEXPERT_H) */
9160 
9161 /************************* End ../ext/expert/sqlite3expert.h ********************/
9162 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
9163 /*
9164 ** 2017 April 09
9165 **
9166 ** The author disclaims copyright to this source code.  In place of
9167 ** a legal notice, here is a blessing:
9168 **
9169 **    May you do good and not evil.
9170 **    May you find forgiveness for yourself and forgive others.
9171 **    May you share freely, never taking more than you give.
9172 **
9173 *************************************************************************
9174 */
9175 /* #include "sqlite3expert.h" */
9176 #include <assert.h>
9177 #include <string.h>
9178 #include <stdio.h>
9179 
9180 #ifndef SQLITE_OMIT_VIRTUALTABLE
9181 
9182 /* typedef sqlite3_int64 i64; */
9183 /* typedef sqlite3_uint64 u64; */
9184 
9185 typedef struct IdxColumn IdxColumn;
9186 typedef struct IdxConstraint IdxConstraint;
9187 typedef struct IdxScan IdxScan;
9188 typedef struct IdxStatement IdxStatement;
9189 typedef struct IdxTable IdxTable;
9190 typedef struct IdxWrite IdxWrite;
9191 
9192 #define STRLEN  (int)strlen
9193 
9194 /*
9195 ** A temp table name that we assume no user database will actually use.
9196 ** If this assumption proves incorrect triggers on the table with the
9197 ** conflicting name will be ignored.
9198 */
9199 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
9200 
9201 /*
9202 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
9203 ** any other type of single-ended range constraint on a column).
9204 **
9205 ** pLink:
9206 **   Used to temporarily link IdxConstraint objects into lists while
9207 **   creating candidate indexes.
9208 */
9209 struct IdxConstraint {
9210   char *zColl;                    /* Collation sequence */
9211   int bRange;                     /* True for range, false for eq */
9212   int iCol;                       /* Constrained table column */
9213   int bFlag;                      /* Used by idxFindCompatible() */
9214   int bDesc;                      /* True if ORDER BY <expr> DESC */
9215   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
9216   IdxConstraint *pLink;           /* See above */
9217 };
9218 
9219 /*
9220 ** A single scan of a single table.
9221 */
9222 struct IdxScan {
9223   IdxTable *pTab;                 /* Associated table object */
9224   int iDb;                        /* Database containing table zTable */
9225   i64 covering;                   /* Mask of columns required for cov. index */
9226   IdxConstraint *pOrder;          /* ORDER BY columns */
9227   IdxConstraint *pEq;             /* List of == constraints */
9228   IdxConstraint *pRange;          /* List of < constraints */
9229   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
9230 };
9231 
9232 /*
9233 ** Information regarding a single database table. Extracted from
9234 ** "PRAGMA table_info" by function idxGetTableInfo().
9235 */
9236 struct IdxColumn {
9237   char *zName;
9238   char *zColl;
9239   int iPk;
9240 };
9241 struct IdxTable {
9242   int nCol;
9243   char *zName;                    /* Table name */
9244   IdxColumn *aCol;
9245   IdxTable *pNext;                /* Next table in linked list of all tables */
9246 };
9247 
9248 /*
9249 ** An object of the following type is created for each unique table/write-op
9250 ** seen. The objects are stored in a singly-linked list beginning at
9251 ** sqlite3expert.pWrite.
9252 */
9253 struct IdxWrite {
9254   IdxTable *pTab;
9255   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
9256   IdxWrite *pNext;
9257 };
9258 
9259 /*
9260 ** Each statement being analyzed is represented by an instance of this
9261 ** structure.
9262 */
9263 struct IdxStatement {
9264   int iId;                        /* Statement number */
9265   char *zSql;                     /* SQL statement */
9266   char *zIdx;                     /* Indexes */
9267   char *zEQP;                     /* Plan */
9268   IdxStatement *pNext;
9269 };
9270 
9271 
9272 /*
9273 ** A hash table for storing strings. With space for a payload string
9274 ** with each entry. Methods are:
9275 **
9276 **   idxHashInit()
9277 **   idxHashClear()
9278 **   idxHashAdd()
9279 **   idxHashSearch()
9280 */
9281 #define IDX_HASH_SIZE 1023
9282 typedef struct IdxHashEntry IdxHashEntry;
9283 typedef struct IdxHash IdxHash;
9284 struct IdxHashEntry {
9285   char *zKey;                     /* nul-terminated key */
9286   char *zVal;                     /* nul-terminated value string */
9287   char *zVal2;                    /* nul-terminated value string 2 */
9288   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
9289   IdxHashEntry *pNext;            /* Next entry in hash */
9290 };
9291 struct IdxHash {
9292   IdxHashEntry *pFirst;
9293   IdxHashEntry *aHash[IDX_HASH_SIZE];
9294 };
9295 
9296 /*
9297 ** sqlite3expert object.
9298 */
9299 struct sqlite3expert {
9300   int iSample;                    /* Percentage of tables to sample for stat1 */
9301   sqlite3 *db;                    /* User database */
9302   sqlite3 *dbm;                   /* In-memory db for this analysis */
9303   sqlite3 *dbv;                   /* Vtab schema for this analysis */
9304   IdxTable *pTable;               /* List of all IdxTable objects */
9305   IdxScan *pScan;                 /* List of scan objects */
9306   IdxWrite *pWrite;               /* List of write objects */
9307   IdxStatement *pStatement;       /* List of IdxStatement objects */
9308   int bRun;                       /* True once analysis has run */
9309   char **pzErrmsg;
9310   int rc;                         /* Error code from whereinfo hook */
9311   IdxHash hIdx;                   /* Hash containing all candidate indexes */
9312   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
9313 };
9314 
9315 
9316 /*
9317 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
9318 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
9319 */
idxMalloc(int * pRc,int nByte)9320 static void *idxMalloc(int *pRc, int nByte){
9321   void *pRet;
9322   assert( *pRc==SQLITE_OK );
9323   assert( nByte>0 );
9324   pRet = sqlite3_malloc(nByte);
9325   if( pRet ){
9326     memset(pRet, 0, nByte);
9327   }else{
9328     *pRc = SQLITE_NOMEM;
9329   }
9330   return pRet;
9331 }
9332 
9333 /*
9334 ** Initialize an IdxHash hash table.
9335 */
idxHashInit(IdxHash * pHash)9336 static void idxHashInit(IdxHash *pHash){
9337   memset(pHash, 0, sizeof(IdxHash));
9338 }
9339 
9340 /*
9341 ** Reset an IdxHash hash table.
9342 */
idxHashClear(IdxHash * pHash)9343 static void idxHashClear(IdxHash *pHash){
9344   int i;
9345   for(i=0; i<IDX_HASH_SIZE; i++){
9346     IdxHashEntry *pEntry;
9347     IdxHashEntry *pNext;
9348     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
9349       pNext = pEntry->pHashNext;
9350       sqlite3_free(pEntry->zVal2);
9351       sqlite3_free(pEntry);
9352     }
9353   }
9354   memset(pHash, 0, sizeof(IdxHash));
9355 }
9356 
9357 /*
9358 ** Return the index of the hash bucket that the string specified by the
9359 ** arguments to this function belongs.
9360 */
idxHashString(const char * z,int n)9361 static int idxHashString(const char *z, int n){
9362   unsigned int ret = 0;
9363   int i;
9364   for(i=0; i<n; i++){
9365     ret += (ret<<3) + (unsigned char)(z[i]);
9366   }
9367   return (int)(ret % IDX_HASH_SIZE);
9368 }
9369 
9370 /*
9371 ** If zKey is already present in the hash table, return non-zero and do
9372 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
9373 ** the hash table passed as the second argument.
9374 */
idxHashAdd(int * pRc,IdxHash * pHash,const char * zKey,const char * zVal)9375 static int idxHashAdd(
9376   int *pRc,
9377   IdxHash *pHash,
9378   const char *zKey,
9379   const char *zVal
9380 ){
9381   int nKey = STRLEN(zKey);
9382   int iHash = idxHashString(zKey, nKey);
9383   int nVal = (zVal ? STRLEN(zVal) : 0);
9384   IdxHashEntry *pEntry;
9385   assert( iHash>=0 );
9386   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
9387     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
9388       return 1;
9389     }
9390   }
9391   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
9392   if( pEntry ){
9393     pEntry->zKey = (char*)&pEntry[1];
9394     memcpy(pEntry->zKey, zKey, nKey);
9395     if( zVal ){
9396       pEntry->zVal = &pEntry->zKey[nKey+1];
9397       memcpy(pEntry->zVal, zVal, nVal);
9398     }
9399     pEntry->pHashNext = pHash->aHash[iHash];
9400     pHash->aHash[iHash] = pEntry;
9401 
9402     pEntry->pNext = pHash->pFirst;
9403     pHash->pFirst = pEntry;
9404   }
9405   return 0;
9406 }
9407 
9408 /*
9409 ** If zKey/nKey is present in the hash table, return a pointer to the
9410 ** hash-entry object.
9411 */
idxHashFind(IdxHash * pHash,const char * zKey,int nKey)9412 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
9413   int iHash;
9414   IdxHashEntry *pEntry;
9415   if( nKey<0 ) nKey = STRLEN(zKey);
9416   iHash = idxHashString(zKey, nKey);
9417   assert( iHash>=0 );
9418   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
9419     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
9420       return pEntry;
9421     }
9422   }
9423   return 0;
9424 }
9425 
9426 /*
9427 ** If the hash table contains an entry with a key equal to the string
9428 ** passed as the final two arguments to this function, return a pointer
9429 ** to the payload string. Otherwise, if zKey/nKey is not present in the
9430 ** hash table, return NULL.
9431 */
idxHashSearch(IdxHash * pHash,const char * zKey,int nKey)9432 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
9433   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
9434   if( pEntry ) return pEntry->zVal;
9435   return 0;
9436 }
9437 
9438 /*
9439 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
9440 ** variable to point to a copy of nul-terminated string zColl.
9441 */
idxNewConstraint(int * pRc,const char * zColl)9442 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
9443   IdxConstraint *pNew;
9444   int nColl = STRLEN(zColl);
9445 
9446   assert( *pRc==SQLITE_OK );
9447   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
9448   if( pNew ){
9449     pNew->zColl = (char*)&pNew[1];
9450     memcpy(pNew->zColl, zColl, nColl+1);
9451   }
9452   return pNew;
9453 }
9454 
9455 /*
9456 ** An error associated with database handle db has just occurred. Pass
9457 ** the error message to callback function xOut.
9458 */
idxDatabaseError(sqlite3 * db,char ** pzErrmsg)9459 static void idxDatabaseError(
9460   sqlite3 *db,                    /* Database handle */
9461   char **pzErrmsg                 /* Write error here */
9462 ){
9463   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
9464 }
9465 
9466 /*
9467 ** Prepare an SQL statement.
9468 */
idxPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zSql)9469 static int idxPrepareStmt(
9470   sqlite3 *db,                    /* Database handle to compile against */
9471   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
9472   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
9473   const char *zSql                /* SQL statement to compile */
9474 ){
9475   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
9476   if( rc!=SQLITE_OK ){
9477     *ppStmt = 0;
9478     idxDatabaseError(db, pzErrmsg);
9479   }
9480   return rc;
9481 }
9482 
9483 /*
9484 ** Prepare an SQL statement using the results of a printf() formatting.
9485 */
idxPrintfPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zFmt,...)9486 static int idxPrintfPrepareStmt(
9487   sqlite3 *db,                    /* Database handle to compile against */
9488   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
9489   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
9490   const char *zFmt,               /* printf() format of SQL statement */
9491   ...                             /* Trailing printf() arguments */
9492 ){
9493   va_list ap;
9494   int rc;
9495   char *zSql;
9496   va_start(ap, zFmt);
9497   zSql = sqlite3_vmprintf(zFmt, ap);
9498   if( zSql==0 ){
9499     rc = SQLITE_NOMEM;
9500   }else{
9501     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
9502     sqlite3_free(zSql);
9503   }
9504   va_end(ap);
9505   return rc;
9506 }
9507 
9508 
9509 /*************************************************************************
9510 ** Beginning of virtual table implementation.
9511 */
9512 typedef struct ExpertVtab ExpertVtab;
9513 struct ExpertVtab {
9514   sqlite3_vtab base;
9515   IdxTable *pTab;
9516   sqlite3expert *pExpert;
9517 };
9518 
9519 typedef struct ExpertCsr ExpertCsr;
9520 struct ExpertCsr {
9521   sqlite3_vtab_cursor base;
9522   sqlite3_stmt *pData;
9523 };
9524 
expertDequote(const char * zIn)9525 static char *expertDequote(const char *zIn){
9526   int n = STRLEN(zIn);
9527   char *zRet = sqlite3_malloc(n);
9528 
9529   assert( zIn[0]=='\'' );
9530   assert( zIn[n-1]=='\'' );
9531 
9532   if( zRet ){
9533     int iOut = 0;
9534     int iIn = 0;
9535     for(iIn=1; iIn<(n-1); iIn++){
9536       if( zIn[iIn]=='\'' ){
9537         assert( zIn[iIn+1]=='\'' );
9538         iIn++;
9539       }
9540       zRet[iOut++] = zIn[iIn];
9541     }
9542     zRet[iOut] = '\0';
9543   }
9544 
9545   return zRet;
9546 }
9547 
9548 /*
9549 ** This function is the implementation of both the xConnect and xCreate
9550 ** methods of the r-tree virtual table.
9551 **
9552 **   argv[0]   -> module name
9553 **   argv[1]   -> database name
9554 **   argv[2]   -> table name
9555 **   argv[...] -> column names...
9556 */
expertConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)9557 static int expertConnect(
9558   sqlite3 *db,
9559   void *pAux,
9560   int argc, const char *const*argv,
9561   sqlite3_vtab **ppVtab,
9562   char **pzErr
9563 ){
9564   sqlite3expert *pExpert = (sqlite3expert*)pAux;
9565   ExpertVtab *p = 0;
9566   int rc;
9567 
9568   if( argc!=4 ){
9569     *pzErr = sqlite3_mprintf("internal error!");
9570     rc = SQLITE_ERROR;
9571   }else{
9572     char *zCreateTable = expertDequote(argv[3]);
9573     if( zCreateTable ){
9574       rc = sqlite3_declare_vtab(db, zCreateTable);
9575       if( rc==SQLITE_OK ){
9576         p = idxMalloc(&rc, sizeof(ExpertVtab));
9577       }
9578       if( rc==SQLITE_OK ){
9579         p->pExpert = pExpert;
9580         p->pTab = pExpert->pTable;
9581         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
9582       }
9583       sqlite3_free(zCreateTable);
9584     }else{
9585       rc = SQLITE_NOMEM;
9586     }
9587   }
9588 
9589   *ppVtab = (sqlite3_vtab*)p;
9590   return rc;
9591 }
9592 
expertDisconnect(sqlite3_vtab * pVtab)9593 static int expertDisconnect(sqlite3_vtab *pVtab){
9594   ExpertVtab *p = (ExpertVtab*)pVtab;
9595   sqlite3_free(p);
9596   return SQLITE_OK;
9597 }
9598 
expertBestIndex(sqlite3_vtab * pVtab,sqlite3_index_info * pIdxInfo)9599 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
9600   ExpertVtab *p = (ExpertVtab*)pVtab;
9601   int rc = SQLITE_OK;
9602   int n = 0;
9603   IdxScan *pScan;
9604   const int opmask =
9605     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
9606     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
9607     SQLITE_INDEX_CONSTRAINT_LE;
9608 
9609   pScan = idxMalloc(&rc, sizeof(IdxScan));
9610   if( pScan ){
9611     int i;
9612 
9613     /* Link the new scan object into the list */
9614     pScan->pTab = p->pTab;
9615     pScan->pNextScan = p->pExpert->pScan;
9616     p->pExpert->pScan = pScan;
9617 
9618     /* Add the constraints to the IdxScan object */
9619     for(i=0; i<pIdxInfo->nConstraint; i++){
9620       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
9621       if( pCons->usable
9622        && pCons->iColumn>=0
9623        && p->pTab->aCol[pCons->iColumn].iPk==0
9624        && (pCons->op & opmask)
9625       ){
9626         IdxConstraint *pNew;
9627         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
9628         pNew = idxNewConstraint(&rc, zColl);
9629         if( pNew ){
9630           pNew->iCol = pCons->iColumn;
9631           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
9632             pNew->pNext = pScan->pEq;
9633             pScan->pEq = pNew;
9634           }else{
9635             pNew->bRange = 1;
9636             pNew->pNext = pScan->pRange;
9637             pScan->pRange = pNew;
9638           }
9639         }
9640         n++;
9641         pIdxInfo->aConstraintUsage[i].argvIndex = n;
9642       }
9643     }
9644 
9645     /* Add the ORDER BY to the IdxScan object */
9646     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
9647       int iCol = pIdxInfo->aOrderBy[i].iColumn;
9648       if( iCol>=0 ){
9649         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
9650         if( pNew ){
9651           pNew->iCol = iCol;
9652           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
9653           pNew->pNext = pScan->pOrder;
9654           pNew->pLink = pScan->pOrder;
9655           pScan->pOrder = pNew;
9656           n++;
9657         }
9658       }
9659     }
9660   }
9661 
9662   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
9663   return rc;
9664 }
9665 
expertUpdate(sqlite3_vtab * pVtab,int nData,sqlite3_value ** azData,sqlite_int64 * pRowid)9666 static int expertUpdate(
9667   sqlite3_vtab *pVtab,
9668   int nData,
9669   sqlite3_value **azData,
9670   sqlite_int64 *pRowid
9671 ){
9672   (void)pVtab;
9673   (void)nData;
9674   (void)azData;
9675   (void)pRowid;
9676   return SQLITE_OK;
9677 }
9678 
9679 /*
9680 ** Virtual table module xOpen method.
9681 */
expertOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)9682 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
9683   int rc = SQLITE_OK;
9684   ExpertCsr *pCsr;
9685   (void)pVTab;
9686   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
9687   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
9688   return rc;
9689 }
9690 
9691 /*
9692 ** Virtual table module xClose method.
9693 */
expertClose(sqlite3_vtab_cursor * cur)9694 static int expertClose(sqlite3_vtab_cursor *cur){
9695   ExpertCsr *pCsr = (ExpertCsr*)cur;
9696   sqlite3_finalize(pCsr->pData);
9697   sqlite3_free(pCsr);
9698   return SQLITE_OK;
9699 }
9700 
9701 /*
9702 ** Virtual table module xEof method.
9703 **
9704 ** Return non-zero if the cursor does not currently point to a valid
9705 ** record (i.e if the scan has finished), or zero otherwise.
9706 */
expertEof(sqlite3_vtab_cursor * cur)9707 static int expertEof(sqlite3_vtab_cursor *cur){
9708   ExpertCsr *pCsr = (ExpertCsr*)cur;
9709   return pCsr->pData==0;
9710 }
9711 
9712 /*
9713 ** Virtual table module xNext method.
9714 */
expertNext(sqlite3_vtab_cursor * cur)9715 static int expertNext(sqlite3_vtab_cursor *cur){
9716   ExpertCsr *pCsr = (ExpertCsr*)cur;
9717   int rc = SQLITE_OK;
9718 
9719   assert( pCsr->pData );
9720   rc = sqlite3_step(pCsr->pData);
9721   if( rc!=SQLITE_ROW ){
9722     rc = sqlite3_finalize(pCsr->pData);
9723     pCsr->pData = 0;
9724   }else{
9725     rc = SQLITE_OK;
9726   }
9727 
9728   return rc;
9729 }
9730 
9731 /*
9732 ** Virtual table module xRowid method.
9733 */
expertRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)9734 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
9735   (void)cur;
9736   *pRowid = 0;
9737   return SQLITE_OK;
9738 }
9739 
9740 /*
9741 ** Virtual table module xColumn method.
9742 */
expertColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)9743 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
9744   ExpertCsr *pCsr = (ExpertCsr*)cur;
9745   sqlite3_value *pVal;
9746   pVal = sqlite3_column_value(pCsr->pData, i);
9747   if( pVal ){
9748     sqlite3_result_value(ctx, pVal);
9749   }
9750   return SQLITE_OK;
9751 }
9752 
9753 /*
9754 ** Virtual table module xFilter method.
9755 */
expertFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)9756 static int expertFilter(
9757   sqlite3_vtab_cursor *cur,
9758   int idxNum, const char *idxStr,
9759   int argc, sqlite3_value **argv
9760 ){
9761   ExpertCsr *pCsr = (ExpertCsr*)cur;
9762   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
9763   sqlite3expert *pExpert = pVtab->pExpert;
9764   int rc;
9765 
9766   (void)idxNum;
9767   (void)idxStr;
9768   (void)argc;
9769   (void)argv;
9770   rc = sqlite3_finalize(pCsr->pData);
9771   pCsr->pData = 0;
9772   if( rc==SQLITE_OK ){
9773     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
9774         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
9775     );
9776   }
9777 
9778   if( rc==SQLITE_OK ){
9779     rc = expertNext(cur);
9780   }
9781   return rc;
9782 }
9783 
idxRegisterVtab(sqlite3expert * p)9784 static int idxRegisterVtab(sqlite3expert *p){
9785   static sqlite3_module expertModule = {
9786     2,                            /* iVersion */
9787     expertConnect,                /* xCreate - create a table */
9788     expertConnect,                /* xConnect - connect to an existing table */
9789     expertBestIndex,              /* xBestIndex - Determine search strategy */
9790     expertDisconnect,             /* xDisconnect - Disconnect from a table */
9791     expertDisconnect,             /* xDestroy - Drop a table */
9792     expertOpen,                   /* xOpen - open a cursor */
9793     expertClose,                  /* xClose - close a cursor */
9794     expertFilter,                 /* xFilter - configure scan constraints */
9795     expertNext,                   /* xNext - advance a cursor */
9796     expertEof,                    /* xEof */
9797     expertColumn,                 /* xColumn - read data */
9798     expertRowid,                  /* xRowid - read data */
9799     expertUpdate,                 /* xUpdate - write data */
9800     0,                            /* xBegin - begin transaction */
9801     0,                            /* xSync - sync transaction */
9802     0,                            /* xCommit - commit transaction */
9803     0,                            /* xRollback - rollback transaction */
9804     0,                            /* xFindFunction - function overloading */
9805     0,                            /* xRename - rename the table */
9806     0,                            /* xSavepoint */
9807     0,                            /* xRelease */
9808     0,                            /* xRollbackTo */
9809     0,                            /* xShadowName */
9810   };
9811 
9812   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
9813 }
9814 /*
9815 ** End of virtual table implementation.
9816 *************************************************************************/
9817 /*
9818 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
9819 ** is called, set it to the return value of sqlite3_finalize() before
9820 ** returning. Otherwise, discard the sqlite3_finalize() return value.
9821 */
idxFinalize(int * pRc,sqlite3_stmt * pStmt)9822 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
9823   int rc = sqlite3_finalize(pStmt);
9824   if( *pRc==SQLITE_OK ) *pRc = rc;
9825 }
9826 
9827 /*
9828 ** Attempt to allocate an IdxTable structure corresponding to table zTab
9829 ** in the main database of connection db. If successful, set (*ppOut) to
9830 ** point to the new object and return SQLITE_OK. Otherwise, return an
9831 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
9832 ** set to point to an error string.
9833 **
9834 ** It is the responsibility of the caller to eventually free either the
9835 ** IdxTable object or error message using sqlite3_free().
9836 */
idxGetTableInfo(sqlite3 * db,const char * zTab,IdxTable ** ppOut,char ** pzErrmsg)9837 static int idxGetTableInfo(
9838   sqlite3 *db,                    /* Database connection to read details from */
9839   const char *zTab,               /* Table name */
9840   IdxTable **ppOut,               /* OUT: New object (if successful) */
9841   char **pzErrmsg                 /* OUT: Error message (if not) */
9842 ){
9843   sqlite3_stmt *p1 = 0;
9844   int nCol = 0;
9845   int nTab = STRLEN(zTab);
9846   int nByte = sizeof(IdxTable) + nTab + 1;
9847   IdxTable *pNew = 0;
9848   int rc, rc2;
9849   char *pCsr = 0;
9850   int nPk = 0;
9851 
9852   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
9853   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
9854     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
9855     const char *zColSeq = 0;
9856     nByte += 1 + STRLEN(zCol);
9857     rc = sqlite3_table_column_metadata(
9858         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
9859     );
9860     if( zColSeq==0 ) zColSeq = "binary";
9861     nByte += 1 + STRLEN(zColSeq);
9862     nCol++;
9863     nPk += (sqlite3_column_int(p1, 5)>0);
9864   }
9865   rc2 = sqlite3_reset(p1);
9866   if( rc==SQLITE_OK ) rc = rc2;
9867 
9868   nByte += sizeof(IdxColumn) * nCol;
9869   if( rc==SQLITE_OK ){
9870     pNew = idxMalloc(&rc, nByte);
9871   }
9872   if( rc==SQLITE_OK ){
9873     pNew->aCol = (IdxColumn*)&pNew[1];
9874     pNew->nCol = nCol;
9875     pCsr = (char*)&pNew->aCol[nCol];
9876   }
9877 
9878   nCol = 0;
9879   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
9880     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
9881     const char *zColSeq = 0;
9882     int nCopy = STRLEN(zCol) + 1;
9883     pNew->aCol[nCol].zName = pCsr;
9884     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
9885     memcpy(pCsr, zCol, nCopy);
9886     pCsr += nCopy;
9887 
9888     rc = sqlite3_table_column_metadata(
9889         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
9890     );
9891     if( rc==SQLITE_OK ){
9892       if( zColSeq==0 ) zColSeq = "binary";
9893       nCopy = STRLEN(zColSeq) + 1;
9894       pNew->aCol[nCol].zColl = pCsr;
9895       memcpy(pCsr, zColSeq, nCopy);
9896       pCsr += nCopy;
9897     }
9898 
9899     nCol++;
9900   }
9901   idxFinalize(&rc, p1);
9902 
9903   if( rc!=SQLITE_OK ){
9904     sqlite3_free(pNew);
9905     pNew = 0;
9906   }else{
9907     pNew->zName = pCsr;
9908     memcpy(pNew->zName, zTab, nTab+1);
9909   }
9910 
9911   *ppOut = pNew;
9912   return rc;
9913 }
9914 
9915 /*
9916 ** This function is a no-op if *pRc is set to anything other than
9917 ** SQLITE_OK when it is called.
9918 **
9919 ** If *pRc is initially set to SQLITE_OK, then the text specified by
9920 ** the printf() style arguments is appended to zIn and the result returned
9921 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
9922 ** zIn before returning.
9923 */
idxAppendText(int * pRc,char * zIn,const char * zFmt,...)9924 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
9925   va_list ap;
9926   char *zAppend = 0;
9927   char *zRet = 0;
9928   int nIn = zIn ? STRLEN(zIn) : 0;
9929   int nAppend = 0;
9930   va_start(ap, zFmt);
9931   if( *pRc==SQLITE_OK ){
9932     zAppend = sqlite3_vmprintf(zFmt, ap);
9933     if( zAppend ){
9934       nAppend = STRLEN(zAppend);
9935       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
9936     }
9937     if( zAppend && zRet ){
9938       if( nIn ) memcpy(zRet, zIn, nIn);
9939       memcpy(&zRet[nIn], zAppend, nAppend+1);
9940     }else{
9941       sqlite3_free(zRet);
9942       zRet = 0;
9943       *pRc = SQLITE_NOMEM;
9944     }
9945     sqlite3_free(zAppend);
9946     sqlite3_free(zIn);
9947   }
9948   va_end(ap);
9949   return zRet;
9950 }
9951 
9952 /*
9953 ** Return true if zId must be quoted in order to use it as an SQL
9954 ** identifier, or false otherwise.
9955 */
idxIdentifierRequiresQuotes(const char * zId)9956 static int idxIdentifierRequiresQuotes(const char *zId){
9957   int i;
9958   for(i=0; zId[i]; i++){
9959     if( !(zId[i]=='_')
9960      && !(zId[i]>='0' && zId[i]<='9')
9961      && !(zId[i]>='a' && zId[i]<='z')
9962      && !(zId[i]>='A' && zId[i]<='Z')
9963     ){
9964       return 1;
9965     }
9966   }
9967   return 0;
9968 }
9969 
9970 /*
9971 ** This function appends an index column definition suitable for constraint
9972 ** pCons to the string passed as zIn and returns the result.
9973 */
idxAppendColDefn(int * pRc,char * zIn,IdxTable * pTab,IdxConstraint * pCons)9974 static char *idxAppendColDefn(
9975   int *pRc,                       /* IN/OUT: Error code */
9976   char *zIn,                      /* Column defn accumulated so far */
9977   IdxTable *pTab,                 /* Table index will be created on */
9978   IdxConstraint *pCons
9979 ){
9980   char *zRet = zIn;
9981   IdxColumn *p = &pTab->aCol[pCons->iCol];
9982   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
9983 
9984   if( idxIdentifierRequiresQuotes(p->zName) ){
9985     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
9986   }else{
9987     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
9988   }
9989 
9990   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
9991     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
9992       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
9993     }else{
9994       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
9995     }
9996   }
9997 
9998   if( pCons->bDesc ){
9999     zRet = idxAppendText(pRc, zRet, " DESC");
10000   }
10001   return zRet;
10002 }
10003 
10004 /*
10005 ** Search database dbm for an index compatible with the one idxCreateFromCons()
10006 ** would create from arguments pScan, pEq and pTail. If no error occurs and
10007 ** such an index is found, return non-zero. Or, if no such index is found,
10008 ** return zero.
10009 **
10010 ** If an error occurs, set *pRc to an SQLite error code and return zero.
10011 */
idxFindCompatible(int * pRc,sqlite3 * dbm,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)10012 static int idxFindCompatible(
10013   int *pRc,                       /* OUT: Error code */
10014   sqlite3* dbm,                   /* Database to search */
10015   IdxScan *pScan,                 /* Scan for table to search for index on */
10016   IdxConstraint *pEq,             /* List of == constraints */
10017   IdxConstraint *pTail            /* List of range constraints */
10018 ){
10019   const char *zTbl = pScan->pTab->zName;
10020   sqlite3_stmt *pIdxList = 0;
10021   IdxConstraint *pIter;
10022   int nEq = 0;                    /* Number of elements in pEq */
10023   int rc;
10024 
10025   /* Count the elements in list pEq */
10026   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
10027 
10028   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
10029   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
10030     int bMatch = 1;
10031     IdxConstraint *pT = pTail;
10032     sqlite3_stmt *pInfo = 0;
10033     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
10034 
10035     /* Zero the IdxConstraint.bFlag values in the pEq list */
10036     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
10037 
10038     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
10039     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
10040       int iIdx = sqlite3_column_int(pInfo, 0);
10041       int iCol = sqlite3_column_int(pInfo, 1);
10042       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
10043 
10044       if( iIdx<nEq ){
10045         for(pIter=pEq; pIter; pIter=pIter->pLink){
10046           if( pIter->bFlag ) continue;
10047           if( pIter->iCol!=iCol ) continue;
10048           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
10049           pIter->bFlag = 1;
10050           break;
10051         }
10052         if( pIter==0 ){
10053           bMatch = 0;
10054           break;
10055         }
10056       }else{
10057         if( pT ){
10058           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
10059             bMatch = 0;
10060             break;
10061           }
10062           pT = pT->pLink;
10063         }
10064       }
10065     }
10066     idxFinalize(&rc, pInfo);
10067 
10068     if( rc==SQLITE_OK && bMatch ){
10069       sqlite3_finalize(pIdxList);
10070       return 1;
10071     }
10072   }
10073   idxFinalize(&rc, pIdxList);
10074 
10075   *pRc = rc;
10076   return 0;
10077 }
10078 
idxCreateFromCons(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)10079 static int idxCreateFromCons(
10080   sqlite3expert *p,
10081   IdxScan *pScan,
10082   IdxConstraint *pEq,
10083   IdxConstraint *pTail
10084 ){
10085   sqlite3 *dbm = p->dbm;
10086   int rc = SQLITE_OK;
10087   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
10088     IdxTable *pTab = pScan->pTab;
10089     char *zCols = 0;
10090     char *zIdx = 0;
10091     IdxConstraint *pCons;
10092     unsigned int h = 0;
10093     const char *zFmt;
10094 
10095     for(pCons=pEq; pCons; pCons=pCons->pLink){
10096       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
10097     }
10098     for(pCons=pTail; pCons; pCons=pCons->pLink){
10099       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
10100     }
10101 
10102     if( rc==SQLITE_OK ){
10103       /* Hash the list of columns to come up with a name for the index */
10104       const char *zTable = pScan->pTab->zName;
10105       char *zName;                /* Index name */
10106       int i;
10107       for(i=0; zCols[i]; i++){
10108         h += ((h<<3) + zCols[i]);
10109       }
10110       zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
10111       if( zName==0 ){
10112         rc = SQLITE_NOMEM;
10113       }else{
10114         if( idxIdentifierRequiresQuotes(zTable) ){
10115           zFmt = "CREATE INDEX '%q' ON %Q(%s)";
10116         }else{
10117           zFmt = "CREATE INDEX %s ON %s(%s)";
10118         }
10119         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
10120         if( !zIdx ){
10121           rc = SQLITE_NOMEM;
10122         }else{
10123           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
10124           idxHashAdd(&rc, &p->hIdx, zName, zIdx);
10125         }
10126         sqlite3_free(zName);
10127         sqlite3_free(zIdx);
10128       }
10129     }
10130 
10131     sqlite3_free(zCols);
10132   }
10133   return rc;
10134 }
10135 
10136 /*
10137 ** Return true if list pList (linked by IdxConstraint.pLink) contains
10138 ** a constraint compatible with *p. Otherwise return false.
10139 */
idxFindConstraint(IdxConstraint * pList,IdxConstraint * p)10140 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
10141   IdxConstraint *pCmp;
10142   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
10143     if( p->iCol==pCmp->iCol ) return 1;
10144   }
10145   return 0;
10146 }
10147 
idxCreateFromWhere(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pTail)10148 static int idxCreateFromWhere(
10149   sqlite3expert *p,
10150   IdxScan *pScan,                 /* Create indexes for this scan */
10151   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
10152 ){
10153   IdxConstraint *p1 = 0;
10154   IdxConstraint *pCon;
10155   int rc;
10156 
10157   /* Gather up all the == constraints. */
10158   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
10159     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
10160       pCon->pLink = p1;
10161       p1 = pCon;
10162     }
10163   }
10164 
10165   /* Create an index using the == constraints collected above. And the
10166   ** range constraint/ORDER BY terms passed in by the caller, if any. */
10167   rc = idxCreateFromCons(p, pScan, p1, pTail);
10168 
10169   /* If no range/ORDER BY passed by the caller, create a version of the
10170   ** index for each range constraint.  */
10171   if( pTail==0 ){
10172     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
10173       assert( pCon->pLink==0 );
10174       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
10175         rc = idxCreateFromCons(p, pScan, p1, pCon);
10176       }
10177     }
10178   }
10179 
10180   return rc;
10181 }
10182 
10183 /*
10184 ** Create candidate indexes in database [dbm] based on the data in
10185 ** linked-list pScan.
10186 */
idxCreateCandidates(sqlite3expert * p)10187 static int idxCreateCandidates(sqlite3expert *p){
10188   int rc = SQLITE_OK;
10189   IdxScan *pIter;
10190 
10191   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
10192     rc = idxCreateFromWhere(p, pIter, 0);
10193     if( rc==SQLITE_OK && pIter->pOrder ){
10194       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
10195     }
10196   }
10197 
10198   return rc;
10199 }
10200 
10201 /*
10202 ** Free all elements of the linked list starting at pConstraint.
10203 */
idxConstraintFree(IdxConstraint * pConstraint)10204 static void idxConstraintFree(IdxConstraint *pConstraint){
10205   IdxConstraint *pNext;
10206   IdxConstraint *p;
10207 
10208   for(p=pConstraint; p; p=pNext){
10209     pNext = p->pNext;
10210     sqlite3_free(p);
10211   }
10212 }
10213 
10214 /*
10215 ** Free all elements of the linked list starting from pScan up until pLast
10216 ** (pLast is not freed).
10217 */
idxScanFree(IdxScan * pScan,IdxScan * pLast)10218 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
10219   IdxScan *p;
10220   IdxScan *pNext;
10221   for(p=pScan; p!=pLast; p=pNext){
10222     pNext = p->pNextScan;
10223     idxConstraintFree(p->pOrder);
10224     idxConstraintFree(p->pEq);
10225     idxConstraintFree(p->pRange);
10226     sqlite3_free(p);
10227   }
10228 }
10229 
10230 /*
10231 ** Free all elements of the linked list starting from pStatement up
10232 ** until pLast (pLast is not freed).
10233 */
idxStatementFree(IdxStatement * pStatement,IdxStatement * pLast)10234 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
10235   IdxStatement *p;
10236   IdxStatement *pNext;
10237   for(p=pStatement; p!=pLast; p=pNext){
10238     pNext = p->pNext;
10239     sqlite3_free(p->zEQP);
10240     sqlite3_free(p->zIdx);
10241     sqlite3_free(p);
10242   }
10243 }
10244 
10245 /*
10246 ** Free the linked list of IdxTable objects starting at pTab.
10247 */
idxTableFree(IdxTable * pTab)10248 static void idxTableFree(IdxTable *pTab){
10249   IdxTable *pIter;
10250   IdxTable *pNext;
10251   for(pIter=pTab; pIter; pIter=pNext){
10252     pNext = pIter->pNext;
10253     sqlite3_free(pIter);
10254   }
10255 }
10256 
10257 /*
10258 ** Free the linked list of IdxWrite objects starting at pTab.
10259 */
idxWriteFree(IdxWrite * pTab)10260 static void idxWriteFree(IdxWrite *pTab){
10261   IdxWrite *pIter;
10262   IdxWrite *pNext;
10263   for(pIter=pTab; pIter; pIter=pNext){
10264     pNext = pIter->pNext;
10265     sqlite3_free(pIter);
10266   }
10267 }
10268 
10269 
10270 
10271 /*
10272 ** This function is called after candidate indexes have been created. It
10273 ** runs all the queries to see which indexes they prefer, and populates
10274 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
10275 */
idxFindIndexes(sqlite3expert * p,char ** pzErr)10276 int idxFindIndexes(
10277   sqlite3expert *p,
10278   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
10279 ){
10280   IdxStatement *pStmt;
10281   sqlite3 *dbm = p->dbm;
10282   int rc = SQLITE_OK;
10283 
10284   IdxHash hIdx;
10285   idxHashInit(&hIdx);
10286 
10287   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
10288     IdxHashEntry *pEntry;
10289     sqlite3_stmt *pExplain = 0;
10290     idxHashClear(&hIdx);
10291     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
10292         "EXPLAIN QUERY PLAN %s", pStmt->zSql
10293     );
10294     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
10295       /* int iId = sqlite3_column_int(pExplain, 0); */
10296       /* int iParent = sqlite3_column_int(pExplain, 1); */
10297       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
10298       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
10299       int nDetail;
10300       int i;
10301 
10302       if( !zDetail ) continue;
10303       nDetail = STRLEN(zDetail);
10304 
10305       for(i=0; i<nDetail; i++){
10306         const char *zIdx = 0;
10307         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
10308           zIdx = &zDetail[i+13];
10309         }else if( i+22<nDetail
10310             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
10311         ){
10312           zIdx = &zDetail[i+22];
10313         }
10314         if( zIdx ){
10315           const char *zSql;
10316           int nIdx = 0;
10317           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
10318             nIdx++;
10319           }
10320           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
10321           if( zSql ){
10322             idxHashAdd(&rc, &hIdx, zSql, 0);
10323             if( rc ) goto find_indexes_out;
10324           }
10325           break;
10326         }
10327       }
10328 
10329       if( zDetail[0]!='-' ){
10330         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
10331       }
10332     }
10333 
10334     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
10335       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
10336     }
10337 
10338     idxFinalize(&rc, pExplain);
10339   }
10340 
10341  find_indexes_out:
10342   idxHashClear(&hIdx);
10343   return rc;
10344 }
10345 
idxAuthCallback(void * pCtx,int eOp,const char * z3,const char * z4,const char * zDb,const char * zTrigger)10346 static int idxAuthCallback(
10347   void *pCtx,
10348   int eOp,
10349   const char *z3,
10350   const char *z4,
10351   const char *zDb,
10352   const char *zTrigger
10353 ){
10354   int rc = SQLITE_OK;
10355   (void)z4;
10356   (void)zTrigger;
10357   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
10358     if( sqlite3_stricmp(zDb, "main")==0 ){
10359       sqlite3expert *p = (sqlite3expert*)pCtx;
10360       IdxTable *pTab;
10361       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
10362         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
10363       }
10364       if( pTab ){
10365         IdxWrite *pWrite;
10366         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
10367           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
10368         }
10369         if( pWrite==0 ){
10370           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
10371           if( rc==SQLITE_OK ){
10372             pWrite->pTab = pTab;
10373             pWrite->eOp = eOp;
10374             pWrite->pNext = p->pWrite;
10375             p->pWrite = pWrite;
10376           }
10377         }
10378       }
10379     }
10380   }
10381   return rc;
10382 }
10383 
idxProcessOneTrigger(sqlite3expert * p,IdxWrite * pWrite,char ** pzErr)10384 static int idxProcessOneTrigger(
10385   sqlite3expert *p,
10386   IdxWrite *pWrite,
10387   char **pzErr
10388 ){
10389   static const char *zInt = UNIQUE_TABLE_NAME;
10390   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
10391   IdxTable *pTab = pWrite->pTab;
10392   const char *zTab = pTab->zName;
10393   const char *zSql =
10394     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
10395     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
10396     "ORDER BY type;";
10397   sqlite3_stmt *pSelect = 0;
10398   int rc = SQLITE_OK;
10399   char *zWrite = 0;
10400 
10401   /* Create the table and its triggers in the temp schema */
10402   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
10403   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
10404     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
10405     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
10406   }
10407   idxFinalize(&rc, pSelect);
10408 
10409   /* Rename the table in the temp schema to zInt */
10410   if( rc==SQLITE_OK ){
10411     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
10412     if( z==0 ){
10413       rc = SQLITE_NOMEM;
10414     }else{
10415       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
10416       sqlite3_free(z);
10417     }
10418   }
10419 
10420   switch( pWrite->eOp ){
10421     case SQLITE_INSERT: {
10422       int i;
10423       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
10424       for(i=0; i<pTab->nCol; i++){
10425         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
10426       }
10427       zWrite = idxAppendText(&rc, zWrite, ")");
10428       break;
10429     }
10430     case SQLITE_UPDATE: {
10431       int i;
10432       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
10433       for(i=0; i<pTab->nCol; i++){
10434         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
10435             pTab->aCol[i].zName
10436         );
10437       }
10438       break;
10439     }
10440     default: {
10441       assert( pWrite->eOp==SQLITE_DELETE );
10442       if( rc==SQLITE_OK ){
10443         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
10444         if( zWrite==0 ) rc = SQLITE_NOMEM;
10445       }
10446     }
10447   }
10448 
10449   if( rc==SQLITE_OK ){
10450     sqlite3_stmt *pX = 0;
10451     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
10452     idxFinalize(&rc, pX);
10453     if( rc!=SQLITE_OK ){
10454       idxDatabaseError(p->dbv, pzErr);
10455     }
10456   }
10457   sqlite3_free(zWrite);
10458 
10459   if( rc==SQLITE_OK ){
10460     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
10461   }
10462 
10463   return rc;
10464 }
10465 
idxProcessTriggers(sqlite3expert * p,char ** pzErr)10466 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
10467   int rc = SQLITE_OK;
10468   IdxWrite *pEnd = 0;
10469   IdxWrite *pFirst = p->pWrite;
10470 
10471   while( rc==SQLITE_OK && pFirst!=pEnd ){
10472     IdxWrite *pIter;
10473     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
10474       rc = idxProcessOneTrigger(p, pIter, pzErr);
10475     }
10476     pEnd = pFirst;
10477     pFirst = p->pWrite;
10478   }
10479 
10480   return rc;
10481 }
10482 
10483 
idxCreateVtabSchema(sqlite3expert * p,char ** pzErrmsg)10484 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
10485   int rc = idxRegisterVtab(p);
10486   sqlite3_stmt *pSchema = 0;
10487 
10488   /* For each table in the main db schema:
10489   **
10490   **   1) Add an entry to the p->pTable list, and
10491   **   2) Create the equivalent virtual table in dbv.
10492   */
10493   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
10494       "SELECT type, name, sql, 1 FROM sqlite_schema "
10495       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
10496       " UNION ALL "
10497       "SELECT type, name, sql, 2 FROM sqlite_schema "
10498       "WHERE type = 'trigger'"
10499       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
10500       "ORDER BY 4, 1"
10501   );
10502   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
10503     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
10504     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
10505     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
10506 
10507     if( zType[0]=='v' || zType[1]=='r' ){
10508       rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
10509     }else{
10510       IdxTable *pTab;
10511       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
10512       if( rc==SQLITE_OK ){
10513         int i;
10514         char *zInner = 0;
10515         char *zOuter = 0;
10516         pTab->pNext = p->pTable;
10517         p->pTable = pTab;
10518 
10519         /* The statement the vtab will pass to sqlite3_declare_vtab() */
10520         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
10521         for(i=0; i<pTab->nCol; i++){
10522           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
10523               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
10524           );
10525         }
10526         zInner = idxAppendText(&rc, zInner, ")");
10527 
10528         /* The CVT statement to create the vtab */
10529         zOuter = idxAppendText(&rc, 0,
10530             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
10531         );
10532         if( rc==SQLITE_OK ){
10533           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
10534         }
10535         sqlite3_free(zInner);
10536         sqlite3_free(zOuter);
10537       }
10538     }
10539   }
10540   idxFinalize(&rc, pSchema);
10541   return rc;
10542 }
10543 
10544 struct IdxSampleCtx {
10545   int iTarget;
10546   double target;                  /* Target nRet/nRow value */
10547   double nRow;                    /* Number of rows seen */
10548   double nRet;                    /* Number of rows returned */
10549 };
10550 
idxSampleFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)10551 static void idxSampleFunc(
10552   sqlite3_context *pCtx,
10553   int argc,
10554   sqlite3_value **argv
10555 ){
10556   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
10557   int bRet;
10558 
10559   (void)argv;
10560   assert( argc==0 );
10561   if( p->nRow==0.0 ){
10562     bRet = 1;
10563   }else{
10564     bRet = (p->nRet / p->nRow) <= p->target;
10565     if( bRet==0 ){
10566       unsigned short rnd;
10567       sqlite3_randomness(2, (void*)&rnd);
10568       bRet = ((int)rnd % 100) <= p->iTarget;
10569     }
10570   }
10571 
10572   sqlite3_result_int(pCtx, bRet);
10573   p->nRow += 1.0;
10574   p->nRet += (double)bRet;
10575 }
10576 
10577 struct IdxRemCtx {
10578   int nSlot;
10579   struct IdxRemSlot {
10580     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
10581     i64 iVal;                     /* SQLITE_INTEGER value */
10582     double rVal;                  /* SQLITE_FLOAT value */
10583     int nByte;                    /* Bytes of space allocated at z */
10584     int n;                        /* Size of buffer z */
10585     char *z;                      /* SQLITE_TEXT/BLOB value */
10586   } aSlot[1];
10587 };
10588 
10589 /*
10590 ** Implementation of scalar function rem().
10591 */
idxRemFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)10592 static void idxRemFunc(
10593   sqlite3_context *pCtx,
10594   int argc,
10595   sqlite3_value **argv
10596 ){
10597   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
10598   struct IdxRemSlot *pSlot;
10599   int iSlot;
10600   assert( argc==2 );
10601 
10602   iSlot = sqlite3_value_int(argv[0]);
10603   assert( iSlot<=p->nSlot );
10604   pSlot = &p->aSlot[iSlot];
10605 
10606   switch( pSlot->eType ){
10607     case SQLITE_NULL:
10608       /* no-op */
10609       break;
10610 
10611     case SQLITE_INTEGER:
10612       sqlite3_result_int64(pCtx, pSlot->iVal);
10613       break;
10614 
10615     case SQLITE_FLOAT:
10616       sqlite3_result_double(pCtx, pSlot->rVal);
10617       break;
10618 
10619     case SQLITE_BLOB:
10620       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
10621       break;
10622 
10623     case SQLITE_TEXT:
10624       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
10625       break;
10626   }
10627 
10628   pSlot->eType = sqlite3_value_type(argv[1]);
10629   switch( pSlot->eType ){
10630     case SQLITE_NULL:
10631       /* no-op */
10632       break;
10633 
10634     case SQLITE_INTEGER:
10635       pSlot->iVal = sqlite3_value_int64(argv[1]);
10636       break;
10637 
10638     case SQLITE_FLOAT:
10639       pSlot->rVal = sqlite3_value_double(argv[1]);
10640       break;
10641 
10642     case SQLITE_BLOB:
10643     case SQLITE_TEXT: {
10644       int nByte = sqlite3_value_bytes(argv[1]);
10645       if( nByte>pSlot->nByte ){
10646         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
10647         if( zNew==0 ){
10648           sqlite3_result_error_nomem(pCtx);
10649           return;
10650         }
10651         pSlot->nByte = nByte*2;
10652         pSlot->z = zNew;
10653       }
10654       pSlot->n = nByte;
10655       if( pSlot->eType==SQLITE_BLOB ){
10656         memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
10657       }else{
10658         memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
10659       }
10660       break;
10661     }
10662   }
10663 }
10664 
idxLargestIndex(sqlite3 * db,int * pnMax,char ** pzErr)10665 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
10666   int rc = SQLITE_OK;
10667   const char *zMax =
10668     "SELECT max(i.seqno) FROM "
10669     "  sqlite_schema AS s, "
10670     "  pragma_index_list(s.name) AS l, "
10671     "  pragma_index_info(l.name) AS i "
10672     "WHERE s.type = 'table'";
10673   sqlite3_stmt *pMax = 0;
10674 
10675   *pnMax = 0;
10676   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
10677   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
10678     *pnMax = sqlite3_column_int(pMax, 0) + 1;
10679   }
10680   idxFinalize(&rc, pMax);
10681 
10682   return rc;
10683 }
10684 
idxPopulateOneStat1(sqlite3expert * p,sqlite3_stmt * pIndexXInfo,sqlite3_stmt * pWriteStat,const char * zTab,const char * zIdx,char ** pzErr)10685 static int idxPopulateOneStat1(
10686   sqlite3expert *p,
10687   sqlite3_stmt *pIndexXInfo,
10688   sqlite3_stmt *pWriteStat,
10689   const char *zTab,
10690   const char *zIdx,
10691   char **pzErr
10692 ){
10693   char *zCols = 0;
10694   char *zOrder = 0;
10695   char *zQuery = 0;
10696   int nCol = 0;
10697   int i;
10698   sqlite3_stmt *pQuery = 0;
10699   int *aStat = 0;
10700   int rc = SQLITE_OK;
10701 
10702   assert( p->iSample>0 );
10703 
10704   /* Formulate the query text */
10705   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
10706   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
10707     const char *zComma = zCols==0 ? "" : ", ";
10708     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
10709     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
10710     zCols = idxAppendText(&rc, zCols,
10711         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
10712     );
10713     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
10714   }
10715   sqlite3_reset(pIndexXInfo);
10716   if( rc==SQLITE_OK ){
10717     if( p->iSample==100 ){
10718       zQuery = sqlite3_mprintf(
10719           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
10720       );
10721     }else{
10722       zQuery = sqlite3_mprintf(
10723           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
10724       );
10725     }
10726   }
10727   sqlite3_free(zCols);
10728   sqlite3_free(zOrder);
10729 
10730   /* Formulate the query text */
10731   if( rc==SQLITE_OK ){
10732     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
10733     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
10734   }
10735   sqlite3_free(zQuery);
10736 
10737   if( rc==SQLITE_OK ){
10738     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
10739   }
10740   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
10741     IdxHashEntry *pEntry;
10742     char *zStat = 0;
10743     for(i=0; i<=nCol; i++) aStat[i] = 1;
10744     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
10745       aStat[0]++;
10746       for(i=0; i<nCol; i++){
10747         if( sqlite3_column_int(pQuery, i)==0 ) break;
10748       }
10749       for(/*no-op*/; i<nCol; i++){
10750         aStat[i+1]++;
10751       }
10752     }
10753 
10754     if( rc==SQLITE_OK ){
10755       int s0 = aStat[0];
10756       zStat = sqlite3_mprintf("%d", s0);
10757       if( zStat==0 ) rc = SQLITE_NOMEM;
10758       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
10759         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
10760       }
10761     }
10762 
10763     if( rc==SQLITE_OK ){
10764       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
10765       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
10766       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
10767       sqlite3_step(pWriteStat);
10768       rc = sqlite3_reset(pWriteStat);
10769     }
10770 
10771     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
10772     if( pEntry ){
10773       assert( pEntry->zVal2==0 );
10774       pEntry->zVal2 = zStat;
10775     }else{
10776       sqlite3_free(zStat);
10777     }
10778   }
10779   sqlite3_free(aStat);
10780   idxFinalize(&rc, pQuery);
10781 
10782   return rc;
10783 }
10784 
idxBuildSampleTable(sqlite3expert * p,const char * zTab)10785 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
10786   int rc;
10787   char *zSql;
10788 
10789   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
10790   if( rc!=SQLITE_OK ) return rc;
10791 
10792   zSql = sqlite3_mprintf(
10793       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
10794   );
10795   if( zSql==0 ) return SQLITE_NOMEM;
10796   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
10797   sqlite3_free(zSql);
10798 
10799   return rc;
10800 }
10801 
10802 /*
10803 ** This function is called as part of sqlite3_expert_analyze(). Candidate
10804 ** indexes have already been created in database sqlite3expert.dbm, this
10805 ** function populates sqlite_stat1 table in the same database.
10806 **
10807 ** The stat1 data is generated by querying the
10808 */
idxPopulateStat1(sqlite3expert * p,char ** pzErr)10809 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
10810   int rc = SQLITE_OK;
10811   int nMax =0;
10812   struct IdxRemCtx *pCtx = 0;
10813   struct IdxSampleCtx samplectx;
10814   int i;
10815   i64 iPrev = -100000;
10816   sqlite3_stmt *pAllIndex = 0;
10817   sqlite3_stmt *pIndexXInfo = 0;
10818   sqlite3_stmt *pWrite = 0;
10819 
10820   const char *zAllIndex =
10821     "SELECT s.rowid, s.name, l.name FROM "
10822     "  sqlite_schema AS s, "
10823     "  pragma_index_list(s.name) AS l "
10824     "WHERE s.type = 'table'";
10825   const char *zIndexXInfo =
10826     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
10827   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
10828 
10829   /* If iSample==0, no sqlite_stat1 data is required. */
10830   if( p->iSample==0 ) return SQLITE_OK;
10831 
10832   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
10833   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
10834 
10835   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
10836 
10837   if( rc==SQLITE_OK ){
10838     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
10839     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
10840   }
10841 
10842   if( rc==SQLITE_OK ){
10843     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
10844     rc = sqlite3_create_function(
10845         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
10846     );
10847   }
10848   if( rc==SQLITE_OK ){
10849     rc = sqlite3_create_function(
10850         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
10851     );
10852   }
10853 
10854   if( rc==SQLITE_OK ){
10855     pCtx->nSlot = nMax+1;
10856     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
10857   }
10858   if( rc==SQLITE_OK ){
10859     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
10860   }
10861   if( rc==SQLITE_OK ){
10862     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
10863   }
10864 
10865   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
10866     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
10867     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
10868     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
10869     if( p->iSample<100 && iPrev!=iRowid ){
10870       samplectx.target = (double)p->iSample / 100.0;
10871       samplectx.iTarget = p->iSample;
10872       samplectx.nRow = 0.0;
10873       samplectx.nRet = 0.0;
10874       rc = idxBuildSampleTable(p, zTab);
10875       if( rc!=SQLITE_OK ) break;
10876     }
10877     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
10878     iPrev = iRowid;
10879   }
10880   if( rc==SQLITE_OK && p->iSample<100 ){
10881     rc = sqlite3_exec(p->dbv,
10882         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
10883     );
10884   }
10885 
10886   idxFinalize(&rc, pAllIndex);
10887   idxFinalize(&rc, pIndexXInfo);
10888   idxFinalize(&rc, pWrite);
10889 
10890   if( pCtx ){
10891     for(i=0; i<pCtx->nSlot; i++){
10892       sqlite3_free(pCtx->aSlot[i].z);
10893     }
10894     sqlite3_free(pCtx);
10895   }
10896 
10897   if( rc==SQLITE_OK ){
10898     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
10899   }
10900 
10901   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
10902   return rc;
10903 }
10904 
10905 /*
10906 ** Allocate a new sqlite3expert object.
10907 */
sqlite3_expert_new(sqlite3 * db,char ** pzErrmsg)10908 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
10909   int rc = SQLITE_OK;
10910   sqlite3expert *pNew;
10911 
10912   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
10913 
10914   /* Open two in-memory databases to work with. The "vtab database" (dbv)
10915   ** will contain a virtual table corresponding to each real table in
10916   ** the user database schema, and a copy of each view. It is used to
10917   ** collect information regarding the WHERE, ORDER BY and other clauses
10918   ** of the user's query.
10919   */
10920   if( rc==SQLITE_OK ){
10921     pNew->db = db;
10922     pNew->iSample = 100;
10923     rc = sqlite3_open(":memory:", &pNew->dbv);
10924   }
10925   if( rc==SQLITE_OK ){
10926     rc = sqlite3_open(":memory:", &pNew->dbm);
10927     if( rc==SQLITE_OK ){
10928       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
10929     }
10930   }
10931 
10932 
10933   /* Copy the entire schema of database [db] into [dbm]. */
10934   if( rc==SQLITE_OK ){
10935     sqlite3_stmt *pSql;
10936     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
10937         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
10938         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
10939     );
10940     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
10941       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
10942       rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
10943     }
10944     idxFinalize(&rc, pSql);
10945   }
10946 
10947   /* Create the vtab schema */
10948   if( rc==SQLITE_OK ){
10949     rc = idxCreateVtabSchema(pNew, pzErrmsg);
10950   }
10951 
10952   /* Register the auth callback with dbv */
10953   if( rc==SQLITE_OK ){
10954     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
10955   }
10956 
10957   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
10958   ** return the new sqlite3expert handle.  */
10959   if( rc!=SQLITE_OK ){
10960     sqlite3_expert_destroy(pNew);
10961     pNew = 0;
10962   }
10963   return pNew;
10964 }
10965 
10966 /*
10967 ** Configure an sqlite3expert object.
10968 */
sqlite3_expert_config(sqlite3expert * p,int op,...)10969 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
10970   int rc = SQLITE_OK;
10971   va_list ap;
10972   va_start(ap, op);
10973   switch( op ){
10974     case EXPERT_CONFIG_SAMPLE: {
10975       int iVal = va_arg(ap, int);
10976       if( iVal<0 ) iVal = 0;
10977       if( iVal>100 ) iVal = 100;
10978       p->iSample = iVal;
10979       break;
10980     }
10981     default:
10982       rc = SQLITE_NOTFOUND;
10983       break;
10984   }
10985 
10986   va_end(ap);
10987   return rc;
10988 }
10989 
10990 /*
10991 ** Add an SQL statement to the analysis.
10992 */
sqlite3_expert_sql(sqlite3expert * p,const char * zSql,char ** pzErr)10993 int sqlite3_expert_sql(
10994   sqlite3expert *p,               /* From sqlite3_expert_new() */
10995   const char *zSql,               /* SQL statement to add */
10996   char **pzErr                    /* OUT: Error message (if any) */
10997 ){
10998   IdxScan *pScanOrig = p->pScan;
10999   IdxStatement *pStmtOrig = p->pStatement;
11000   int rc = SQLITE_OK;
11001   const char *zStmt = zSql;
11002 
11003   if( p->bRun ) return SQLITE_MISUSE;
11004 
11005   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
11006     sqlite3_stmt *pStmt = 0;
11007     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
11008     if( rc==SQLITE_OK ){
11009       if( pStmt ){
11010         IdxStatement *pNew;
11011         const char *z = sqlite3_sql(pStmt);
11012         int n = STRLEN(z);
11013         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
11014         if( rc==SQLITE_OK ){
11015           pNew->zSql = (char*)&pNew[1];
11016           memcpy(pNew->zSql, z, n+1);
11017           pNew->pNext = p->pStatement;
11018           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
11019           p->pStatement = pNew;
11020         }
11021         sqlite3_finalize(pStmt);
11022       }
11023     }else{
11024       idxDatabaseError(p->dbv, pzErr);
11025     }
11026   }
11027 
11028   if( rc!=SQLITE_OK ){
11029     idxScanFree(p->pScan, pScanOrig);
11030     idxStatementFree(p->pStatement, pStmtOrig);
11031     p->pScan = pScanOrig;
11032     p->pStatement = pStmtOrig;
11033   }
11034 
11035   return rc;
11036 }
11037 
sqlite3_expert_analyze(sqlite3expert * p,char ** pzErr)11038 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
11039   int rc;
11040   IdxHashEntry *pEntry;
11041 
11042   /* Do trigger processing to collect any extra IdxScan structures */
11043   rc = idxProcessTriggers(p, pzErr);
11044 
11045   /* Create candidate indexes within the in-memory database file */
11046   if( rc==SQLITE_OK ){
11047     rc = idxCreateCandidates(p);
11048   }
11049 
11050   /* Generate the stat1 data */
11051   if( rc==SQLITE_OK ){
11052     rc = idxPopulateStat1(p, pzErr);
11053   }
11054 
11055   /* Formulate the EXPERT_REPORT_CANDIDATES text */
11056   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
11057     p->zCandidates = idxAppendText(&rc, p->zCandidates,
11058         "%s;%s%s\n", pEntry->zVal,
11059         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
11060     );
11061   }
11062 
11063   /* Figure out which of the candidate indexes are preferred by the query
11064   ** planner and report the results to the user.  */
11065   if( rc==SQLITE_OK ){
11066     rc = idxFindIndexes(p, pzErr);
11067   }
11068 
11069   if( rc==SQLITE_OK ){
11070     p->bRun = 1;
11071   }
11072   return rc;
11073 }
11074 
11075 /*
11076 ** Return the total number of statements that have been added to this
11077 ** sqlite3expert using sqlite3_expert_sql().
11078 */
sqlite3_expert_count(sqlite3expert * p)11079 int sqlite3_expert_count(sqlite3expert *p){
11080   int nRet = 0;
11081   if( p->pStatement ) nRet = p->pStatement->iId+1;
11082   return nRet;
11083 }
11084 
11085 /*
11086 ** Return a component of the report.
11087 */
sqlite3_expert_report(sqlite3expert * p,int iStmt,int eReport)11088 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
11089   const char *zRet = 0;
11090   IdxStatement *pStmt;
11091 
11092   if( p->bRun==0 ) return 0;
11093   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
11094   switch( eReport ){
11095     case EXPERT_REPORT_SQL:
11096       if( pStmt ) zRet = pStmt->zSql;
11097       break;
11098     case EXPERT_REPORT_INDEXES:
11099       if( pStmt ) zRet = pStmt->zIdx;
11100       break;
11101     case EXPERT_REPORT_PLAN:
11102       if( pStmt ) zRet = pStmt->zEQP;
11103       break;
11104     case EXPERT_REPORT_CANDIDATES:
11105       zRet = p->zCandidates;
11106       break;
11107   }
11108   return zRet;
11109 }
11110 
11111 /*
11112 ** Free an sqlite3expert object.
11113 */
sqlite3_expert_destroy(sqlite3expert * p)11114 void sqlite3_expert_destroy(sqlite3expert *p){
11115   if( p ){
11116     sqlite3_close(p->dbm);
11117     sqlite3_close(p->dbv);
11118     idxScanFree(p->pScan, 0);
11119     idxStatementFree(p->pStatement, 0);
11120     idxTableFree(p->pTable);
11121     idxWriteFree(p->pWrite);
11122     idxHashClear(&p->hIdx);
11123     sqlite3_free(p->zCandidates);
11124     sqlite3_free(p);
11125   }
11126 }
11127 
11128 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
11129 
11130 /************************* End ../ext/expert/sqlite3expert.c ********************/
11131 
11132 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
11133 /************************* Begin ../ext/misc/dbdata.c ******************/
11134 /*
11135 ** 2019-04-17
11136 **
11137 ** The author disclaims copyright to this source code.  In place of
11138 ** a legal notice, here is a blessing:
11139 **
11140 **    May you do good and not evil.
11141 **    May you find forgiveness for yourself and forgive others.
11142 **    May you share freely, never taking more than you give.
11143 **
11144 ******************************************************************************
11145 **
11146 ** This file contains an implementation of two eponymous virtual tables,
11147 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
11148 ** "sqlite_dbpage" eponymous virtual table be available.
11149 **
11150 ** SQLITE_DBDATA:
11151 **   sqlite_dbdata is used to extract data directly from a database b-tree
11152 **   page and its associated overflow pages, bypassing the b-tree layer.
11153 **   The table schema is equivalent to:
11154 **
11155 **     CREATE TABLE sqlite_dbdata(
11156 **       pgno INTEGER,
11157 **       cell INTEGER,
11158 **       field INTEGER,
11159 **       value ANY,
11160 **       schema TEXT HIDDEN
11161 **     );
11162 **
11163 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
11164 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
11165 **   "schema".
11166 **
11167 **   Each page of the database is inspected. If it cannot be interpreted as
11168 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
11169 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
11170 **   table contains one row for each field in the record associated with
11171 **   each cell on the page. For intkey b-trees, the key value is stored in
11172 **   field -1.
11173 **
11174 **   For example, for the database:
11175 **
11176 **     CREATE TABLE t1(a, b);     -- root page is page 2
11177 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
11178 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
11179 **
11180 **   the sqlite_dbdata table contains, as well as from entries related to
11181 **   page 1, content equivalent to:
11182 **
11183 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
11184 **         (2, 0, -1, 5     ),
11185 **         (2, 0,  0, 'v'   ),
11186 **         (2, 0,  1, 'five'),
11187 **         (2, 1, -1, 10    ),
11188 **         (2, 1,  0, 'x'   ),
11189 **         (2, 1,  1, 'ten' );
11190 **
11191 **   If database corruption is encountered, this module does not report an
11192 **   error. Instead, it attempts to extract as much data as possible and
11193 **   ignores the corruption.
11194 **
11195 ** SQLITE_DBPTR:
11196 **   The sqlite_dbptr table has the following schema:
11197 **
11198 **     CREATE TABLE sqlite_dbptr(
11199 **       pgno INTEGER,
11200 **       child INTEGER,
11201 **       schema TEXT HIDDEN
11202 **     );
11203 **
11204 **   It contains one entry for each b-tree pointer between a parent and
11205 **   child page in the database.
11206 */
11207 #if !defined(SQLITEINT_H)
11208 /* #include "sqlite3ext.h" */
11209 
11210 /* typedef unsigned char u8; */
11211 
11212 #endif
11213 SQLITE_EXTENSION_INIT1
11214 #include <string.h>
11215 #include <assert.h>
11216 
11217 #define DBDATA_PADDING_BYTES 100
11218 
11219 typedef struct DbdataTable DbdataTable;
11220 typedef struct DbdataCursor DbdataCursor;
11221 
11222 /* Cursor object */
11223 struct DbdataCursor {
11224   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
11225   sqlite3_stmt *pStmt;            /* For fetching database pages */
11226 
11227   int iPgno;                      /* Current page number */
11228   u8 *aPage;                      /* Buffer containing page */
11229   int nPage;                      /* Size of aPage[] in bytes */
11230   int nCell;                      /* Number of cells on aPage[] */
11231   int iCell;                      /* Current cell number */
11232   int bOnePage;                   /* True to stop after one page */
11233   int szDb;
11234   sqlite3_int64 iRowid;
11235 
11236   /* Only for the sqlite_dbdata table */
11237   u8 *pRec;                       /* Buffer containing current record */
11238   int nRec;                       /* Size of pRec[] in bytes */
11239   int nHdr;                       /* Size of header in bytes */
11240   int iField;                     /* Current field number */
11241   u8 *pHdrPtr;
11242   u8 *pPtr;
11243 
11244   sqlite3_int64 iIntkey;          /* Integer key value */
11245 };
11246 
11247 /* Table object */
11248 struct DbdataTable {
11249   sqlite3_vtab base;              /* Base class.  Must be first */
11250   sqlite3 *db;                    /* The database connection */
11251   sqlite3_stmt *pStmt;            /* For fetching database pages */
11252   int bPtr;                       /* True for sqlite3_dbptr table */
11253 };
11254 
11255 /* Column and schema definitions for sqlite_dbdata */
11256 #define DBDATA_COLUMN_PGNO        0
11257 #define DBDATA_COLUMN_CELL        1
11258 #define DBDATA_COLUMN_FIELD       2
11259 #define DBDATA_COLUMN_VALUE       3
11260 #define DBDATA_COLUMN_SCHEMA      4
11261 #define DBDATA_SCHEMA             \
11262       "CREATE TABLE x("           \
11263       "  pgno INTEGER,"           \
11264       "  cell INTEGER,"           \
11265       "  field INTEGER,"          \
11266       "  value ANY,"              \
11267       "  schema TEXT HIDDEN"      \
11268       ")"
11269 
11270 /* Column and schema definitions for sqlite_dbptr */
11271 #define DBPTR_COLUMN_PGNO         0
11272 #define DBPTR_COLUMN_CHILD        1
11273 #define DBPTR_COLUMN_SCHEMA       2
11274 #define DBPTR_SCHEMA              \
11275       "CREATE TABLE x("           \
11276       "  pgno INTEGER,"           \
11277       "  child INTEGER,"          \
11278       "  schema TEXT HIDDEN"      \
11279       ")"
11280 
11281 /*
11282 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
11283 ** table.
11284 */
dbdataConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)11285 static int dbdataConnect(
11286   sqlite3 *db,
11287   void *pAux,
11288   int argc, const char *const*argv,
11289   sqlite3_vtab **ppVtab,
11290   char **pzErr
11291 ){
11292   DbdataTable *pTab = 0;
11293   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
11294 
11295   if( rc==SQLITE_OK ){
11296     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
11297     if( pTab==0 ){
11298       rc = SQLITE_NOMEM;
11299     }else{
11300       memset(pTab, 0, sizeof(DbdataTable));
11301       pTab->db = db;
11302       pTab->bPtr = (pAux!=0);
11303     }
11304   }
11305 
11306   *ppVtab = (sqlite3_vtab*)pTab;
11307   return rc;
11308 }
11309 
11310 /*
11311 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
11312 */
dbdataDisconnect(sqlite3_vtab * pVtab)11313 static int dbdataDisconnect(sqlite3_vtab *pVtab){
11314   DbdataTable *pTab = (DbdataTable*)pVtab;
11315   if( pTab ){
11316     sqlite3_finalize(pTab->pStmt);
11317     sqlite3_free(pVtab);
11318   }
11319   return SQLITE_OK;
11320 }
11321 
11322 /*
11323 ** This function interprets two types of constraints:
11324 **
11325 **       schema=?
11326 **       pgno=?
11327 **
11328 ** If neither are present, idxNum is set to 0. If schema=? is present,
11329 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
11330 ** in idxNum is set.
11331 **
11332 ** If both parameters are present, schema is in position 0 and pgno in
11333 ** position 1.
11334 */
dbdataBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdx)11335 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
11336   DbdataTable *pTab = (DbdataTable*)tab;
11337   int i;
11338   int iSchema = -1;
11339   int iPgno = -1;
11340   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
11341 
11342   for(i=0; i<pIdx->nConstraint; i++){
11343     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
11344     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
11345       if( p->iColumn==colSchema ){
11346         if( p->usable==0 ) return SQLITE_CONSTRAINT;
11347         iSchema = i;
11348       }
11349       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
11350         iPgno = i;
11351       }
11352     }
11353   }
11354 
11355   if( iSchema>=0 ){
11356     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
11357     pIdx->aConstraintUsage[iSchema].omit = 1;
11358   }
11359   if( iPgno>=0 ){
11360     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
11361     pIdx->aConstraintUsage[iPgno].omit = 1;
11362     pIdx->estimatedCost = 100;
11363     pIdx->estimatedRows =  50;
11364 
11365     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
11366       int iCol = pIdx->aOrderBy[0].iColumn;
11367       if( pIdx->nOrderBy==1 ){
11368         pIdx->orderByConsumed = (iCol==0 || iCol==1);
11369       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
11370         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
11371       }
11372     }
11373 
11374   }else{
11375     pIdx->estimatedCost = 100000000;
11376     pIdx->estimatedRows = 1000000000;
11377   }
11378   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
11379   return SQLITE_OK;
11380 }
11381 
11382 /*
11383 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
11384 */
dbdataOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)11385 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
11386   DbdataCursor *pCsr;
11387 
11388   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
11389   if( pCsr==0 ){
11390     return SQLITE_NOMEM;
11391   }else{
11392     memset(pCsr, 0, sizeof(DbdataCursor));
11393     pCsr->base.pVtab = pVTab;
11394   }
11395 
11396   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
11397   return SQLITE_OK;
11398 }
11399 
11400 /*
11401 ** Restore a cursor object to the state it was in when first allocated
11402 ** by dbdataOpen().
11403 */
dbdataResetCursor(DbdataCursor * pCsr)11404 static void dbdataResetCursor(DbdataCursor *pCsr){
11405   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
11406   if( pTab->pStmt==0 ){
11407     pTab->pStmt = pCsr->pStmt;
11408   }else{
11409     sqlite3_finalize(pCsr->pStmt);
11410   }
11411   pCsr->pStmt = 0;
11412   pCsr->iPgno = 1;
11413   pCsr->iCell = 0;
11414   pCsr->iField = 0;
11415   pCsr->bOnePage = 0;
11416   sqlite3_free(pCsr->aPage);
11417   sqlite3_free(pCsr->pRec);
11418   pCsr->pRec = 0;
11419   pCsr->aPage = 0;
11420 }
11421 
11422 /*
11423 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
11424 */
dbdataClose(sqlite3_vtab_cursor * pCursor)11425 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
11426   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11427   dbdataResetCursor(pCsr);
11428   sqlite3_free(pCsr);
11429   return SQLITE_OK;
11430 }
11431 
11432 /*
11433 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
11434 */
get_uint16(unsigned char * a)11435 static unsigned int get_uint16(unsigned char *a){
11436   return (a[0]<<8)|a[1];
11437 }
get_uint32(unsigned char * a)11438 static unsigned int get_uint32(unsigned char *a){
11439   return ((unsigned int)a[0]<<24)
11440        | ((unsigned int)a[1]<<16)
11441        | ((unsigned int)a[2]<<8)
11442        | ((unsigned int)a[3]);
11443 }
11444 
11445 /*
11446 ** Load page pgno from the database via the sqlite_dbpage virtual table.
11447 ** If successful, set (*ppPage) to point to a buffer containing the page
11448 ** data, (*pnPage) to the size of that buffer in bytes and return
11449 ** SQLITE_OK. In this case it is the responsibility of the caller to
11450 ** eventually free the buffer using sqlite3_free().
11451 **
11452 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
11453 ** return an SQLite error code.
11454 */
dbdataLoadPage(DbdataCursor * pCsr,unsigned int pgno,u8 ** ppPage,int * pnPage)11455 static int dbdataLoadPage(
11456   DbdataCursor *pCsr,             /* Cursor object */
11457   unsigned int pgno,              /* Page number of page to load */
11458   u8 **ppPage,                    /* OUT: pointer to page buffer */
11459   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
11460 ){
11461   int rc2;
11462   int rc = SQLITE_OK;
11463   sqlite3_stmt *pStmt = pCsr->pStmt;
11464 
11465   *ppPage = 0;
11466   *pnPage = 0;
11467   sqlite3_bind_int64(pStmt, 2, pgno);
11468   if( SQLITE_ROW==sqlite3_step(pStmt) ){
11469     int nCopy = sqlite3_column_bytes(pStmt, 0);
11470     if( nCopy>0 ){
11471       u8 *pPage;
11472       pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
11473       if( pPage==0 ){
11474         rc = SQLITE_NOMEM;
11475       }else{
11476         const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
11477         memcpy(pPage, pCopy, nCopy);
11478         memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
11479       }
11480       *ppPage = pPage;
11481       *pnPage = nCopy;
11482     }
11483   }
11484   rc2 = sqlite3_reset(pStmt);
11485   if( rc==SQLITE_OK ) rc = rc2;
11486 
11487   return rc;
11488 }
11489 
11490 /*
11491 ** Read a varint.  Put the value in *pVal and return the number of bytes.
11492 */
dbdataGetVarint(const u8 * z,sqlite3_int64 * pVal)11493 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
11494   sqlite3_int64 v = 0;
11495   int i;
11496   for(i=0; i<8; i++){
11497     v = (v<<7) + (z[i]&0x7f);
11498     if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
11499   }
11500   v = (v<<8) + (z[i]&0xff);
11501   *pVal = v;
11502   return 9;
11503 }
11504 
11505 /*
11506 ** Return the number of bytes of space used by an SQLite value of type
11507 ** eType.
11508 */
dbdataValueBytes(int eType)11509 static int dbdataValueBytes(int eType){
11510   switch( eType ){
11511     case 0: case 8: case 9:
11512     case 10: case 11:
11513       return 0;
11514     case 1:
11515       return 1;
11516     case 2:
11517       return 2;
11518     case 3:
11519       return 3;
11520     case 4:
11521       return 4;
11522     case 5:
11523       return 6;
11524     case 6:
11525     case 7:
11526       return 8;
11527     default:
11528       if( eType>0 ){
11529         return ((eType-12) / 2);
11530       }
11531       return 0;
11532   }
11533 }
11534 
11535 /*
11536 ** Load a value of type eType from buffer pData and use it to set the
11537 ** result of context object pCtx.
11538 */
dbdataValue(sqlite3_context * pCtx,int eType,u8 * pData,int nData)11539 static void dbdataValue(
11540   sqlite3_context *pCtx,
11541   int eType,
11542   u8 *pData,
11543   int nData
11544 ){
11545   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
11546     switch( eType ){
11547       case 0:
11548       case 10:
11549       case 11:
11550         sqlite3_result_null(pCtx);
11551         break;
11552 
11553       case 8:
11554         sqlite3_result_int(pCtx, 0);
11555         break;
11556       case 9:
11557         sqlite3_result_int(pCtx, 1);
11558         break;
11559 
11560       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
11561         sqlite3_uint64 v = (signed char)pData[0];
11562         pData++;
11563         switch( eType ){
11564           case 7:
11565           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
11566           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
11567           case 4:  v = (v<<8) + pData[0];  pData++;
11568           case 3:  v = (v<<8) + pData[0];  pData++;
11569           case 2:  v = (v<<8) + pData[0];  pData++;
11570         }
11571 
11572         if( eType==7 ){
11573           double r;
11574           memcpy(&r, &v, sizeof(r));
11575           sqlite3_result_double(pCtx, r);
11576         }else{
11577           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
11578         }
11579         break;
11580       }
11581 
11582       default: {
11583         int n = ((eType-12) / 2);
11584         if( eType % 2 ){
11585           sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
11586         }else{
11587           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
11588         }
11589       }
11590     }
11591   }
11592 }
11593 
11594 /*
11595 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
11596 */
dbdataNext(sqlite3_vtab_cursor * pCursor)11597 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
11598   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11599   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
11600 
11601   pCsr->iRowid++;
11602   while( 1 ){
11603     int rc;
11604     int iOff = (pCsr->iPgno==1 ? 100 : 0);
11605     int bNextPage = 0;
11606 
11607     if( pCsr->aPage==0 ){
11608       while( 1 ){
11609         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
11610         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
11611         if( rc!=SQLITE_OK ) return rc;
11612         if( pCsr->aPage ) break;
11613         pCsr->iPgno++;
11614       }
11615       pCsr->iCell = pTab->bPtr ? -2 : 0;
11616       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
11617     }
11618 
11619     if( pTab->bPtr ){
11620       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
11621         pCsr->iCell = pCsr->nCell;
11622       }
11623       pCsr->iCell++;
11624       if( pCsr->iCell>=pCsr->nCell ){
11625         sqlite3_free(pCsr->aPage);
11626         pCsr->aPage = 0;
11627         if( pCsr->bOnePage ) return SQLITE_OK;
11628         pCsr->iPgno++;
11629       }else{
11630         return SQLITE_OK;
11631       }
11632     }else{
11633       /* If there is no record loaded, load it now. */
11634       if( pCsr->pRec==0 ){
11635         int bHasRowid = 0;
11636         int nPointer = 0;
11637         sqlite3_int64 nPayload = 0;
11638         sqlite3_int64 nHdr = 0;
11639         int iHdr;
11640         int U, X;
11641         int nLocal;
11642 
11643         switch( pCsr->aPage[iOff] ){
11644           case 0x02:
11645             nPointer = 4;
11646             break;
11647           case 0x0a:
11648             break;
11649           case 0x0d:
11650             bHasRowid = 1;
11651             break;
11652           default:
11653             /* This is not a b-tree page with records on it. Continue. */
11654             pCsr->iCell = pCsr->nCell;
11655             break;
11656         }
11657 
11658         if( pCsr->iCell>=pCsr->nCell ){
11659           bNextPage = 1;
11660         }else{
11661 
11662           iOff += 8 + nPointer + pCsr->iCell*2;
11663           if( iOff>pCsr->nPage ){
11664             bNextPage = 1;
11665           }else{
11666             iOff = get_uint16(&pCsr->aPage[iOff]);
11667           }
11668 
11669           /* For an interior node cell, skip past the child-page number */
11670           iOff += nPointer;
11671 
11672           /* Load the "byte of payload including overflow" field */
11673           if( bNextPage || iOff>pCsr->nPage ){
11674             bNextPage = 1;
11675           }else{
11676             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
11677           }
11678 
11679           /* If this is a leaf intkey cell, load the rowid */
11680           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
11681             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
11682           }
11683 
11684           /* Figure out how much data to read from the local page */
11685           U = pCsr->nPage;
11686           if( bHasRowid ){
11687             X = U-35;
11688           }else{
11689             X = ((U-12)*64/255)-23;
11690           }
11691           if( nPayload<=X ){
11692             nLocal = nPayload;
11693           }else{
11694             int M, K;
11695             M = ((U-12)*32/255)-23;
11696             K = M+((nPayload-M)%(U-4));
11697             if( K<=X ){
11698               nLocal = K;
11699             }else{
11700               nLocal = M;
11701             }
11702           }
11703 
11704           if( bNextPage || nLocal+iOff>pCsr->nPage ){
11705             bNextPage = 1;
11706           }else{
11707 
11708             /* Allocate space for payload. And a bit more to catch small buffer
11709             ** overruns caused by attempting to read a varint or similar from
11710             ** near the end of a corrupt record.  */
11711             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
11712             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
11713             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
11714             pCsr->nRec = nPayload;
11715 
11716             /* Load the nLocal bytes of payload */
11717             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
11718             iOff += nLocal;
11719 
11720             /* Load content from overflow pages */
11721             if( nPayload>nLocal ){
11722               sqlite3_int64 nRem = nPayload - nLocal;
11723               unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
11724               while( nRem>0 ){
11725                 u8 *aOvfl = 0;
11726                 int nOvfl = 0;
11727                 int nCopy;
11728                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
11729                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
11730                 if( rc!=SQLITE_OK ) return rc;
11731                 if( aOvfl==0 ) break;
11732 
11733                 nCopy = U-4;
11734                 if( nCopy>nRem ) nCopy = nRem;
11735                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
11736                 nRem -= nCopy;
11737 
11738                 pgnoOvfl = get_uint32(aOvfl);
11739                 sqlite3_free(aOvfl);
11740               }
11741             }
11742 
11743             iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
11744             pCsr->nHdr = nHdr;
11745             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
11746             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
11747             pCsr->iField = (bHasRowid ? -1 : 0);
11748           }
11749         }
11750       }else{
11751         pCsr->iField++;
11752         if( pCsr->iField>0 ){
11753           sqlite3_int64 iType;
11754           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
11755             bNextPage = 1;
11756           }else{
11757             pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
11758             pCsr->pPtr += dbdataValueBytes(iType);
11759           }
11760         }
11761       }
11762 
11763       if( bNextPage ){
11764         sqlite3_free(pCsr->aPage);
11765         sqlite3_free(pCsr->pRec);
11766         pCsr->aPage = 0;
11767         pCsr->pRec = 0;
11768         if( pCsr->bOnePage ) return SQLITE_OK;
11769         pCsr->iPgno++;
11770       }else{
11771         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
11772           return SQLITE_OK;
11773         }
11774 
11775         /* Advance to the next cell. The next iteration of the loop will load
11776         ** the record and so on. */
11777         sqlite3_free(pCsr->pRec);
11778         pCsr->pRec = 0;
11779         pCsr->iCell++;
11780       }
11781     }
11782   }
11783 
11784   assert( !"can't get here" );
11785   return SQLITE_OK;
11786 }
11787 
11788 /*
11789 ** Return true if the cursor is at EOF.
11790 */
dbdataEof(sqlite3_vtab_cursor * pCursor)11791 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
11792   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11793   return pCsr->aPage==0;
11794 }
11795 
11796 /*
11797 ** Determine the size in pages of database zSchema (where zSchema is
11798 ** "main", "temp" or the name of an attached database) and set
11799 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
11800 ** an SQLite error code.
11801 */
dbdataDbsize(DbdataCursor * pCsr,const char * zSchema)11802 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
11803   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
11804   char *zSql = 0;
11805   int rc, rc2;
11806   sqlite3_stmt *pStmt = 0;
11807 
11808   zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
11809   if( zSql==0 ) return SQLITE_NOMEM;
11810   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
11811   sqlite3_free(zSql);
11812   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
11813     pCsr->szDb = sqlite3_column_int(pStmt, 0);
11814   }
11815   rc2 = sqlite3_finalize(pStmt);
11816   if( rc==SQLITE_OK ) rc = rc2;
11817   return rc;
11818 }
11819 
11820 /*
11821 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
11822 */
dbdataFilter(sqlite3_vtab_cursor * pCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)11823 static int dbdataFilter(
11824   sqlite3_vtab_cursor *pCursor,
11825   int idxNum, const char *idxStr,
11826   int argc, sqlite3_value **argv
11827 ){
11828   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11829   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
11830   int rc = SQLITE_OK;
11831   const char *zSchema = "main";
11832 
11833   dbdataResetCursor(pCsr);
11834   assert( pCsr->iPgno==1 );
11835   if( idxNum & 0x01 ){
11836     zSchema = (const char*)sqlite3_value_text(argv[0]);
11837   }
11838   if( idxNum & 0x02 ){
11839     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
11840     pCsr->bOnePage = 1;
11841   }else{
11842     pCsr->nPage = dbdataDbsize(pCsr, zSchema);
11843     rc = dbdataDbsize(pCsr, zSchema);
11844   }
11845 
11846   if( rc==SQLITE_OK ){
11847     if( pTab->pStmt ){
11848       pCsr->pStmt = pTab->pStmt;
11849       pTab->pStmt = 0;
11850     }else{
11851       rc = sqlite3_prepare_v2(pTab->db,
11852           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
11853           &pCsr->pStmt, 0
11854       );
11855     }
11856   }
11857   if( rc==SQLITE_OK ){
11858     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
11859   }else{
11860     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
11861   }
11862   if( rc==SQLITE_OK ){
11863     rc = dbdataNext(pCursor);
11864   }
11865   return rc;
11866 }
11867 
11868 /*
11869 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
11870 */
dbdataColumn(sqlite3_vtab_cursor * pCursor,sqlite3_context * ctx,int i)11871 static int dbdataColumn(
11872   sqlite3_vtab_cursor *pCursor,
11873   sqlite3_context *ctx,
11874   int i
11875 ){
11876   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11877   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
11878   if( pTab->bPtr ){
11879     switch( i ){
11880       case DBPTR_COLUMN_PGNO:
11881         sqlite3_result_int64(ctx, pCsr->iPgno);
11882         break;
11883       case DBPTR_COLUMN_CHILD: {
11884         int iOff = pCsr->iPgno==1 ? 100 : 0;
11885         if( pCsr->iCell<0 ){
11886           iOff += 8;
11887         }else{
11888           iOff += 12 + pCsr->iCell*2;
11889           if( iOff>pCsr->nPage ) return SQLITE_OK;
11890           iOff = get_uint16(&pCsr->aPage[iOff]);
11891         }
11892         if( iOff<=pCsr->nPage ){
11893           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
11894         }
11895         break;
11896       }
11897     }
11898   }else{
11899     switch( i ){
11900       case DBDATA_COLUMN_PGNO:
11901         sqlite3_result_int64(ctx, pCsr->iPgno);
11902         break;
11903       case DBDATA_COLUMN_CELL:
11904         sqlite3_result_int(ctx, pCsr->iCell);
11905         break;
11906       case DBDATA_COLUMN_FIELD:
11907         sqlite3_result_int(ctx, pCsr->iField);
11908         break;
11909       case DBDATA_COLUMN_VALUE: {
11910         if( pCsr->iField<0 ){
11911           sqlite3_result_int64(ctx, pCsr->iIntkey);
11912         }else{
11913           sqlite3_int64 iType;
11914           dbdataGetVarint(pCsr->pHdrPtr, &iType);
11915           dbdataValue(
11916               ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
11917           );
11918         }
11919         break;
11920       }
11921     }
11922   }
11923   return SQLITE_OK;
11924 }
11925 
11926 /*
11927 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
11928 */
dbdataRowid(sqlite3_vtab_cursor * pCursor,sqlite_int64 * pRowid)11929 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
11930   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11931   *pRowid = pCsr->iRowid;
11932   return SQLITE_OK;
11933 }
11934 
11935 
11936 /*
11937 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
11938 */
sqlite3DbdataRegister(sqlite3 * db)11939 static int sqlite3DbdataRegister(sqlite3 *db){
11940   static sqlite3_module dbdata_module = {
11941     0,                            /* iVersion */
11942     0,                            /* xCreate */
11943     dbdataConnect,                /* xConnect */
11944     dbdataBestIndex,              /* xBestIndex */
11945     dbdataDisconnect,             /* xDisconnect */
11946     0,                            /* xDestroy */
11947     dbdataOpen,                   /* xOpen - open a cursor */
11948     dbdataClose,                  /* xClose - close a cursor */
11949     dbdataFilter,                 /* xFilter - configure scan constraints */
11950     dbdataNext,                   /* xNext - advance a cursor */
11951     dbdataEof,                    /* xEof - check for end of scan */
11952     dbdataColumn,                 /* xColumn - read data */
11953     dbdataRowid,                  /* xRowid - read data */
11954     0,                            /* xUpdate */
11955     0,                            /* xBegin */
11956     0,                            /* xSync */
11957     0,                            /* xCommit */
11958     0,                            /* xRollback */
11959     0,                            /* xFindMethod */
11960     0,                            /* xRename */
11961     0,                            /* xSavepoint */
11962     0,                            /* xRelease */
11963     0,                            /* xRollbackTo */
11964     0                             /* xShadowName */
11965   };
11966 
11967   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
11968   if( rc==SQLITE_OK ){
11969     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
11970   }
11971   return rc;
11972 }
11973 
11974 #ifdef _WIN32
11975 
11976 #endif
sqlite3_dbdata_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)11977 int sqlite3_dbdata_init(
11978   sqlite3 *db,
11979   char **pzErrMsg,
11980   const sqlite3_api_routines *pApi
11981 ){
11982   SQLITE_EXTENSION_INIT2(pApi);
11983   return sqlite3DbdataRegister(db);
11984 }
11985 
11986 /************************* End ../ext/misc/dbdata.c ********************/
11987 #endif
11988 
11989 #if defined(SQLITE_ENABLE_SESSION)
11990 /*
11991 ** State information for a single open session
11992 */
11993 typedef struct OpenSession OpenSession;
11994 struct OpenSession {
11995   char *zName;             /* Symbolic name for this session */
11996   int nFilter;             /* Number of xFilter rejection GLOB patterns */
11997   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
11998   sqlite3_session *p;      /* The open session */
11999 };
12000 #endif
12001 
12002 typedef struct ExpertInfo ExpertInfo;
12003 struct ExpertInfo {
12004   sqlite3expert *pExpert;
12005   int bVerbose;
12006 };
12007 
12008 /* A single line in the EQP output */
12009 typedef struct EQPGraphRow EQPGraphRow;
12010 struct EQPGraphRow {
12011   int iEqpId;           /* ID for this row */
12012   int iParentId;        /* ID of the parent row */
12013   EQPGraphRow *pNext;   /* Next row in sequence */
12014   char zText[1];        /* Text to display for this row */
12015 };
12016 
12017 /* All EQP output is collected into an instance of the following */
12018 typedef struct EQPGraph EQPGraph;
12019 struct EQPGraph {
12020   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
12021   EQPGraphRow *pLast;   /* Last element of the pRow list */
12022   char zPrefix[100];    /* Graph prefix */
12023 };
12024 
12025 /*
12026 ** State information about the database connection is contained in an
12027 ** instance of the following structure.
12028 */
12029 typedef struct ShellState ShellState;
12030 struct ShellState {
12031   sqlite3 *db;           /* The database */
12032   u8 autoExplain;        /* Automatically turn on .explain mode */
12033   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
12034   u8 autoEQPtest;        /* autoEQP is in test mode */
12035   u8 autoEQPtrace;       /* autoEQP is in trace mode */
12036   u8 scanstatsOn;        /* True to display scan stats before each finalize */
12037   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
12038   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
12039   u8 nEqpLevel;          /* Depth of the EQP output graph */
12040   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
12041   unsigned statsOn;      /* True to display memory stats before each finalize */
12042   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
12043   int outCount;          /* Revert to stdout when reaching zero */
12044   int cnt;               /* Number of records displayed so far */
12045   int lineno;            /* Line number of last line read from in */
12046   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
12047   FILE *in;              /* Read commands from this stream */
12048   FILE *out;             /* Write results here */
12049   FILE *traceOut;        /* Output for sqlite3_trace() */
12050   int nErr;              /* Number of errors seen */
12051   int mode;              /* An output mode setting */
12052   int modePrior;         /* Saved mode */
12053   int cMode;             /* temporary output mode for the current query */
12054   int normalMode;        /* Output mode before ".explain on" */
12055   int writableSchema;    /* True if PRAGMA writable_schema=ON */
12056   int showHeader;        /* True to show column names in List or Column mode */
12057   int nCheck;            /* Number of ".check" commands run */
12058   unsigned nProgress;    /* Number of progress callbacks encountered */
12059   unsigned mxProgress;   /* Maximum progress callbacks before failing */
12060   unsigned flgProgress;  /* Flags for the progress callback */
12061   unsigned shellFlgs;    /* Various flags */
12062   unsigned priorShFlgs;  /* Saved copy of flags */
12063   sqlite3_int64 szMax;   /* --maxsize argument to .open */
12064   char *zDestTable;      /* Name of destination table when MODE_Insert */
12065   char *zTempFile;       /* Temporary file that might need deleting */
12066   char zTestcase[30];    /* Name of current test case */
12067   char colSeparator[20]; /* Column separator character for several modes */
12068   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
12069   char colSepPrior[20];  /* Saved column separator */
12070   char rowSepPrior[20];  /* Saved row separator */
12071   int *colWidth;         /* Requested width of each column in columnar modes */
12072   int *actualWidth;      /* Actual width of each column */
12073   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
12074   char nullValue[20];    /* The text to print when a NULL comes back from
12075                          ** the database */
12076   char outfile[FILENAME_MAX]; /* Filename for *out */
12077   const char *zDbFilename;    /* name of the database file */
12078   char *zFreeOnClose;         /* Filename to free when closing */
12079   const char *zVfs;           /* Name of VFS to use */
12080   sqlite3_stmt *pStmt;   /* Current statement if any. */
12081   FILE *pLog;            /* Write log output here */
12082   int *aiIndent;         /* Array of indents used in MODE_Explain */
12083   int nIndent;           /* Size of array aiIndent[] */
12084   int iIndent;           /* Index of current op in aiIndent[] */
12085   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
12086 #if defined(SQLITE_ENABLE_SESSION)
12087   int nSession;             /* Number of active sessions */
12088   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
12089 #endif
12090   ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
12091 };
12092 
12093 
12094 /* Allowed values for ShellState.autoEQP
12095 */
12096 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
12097 #define AUTOEQP_on       1           /* Automatic EQP is on */
12098 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
12099 #define AUTOEQP_full     3           /* Show full EXPLAIN */
12100 
12101 /* Allowed values for ShellState.openMode
12102 */
12103 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
12104 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
12105 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
12106 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
12107 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
12108 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
12109 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
12110 
12111 /* Allowed values for ShellState.eTraceType
12112 */
12113 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
12114 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
12115 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
12116 
12117 /* Bits in the ShellState.flgProgress variable */
12118 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
12119 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
12120                                    ** callback limit is reached, and for each
12121                                    ** top-level SQL statement */
12122 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
12123 
12124 /*
12125 ** These are the allowed shellFlgs values
12126 */
12127 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
12128 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
12129 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
12130 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
12131 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
12132 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
12133 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
12134 #define SHFLG_HeaderSet      0x00000080 /* .header has been used */
12135 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
12136 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
12137 
12138 /*
12139 ** Macros for testing and setting shellFlgs
12140 */
12141 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
12142 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
12143 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
12144 
12145 /*
12146 ** These are the allowed modes.
12147 */
12148 #define MODE_Line     0  /* One column per line.  Blank line between records */
12149 #define MODE_Column   1  /* One record per line in neat columns */
12150 #define MODE_List     2  /* One record per line with a separator */
12151 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
12152 #define MODE_Html     4  /* Generate an XHTML table */
12153 #define MODE_Insert   5  /* Generate SQL "insert" statements */
12154 #define MODE_Quote    6  /* Quote values as for SQL */
12155 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
12156 #define MODE_Csv      8  /* Quote strings, numbers are plain */
12157 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
12158 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
12159 #define MODE_Pretty  11  /* Pretty-print schemas */
12160 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
12161 #define MODE_Json    13  /* Output JSON */
12162 #define MODE_Markdown 14 /* Markdown formatting */
12163 #define MODE_Table   15  /* MySQL-style table formatting */
12164 #define MODE_Box     16  /* Unicode box-drawing characters */
12165 
12166 static const char *modeDescr[] = {
12167   "line",
12168   "column",
12169   "list",
12170   "semi",
12171   "html",
12172   "insert",
12173   "quote",
12174   "tcl",
12175   "csv",
12176   "explain",
12177   "ascii",
12178   "prettyprint",
12179   "eqp",
12180   "json",
12181   "markdown",
12182   "table",
12183   "box"
12184 };
12185 
12186 /*
12187 ** These are the column/row/line separators used by the various
12188 ** import/export modes.
12189 */
12190 #define SEP_Column    "|"
12191 #define SEP_Row       "\n"
12192 #define SEP_Tab       "\t"
12193 #define SEP_Space     " "
12194 #define SEP_Comma     ","
12195 #define SEP_CrLf      "\r\n"
12196 #define SEP_Unit      "\x1F"
12197 #define SEP_Record    "\x1E"
12198 
12199 /*
12200 ** A callback for the sqlite3_log() interface.
12201 */
shellLog(void * pArg,int iErrCode,const char * zMsg)12202 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
12203   ShellState *p = (ShellState*)pArg;
12204   if( p->pLog==0 ) return;
12205   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
12206   fflush(p->pLog);
12207 }
12208 
12209 /*
12210 ** SQL function:  shell_putsnl(X)
12211 **
12212 ** Write the text X to the screen (or whatever output is being directed)
12213 ** adding a newline at the end, and then return X.
12214 */
shellPutsFunc(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)12215 static void shellPutsFunc(
12216   sqlite3_context *pCtx,
12217   int nVal,
12218   sqlite3_value **apVal
12219 ){
12220   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
12221   (void)nVal;
12222   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
12223   sqlite3_result_value(pCtx, apVal[0]);
12224 }
12225 
12226 /*
12227 ** SQL function:   edit(VALUE)
12228 **                 edit(VALUE,EDITOR)
12229 **
12230 ** These steps:
12231 **
12232 **     (1) Write VALUE into a temporary file.
12233 **     (2) Run program EDITOR on that temporary file.
12234 **     (3) Read the temporary file back and return its content as the result.
12235 **     (4) Delete the temporary file
12236 **
12237 ** If the EDITOR argument is omitted, use the value in the VISUAL
12238 ** environment variable.  If still there is no EDITOR, through an error.
12239 **
12240 ** Also throw an error if the EDITOR program returns a non-zero exit code.
12241 */
12242 #ifndef SQLITE_NOHAVE_SYSTEM
editFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)12243 static void editFunc(
12244   sqlite3_context *context,
12245   int argc,
12246   sqlite3_value **argv
12247 ){
12248   const char *zEditor;
12249   char *zTempFile = 0;
12250   sqlite3 *db;
12251   char *zCmd = 0;
12252   int bBin;
12253   int rc;
12254   int hasCRNL = 0;
12255   FILE *f = 0;
12256   sqlite3_int64 sz;
12257   sqlite3_int64 x;
12258   unsigned char *p = 0;
12259 
12260   if( argc==2 ){
12261     zEditor = (const char*)sqlite3_value_text(argv[1]);
12262   }else{
12263     zEditor = getenv("VISUAL");
12264   }
12265   if( zEditor==0 ){
12266     sqlite3_result_error(context, "no editor for edit()", -1);
12267     return;
12268   }
12269   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
12270     sqlite3_result_error(context, "NULL input to edit()", -1);
12271     return;
12272   }
12273   db = sqlite3_context_db_handle(context);
12274   zTempFile = 0;
12275   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
12276   if( zTempFile==0 ){
12277     sqlite3_uint64 r = 0;
12278     sqlite3_randomness(sizeof(r), &r);
12279     zTempFile = sqlite3_mprintf("temp%llx", r);
12280     if( zTempFile==0 ){
12281       sqlite3_result_error_nomem(context);
12282       return;
12283     }
12284   }
12285   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
12286   /* When writing the file to be edited, do \n to \r\n conversions on systems
12287   ** that want \r\n line endings */
12288   f = fopen(zTempFile, bBin ? "wb" : "w");
12289   if( f==0 ){
12290     sqlite3_result_error(context, "edit() cannot open temp file", -1);
12291     goto edit_func_end;
12292   }
12293   sz = sqlite3_value_bytes(argv[0]);
12294   if( bBin ){
12295     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
12296   }else{
12297     const char *z = (const char*)sqlite3_value_text(argv[0]);
12298     /* Remember whether or not the value originally contained \r\n */
12299     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
12300     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
12301   }
12302   fclose(f);
12303   f = 0;
12304   if( x!=sz ){
12305     sqlite3_result_error(context, "edit() could not write the whole file", -1);
12306     goto edit_func_end;
12307   }
12308   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
12309   if( zCmd==0 ){
12310     sqlite3_result_error_nomem(context);
12311     goto edit_func_end;
12312   }
12313   rc = system(zCmd);
12314   sqlite3_free(zCmd);
12315   if( rc ){
12316     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
12317     goto edit_func_end;
12318   }
12319   f = fopen(zTempFile, "rb");
12320   if( f==0 ){
12321     sqlite3_result_error(context,
12322       "edit() cannot reopen temp file after edit", -1);
12323     goto edit_func_end;
12324   }
12325   fseek(f, 0, SEEK_END);
12326   sz = ftell(f);
12327   rewind(f);
12328   p = sqlite3_malloc64( sz+1 );
12329   if( p==0 ){
12330     sqlite3_result_error_nomem(context);
12331     goto edit_func_end;
12332   }
12333   x = fread(p, 1, (size_t)sz, f);
12334   fclose(f);
12335   f = 0;
12336   if( x!=sz ){
12337     sqlite3_result_error(context, "could not read back the whole file", -1);
12338     goto edit_func_end;
12339   }
12340   if( bBin ){
12341     sqlite3_result_blob64(context, p, sz, sqlite3_free);
12342   }else{
12343     sqlite3_int64 i, j;
12344     if( hasCRNL ){
12345       /* If the original contains \r\n then do no conversions back to \n */
12346       j = sz;
12347     }else{
12348       /* If the file did not originally contain \r\n then convert any new
12349       ** \r\n back into \n */
12350       for(i=j=0; i<sz; i++){
12351         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
12352         p[j++] = p[i];
12353       }
12354       sz = j;
12355       p[sz] = 0;
12356     }
12357     sqlite3_result_text64(context, (const char*)p, sz,
12358                           sqlite3_free, SQLITE_UTF8);
12359   }
12360   p = 0;
12361 
12362 edit_func_end:
12363   if( f ) fclose(f);
12364   unlink(zTempFile);
12365   sqlite3_free(zTempFile);
12366   sqlite3_free(p);
12367 }
12368 #endif /* SQLITE_NOHAVE_SYSTEM */
12369 
12370 /*
12371 ** Save or restore the current output mode
12372 */
outputModePush(ShellState * p)12373 static void outputModePush(ShellState *p){
12374   p->modePrior = p->mode;
12375   p->priorShFlgs = p->shellFlgs;
12376   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
12377   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
12378 }
outputModePop(ShellState * p)12379 static void outputModePop(ShellState *p){
12380   p->mode = p->modePrior;
12381   p->shellFlgs = p->priorShFlgs;
12382   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
12383   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
12384 }
12385 
12386 /*
12387 ** Output the given string as a hex-encoded blob (eg. X'1234' )
12388 */
output_hex_blob(FILE * out,const void * pBlob,int nBlob)12389 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
12390   int i;
12391   char *zBlob = (char *)pBlob;
12392   raw_printf(out,"X'");
12393   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
12394   raw_printf(out,"'");
12395 }
12396 
12397 /*
12398 ** Find a string that is not found anywhere in z[].  Return a pointer
12399 ** to that string.
12400 **
12401 ** Try to use zA and zB first.  If both of those are already found in z[]
12402 ** then make up some string and store it in the buffer zBuf.
12403 */
unused_string(const char * z,const char * zA,const char * zB,char * zBuf)12404 static const char *unused_string(
12405   const char *z,                    /* Result must not appear anywhere in z */
12406   const char *zA, const char *zB,   /* Try these first */
12407   char *zBuf                        /* Space to store a generated string */
12408 ){
12409   unsigned i = 0;
12410   if( strstr(z, zA)==0 ) return zA;
12411   if( strstr(z, zB)==0 ) return zB;
12412   do{
12413     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
12414   }while( strstr(z,zBuf)!=0 );
12415   return zBuf;
12416 }
12417 
12418 /*
12419 ** Output the given string as a quoted string using SQL quoting conventions.
12420 **
12421 ** See also: output_quoted_escaped_string()
12422 */
output_quoted_string(FILE * out,const char * z)12423 static void output_quoted_string(FILE *out, const char *z){
12424   int i;
12425   char c;
12426   setBinaryMode(out, 1);
12427   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
12428   if( c==0 ){
12429     utf8_printf(out,"'%s'",z);
12430   }else{
12431     raw_printf(out, "'");
12432     while( *z ){
12433       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
12434       if( c=='\'' ) i++;
12435       if( i ){
12436         utf8_printf(out, "%.*s", i, z);
12437         z += i;
12438       }
12439       if( c=='\'' ){
12440         raw_printf(out, "'");
12441         continue;
12442       }
12443       if( c==0 ){
12444         break;
12445       }
12446       z++;
12447     }
12448     raw_printf(out, "'");
12449   }
12450   setTextMode(out, 1);
12451 }
12452 
12453 /*
12454 ** Output the given string as a quoted string using SQL quoting conventions.
12455 ** Additionallly , escape the "\n" and "\r" characters so that they do not
12456 ** get corrupted by end-of-line translation facilities in some operating
12457 ** systems.
12458 **
12459 ** This is like output_quoted_string() but with the addition of the \r\n
12460 ** escape mechanism.
12461 */
output_quoted_escaped_string(FILE * out,const char * z)12462 static void output_quoted_escaped_string(FILE *out, const char *z){
12463   int i;
12464   char c;
12465   setBinaryMode(out, 1);
12466   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
12467   if( c==0 ){
12468     utf8_printf(out,"'%s'",z);
12469   }else{
12470     const char *zNL = 0;
12471     const char *zCR = 0;
12472     int nNL = 0;
12473     int nCR = 0;
12474     char zBuf1[20], zBuf2[20];
12475     for(i=0; z[i]; i++){
12476       if( z[i]=='\n' ) nNL++;
12477       if( z[i]=='\r' ) nCR++;
12478     }
12479     if( nNL ){
12480       raw_printf(out, "replace(");
12481       zNL = unused_string(z, "\\n", "\\012", zBuf1);
12482     }
12483     if( nCR ){
12484       raw_printf(out, "replace(");
12485       zCR = unused_string(z, "\\r", "\\015", zBuf2);
12486     }
12487     raw_printf(out, "'");
12488     while( *z ){
12489       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
12490       if( c=='\'' ) i++;
12491       if( i ){
12492         utf8_printf(out, "%.*s", i, z);
12493         z += i;
12494       }
12495       if( c=='\'' ){
12496         raw_printf(out, "'");
12497         continue;
12498       }
12499       if( c==0 ){
12500         break;
12501       }
12502       z++;
12503       if( c=='\n' ){
12504         raw_printf(out, "%s", zNL);
12505         continue;
12506       }
12507       raw_printf(out, "%s", zCR);
12508     }
12509     raw_printf(out, "'");
12510     if( nCR ){
12511       raw_printf(out, ",'%s',char(13))", zCR);
12512     }
12513     if( nNL ){
12514       raw_printf(out, ",'%s',char(10))", zNL);
12515     }
12516   }
12517   setTextMode(out, 1);
12518 }
12519 
12520 /*
12521 ** Output the given string as a quoted according to C or TCL quoting rules.
12522 */
output_c_string(FILE * out,const char * z)12523 static void output_c_string(FILE *out, const char *z){
12524   unsigned int c;
12525   fputc('"', out);
12526   while( (c = *(z++))!=0 ){
12527     if( c=='\\' ){
12528       fputc(c, out);
12529       fputc(c, out);
12530     }else if( c=='"' ){
12531       fputc('\\', out);
12532       fputc('"', out);
12533     }else if( c=='\t' ){
12534       fputc('\\', out);
12535       fputc('t', out);
12536     }else if( c=='\n' ){
12537       fputc('\\', out);
12538       fputc('n', out);
12539     }else if( c=='\r' ){
12540       fputc('\\', out);
12541       fputc('r', out);
12542     }else if( !isprint(c&0xff) ){
12543       raw_printf(out, "\\%03o", c&0xff);
12544     }else{
12545       fputc(c, out);
12546     }
12547   }
12548   fputc('"', out);
12549 }
12550 
12551 /*
12552 ** Output the given string as a quoted according to JSON quoting rules.
12553 */
output_json_string(FILE * out,const char * z,int n)12554 static void output_json_string(FILE *out, const char *z, int n){
12555   unsigned int c;
12556   if( n<0 ) n = (int)strlen(z);
12557   fputc('"', out);
12558   while( n-- ){
12559     c = *(z++);
12560     if( c=='\\' || c=='"' ){
12561       fputc('\\', out);
12562       fputc(c, out);
12563     }else if( c<=0x1f ){
12564       fputc('\\', out);
12565       if( c=='\b' ){
12566         fputc('b', out);
12567       }else if( c=='\f' ){
12568         fputc('f', out);
12569       }else if( c=='\n' ){
12570         fputc('n', out);
12571       }else if( c=='\r' ){
12572         fputc('r', out);
12573       }else if( c=='\t' ){
12574         fputc('t', out);
12575       }else{
12576          raw_printf(out, "u%04x",c);
12577       }
12578     }else{
12579       fputc(c, out);
12580     }
12581   }
12582   fputc('"', out);
12583 }
12584 
12585 /*
12586 ** Output the given string with characters that are special to
12587 ** HTML escaped.
12588 */
output_html_string(FILE * out,const char * z)12589 static void output_html_string(FILE *out, const char *z){
12590   int i;
12591   if( z==0 ) z = "";
12592   while( *z ){
12593     for(i=0;   z[i]
12594             && z[i]!='<'
12595             && z[i]!='&'
12596             && z[i]!='>'
12597             && z[i]!='\"'
12598             && z[i]!='\'';
12599         i++){}
12600     if( i>0 ){
12601       utf8_printf(out,"%.*s",i,z);
12602     }
12603     if( z[i]=='<' ){
12604       raw_printf(out,"&lt;");
12605     }else if( z[i]=='&' ){
12606       raw_printf(out,"&amp;");
12607     }else if( z[i]=='>' ){
12608       raw_printf(out,"&gt;");
12609     }else if( z[i]=='\"' ){
12610       raw_printf(out,"&quot;");
12611     }else if( z[i]=='\'' ){
12612       raw_printf(out,"&#39;");
12613     }else{
12614       break;
12615     }
12616     z += i + 1;
12617   }
12618 }
12619 
12620 /*
12621 ** If a field contains any character identified by a 1 in the following
12622 ** array, then the string must be quoted for CSV.
12623 */
12624 static const char needCsvQuote[] = {
12625   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12626   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12627   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
12628   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12629   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12630   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12631   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12632   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
12633   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12634   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12635   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12636   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12637   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12638   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12639   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12640   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12641 };
12642 
12643 /*
12644 ** Output a single term of CSV.  Actually, p->colSeparator is used for
12645 ** the separator, which may or may not be a comma.  p->nullValue is
12646 ** the null value.  Strings are quoted if necessary.  The separator
12647 ** is only issued if bSep is true.
12648 */
output_csv(ShellState * p,const char * z,int bSep)12649 static void output_csv(ShellState *p, const char *z, int bSep){
12650   FILE *out = p->out;
12651   if( z==0 ){
12652     utf8_printf(out,"%s",p->nullValue);
12653   }else{
12654     int i;
12655     int nSep = strlen30(p->colSeparator);
12656     for(i=0; z[i]; i++){
12657       if( needCsvQuote[((unsigned char*)z)[i]]
12658          || (z[i]==p->colSeparator[0] &&
12659              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
12660         i = 0;
12661         break;
12662       }
12663     }
12664     if( i==0 ){
12665       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
12666       utf8_printf(out, "%s", zQuoted);
12667       sqlite3_free(zQuoted);
12668     }else{
12669       utf8_printf(out, "%s", z);
12670     }
12671   }
12672   if( bSep ){
12673     utf8_printf(p->out, "%s", p->colSeparator);
12674   }
12675 }
12676 
12677 /*
12678 ** This routine runs when the user presses Ctrl-C
12679 */
interrupt_handler(int NotUsed)12680 static void interrupt_handler(int NotUsed){
12681   UNUSED_PARAMETER(NotUsed);
12682   seenInterrupt++;
12683   if( seenInterrupt>2 ) exit(1);
12684   if( globalDb ) sqlite3_interrupt(globalDb);
12685 }
12686 
12687 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12688 /*
12689 ** This routine runs for console events (e.g. Ctrl-C) on Win32
12690 */
ConsoleCtrlHandler(DWORD dwCtrlType)12691 static BOOL WINAPI ConsoleCtrlHandler(
12692   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
12693 ){
12694   if( dwCtrlType==CTRL_C_EVENT ){
12695     interrupt_handler(0);
12696     return TRUE;
12697   }
12698   return FALSE;
12699 }
12700 #endif
12701 
12702 #ifndef SQLITE_OMIT_AUTHORIZATION
12703 /*
12704 ** When the ".auth ON" is set, the following authorizer callback is
12705 ** invoked.  It always returns SQLITE_OK.
12706 */
shellAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)12707 static int shellAuth(
12708   void *pClientData,
12709   int op,
12710   const char *zA1,
12711   const char *zA2,
12712   const char *zA3,
12713   const char *zA4
12714 ){
12715   ShellState *p = (ShellState*)pClientData;
12716   static const char *azAction[] = { 0,
12717      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
12718      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
12719      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
12720      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
12721      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
12722      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
12723      "PRAGMA",               "READ",                 "SELECT",
12724      "TRANSACTION",          "UPDATE",               "ATTACH",
12725      "DETACH",               "ALTER_TABLE",          "REINDEX",
12726      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
12727      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
12728   };
12729   int i;
12730   const char *az[4];
12731   az[0] = zA1;
12732   az[1] = zA2;
12733   az[2] = zA3;
12734   az[3] = zA4;
12735   utf8_printf(p->out, "authorizer: %s", azAction[op]);
12736   for(i=0; i<4; i++){
12737     raw_printf(p->out, " ");
12738     if( az[i] ){
12739       output_c_string(p->out, az[i]);
12740     }else{
12741       raw_printf(p->out, "NULL");
12742     }
12743   }
12744   raw_printf(p->out, "\n");
12745   return SQLITE_OK;
12746 }
12747 #endif
12748 
12749 /*
12750 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
12751 **
12752 ** This routine converts some CREATE TABLE statements for shadow tables
12753 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
12754 */
printSchemaLine(FILE * out,const char * z,const char * zTail)12755 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
12756   if( z==0 ) return;
12757   if( zTail==0 ) return;
12758   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
12759     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
12760   }else{
12761     utf8_printf(out, "%s%s", z, zTail);
12762   }
12763 }
printSchemaLineN(FILE * out,char * z,int n,const char * zTail)12764 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
12765   char c = z[n];
12766   z[n] = 0;
12767   printSchemaLine(out, z, zTail);
12768   z[n] = c;
12769 }
12770 
12771 /*
12772 ** Return true if string z[] has nothing but whitespace and comments to the
12773 ** end of the first line.
12774 */
wsToEol(const char * z)12775 static int wsToEol(const char *z){
12776   int i;
12777   for(i=0; z[i]; i++){
12778     if( z[i]=='\n' ) return 1;
12779     if( IsSpace(z[i]) ) continue;
12780     if( z[i]=='-' && z[i+1]=='-' ) return 1;
12781     return 0;
12782   }
12783   return 1;
12784 }
12785 
12786 /*
12787 ** Add a new entry to the EXPLAIN QUERY PLAN data
12788 */
eqp_append(ShellState * p,int iEqpId,int p2,const char * zText)12789 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
12790   EQPGraphRow *pNew;
12791   int nText = strlen30(zText);
12792   if( p->autoEQPtest ){
12793     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
12794   }
12795   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
12796   if( pNew==0 ) shell_out_of_memory();
12797   pNew->iEqpId = iEqpId;
12798   pNew->iParentId = p2;
12799   memcpy(pNew->zText, zText, nText+1);
12800   pNew->pNext = 0;
12801   if( p->sGraph.pLast ){
12802     p->sGraph.pLast->pNext = pNew;
12803   }else{
12804     p->sGraph.pRow = pNew;
12805   }
12806   p->sGraph.pLast = pNew;
12807 }
12808 
12809 /*
12810 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
12811 ** in p->sGraph.
12812 */
eqp_reset(ShellState * p)12813 static void eqp_reset(ShellState *p){
12814   EQPGraphRow *pRow, *pNext;
12815   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
12816     pNext = pRow->pNext;
12817     sqlite3_free(pRow);
12818   }
12819   memset(&p->sGraph, 0, sizeof(p->sGraph));
12820 }
12821 
12822 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
12823 ** pOld, or return the first such line if pOld is NULL
12824 */
eqp_next_row(ShellState * p,int iEqpId,EQPGraphRow * pOld)12825 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
12826   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
12827   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
12828   return pRow;
12829 }
12830 
12831 /* Render a single level of the graph that has iEqpId as its parent.  Called
12832 ** recursively to render sublevels.
12833 */
eqp_render_level(ShellState * p,int iEqpId)12834 static void eqp_render_level(ShellState *p, int iEqpId){
12835   EQPGraphRow *pRow, *pNext;
12836   int n = strlen30(p->sGraph.zPrefix);
12837   char *z;
12838   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
12839     pNext = eqp_next_row(p, iEqpId, pRow);
12840     z = pRow->zText;
12841     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
12842                 pNext ? "|--" : "`--", z);
12843     if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
12844       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
12845       eqp_render_level(p, pRow->iEqpId);
12846       p->sGraph.zPrefix[n] = 0;
12847     }
12848   }
12849 }
12850 
12851 /*
12852 ** Display and reset the EXPLAIN QUERY PLAN data
12853 */
eqp_render(ShellState * p)12854 static void eqp_render(ShellState *p){
12855   EQPGraphRow *pRow = p->sGraph.pRow;
12856   if( pRow ){
12857     if( pRow->zText[0]=='-' ){
12858       if( pRow->pNext==0 ){
12859         eqp_reset(p);
12860         return;
12861       }
12862       utf8_printf(p->out, "%s\n", pRow->zText+3);
12863       p->sGraph.pRow = pRow->pNext;
12864       sqlite3_free(pRow);
12865     }else{
12866       utf8_printf(p->out, "QUERY PLAN\n");
12867     }
12868     p->sGraph.zPrefix[0] = 0;
12869     eqp_render_level(p, 0);
12870     eqp_reset(p);
12871   }
12872 }
12873 
12874 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
12875 /*
12876 ** Progress handler callback.
12877 */
progress_handler(void * pClientData)12878 static int progress_handler(void *pClientData) {
12879   ShellState *p = (ShellState*)pClientData;
12880   p->nProgress++;
12881   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
12882     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
12883     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
12884     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
12885     return 1;
12886   }
12887   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
12888     raw_printf(p->out, "Progress %u\n", p->nProgress);
12889   }
12890   return 0;
12891 }
12892 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
12893 
12894 /*
12895 ** Print N dashes
12896 */
print_dashes(FILE * out,int N)12897 static void print_dashes(FILE *out, int N){
12898   const char zDash[] = "--------------------------------------------------";
12899   const int nDash = sizeof(zDash) - 1;
12900   while( N>nDash ){
12901     fputs(zDash, out);
12902     N -= nDash;
12903   }
12904   raw_printf(out, "%.*s", N, zDash);
12905 }
12906 
12907 /*
12908 ** Print a markdown or table-style row separator using ascii-art
12909 */
print_row_separator(ShellState * p,int nArg,const char * zSep)12910 static void print_row_separator(
12911   ShellState *p,
12912   int nArg,
12913   const char *zSep
12914 ){
12915   int i;
12916   if( nArg>0 ){
12917     fputs(zSep, p->out);
12918     print_dashes(p->out, p->actualWidth[0]+2);
12919     for(i=1; i<nArg; i++){
12920       fputs(zSep, p->out);
12921       print_dashes(p->out, p->actualWidth[i]+2);
12922     }
12923     fputs(zSep, p->out);
12924   }
12925   fputs("\n", p->out);
12926 }
12927 
12928 /*
12929 ** This is the callback routine that the shell
12930 ** invokes for each row of a query result.
12931 */
shell_callback(void * pArg,int nArg,char ** azArg,char ** azCol,int * aiType)12932 static int shell_callback(
12933   void *pArg,
12934   int nArg,        /* Number of result columns */
12935   char **azArg,    /* Text of each result column */
12936   char **azCol,    /* Column names */
12937   int *aiType      /* Column types.  Might be NULL */
12938 ){
12939   int i;
12940   ShellState *p = (ShellState*)pArg;
12941 
12942   if( azArg==0 ) return 0;
12943   switch( p->cMode ){
12944     case MODE_Line: {
12945       int w = 5;
12946       if( azArg==0 ) break;
12947       for(i=0; i<nArg; i++){
12948         int len = strlen30(azCol[i] ? azCol[i] : "");
12949         if( len>w ) w = len;
12950       }
12951       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
12952       for(i=0; i<nArg; i++){
12953         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
12954                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
12955       }
12956       break;
12957     }
12958     case MODE_Explain: {
12959       static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
12960       if( nArg>ArraySize(aExplainWidth) ){
12961         nArg = ArraySize(aExplainWidth);
12962       }
12963       if( p->cnt++==0 ){
12964         for(i=0; i<nArg; i++){
12965           int w = aExplainWidth[i];
12966           utf8_width_print(p->out, w, azCol[i]);
12967           fputs(i==nArg-1 ? "\n" : "  ", p->out);
12968         }
12969         for(i=0; i<nArg; i++){
12970           int w = aExplainWidth[i];
12971           print_dashes(p->out, w);
12972           fputs(i==nArg-1 ? "\n" : "  ", p->out);
12973         }
12974       }
12975       if( azArg==0 ) break;
12976       for(i=0; i<nArg; i++){
12977         int w = aExplainWidth[i];
12978         if( i==nArg-1 ) w = 0;
12979         if( azArg[i] && strlenChar(azArg[i])>w ){
12980           w = strlenChar(azArg[i]);
12981         }
12982         if( i==1 && p->aiIndent && p->pStmt ){
12983           if( p->iIndent<p->nIndent ){
12984             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
12985           }
12986           p->iIndent++;
12987         }
12988         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
12989         fputs(i==nArg-1 ? "\n" : "  ", p->out);
12990       }
12991       break;
12992     }
12993     case MODE_Semi: {   /* .schema and .fullschema output */
12994       printSchemaLine(p->out, azArg[0], ";\n");
12995       break;
12996     }
12997     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
12998       char *z;
12999       int j;
13000       int nParen = 0;
13001       char cEnd = 0;
13002       char c;
13003       int nLine = 0;
13004       assert( nArg==1 );
13005       if( azArg[0]==0 ) break;
13006       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
13007        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
13008       ){
13009         utf8_printf(p->out, "%s;\n", azArg[0]);
13010         break;
13011       }
13012       z = sqlite3_mprintf("%s", azArg[0]);
13013       j = 0;
13014       for(i=0; IsSpace(z[i]); i++){}
13015       for(; (c = z[i])!=0; i++){
13016         if( IsSpace(c) ){
13017           if( z[j-1]=='\r' ) z[j-1] = '\n';
13018           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
13019         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
13020           j--;
13021         }
13022         z[j++] = c;
13023       }
13024       while( j>0 && IsSpace(z[j-1]) ){ j--; }
13025       z[j] = 0;
13026       if( strlen30(z)>=79 ){
13027         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
13028           if( c==cEnd ){
13029             cEnd = 0;
13030           }else if( c=='"' || c=='\'' || c=='`' ){
13031             cEnd = c;
13032           }else if( c=='[' ){
13033             cEnd = ']';
13034           }else if( c=='-' && z[i+1]=='-' ){
13035             cEnd = '\n';
13036           }else if( c=='(' ){
13037             nParen++;
13038           }else if( c==')' ){
13039             nParen--;
13040             if( nLine>0 && nParen==0 && j>0 ){
13041               printSchemaLineN(p->out, z, j, "\n");
13042               j = 0;
13043             }
13044           }
13045           z[j++] = c;
13046           if( nParen==1 && cEnd==0
13047            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
13048           ){
13049             if( c=='\n' ) j--;
13050             printSchemaLineN(p->out, z, j, "\n  ");
13051             j = 0;
13052             nLine++;
13053             while( IsSpace(z[i+1]) ){ i++; }
13054           }
13055         }
13056         z[j] = 0;
13057       }
13058       printSchemaLine(p->out, z, ";\n");
13059       sqlite3_free(z);
13060       break;
13061     }
13062     case MODE_List: {
13063       if( p->cnt++==0 && p->showHeader ){
13064         for(i=0; i<nArg; i++){
13065           utf8_printf(p->out,"%s%s",azCol[i],
13066                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
13067         }
13068       }
13069       if( azArg==0 ) break;
13070       for(i=0; i<nArg; i++){
13071         char *z = azArg[i];
13072         if( z==0 ) z = p->nullValue;
13073         utf8_printf(p->out, "%s", z);
13074         if( i<nArg-1 ){
13075           utf8_printf(p->out, "%s", p->colSeparator);
13076         }else{
13077           utf8_printf(p->out, "%s", p->rowSeparator);
13078         }
13079       }
13080       break;
13081     }
13082     case MODE_Html: {
13083       if( p->cnt++==0 && p->showHeader ){
13084         raw_printf(p->out,"<TR>");
13085         for(i=0; i<nArg; i++){
13086           raw_printf(p->out,"<TH>");
13087           output_html_string(p->out, azCol[i]);
13088           raw_printf(p->out,"</TH>\n");
13089         }
13090         raw_printf(p->out,"</TR>\n");
13091       }
13092       if( azArg==0 ) break;
13093       raw_printf(p->out,"<TR>");
13094       for(i=0; i<nArg; i++){
13095         raw_printf(p->out,"<TD>");
13096         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
13097         raw_printf(p->out,"</TD>\n");
13098       }
13099       raw_printf(p->out,"</TR>\n");
13100       break;
13101     }
13102     case MODE_Tcl: {
13103       if( p->cnt++==0 && p->showHeader ){
13104         for(i=0; i<nArg; i++){
13105           output_c_string(p->out,azCol[i] ? azCol[i] : "");
13106           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
13107         }
13108         utf8_printf(p->out, "%s", p->rowSeparator);
13109       }
13110       if( azArg==0 ) break;
13111       for(i=0; i<nArg; i++){
13112         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
13113         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
13114       }
13115       utf8_printf(p->out, "%s", p->rowSeparator);
13116       break;
13117     }
13118     case MODE_Csv: {
13119       setBinaryMode(p->out, 1);
13120       if( p->cnt++==0 && p->showHeader ){
13121         for(i=0; i<nArg; i++){
13122           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
13123         }
13124         utf8_printf(p->out, "%s", p->rowSeparator);
13125       }
13126       if( nArg>0 ){
13127         for(i=0; i<nArg; i++){
13128           output_csv(p, azArg[i], i<nArg-1);
13129         }
13130         utf8_printf(p->out, "%s", p->rowSeparator);
13131       }
13132       setTextMode(p->out, 1);
13133       break;
13134     }
13135     case MODE_Insert: {
13136       if( azArg==0 ) break;
13137       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
13138       if( p->showHeader ){
13139         raw_printf(p->out,"(");
13140         for(i=0; i<nArg; i++){
13141           if( i>0 ) raw_printf(p->out, ",");
13142           if( quoteChar(azCol[i]) ){
13143             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
13144             utf8_printf(p->out, "%s", z);
13145             sqlite3_free(z);
13146           }else{
13147             raw_printf(p->out, "%s", azCol[i]);
13148           }
13149         }
13150         raw_printf(p->out,")");
13151       }
13152       p->cnt++;
13153       for(i=0; i<nArg; i++){
13154         raw_printf(p->out, i>0 ? "," : " VALUES(");
13155         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
13156           utf8_printf(p->out,"NULL");
13157         }else if( aiType && aiType[i]==SQLITE_TEXT ){
13158           if( ShellHasFlag(p, SHFLG_Newlines) ){
13159             output_quoted_string(p->out, azArg[i]);
13160           }else{
13161             output_quoted_escaped_string(p->out, azArg[i]);
13162           }
13163         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
13164           utf8_printf(p->out,"%s", azArg[i]);
13165         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
13166           char z[50];
13167           double r = sqlite3_column_double(p->pStmt, i);
13168           sqlite3_uint64 ur;
13169           memcpy(&ur,&r,sizeof(r));
13170           if( ur==0x7ff0000000000000LL ){
13171             raw_printf(p->out, "1e999");
13172           }else if( ur==0xfff0000000000000LL ){
13173             raw_printf(p->out, "-1e999");
13174           }else{
13175             sqlite3_snprintf(50,z,"%!.20g", r);
13176             raw_printf(p->out, "%s", z);
13177           }
13178         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
13179           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
13180           int nBlob = sqlite3_column_bytes(p->pStmt, i);
13181           output_hex_blob(p->out, pBlob, nBlob);
13182         }else if( isNumber(azArg[i], 0) ){
13183           utf8_printf(p->out,"%s", azArg[i]);
13184         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
13185           output_quoted_string(p->out, azArg[i]);
13186         }else{
13187           output_quoted_escaped_string(p->out, azArg[i]);
13188         }
13189       }
13190       raw_printf(p->out,");\n");
13191       break;
13192     }
13193     case MODE_Json: {
13194       if( azArg==0 ) break;
13195       if( p->cnt==0 ){
13196         fputs("[{", p->out);
13197       }else{
13198         fputs(",\n{", p->out);
13199       }
13200       p->cnt++;
13201       for(i=0; i<nArg; i++){
13202         output_json_string(p->out, azCol[i], -1);
13203         putc(':', p->out);
13204         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
13205           fputs("null",p->out);
13206         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
13207           char z[50];
13208           double r = sqlite3_column_double(p->pStmt, i);
13209           sqlite3_uint64 ur;
13210           memcpy(&ur,&r,sizeof(r));
13211           if( ur==0x7ff0000000000000LL ){
13212             raw_printf(p->out, "1e999");
13213           }else if( ur==0xfff0000000000000LL ){
13214             raw_printf(p->out, "-1e999");
13215           }else{
13216             sqlite3_snprintf(50,z,"%!.20g", r);
13217             raw_printf(p->out, "%s", z);
13218           }
13219         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
13220           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
13221           int nBlob = sqlite3_column_bytes(p->pStmt, i);
13222           output_json_string(p->out, pBlob, nBlob);
13223         }else if( aiType && aiType[i]==SQLITE_TEXT ){
13224           output_json_string(p->out, azArg[i], -1);
13225         }else{
13226           utf8_printf(p->out,"%s", azArg[i]);
13227         }
13228         if( i<nArg-1 ){
13229           putc(',', p->out);
13230         }
13231       }
13232       putc('}', p->out);
13233       break;
13234     }
13235     case MODE_Quote: {
13236       if( azArg==0 ) break;
13237       if( p->cnt==0 && p->showHeader ){
13238         for(i=0; i<nArg; i++){
13239           if( i>0 ) fputs(p->colSeparator, p->out);
13240           output_quoted_string(p->out, azCol[i]);
13241         }
13242         fputs(p->rowSeparator, p->out);
13243       }
13244       p->cnt++;
13245       for(i=0; i<nArg; i++){
13246         if( i>0 ) fputs(p->colSeparator, p->out);
13247         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
13248           utf8_printf(p->out,"NULL");
13249         }else if( aiType && aiType[i]==SQLITE_TEXT ){
13250           output_quoted_string(p->out, azArg[i]);
13251         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
13252           utf8_printf(p->out,"%s", azArg[i]);
13253         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
13254           char z[50];
13255           double r = sqlite3_column_double(p->pStmt, i);
13256           sqlite3_snprintf(50,z,"%!.20g", r);
13257           raw_printf(p->out, "%s", z);
13258         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
13259           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
13260           int nBlob = sqlite3_column_bytes(p->pStmt, i);
13261           output_hex_blob(p->out, pBlob, nBlob);
13262         }else if( isNumber(azArg[i], 0) ){
13263           utf8_printf(p->out,"%s", azArg[i]);
13264         }else{
13265           output_quoted_string(p->out, azArg[i]);
13266         }
13267       }
13268       fputs(p->rowSeparator, p->out);
13269       break;
13270     }
13271     case MODE_Ascii: {
13272       if( p->cnt++==0 && p->showHeader ){
13273         for(i=0; i<nArg; i++){
13274           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
13275           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
13276         }
13277         utf8_printf(p->out, "%s", p->rowSeparator);
13278       }
13279       if( azArg==0 ) break;
13280       for(i=0; i<nArg; i++){
13281         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
13282         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
13283       }
13284       utf8_printf(p->out, "%s", p->rowSeparator);
13285       break;
13286     }
13287     case MODE_EQP: {
13288       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
13289       break;
13290     }
13291   }
13292   return 0;
13293 }
13294 
13295 /*
13296 ** This is the callback routine that the SQLite library
13297 ** invokes for each row of a query result.
13298 */
callback(void * pArg,int nArg,char ** azArg,char ** azCol)13299 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
13300   /* since we don't have type info, call the shell_callback with a NULL value */
13301   return shell_callback(pArg, nArg, azArg, azCol, NULL);
13302 }
13303 
13304 /*
13305 ** This is the callback routine from sqlite3_exec() that appends all
13306 ** output onto the end of a ShellText object.
13307 */
captureOutputCallback(void * pArg,int nArg,char ** azArg,char ** az)13308 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
13309   ShellText *p = (ShellText*)pArg;
13310   int i;
13311   UNUSED_PARAMETER(az);
13312   if( azArg==0 ) return 0;
13313   if( p->n ) appendText(p, "|", 0);
13314   for(i=0; i<nArg; i++){
13315     if( i ) appendText(p, ",", 0);
13316     if( azArg[i] ) appendText(p, azArg[i], 0);
13317   }
13318   return 0;
13319 }
13320 
13321 /*
13322 ** Generate an appropriate SELFTEST table in the main database.
13323 */
createSelftestTable(ShellState * p)13324 static void createSelftestTable(ShellState *p){
13325   char *zErrMsg = 0;
13326   sqlite3_exec(p->db,
13327     "SAVEPOINT selftest_init;\n"
13328     "CREATE TABLE IF NOT EXISTS selftest(\n"
13329     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
13330     "  op TEXT,\n"                   /* Operator:  memo run */
13331     "  cmd TEXT,\n"                  /* Command text */
13332     "  ans TEXT\n"                   /* Desired answer */
13333     ");"
13334     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
13335     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
13336     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
13337     "         'memo','Tests generated by --init');\n"
13338     "INSERT INTO [_shell$self]\n"
13339     "  SELECT 'run',\n"
13340     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
13341                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
13342     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
13343                           "FROM sqlite_schema ORDER BY 2',224));\n"
13344     "INSERT INTO [_shell$self]\n"
13345     "  SELECT 'run',"
13346     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
13347     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
13348     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
13349     "  FROM (\n"
13350     "    SELECT name FROM sqlite_schema\n"
13351     "     WHERE type='table'\n"
13352     "       AND name<>'selftest'\n"
13353     "       AND coalesce(rootpage,0)>0\n"
13354     "  )\n"
13355     " ORDER BY name;\n"
13356     "INSERT INTO [_shell$self]\n"
13357     "  VALUES('run','PRAGMA integrity_check','ok');\n"
13358     "INSERT INTO selftest(tno,op,cmd,ans)"
13359     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
13360     "DROP TABLE [_shell$self];"
13361     ,0,0,&zErrMsg);
13362   if( zErrMsg ){
13363     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
13364     sqlite3_free(zErrMsg);
13365   }
13366   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
13367 }
13368 
13369 
13370 /*
13371 ** Set the destination table field of the ShellState structure to
13372 ** the name of the table given.  Escape any quote characters in the
13373 ** table name.
13374 */
set_table_name(ShellState * p,const char * zName)13375 static void set_table_name(ShellState *p, const char *zName){
13376   int i, n;
13377   char cQuote;
13378   char *z;
13379 
13380   if( p->zDestTable ){
13381     free(p->zDestTable);
13382     p->zDestTable = 0;
13383   }
13384   if( zName==0 ) return;
13385   cQuote = quoteChar(zName);
13386   n = strlen30(zName);
13387   if( cQuote ) n += n+2;
13388   z = p->zDestTable = malloc( n+1 );
13389   if( z==0 ) shell_out_of_memory();
13390   n = 0;
13391   if( cQuote ) z[n++] = cQuote;
13392   for(i=0; zName[i]; i++){
13393     z[n++] = zName[i];
13394     if( zName[i]==cQuote ) z[n++] = cQuote;
13395   }
13396   if( cQuote ) z[n++] = cQuote;
13397   z[n] = 0;
13398 }
13399 
13400 
13401 /*
13402 ** Execute a query statement that will generate SQL output.  Print
13403 ** the result columns, comma-separated, on a line and then add a
13404 ** semicolon terminator to the end of that line.
13405 **
13406 ** If the number of columns is 1 and that column contains text "--"
13407 ** then write the semicolon on a separate line.  That way, if a
13408 ** "--" comment occurs at the end of the statement, the comment
13409 ** won't consume the semicolon terminator.
13410 */
run_table_dump_query(ShellState * p,const char * zSelect)13411 static int run_table_dump_query(
13412   ShellState *p,           /* Query context */
13413   const char *zSelect      /* SELECT statement to extract content */
13414 ){
13415   sqlite3_stmt *pSelect;
13416   int rc;
13417   int nResult;
13418   int i;
13419   const char *z;
13420   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
13421   if( rc!=SQLITE_OK || !pSelect ){
13422     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
13423                 sqlite3_errmsg(p->db));
13424     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
13425     return rc;
13426   }
13427   rc = sqlite3_step(pSelect);
13428   nResult = sqlite3_column_count(pSelect);
13429   while( rc==SQLITE_ROW ){
13430     z = (const char*)sqlite3_column_text(pSelect, 0);
13431     utf8_printf(p->out, "%s", z);
13432     for(i=1; i<nResult; i++){
13433       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
13434     }
13435     if( z==0 ) z = "";
13436     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
13437     if( z[0] ){
13438       raw_printf(p->out, "\n;\n");
13439     }else{
13440       raw_printf(p->out, ";\n");
13441     }
13442     rc = sqlite3_step(pSelect);
13443   }
13444   rc = sqlite3_finalize(pSelect);
13445   if( rc!=SQLITE_OK ){
13446     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
13447                 sqlite3_errmsg(p->db));
13448     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
13449   }
13450   return rc;
13451 }
13452 
13453 /*
13454 ** Allocate space and save off current error string.
13455 */
save_err_msg(sqlite3 * db)13456 static char *save_err_msg(
13457   sqlite3 *db            /* Database to query */
13458 ){
13459   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
13460   char *zErrMsg = sqlite3_malloc64(nErrMsg);
13461   if( zErrMsg ){
13462     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
13463   }
13464   return zErrMsg;
13465 }
13466 
13467 #ifdef __linux__
13468 /*
13469 ** Attempt to display I/O stats on Linux using /proc/PID/io
13470 */
displayLinuxIoStats(FILE * out)13471 static void displayLinuxIoStats(FILE *out){
13472   FILE *in;
13473   char z[200];
13474   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
13475   in = fopen(z, "rb");
13476   if( in==0 ) return;
13477   while( fgets(z, sizeof(z), in)!=0 ){
13478     static const struct {
13479       const char *zPattern;
13480       const char *zDesc;
13481     } aTrans[] = {
13482       { "rchar: ",                  "Bytes received by read():" },
13483       { "wchar: ",                  "Bytes sent to write():"    },
13484       { "syscr: ",                  "Read() system calls:"      },
13485       { "syscw: ",                  "Write() system calls:"     },
13486       { "read_bytes: ",             "Bytes read from storage:"  },
13487       { "write_bytes: ",            "Bytes written to storage:" },
13488       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
13489     };
13490     int i;
13491     for(i=0; i<ArraySize(aTrans); i++){
13492       int n = strlen30(aTrans[i].zPattern);
13493       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
13494         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
13495         break;
13496       }
13497     }
13498   }
13499   fclose(in);
13500 }
13501 #endif
13502 
13503 /*
13504 ** Display a single line of status using 64-bit values.
13505 */
displayStatLine(ShellState * p,char * zLabel,char * zFormat,int iStatusCtrl,int bReset)13506 static void displayStatLine(
13507   ShellState *p,            /* The shell context */
13508   char *zLabel,             /* Label for this one line */
13509   char *zFormat,            /* Format for the result */
13510   int iStatusCtrl,          /* Which status to display */
13511   int bReset                /* True to reset the stats */
13512 ){
13513   sqlite3_int64 iCur = -1;
13514   sqlite3_int64 iHiwtr = -1;
13515   int i, nPercent;
13516   char zLine[200];
13517   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
13518   for(i=0, nPercent=0; zFormat[i]; i++){
13519     if( zFormat[i]=='%' ) nPercent++;
13520   }
13521   if( nPercent>1 ){
13522     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
13523   }else{
13524     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
13525   }
13526   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
13527 }
13528 
13529 /*
13530 ** Display memory stats.
13531 */
display_stats(sqlite3 * db,ShellState * pArg,int bReset)13532 static int display_stats(
13533   sqlite3 *db,                /* Database to query */
13534   ShellState *pArg,           /* Pointer to ShellState */
13535   int bReset                  /* True to reset the stats */
13536 ){
13537   int iCur;
13538   int iHiwtr;
13539   FILE *out;
13540   if( pArg==0 || pArg->out==0 ) return 0;
13541   out = pArg->out;
13542 
13543   if( pArg->pStmt && pArg->statsOn==2 ){
13544     int nCol, i, x;
13545     sqlite3_stmt *pStmt = pArg->pStmt;
13546     char z[100];
13547     nCol = sqlite3_column_count(pStmt);
13548     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
13549     for(i=0; i<nCol; i++){
13550       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
13551       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
13552 #ifndef SQLITE_OMIT_DECLTYPE
13553       sqlite3_snprintf(30, z+x, "declared type:");
13554       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
13555 #endif
13556 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13557       sqlite3_snprintf(30, z+x, "database name:");
13558       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
13559       sqlite3_snprintf(30, z+x, "table name:");
13560       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
13561       sqlite3_snprintf(30, z+x, "origin name:");
13562       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
13563 #endif
13564     }
13565   }
13566 
13567   if( pArg->statsOn==3 ){
13568     if( pArg->pStmt ){
13569       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
13570       raw_printf(pArg->out, "VM-steps: %d\n", iCur);
13571     }
13572     return 0;
13573   }
13574 
13575   displayStatLine(pArg, "Memory Used:",
13576      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
13577   displayStatLine(pArg, "Number of Outstanding Allocations:",
13578      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
13579   if( pArg->shellFlgs & SHFLG_Pagecache ){
13580     displayStatLine(pArg, "Number of Pcache Pages Used:",
13581        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
13582   }
13583   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
13584      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
13585   displayStatLine(pArg, "Largest Allocation:",
13586      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
13587   displayStatLine(pArg, "Largest Pcache Allocation:",
13588      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
13589 #ifdef YYTRACKMAXSTACKDEPTH
13590   displayStatLine(pArg, "Deepest Parser Stack:",
13591      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
13592 #endif
13593 
13594   if( db ){
13595     if( pArg->shellFlgs & SHFLG_Lookaside ){
13596       iHiwtr = iCur = -1;
13597       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
13598                         &iCur, &iHiwtr, bReset);
13599       raw_printf(pArg->out,
13600               "Lookaside Slots Used:                %d (max %d)\n",
13601               iCur, iHiwtr);
13602       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
13603                         &iCur, &iHiwtr, bReset);
13604       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
13605               iHiwtr);
13606       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
13607                         &iCur, &iHiwtr, bReset);
13608       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
13609               iHiwtr);
13610       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
13611                         &iCur, &iHiwtr, bReset);
13612       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
13613               iHiwtr);
13614     }
13615     iHiwtr = iCur = -1;
13616     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
13617     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
13618             iCur);
13619     iHiwtr = iCur = -1;
13620     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
13621     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
13622     iHiwtr = iCur = -1;
13623     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
13624     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
13625     iHiwtr = iCur = -1;
13626     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
13627     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
13628     iHiwtr = iCur = -1;
13629     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
13630     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
13631     iHiwtr = iCur = -1;
13632     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
13633     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
13634             iCur);
13635     iHiwtr = iCur = -1;
13636     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
13637     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
13638             iCur);
13639   }
13640 
13641   if( pArg->pStmt ){
13642     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
13643                                bReset);
13644     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
13645     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
13646     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
13647     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
13648     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
13649     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
13650     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
13651     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
13652     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
13653     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
13654     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
13655     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
13656     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
13657   }
13658 
13659 #ifdef __linux__
13660   displayLinuxIoStats(pArg->out);
13661 #endif
13662 
13663   /* Do not remove this machine readable comment: extra-stats-output-here */
13664 
13665   return 0;
13666 }
13667 
13668 /*
13669 ** Display scan stats.
13670 */
display_scanstats(sqlite3 * db,ShellState * pArg)13671 static void display_scanstats(
13672   sqlite3 *db,                    /* Database to query */
13673   ShellState *pArg                /* Pointer to ShellState */
13674 ){
13675 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
13676   UNUSED_PARAMETER(db);
13677   UNUSED_PARAMETER(pArg);
13678 #else
13679   int i, k, n, mx;
13680   raw_printf(pArg->out, "-------- scanstats --------\n");
13681   mx = 0;
13682   for(k=0; k<=mx; k++){
13683     double rEstLoop = 1.0;
13684     for(i=n=0; 1; i++){
13685       sqlite3_stmt *p = pArg->pStmt;
13686       sqlite3_int64 nLoop, nVisit;
13687       double rEst;
13688       int iSid;
13689       const char *zExplain;
13690       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
13691         break;
13692       }
13693       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
13694       if( iSid>mx ) mx = iSid;
13695       if( iSid!=k ) continue;
13696       if( n==0 ){
13697         rEstLoop = (double)nLoop;
13698         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
13699       }
13700       n++;
13701       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
13702       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
13703       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
13704       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
13705       rEstLoop *= rEst;
13706       raw_printf(pArg->out,
13707           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
13708           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
13709       );
13710     }
13711   }
13712   raw_printf(pArg->out, "---------------------------\n");
13713 #endif
13714 }
13715 
13716 /*
13717 ** Parameter azArray points to a zero-terminated array of strings. zStr
13718 ** points to a single nul-terminated string. Return non-zero if zStr
13719 ** is equal, according to strcmp(), to any of the strings in the array.
13720 ** Otherwise, return zero.
13721 */
str_in_array(const char * zStr,const char ** azArray)13722 static int str_in_array(const char *zStr, const char **azArray){
13723   int i;
13724   for(i=0; azArray[i]; i++){
13725     if( 0==strcmp(zStr, azArray[i]) ) return 1;
13726   }
13727   return 0;
13728 }
13729 
13730 /*
13731 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
13732 ** and populate the ShellState.aiIndent[] array with the number of
13733 ** spaces each opcode should be indented before it is output.
13734 **
13735 ** The indenting rules are:
13736 **
13737 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
13738 **       all opcodes that occur between the p2 jump destination and the opcode
13739 **       itself by 2 spaces.
13740 **
13741 **     * For each "Goto", if the jump destination is earlier in the program
13742 **       and ends on one of:
13743 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
13744 **       or if the P1 parameter is one instead of zero,
13745 **       then indent all opcodes between the earlier instruction
13746 **       and "Goto" by 2 spaces.
13747 */
explain_data_prepare(ShellState * p,sqlite3_stmt * pSql)13748 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
13749   const char *zSql;               /* The text of the SQL statement */
13750   const char *z;                  /* Used to check if this is an EXPLAIN */
13751   int *abYield = 0;               /* True if op is an OP_Yield */
13752   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
13753   int iOp;                        /* Index of operation in p->aiIndent[] */
13754 
13755   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
13756   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
13757                             "Rewind", 0 };
13758   const char *azGoto[] = { "Goto", 0 };
13759 
13760   /* Try to figure out if this is really an EXPLAIN statement. If this
13761   ** cannot be verified, return early.  */
13762   if( sqlite3_column_count(pSql)!=8 ){
13763     p->cMode = p->mode;
13764     return;
13765   }
13766   zSql = sqlite3_sql(pSql);
13767   if( zSql==0 ) return;
13768   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
13769   if( sqlite3_strnicmp(z, "explain", 7) ){
13770     p->cMode = p->mode;
13771     return;
13772   }
13773 
13774   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
13775     int i;
13776     int iAddr = sqlite3_column_int(pSql, 0);
13777     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
13778 
13779     /* Set p2 to the P2 field of the current opcode. Then, assuming that
13780     ** p2 is an instruction address, set variable p2op to the index of that
13781     ** instruction in the aiIndent[] array. p2 and p2op may be different if
13782     ** the current instruction is part of a sub-program generated by an
13783     ** SQL trigger or foreign key.  */
13784     int p2 = sqlite3_column_int(pSql, 3);
13785     int p2op = (p2 + (iOp-iAddr));
13786 
13787     /* Grow the p->aiIndent array as required */
13788     if( iOp>=nAlloc ){
13789       if( iOp==0 ){
13790         /* Do further verfication that this is explain output.  Abort if
13791         ** it is not */
13792         static const char *explainCols[] = {
13793            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
13794         int jj;
13795         for(jj=0; jj<ArraySize(explainCols); jj++){
13796           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
13797             p->cMode = p->mode;
13798             sqlite3_reset(pSql);
13799             return;
13800           }
13801         }
13802       }
13803       nAlloc += 100;
13804       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
13805       if( p->aiIndent==0 ) shell_out_of_memory();
13806       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
13807       if( abYield==0 ) shell_out_of_memory();
13808     }
13809     abYield[iOp] = str_in_array(zOp, azYield);
13810     p->aiIndent[iOp] = 0;
13811     p->nIndent = iOp+1;
13812 
13813     if( str_in_array(zOp, azNext) ){
13814       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
13815     }
13816     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
13817      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
13818     ){
13819       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
13820     }
13821   }
13822 
13823   p->iIndent = 0;
13824   sqlite3_free(abYield);
13825   sqlite3_reset(pSql);
13826 }
13827 
13828 /*
13829 ** Free the array allocated by explain_data_prepare().
13830 */
explain_data_delete(ShellState * p)13831 static void explain_data_delete(ShellState *p){
13832   sqlite3_free(p->aiIndent);
13833   p->aiIndent = 0;
13834   p->nIndent = 0;
13835   p->iIndent = 0;
13836 }
13837 
13838 /*
13839 ** Disable and restore .wheretrace and .selecttrace settings.
13840 */
13841 static unsigned int savedSelectTrace;
13842 static unsigned int savedWhereTrace;
disable_debug_trace_modes(void)13843 static void disable_debug_trace_modes(void){
13844   unsigned int zero = 0;
13845   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
13846   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
13847   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
13848   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
13849 }
restore_debug_trace_modes(void)13850 static void restore_debug_trace_modes(void){
13851   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
13852   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
13853 }
13854 
13855 /* Create the TEMP table used to store parameter bindings */
bind_table_init(ShellState * p)13856 static void bind_table_init(ShellState *p){
13857   int wrSchema = 0;
13858   int defensiveMode = 0;
13859   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
13860   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
13861   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
13862   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
13863   sqlite3_exec(p->db,
13864     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
13865     "  key TEXT PRIMARY KEY,\n"
13866     "  value\n"
13867     ") WITHOUT ROWID;",
13868     0, 0, 0);
13869   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
13870   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
13871 }
13872 
13873 /*
13874 ** Bind parameters on a prepared statement.
13875 **
13876 ** Parameter bindings are taken from a TEMP table of the form:
13877 **
13878 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
13879 **    WITHOUT ROWID;
13880 **
13881 ** No bindings occur if this table does not exist.  The name of the table
13882 ** begins with "sqlite_" so that it will not collide with ordinary application
13883 ** tables.  The table must be in the TEMP schema.
13884 */
bind_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)13885 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
13886   int nVar;
13887   int i;
13888   int rc;
13889   sqlite3_stmt *pQ = 0;
13890 
13891   nVar = sqlite3_bind_parameter_count(pStmt);
13892   if( nVar==0 ) return;  /* Nothing to do */
13893   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
13894                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
13895     return; /* Parameter table does not exist */
13896   }
13897   rc = sqlite3_prepare_v2(pArg->db,
13898           "SELECT value FROM temp.sqlite_parameters"
13899           " WHERE key=?1", -1, &pQ, 0);
13900   if( rc || pQ==0 ) return;
13901   for(i=1; i<=nVar; i++){
13902     char zNum[30];
13903     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
13904     if( zVar==0 ){
13905       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
13906       zVar = zNum;
13907     }
13908     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
13909     if( sqlite3_step(pQ)==SQLITE_ROW ){
13910       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
13911     }else{
13912       sqlite3_bind_null(pStmt, i);
13913     }
13914     sqlite3_reset(pQ);
13915   }
13916   sqlite3_finalize(pQ);
13917 }
13918 
13919 /*
13920 ** UTF8 box-drawing characters.  Imagine box lines like this:
13921 **
13922 **           1
13923 **           |
13924 **       4 --+-- 2
13925 **           |
13926 **           3
13927 **
13928 ** Each box characters has between 2 and 4 of the lines leading from
13929 ** the center.  The characters are here identified by the numbers of
13930 ** their corresponding lines.
13931 */
13932 #define BOX_24   "\342\224\200"  /* U+2500 --- */
13933 #define BOX_13   "\342\224\202"  /* U+2502  |  */
13934 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
13935 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
13936 #define BOX_12   "\342\224\224"  /* U+2514  '- */
13937 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
13938 #define BOX_123  "\342\224\234"  /* U+251c  |- */
13939 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
13940 #define BOX_234  "\342\224\254"  /* U+252c -,- */
13941 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
13942 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
13943 
13944 /* Draw horizontal line N characters long using unicode box
13945 ** characters
13946 */
print_box_line(FILE * out,int N)13947 static void print_box_line(FILE *out, int N){
13948   const char zDash[] =
13949       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
13950       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
13951   const int nDash = sizeof(zDash) - 1;
13952   N *= 3;
13953   while( N>nDash ){
13954     utf8_printf(out, zDash);
13955     N -= nDash;
13956   }
13957   utf8_printf(out, "%.*s", N, zDash);
13958 }
13959 
13960 /*
13961 ** Draw a horizontal separator for a MODE_Box table.
13962 */
print_box_row_separator(ShellState * p,int nArg,const char * zSep1,const char * zSep2,const char * zSep3)13963 static void print_box_row_separator(
13964   ShellState *p,
13965   int nArg,
13966   const char *zSep1,
13967   const char *zSep2,
13968   const char *zSep3
13969 ){
13970   int i;
13971   if( nArg>0 ){
13972     utf8_printf(p->out, "%s", zSep1);
13973     print_box_line(p->out, p->actualWidth[0]+2);
13974     for(i=1; i<nArg; i++){
13975       utf8_printf(p->out, "%s", zSep2);
13976       print_box_line(p->out, p->actualWidth[i]+2);
13977     }
13978     utf8_printf(p->out, "%s", zSep3);
13979   }
13980   fputs("\n", p->out);
13981 }
13982 
13983 
13984 
13985 /*
13986 ** Run a prepared statement and output the result in one of the
13987 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
13988 ** or MODE_Box.
13989 **
13990 ** This is different from ordinary exec_prepared_stmt() in that
13991 ** it has to run the entire query and gather the results into memory
13992 ** first, in order to determine column widths, before providing
13993 ** any output.
13994 */
exec_prepared_stmt_columnar(ShellState * p,sqlite3_stmt * pStmt)13995 static void exec_prepared_stmt_columnar(
13996   ShellState *p,                        /* Pointer to ShellState */
13997   sqlite3_stmt *pStmt                   /* Statment to run */
13998 ){
13999   sqlite3_int64 nRow = 0;
14000   int nColumn = 0;
14001   char **azData = 0;
14002   sqlite3_int64 nAlloc = 0;
14003   const char *z;
14004   int rc;
14005   sqlite3_int64 i, nData;
14006   int j, nTotal, w, n;
14007   const char *colSep = 0;
14008   const char *rowSep = 0;
14009 
14010   rc = sqlite3_step(pStmt);
14011   if( rc!=SQLITE_ROW ) return;
14012   nColumn = sqlite3_column_count(pStmt);
14013   nAlloc = nColumn*4;
14014   if( nAlloc<=0 ) nAlloc = 1;
14015   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
14016   if( azData==0 ) shell_out_of_memory();
14017   for(i=0; i<nColumn; i++){
14018     azData[i] = strdup(sqlite3_column_name(pStmt,i));
14019   }
14020   do{
14021     if( (nRow+2)*nColumn >= nAlloc ){
14022       nAlloc *= 2;
14023       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
14024       if( azData==0 ) shell_out_of_memory();
14025     }
14026     nRow++;
14027     for(i=0; i<nColumn; i++){
14028       z = (const char*)sqlite3_column_text(pStmt,i);
14029       azData[nRow*nColumn + i] = z ? strdup(z) : 0;
14030     }
14031   }while( (rc = sqlite3_step(pStmt))==SQLITE_ROW );
14032   if( nColumn>p->nWidth ){
14033     p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int));
14034     if( p->colWidth==0 ) shell_out_of_memory();
14035     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
14036     p->nWidth = nColumn;
14037     p->actualWidth = &p->colWidth[nColumn];
14038   }
14039   memset(p->actualWidth, 0, nColumn*sizeof(int));
14040   for(i=0; i<nColumn; i++){
14041     w = p->colWidth[i];
14042     if( w<0 ) w = -w;
14043     p->actualWidth[i] = w;
14044   }
14045   nTotal = nColumn*(nRow+1);
14046   for(i=0; i<nTotal; i++){
14047     z = azData[i];
14048     if( z==0 ) z = p->nullValue;
14049     n = strlenChar(z);
14050     j = i%nColumn;
14051     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
14052   }
14053   if( seenInterrupt ) goto columnar_end;
14054   if( nColumn==0 ) goto columnar_end;
14055   switch( p->cMode ){
14056     case MODE_Column: {
14057       colSep = "  ";
14058       rowSep = "\n";
14059       if( p->showHeader ){
14060         for(i=0; i<nColumn; i++){
14061           w = p->actualWidth[i];
14062           if( p->colWidth[i]<0 ) w = -w;
14063           utf8_width_print(p->out, w, azData[i]);
14064           fputs(i==nColumn-1?"\n":"  ", p->out);
14065         }
14066         for(i=0; i<nColumn; i++){
14067           print_dashes(p->out, p->actualWidth[i]);
14068           fputs(i==nColumn-1?"\n":"  ", p->out);
14069         }
14070       }
14071       break;
14072     }
14073     case MODE_Table: {
14074       colSep = " | ";
14075       rowSep = " |\n";
14076       print_row_separator(p, nColumn, "+");
14077       fputs("| ", p->out);
14078       for(i=0; i<nColumn; i++){
14079         w = p->actualWidth[i];
14080         n = strlenChar(azData[i]);
14081         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
14082         fputs(i==nColumn-1?" |\n":" | ", p->out);
14083       }
14084       print_row_separator(p, nColumn, "+");
14085       break;
14086     }
14087     case MODE_Markdown: {
14088       colSep = " | ";
14089       rowSep = " |\n";
14090       fputs("| ", p->out);
14091       for(i=0; i<nColumn; i++){
14092         w = p->actualWidth[i];
14093         n = strlenChar(azData[i]);
14094         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
14095         fputs(i==nColumn-1?" |\n":" | ", p->out);
14096       }
14097       print_row_separator(p, nColumn, "|");
14098       break;
14099     }
14100     case MODE_Box: {
14101       colSep = " " BOX_13 " ";
14102       rowSep = " " BOX_13 "\n";
14103       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
14104       utf8_printf(p->out, BOX_13 " ");
14105       for(i=0; i<nColumn; i++){
14106         w = p->actualWidth[i];
14107         n = strlenChar(azData[i]);
14108         utf8_printf(p->out, "%*s%s%*s%s",
14109             (w-n)/2, "", azData[i], (w-n+1)/2, "",
14110             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
14111       }
14112       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
14113       break;
14114     }
14115   }
14116   for(i=nColumn, j=0; i<nTotal; i++, j++){
14117     if( j==0 && p->cMode!=MODE_Column ){
14118       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
14119     }
14120     z = azData[i];
14121     if( z==0 ) z = p->nullValue;
14122     w = p->actualWidth[j];
14123     if( p->colWidth[j]<0 ) w = -w;
14124     utf8_width_print(p->out, w, z);
14125     if( j==nColumn-1 ){
14126       utf8_printf(p->out, "%s", rowSep);
14127       j = -1;
14128       if( seenInterrupt ) goto columnar_end;
14129     }else{
14130       utf8_printf(p->out, "%s", colSep);
14131     }
14132   }
14133   if( p->cMode==MODE_Table ){
14134     print_row_separator(p, nColumn, "+");
14135   }else if( p->cMode==MODE_Box ){
14136     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
14137   }
14138 columnar_end:
14139   if( seenInterrupt ){
14140     utf8_printf(p->out, "Interrupt\n");
14141   }
14142   nData = (nRow+1)*nColumn;
14143   for(i=0; i<nData; i++) free(azData[i]);
14144   sqlite3_free(azData);
14145 }
14146 
14147 /*
14148 ** Run a prepared statement
14149 */
exec_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)14150 static void exec_prepared_stmt(
14151   ShellState *pArg,                                /* Pointer to ShellState */
14152   sqlite3_stmt *pStmt                              /* Statment to run */
14153 ){
14154   int rc;
14155 
14156   if( pArg->cMode==MODE_Column
14157    || pArg->cMode==MODE_Table
14158    || pArg->cMode==MODE_Box
14159    || pArg->cMode==MODE_Markdown
14160   ){
14161     exec_prepared_stmt_columnar(pArg, pStmt);
14162     return;
14163   }
14164 
14165   /* perform the first step.  this will tell us if we
14166   ** have a result set or not and how wide it is.
14167   */
14168   rc = sqlite3_step(pStmt);
14169   /* if we have a result set... */
14170   if( SQLITE_ROW == rc ){
14171     /* allocate space for col name ptr, value ptr, and type */
14172     int nCol = sqlite3_column_count(pStmt);
14173     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
14174     if( !pData ){
14175       rc = SQLITE_NOMEM;
14176     }else{
14177       char **azCols = (char **)pData;      /* Names of result columns */
14178       char **azVals = &azCols[nCol];       /* Results */
14179       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
14180       int i, x;
14181       assert(sizeof(int) <= sizeof(char *));
14182       /* save off ptrs to column names */
14183       for(i=0; i<nCol; i++){
14184         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
14185       }
14186       do{
14187         /* extract the data and data types */
14188         for(i=0; i<nCol; i++){
14189           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
14190           if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
14191             azVals[i] = "";
14192           }else{
14193             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
14194           }
14195           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
14196             rc = SQLITE_NOMEM;
14197             break; /* from for */
14198           }
14199         } /* end for */
14200 
14201         /* if data and types extracted successfully... */
14202         if( SQLITE_ROW == rc ){
14203           /* call the supplied callback with the result row data */
14204           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
14205             rc = SQLITE_ABORT;
14206           }else{
14207             rc = sqlite3_step(pStmt);
14208           }
14209         }
14210       } while( SQLITE_ROW == rc );
14211       sqlite3_free(pData);
14212       if( pArg->cMode==MODE_Json ){
14213         fputs("]\n", pArg->out);
14214       }
14215     }
14216   }
14217 }
14218 
14219 #ifndef SQLITE_OMIT_VIRTUALTABLE
14220 /*
14221 ** This function is called to process SQL if the previous shell command
14222 ** was ".expert". It passes the SQL in the second argument directly to
14223 ** the sqlite3expert object.
14224 **
14225 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
14226 ** code. In this case, (*pzErr) may be set to point to a buffer containing
14227 ** an English language error message. It is the responsibility of the
14228 ** caller to eventually free this buffer using sqlite3_free().
14229 */
expertHandleSQL(ShellState * pState,const char * zSql,char ** pzErr)14230 static int expertHandleSQL(
14231   ShellState *pState,
14232   const char *zSql,
14233   char **pzErr
14234 ){
14235   assert( pState->expert.pExpert );
14236   assert( pzErr==0 || *pzErr==0 );
14237   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
14238 }
14239 
14240 /*
14241 ** This function is called either to silently clean up the object
14242 ** created by the ".expert" command (if bCancel==1), or to generate a
14243 ** report from it and then clean it up (if bCancel==0).
14244 **
14245 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
14246 ** code. In this case, (*pzErr) may be set to point to a buffer containing
14247 ** an English language error message. It is the responsibility of the
14248 ** caller to eventually free this buffer using sqlite3_free().
14249 */
expertFinish(ShellState * pState,int bCancel,char ** pzErr)14250 static int expertFinish(
14251   ShellState *pState,
14252   int bCancel,
14253   char **pzErr
14254 ){
14255   int rc = SQLITE_OK;
14256   sqlite3expert *p = pState->expert.pExpert;
14257   assert( p );
14258   assert( bCancel || pzErr==0 || *pzErr==0 );
14259   if( bCancel==0 ){
14260     FILE *out = pState->out;
14261     int bVerbose = pState->expert.bVerbose;
14262 
14263     rc = sqlite3_expert_analyze(p, pzErr);
14264     if( rc==SQLITE_OK ){
14265       int nQuery = sqlite3_expert_count(p);
14266       int i;
14267 
14268       if( bVerbose ){
14269         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
14270         raw_printf(out, "-- Candidates -----------------------------\n");
14271         raw_printf(out, "%s\n", zCand);
14272       }
14273       for(i=0; i<nQuery; i++){
14274         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
14275         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
14276         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
14277         if( zIdx==0 ) zIdx = "(no new indexes)\n";
14278         if( bVerbose ){
14279           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
14280           raw_printf(out, "%s\n\n", zSql);
14281         }
14282         raw_printf(out, "%s\n", zIdx);
14283         raw_printf(out, "%s\n", zEQP);
14284       }
14285     }
14286   }
14287   sqlite3_expert_destroy(p);
14288   pState->expert.pExpert = 0;
14289   return rc;
14290 }
14291 
14292 /*
14293 ** Implementation of ".expert" dot command.
14294 */
expertDotCommand(ShellState * pState,char ** azArg,int nArg)14295 static int expertDotCommand(
14296   ShellState *pState,             /* Current shell tool state */
14297   char **azArg,                   /* Array of arguments passed to dot command */
14298   int nArg                        /* Number of entries in azArg[] */
14299 ){
14300   int rc = SQLITE_OK;
14301   char *zErr = 0;
14302   int i;
14303   int iSample = 0;
14304 
14305   assert( pState->expert.pExpert==0 );
14306   memset(&pState->expert, 0, sizeof(ExpertInfo));
14307 
14308   for(i=1; rc==SQLITE_OK && i<nArg; i++){
14309     char *z = azArg[i];
14310     int n;
14311     if( z[0]=='-' && z[1]=='-' ) z++;
14312     n = strlen30(z);
14313     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
14314       pState->expert.bVerbose = 1;
14315     }
14316     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
14317       if( i==(nArg-1) ){
14318         raw_printf(stderr, "option requires an argument: %s\n", z);
14319         rc = SQLITE_ERROR;
14320       }else{
14321         iSample = (int)integerValue(azArg[++i]);
14322         if( iSample<0 || iSample>100 ){
14323           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
14324           rc = SQLITE_ERROR;
14325         }
14326       }
14327     }
14328     else{
14329       raw_printf(stderr, "unknown option: %s\n", z);
14330       rc = SQLITE_ERROR;
14331     }
14332   }
14333 
14334   if( rc==SQLITE_OK ){
14335     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
14336     if( pState->expert.pExpert==0 ){
14337       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
14338       rc = SQLITE_ERROR;
14339     }else{
14340       sqlite3_expert_config(
14341           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
14342       );
14343     }
14344   }
14345 
14346   return rc;
14347 }
14348 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
14349 
14350 /*
14351 ** Execute a statement or set of statements.  Print
14352 ** any result rows/columns depending on the current mode
14353 ** set via the supplied callback.
14354 **
14355 ** This is very similar to SQLite's built-in sqlite3_exec()
14356 ** function except it takes a slightly different callback
14357 ** and callback data argument.
14358 */
shell_exec(ShellState * pArg,const char * zSql,char ** pzErrMsg)14359 static int shell_exec(
14360   ShellState *pArg,                         /* Pointer to ShellState */
14361   const char *zSql,                         /* SQL to be evaluated */
14362   char **pzErrMsg                           /* Error msg written here */
14363 ){
14364   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
14365   int rc = SQLITE_OK;             /* Return Code */
14366   int rc2;
14367   const char *zLeftover;          /* Tail of unprocessed SQL */
14368   sqlite3 *db = pArg->db;
14369 
14370   if( pzErrMsg ){
14371     *pzErrMsg = NULL;
14372   }
14373 
14374 #ifndef SQLITE_OMIT_VIRTUALTABLE
14375   if( pArg->expert.pExpert ){
14376     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
14377     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
14378   }
14379 #endif
14380 
14381   while( zSql[0] && (SQLITE_OK == rc) ){
14382     static const char *zStmtSql;
14383     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
14384     if( SQLITE_OK != rc ){
14385       if( pzErrMsg ){
14386         *pzErrMsg = save_err_msg(db);
14387       }
14388     }else{
14389       if( !pStmt ){
14390         /* this happens for a comment or white-space */
14391         zSql = zLeftover;
14392         while( IsSpace(zSql[0]) ) zSql++;
14393         continue;
14394       }
14395       zStmtSql = sqlite3_sql(pStmt);
14396       if( zStmtSql==0 ) zStmtSql = "";
14397       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
14398 
14399       /* save off the prepared statment handle and reset row count */
14400       if( pArg ){
14401         pArg->pStmt = pStmt;
14402         pArg->cnt = 0;
14403       }
14404 
14405       /* echo the sql statement if echo on */
14406       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
14407         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
14408       }
14409 
14410       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
14411       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
14412         sqlite3_stmt *pExplain;
14413         char *zEQP;
14414         int triggerEQP = 0;
14415         disable_debug_trace_modes();
14416         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
14417         if( pArg->autoEQP>=AUTOEQP_trigger ){
14418           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
14419         }
14420         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
14421         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
14422         if( rc==SQLITE_OK ){
14423           while( sqlite3_step(pExplain)==SQLITE_ROW ){
14424             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
14425             int iEqpId = sqlite3_column_int(pExplain, 0);
14426             int iParentId = sqlite3_column_int(pExplain, 1);
14427             if( zEQPLine==0 ) zEQPLine = "";
14428             if( zEQPLine[0]=='-' ) eqp_render(pArg);
14429             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
14430           }
14431           eqp_render(pArg);
14432         }
14433         sqlite3_finalize(pExplain);
14434         sqlite3_free(zEQP);
14435         if( pArg->autoEQP>=AUTOEQP_full ){
14436           /* Also do an EXPLAIN for ".eqp full" mode */
14437           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
14438           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
14439           if( rc==SQLITE_OK ){
14440             pArg->cMode = MODE_Explain;
14441             explain_data_prepare(pArg, pExplain);
14442             exec_prepared_stmt(pArg, pExplain);
14443             explain_data_delete(pArg);
14444           }
14445           sqlite3_finalize(pExplain);
14446           sqlite3_free(zEQP);
14447         }
14448         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
14449           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
14450           /* Reprepare pStmt before reactiving trace modes */
14451           sqlite3_finalize(pStmt);
14452           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
14453           if( pArg ) pArg->pStmt = pStmt;
14454         }
14455         restore_debug_trace_modes();
14456       }
14457 
14458       if( pArg ){
14459         pArg->cMode = pArg->mode;
14460         if( pArg->autoExplain ){
14461           if( sqlite3_stmt_isexplain(pStmt)==1 ){
14462             pArg->cMode = MODE_Explain;
14463           }
14464           if( sqlite3_stmt_isexplain(pStmt)==2 ){
14465             pArg->cMode = MODE_EQP;
14466           }
14467         }
14468 
14469         /* If the shell is currently in ".explain" mode, gather the extra
14470         ** data required to add indents to the output.*/
14471         if( pArg->cMode==MODE_Explain ){
14472           explain_data_prepare(pArg, pStmt);
14473         }
14474       }
14475 
14476       bind_prepared_stmt(pArg, pStmt);
14477       exec_prepared_stmt(pArg, pStmt);
14478       explain_data_delete(pArg);
14479       eqp_render(pArg);
14480 
14481       /* print usage stats if stats on */
14482       if( pArg && pArg->statsOn ){
14483         display_stats(db, pArg, 0);
14484       }
14485 
14486       /* print loop-counters if required */
14487       if( pArg && pArg->scanstatsOn ){
14488         display_scanstats(db, pArg);
14489       }
14490 
14491       /* Finalize the statement just executed. If this fails, save a
14492       ** copy of the error message. Otherwise, set zSql to point to the
14493       ** next statement to execute. */
14494       rc2 = sqlite3_finalize(pStmt);
14495       if( rc!=SQLITE_NOMEM ) rc = rc2;
14496       if( rc==SQLITE_OK ){
14497         zSql = zLeftover;
14498         while( IsSpace(zSql[0]) ) zSql++;
14499       }else if( pzErrMsg ){
14500         *pzErrMsg = save_err_msg(db);
14501       }
14502 
14503       /* clear saved stmt handle */
14504       if( pArg ){
14505         pArg->pStmt = NULL;
14506       }
14507     }
14508   } /* end while */
14509 
14510   return rc;
14511 }
14512 
14513 /*
14514 ** Release memory previously allocated by tableColumnList().
14515 */
freeColumnList(char ** azCol)14516 static void freeColumnList(char **azCol){
14517   int i;
14518   for(i=1; azCol[i]; i++){
14519     sqlite3_free(azCol[i]);
14520   }
14521   /* azCol[0] is a static string */
14522   sqlite3_free(azCol);
14523 }
14524 
14525 /*
14526 ** Return a list of pointers to strings which are the names of all
14527 ** columns in table zTab.   The memory to hold the names is dynamically
14528 ** allocated and must be released by the caller using a subsequent call
14529 ** to freeColumnList().
14530 **
14531 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
14532 ** value that needs to be preserved, then azCol[0] is filled in with the
14533 ** name of the rowid column.
14534 **
14535 ** The first regular column in the table is azCol[1].  The list is terminated
14536 ** by an entry with azCol[i]==0.
14537 */
tableColumnList(ShellState * p,const char * zTab)14538 static char **tableColumnList(ShellState *p, const char *zTab){
14539   char **azCol = 0;
14540   sqlite3_stmt *pStmt;
14541   char *zSql;
14542   int nCol = 0;
14543   int nAlloc = 0;
14544   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
14545   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
14546   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
14547   int rc;
14548 
14549   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
14550   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
14551   sqlite3_free(zSql);
14552   if( rc ) return 0;
14553   while( sqlite3_step(pStmt)==SQLITE_ROW ){
14554     if( nCol>=nAlloc-2 ){
14555       nAlloc = nAlloc*2 + nCol + 10;
14556       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
14557       if( azCol==0 ) shell_out_of_memory();
14558     }
14559     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
14560     if( sqlite3_column_int(pStmt, 5) ){
14561       nPK++;
14562       if( nPK==1
14563        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
14564                           "INTEGER")==0
14565       ){
14566         isIPK = 1;
14567       }else{
14568         isIPK = 0;
14569       }
14570     }
14571   }
14572   sqlite3_finalize(pStmt);
14573   if( azCol==0 ) return 0;
14574   azCol[0] = 0;
14575   azCol[nCol+1] = 0;
14576 
14577   /* The decision of whether or not a rowid really needs to be preserved
14578   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
14579   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
14580   ** rowids on tables where the rowid is inaccessible because there are other
14581   ** columns in the table named "rowid", "_rowid_", and "oid".
14582   */
14583   if( preserveRowid && isIPK ){
14584     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
14585     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
14586     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
14587     ** ROWID aliases.  To distinguish these cases, check to see if
14588     ** there is a "pk" entry in "PRAGMA index_list".  There will be
14589     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
14590     */
14591     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
14592                            " WHERE origin='pk'", zTab);
14593     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
14594     sqlite3_free(zSql);
14595     if( rc ){
14596       freeColumnList(azCol);
14597       return 0;
14598     }
14599     rc = sqlite3_step(pStmt);
14600     sqlite3_finalize(pStmt);
14601     preserveRowid = rc==SQLITE_ROW;
14602   }
14603   if( preserveRowid ){
14604     /* Only preserve the rowid if we can find a name to use for the
14605     ** rowid */
14606     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
14607     int i, j;
14608     for(j=0; j<3; j++){
14609       for(i=1; i<=nCol; i++){
14610         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
14611       }
14612       if( i>nCol ){
14613         /* At this point, we know that azRowid[j] is not the name of any
14614         ** ordinary column in the table.  Verify that azRowid[j] is a valid
14615         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
14616         ** tables will fail this last check */
14617         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
14618         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
14619         break;
14620       }
14621     }
14622   }
14623   return azCol;
14624 }
14625 
14626 /*
14627 ** Toggle the reverse_unordered_selects setting.
14628 */
toggleSelectOrder(sqlite3 * db)14629 static void toggleSelectOrder(sqlite3 *db){
14630   sqlite3_stmt *pStmt = 0;
14631   int iSetting = 0;
14632   char zStmt[100];
14633   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
14634   if( sqlite3_step(pStmt)==SQLITE_ROW ){
14635     iSetting = sqlite3_column_int(pStmt, 0);
14636   }
14637   sqlite3_finalize(pStmt);
14638   sqlite3_snprintf(sizeof(zStmt), zStmt,
14639        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
14640   sqlite3_exec(db, zStmt, 0, 0, 0);
14641 }
14642 
14643 /*
14644 ** This is a different callback routine used for dumping the database.
14645 ** Each row received by this callback consists of a table name,
14646 ** the table type ("index" or "table") and SQL to create the table.
14647 ** This routine should print text sufficient to recreate the table.
14648 */
dump_callback(void * pArg,int nArg,char ** azArg,char ** azNotUsed)14649 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
14650   int rc;
14651   const char *zTable;
14652   const char *zType;
14653   const char *zSql;
14654   ShellState *p = (ShellState *)pArg;
14655   int dataOnly;
14656   int noSys;
14657 
14658   UNUSED_PARAMETER(azNotUsed);
14659   if( nArg!=3 || azArg==0 ) return 0;
14660   zTable = azArg[0];
14661   zType = azArg[1];
14662   zSql = azArg[2];
14663   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
14664   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
14665 
14666   if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
14667     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
14668   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
14669     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
14670   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
14671     return 0;
14672   }else if( dataOnly ){
14673     /* no-op */
14674   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
14675     char *zIns;
14676     if( !p->writableSchema ){
14677       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
14678       p->writableSchema = 1;
14679     }
14680     zIns = sqlite3_mprintf(
14681        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
14682        "VALUES('table','%q','%q',0,'%q');",
14683        zTable, zTable, zSql);
14684     utf8_printf(p->out, "%s\n", zIns);
14685     sqlite3_free(zIns);
14686     return 0;
14687   }else{
14688     printSchemaLine(p->out, zSql, ";\n");
14689   }
14690 
14691   if( strcmp(zType, "table")==0 ){
14692     ShellText sSelect;
14693     ShellText sTable;
14694     char **azCol;
14695     int i;
14696     char *savedDestTable;
14697     int savedMode;
14698 
14699     azCol = tableColumnList(p, zTable);
14700     if( azCol==0 ){
14701       p->nErr++;
14702       return 0;
14703     }
14704 
14705     /* Always quote the table name, even if it appears to be pure ascii,
14706     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
14707     initText(&sTable);
14708     appendText(&sTable, zTable, quoteChar(zTable));
14709     /* If preserving the rowid, add a column list after the table name.
14710     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
14711     ** instead of the usual "INSERT INTO tab VALUES(...)".
14712     */
14713     if( azCol[0] ){
14714       appendText(&sTable, "(", 0);
14715       appendText(&sTable, azCol[0], 0);
14716       for(i=1; azCol[i]; i++){
14717         appendText(&sTable, ",", 0);
14718         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
14719       }
14720       appendText(&sTable, ")", 0);
14721     }
14722 
14723     /* Build an appropriate SELECT statement */
14724     initText(&sSelect);
14725     appendText(&sSelect, "SELECT ", 0);
14726     if( azCol[0] ){
14727       appendText(&sSelect, azCol[0], 0);
14728       appendText(&sSelect, ",", 0);
14729     }
14730     for(i=1; azCol[i]; i++){
14731       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
14732       if( azCol[i+1] ){
14733         appendText(&sSelect, ",", 0);
14734       }
14735     }
14736     freeColumnList(azCol);
14737     appendText(&sSelect, " FROM ", 0);
14738     appendText(&sSelect, zTable, quoteChar(zTable));
14739 
14740     savedDestTable = p->zDestTable;
14741     savedMode = p->mode;
14742     p->zDestTable = sTable.z;
14743     p->mode = p->cMode = MODE_Insert;
14744     rc = shell_exec(p, sSelect.z, 0);
14745     if( (rc&0xff)==SQLITE_CORRUPT ){
14746       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
14747       toggleSelectOrder(p->db);
14748       shell_exec(p, sSelect.z, 0);
14749       toggleSelectOrder(p->db);
14750     }
14751     p->zDestTable = savedDestTable;
14752     p->mode = savedMode;
14753     freeText(&sTable);
14754     freeText(&sSelect);
14755     if( rc ) p->nErr++;
14756   }
14757   return 0;
14758 }
14759 
14760 /*
14761 ** Run zQuery.  Use dump_callback() as the callback routine so that
14762 ** the contents of the query are output as SQL statements.
14763 **
14764 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
14765 ** "ORDER BY rowid DESC" to the end.
14766 */
run_schema_dump_query(ShellState * p,const char * zQuery)14767 static int run_schema_dump_query(
14768   ShellState *p,
14769   const char *zQuery
14770 ){
14771   int rc;
14772   char *zErr = 0;
14773   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
14774   if( rc==SQLITE_CORRUPT ){
14775     char *zQ2;
14776     int len = strlen30(zQuery);
14777     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
14778     if( zErr ){
14779       utf8_printf(p->out, "/****** %s ******/\n", zErr);
14780       sqlite3_free(zErr);
14781       zErr = 0;
14782     }
14783     zQ2 = malloc( len+100 );
14784     if( zQ2==0 ) return rc;
14785     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
14786     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
14787     if( rc ){
14788       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
14789     }else{
14790       rc = SQLITE_CORRUPT;
14791     }
14792     sqlite3_free(zErr);
14793     free(zQ2);
14794   }
14795   return rc;
14796 }
14797 
14798 /*
14799 ** Text of help messages.
14800 **
14801 ** The help text for each individual command begins with a line that starts
14802 ** with ".".  Subsequent lines are supplimental information.
14803 **
14804 ** There must be two or more spaces between the end of the command and the
14805 ** start of the description of what that command does.
14806 */
14807 static const char *(azHelp[]) = {
14808 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
14809   ".archive ...             Manage SQL archives",
14810   "   Each command must have exactly one of the following options:",
14811   "     -c, --create               Create a new archive",
14812   "     -u, --update               Add or update files with changed mtime",
14813   "     -i, --insert               Like -u but always add even if unchanged",
14814   "     -t, --list                 List contents of archive",
14815   "     -x, --extract              Extract files from archive",
14816   "   Optional arguments:",
14817   "     -v, --verbose              Print each filename as it is processed",
14818   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
14819   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
14820   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
14821   "     -n, --dryrun               Show the SQL that would have occurred",
14822   "   Examples:",
14823   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
14824   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
14825   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
14826   "   See also:",
14827   "      http://sqlite.org/cli.html#sqlite_archive_support",
14828 #endif
14829 #ifndef SQLITE_OMIT_AUTHORIZATION
14830   ".auth ON|OFF             Show authorizer callbacks",
14831 #endif
14832   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
14833   "       --append            Use the appendvfs",
14834   "       --async             Write to FILE without journal and fsync()",
14835   ".bail on|off             Stop after hitting an error.  Default OFF",
14836   ".binary on|off           Turn binary output on or off.  Default OFF",
14837   ".cd DIRECTORY            Change the working directory to DIRECTORY",
14838   ".changes on|off          Show number of rows changed by SQL",
14839   ".check GLOB              Fail if output since .testcase does not match",
14840   ".clone NEWDB             Clone data into NEWDB from the existing database",
14841   ".databases               List names and files of attached databases",
14842   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
14843   ".dbinfo ?DB?             Show status information about the database",
14844   ".dump ?OBJECTS?          Render database content as SQL",
14845   "   Options:",
14846   "     --data-only            Output only INSERT statements",
14847   "     --newlines             Allow unescaped newline characters in output",
14848   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
14849   "     --preserve-rowids      Include ROWID values in the output",
14850   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
14851   "   Additional LIKE patterns can be given in subsequent arguments",
14852   ".echo on|off             Turn command echo on or off",
14853   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
14854   "   Other Modes:",
14855 #ifdef SQLITE_DEBUG
14856   "      test                  Show raw EXPLAIN QUERY PLAN output",
14857   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
14858 #endif
14859   "      trigger               Like \"full\" but also show trigger bytecode",
14860   ".excel                   Display the output of next command in spreadsheet",
14861   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
14862   ".exit ?CODE?             Exit this program with return-code CODE",
14863   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
14864   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
14865   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
14866   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
14867   "   --help                  Show CMD details",
14868   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
14869   ".headers on|off          Turn display of headers on or off",
14870   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
14871   ".import FILE TABLE       Import data from FILE into TABLE",
14872   "   Options:",
14873   "     --ascii               Use \\037 and \\036 as column and row separators",
14874   "     --csv                 Use , and \\n as column and row separators",
14875   "     --skip N              Skip the first N rows of input",
14876   "     -v                    \"Verbose\" - increase auxiliary output",
14877   "   Notes:",
14878   "     *  If TABLE does not exist, it is created.  The first row of input",
14879   "        determines the column names.",
14880   "     *  If neither --csv or --ascii are used, the input mode is derived",
14881   "        from the \".mode\" output mode",
14882   "     *  If FILE begins with \"|\" then it is a command that generates the",
14883   "        input text.",
14884 #ifndef SQLITE_OMIT_TEST_CONTROL
14885   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
14886 #endif
14887   ".indexes ?TABLE?         Show names of indexes",
14888   "                           If TABLE is specified, only show indexes for",
14889   "                           tables matching TABLE using the LIKE operator.",
14890 #ifdef SQLITE_ENABLE_IOTRACE
14891   ".iotrace FILE            Enable I/O diagnostic logging to FILE",
14892 #endif
14893   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
14894   ".lint OPTIONS            Report potential schema issues.",
14895   "     Options:",
14896   "        fkey-indexes     Find missing foreign key indexes",
14897 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14898   ".load FILE ?ENTRY?       Load an extension library",
14899 #endif
14900   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
14901   ".mode MODE ?TABLE?       Set output mode",
14902   "   MODE is one of:",
14903   "     ascii     Columns/rows delimited by 0x1F and 0x1E",
14904   "     box       Tables using unicode box-drawing characters",
14905   "     csv       Comma-separated values",
14906   "     column    Output in columns.  (See .width)",
14907   "     html      HTML <table> code",
14908   "     insert    SQL insert statements for TABLE",
14909   "     json      Results in a JSON array",
14910   "     line      One value per line",
14911   "     list      Values delimited by \"|\"",
14912   "     markdown  Markdown table format",
14913   "     quote     Escape answers as for SQL",
14914   "     table     ASCII-art table",
14915   "     tabs      Tab-separated values",
14916   "     tcl       TCL list elements",
14917   ".nullvalue STRING        Use STRING in place of NULL values",
14918   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
14919   "     If FILE begins with '|' then open as a pipe",
14920   "       --bom  Put a UTF8 byte-order mark at the beginning",
14921   "       -e     Send output to the system text editor",
14922   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
14923 #ifdef SQLITE_DEBUG
14924   ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
14925 #endif
14926   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
14927   "     Options:",
14928   "        --append        Use appendvfs to append database to the end of FILE",
14929 #ifndef SQLITE_OMIT_DESERIALIZE
14930   "        --deserialize   Load into memory using sqlite3_deserialize()",
14931   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
14932   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
14933 #endif
14934   "        --new           Initialize FILE to an empty database",
14935   "        --nofollow      Do not follow symbolic links",
14936   "        --readonly      Open FILE readonly",
14937   "        --zip           FILE is a ZIP archive",
14938   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
14939   "   If FILE begins with '|' then open it as a pipe.",
14940   "   Options:",
14941   "     --bom                 Prefix output with a UTF8 byte-order mark",
14942   "     -e                    Send output to the system text editor",
14943   "     -x                    Send output as CSV to a spreadsheet",
14944   ".parameter CMD ...       Manage SQL parameter bindings",
14945   "   clear                   Erase all bindings",
14946   "   init                    Initialize the TEMP table that holds bindings",
14947   "   list                    List the current parameter bindings",
14948   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
14949   "                           PARAMETER should start with one of: $ : @ ?",
14950   "   unset PARAMETER         Remove PARAMETER from the binding table",
14951   ".print STRING...         Print literal STRING",
14952 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
14953   ".progress N              Invoke progress handler after every N opcodes",
14954   "   --limit N                 Interrupt after N progress callbacks",
14955   "   --once                    Do no more than one progress interrupt",
14956   "   --quiet|-q                No output except at interrupts",
14957   "   --reset                   Reset the count for each input and interrupt",
14958 #endif
14959   ".prompt MAIN CONTINUE    Replace the standard prompts",
14960   ".quit                    Exit this program",
14961   ".read FILE               Read input from FILE",
14962 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
14963   ".recover                 Recover as much data as possible from corrupt db.",
14964   "   --freelist-corrupt       Assume the freelist is corrupt",
14965   "   --recovery-db NAME       Store recovery metadata in database file NAME",
14966   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
14967   "   --no-rowids              Do not attempt to recover rowid values",
14968   "                            that are not also INTEGER PRIMARY KEYs",
14969 #endif
14970   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
14971   ".save FILE               Write in-memory database into FILE",
14972   ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
14973   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
14974   "   Options:",
14975   "      --indent             Try to pretty-print the schema",
14976   "      --nosys              Omit objects whose names start with \"sqlite_\"",
14977   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
14978   "    Options:",
14979   "       --init               Create a new SELFTEST table",
14980   "       -v                   Verbose output",
14981   ".separator COL ?ROW?     Change the column and row separators",
14982 #if defined(SQLITE_ENABLE_SESSION)
14983   ".session ?NAME? CMD ...  Create or control sessions",
14984   "   Subcommands:",
14985   "     attach TABLE             Attach TABLE",
14986   "     changeset FILE           Write a changeset into FILE",
14987   "     close                    Close one session",
14988   "     enable ?BOOLEAN?         Set or query the enable bit",
14989   "     filter GLOB...           Reject tables matching GLOBs",
14990   "     indirect ?BOOLEAN?       Mark or query the indirect status",
14991   "     isempty                  Query whether the session is empty",
14992   "     list                     List currently open session names",
14993   "     open DB NAME             Open a new session on DB",
14994   "     patchset FILE            Write a patchset into FILE",
14995   "   If ?NAME? is omitted, the first defined session is used.",
14996 #endif
14997   ".sha3sum ...             Compute a SHA3 hash of database content",
14998   "    Options:",
14999   "      --schema              Also hash the sqlite_schema table",
15000   "      --sha3-224            Use the sha3-224 algorithm",
15001   "      --sha3-256            Use the sha3-256 algorithm (default)",
15002   "      --sha3-384            Use the sha3-384 algorithm",
15003   "      --sha3-512            Use the sha3-512 algorithm",
15004   "    Any other argument is a LIKE pattern for tables to hash",
15005 #ifndef SQLITE_NOHAVE_SYSTEM
15006   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
15007 #endif
15008   ".show                    Show the current values for various settings",
15009   ".stats ?ARG?             Show stats or turn stats on or off",
15010   "   off                      Turn off automatic stat display",
15011   "   on                       Turn on automatic stat display",
15012   "   stmt                     Show statement stats",
15013   "   vmstep                   Show the virtual machine step count only",
15014 #ifndef SQLITE_NOHAVE_SYSTEM
15015   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
15016 #endif
15017   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
15018   ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
15019   ".testctrl CMD ...        Run various sqlite3_test_control() operations",
15020   "                           Run \".testctrl\" with no arguments for details",
15021   ".timeout MS              Try opening locked tables for MS milliseconds",
15022   ".timer on|off            Turn SQL timer on or off",
15023 #ifndef SQLITE_OMIT_TRACE
15024   ".trace ?OPTIONS?         Output each SQL statement as it is run",
15025   "    FILE                    Send output to FILE",
15026   "    stdout                  Send output to stdout",
15027   "    stderr                  Send output to stderr",
15028   "    off                     Disable tracing",
15029   "    --expanded              Expand query parameters",
15030 #ifdef SQLITE_ENABLE_NORMALIZE
15031   "    --normalized            Normal the SQL statements",
15032 #endif
15033   "    --plain                 Show SQL as it is input",
15034   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
15035   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
15036   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
15037   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
15038 #endif /* SQLITE_OMIT_TRACE */
15039 #ifdef SQLITE_DEBUG
15040   ".unmodule NAME ...       Unregister virtual table modules",
15041   "    --allexcept             Unregister everything except those named",
15042 #endif
15043   ".vfsinfo ?AUX?           Information about the top-level VFS",
15044   ".vfslist                 List all available VFSes",
15045   ".vfsname ?AUX?           Print the name of the VFS stack",
15046   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
15047   "     Negative values right-justify",
15048 };
15049 
15050 /*
15051 ** Output help text.
15052 **
15053 ** zPattern describes the set of commands for which help text is provided.
15054 ** If zPattern is NULL, then show all commands, but only give a one-line
15055 ** description of each.
15056 **
15057 ** Return the number of matches.
15058 */
showHelp(FILE * out,const char * zPattern)15059 static int showHelp(FILE *out, const char *zPattern){
15060   int i = 0;
15061   int j = 0;
15062   int n = 0;
15063   char *zPat;
15064   if( zPattern==0
15065    || zPattern[0]=='0'
15066    || strcmp(zPattern,"-a")==0
15067    || strcmp(zPattern,"-all")==0
15068    || strcmp(zPattern,"--all")==0
15069   ){
15070     /* Show all commands, but only one line per command */
15071     if( zPattern==0 ) zPattern = "";
15072     for(i=0; i<ArraySize(azHelp); i++){
15073       if( azHelp[i][0]=='.' || zPattern[0] ){
15074         utf8_printf(out, "%s\n", azHelp[i]);
15075         n++;
15076       }
15077     }
15078   }else{
15079     /* Look for commands that for which zPattern is an exact prefix */
15080     zPat = sqlite3_mprintf(".%s*", zPattern);
15081     for(i=0; i<ArraySize(azHelp); i++){
15082       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
15083         utf8_printf(out, "%s\n", azHelp[i]);
15084         j = i+1;
15085         n++;
15086       }
15087     }
15088     sqlite3_free(zPat);
15089     if( n ){
15090       if( n==1 ){
15091         /* when zPattern is a prefix of exactly one command, then include the
15092         ** details of that command, which should begin at offset j */
15093         while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
15094           utf8_printf(out, "%s\n", azHelp[j]);
15095           j++;
15096         }
15097       }
15098       return n;
15099     }
15100     /* Look for commands that contain zPattern anywhere.  Show the complete
15101     ** text of all commands that match. */
15102     zPat = sqlite3_mprintf("%%%s%%", zPattern);
15103     for(i=0; i<ArraySize(azHelp); i++){
15104       if( azHelp[i][0]=='.' ) j = i;
15105       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
15106         utf8_printf(out, "%s\n", azHelp[j]);
15107         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
15108           j++;
15109           utf8_printf(out, "%s\n", azHelp[j]);
15110         }
15111         i = j;
15112         n++;
15113       }
15114     }
15115     sqlite3_free(zPat);
15116   }
15117   return n;
15118 }
15119 
15120 /* Forward reference */
15121 static int process_input(ShellState *p);
15122 
15123 /*
15124 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
15125 ** and return a pointer to the buffer. The caller is responsible for freeing
15126 ** the memory.
15127 **
15128 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
15129 ** read.
15130 **
15131 ** For convenience, a nul-terminator byte is always appended to the data read
15132 ** from the file before the buffer is returned. This byte is not included in
15133 ** the final value of (*pnByte), if applicable.
15134 **
15135 ** NULL is returned if any error is encountered. The final value of *pnByte
15136 ** is undefined in this case.
15137 */
readFile(const char * zName,int * pnByte)15138 static char *readFile(const char *zName, int *pnByte){
15139   FILE *in = fopen(zName, "rb");
15140   long nIn;
15141   size_t nRead;
15142   char *pBuf;
15143   if( in==0 ) return 0;
15144   fseek(in, 0, SEEK_END);
15145   nIn = ftell(in);
15146   rewind(in);
15147   pBuf = sqlite3_malloc64( nIn+1 );
15148   if( pBuf==0 ){ fclose(in); return 0; }
15149   nRead = fread(pBuf, nIn, 1, in);
15150   fclose(in);
15151   if( nRead!=1 ){
15152     sqlite3_free(pBuf);
15153     return 0;
15154   }
15155   pBuf[nIn] = 0;
15156   if( pnByte ) *pnByte = nIn;
15157   return pBuf;
15158 }
15159 
15160 #if defined(SQLITE_ENABLE_SESSION)
15161 /*
15162 ** Close a single OpenSession object and release all of its associated
15163 ** resources.
15164 */
session_close(OpenSession * pSession)15165 static void session_close(OpenSession *pSession){
15166   int i;
15167   sqlite3session_delete(pSession->p);
15168   sqlite3_free(pSession->zName);
15169   for(i=0; i<pSession->nFilter; i++){
15170     sqlite3_free(pSession->azFilter[i]);
15171   }
15172   sqlite3_free(pSession->azFilter);
15173   memset(pSession, 0, sizeof(OpenSession));
15174 }
15175 #endif
15176 
15177 /*
15178 ** Close all OpenSession objects and release all associated resources.
15179 */
15180 #if defined(SQLITE_ENABLE_SESSION)
session_close_all(ShellState * p)15181 static void session_close_all(ShellState *p){
15182   int i;
15183   for(i=0; i<p->nSession; i++){
15184     session_close(&p->aSession[i]);
15185   }
15186   p->nSession = 0;
15187 }
15188 #else
15189 # define session_close_all(X)
15190 #endif
15191 
15192 /*
15193 ** Implementation of the xFilter function for an open session.  Omit
15194 ** any tables named by ".session filter" but let all other table through.
15195 */
15196 #if defined(SQLITE_ENABLE_SESSION)
session_filter(void * pCtx,const char * zTab)15197 static int session_filter(void *pCtx, const char *zTab){
15198   OpenSession *pSession = (OpenSession*)pCtx;
15199   int i;
15200   for(i=0; i<pSession->nFilter; i++){
15201     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
15202   }
15203   return 1;
15204 }
15205 #endif
15206 
15207 /*
15208 ** Try to deduce the type of file for zName based on its content.  Return
15209 ** one of the SHELL_OPEN_* constants.
15210 **
15211 ** If the file does not exist or is empty but its name looks like a ZIP
15212 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
15213 ** Otherwise, assume an ordinary database regardless of the filename if
15214 ** the type cannot be determined from content.
15215 */
deduceDatabaseType(const char * zName,int dfltZip)15216 int deduceDatabaseType(const char *zName, int dfltZip){
15217   FILE *f = fopen(zName, "rb");
15218   size_t n;
15219   int rc = SHELL_OPEN_UNSPEC;
15220   char zBuf[100];
15221   if( f==0 ){
15222     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
15223        return SHELL_OPEN_ZIPFILE;
15224     }else{
15225        return SHELL_OPEN_NORMAL;
15226     }
15227   }
15228   n = fread(zBuf, 16, 1, f);
15229   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
15230     fclose(f);
15231     return SHELL_OPEN_NORMAL;
15232   }
15233   fseek(f, -25, SEEK_END);
15234   n = fread(zBuf, 25, 1, f);
15235   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
15236     rc = SHELL_OPEN_APPENDVFS;
15237   }else{
15238     fseek(f, -22, SEEK_END);
15239     n = fread(zBuf, 22, 1, f);
15240     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
15241        && zBuf[3]==0x06 ){
15242       rc = SHELL_OPEN_ZIPFILE;
15243     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
15244       rc = SHELL_OPEN_ZIPFILE;
15245     }
15246   }
15247   fclose(f);
15248   return rc;
15249 }
15250 
15251 #ifndef SQLITE_OMIT_DESERIALIZE
15252 /*
15253 ** Reconstruct an in-memory database using the output from the "dbtotxt"
15254 ** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename
15255 ** is 0, then read from standard input.
15256 */
readHexDb(ShellState * p,int * pnData)15257 static unsigned char *readHexDb(ShellState *p, int *pnData){
15258   unsigned char *a = 0;
15259   int nLine;
15260   int n = 0;
15261   int pgsz = 0;
15262   int iOffset = 0;
15263   int j, k;
15264   int rc;
15265   FILE *in;
15266   unsigned int x[16];
15267   char zLine[1000];
15268   if( p->zDbFilename ){
15269     in = fopen(p->zDbFilename, "r");
15270     if( in==0 ){
15271       utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
15272       return 0;
15273     }
15274     nLine = 0;
15275   }else{
15276     in = p->in;
15277     nLine = p->lineno;
15278     if( in==0 ) in = stdin;
15279   }
15280   *pnData = 0;
15281   nLine++;
15282   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
15283   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
15284   if( rc!=2 ) goto readHexDb_error;
15285   if( n<0 ) goto readHexDb_error;
15286   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
15287   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
15288   a = sqlite3_malloc( n ? n : 1 );
15289   if( a==0 ){
15290     utf8_printf(stderr, "Out of memory!\n");
15291     goto readHexDb_error;
15292   }
15293   memset(a, 0, n);
15294   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
15295     utf8_printf(stderr, "invalid pagesize\n");
15296     goto readHexDb_error;
15297   }
15298   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
15299     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
15300     if( rc==2 ){
15301       iOffset = k;
15302       continue;
15303     }
15304     if( strncmp(zLine, "| end ", 6)==0 ){
15305       break;
15306     }
15307     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
15308                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
15309                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
15310     if( rc==17 ){
15311       k = iOffset+j;
15312       if( k+16<=n ){
15313         int ii;
15314         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
15315       }
15316     }
15317   }
15318   *pnData = n;
15319   if( in!=p->in ){
15320     fclose(in);
15321   }else{
15322     p->lineno = nLine;
15323   }
15324   return a;
15325 
15326 readHexDb_error:
15327   if( in!=p->in ){
15328     fclose(in);
15329   }else{
15330     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
15331       nLine++;
15332       if(strncmp(zLine, "| end ", 6)==0 ) break;
15333     }
15334     p->lineno = nLine;
15335   }
15336   sqlite3_free(a);
15337   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
15338   return 0;
15339 }
15340 #endif /* SQLITE_OMIT_DESERIALIZE */
15341 
15342 /*
15343 ** Scalar function "shell_int32". The first argument to this function
15344 ** must be a blob. The second a non-negative integer. This function
15345 ** reads and returns a 32-bit big-endian integer from byte
15346 ** offset (4*<arg2>) of the blob.
15347 */
shellInt32(sqlite3_context * context,int argc,sqlite3_value ** argv)15348 static void shellInt32(
15349   sqlite3_context *context,
15350   int argc,
15351   sqlite3_value **argv
15352 ){
15353   const unsigned char *pBlob;
15354   int nBlob;
15355   int iInt;
15356 
15357   UNUSED_PARAMETER(argc);
15358   nBlob = sqlite3_value_bytes(argv[0]);
15359   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
15360   iInt = sqlite3_value_int(argv[1]);
15361 
15362   if( iInt>=0 && (iInt+1)*4<=nBlob ){
15363     const unsigned char *a = &pBlob[iInt*4];
15364     sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
15365                        + ((sqlite3_int64)a[1]<<16)
15366                        + ((sqlite3_int64)a[2]<< 8)
15367                        + ((sqlite3_int64)a[3]<< 0);
15368     sqlite3_result_int64(context, iVal);
15369   }
15370 }
15371 
15372 /*
15373 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
15374 ** using "..." with internal double-quote characters doubled.
15375 */
shellIdQuote(sqlite3_context * context,int argc,sqlite3_value ** argv)15376 static void shellIdQuote(
15377   sqlite3_context *context,
15378   int argc,
15379   sqlite3_value **argv
15380 ){
15381   const char *zName = (const char*)sqlite3_value_text(argv[0]);
15382   UNUSED_PARAMETER(argc);
15383   if( zName ){
15384     char *z = sqlite3_mprintf("\"%w\"", zName);
15385     sqlite3_result_text(context, z, -1, sqlite3_free);
15386   }
15387 }
15388 
15389 /*
15390 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
15391 */
shellUSleepFunc(sqlite3_context * context,int argcUnused,sqlite3_value ** argv)15392 static void shellUSleepFunc(
15393   sqlite3_context *context,
15394   int argcUnused,
15395   sqlite3_value **argv
15396 ){
15397   int sleep = sqlite3_value_int(argv[0]);
15398   (void)argcUnused;
15399   sqlite3_sleep(sleep/1000);
15400   sqlite3_result_int(context, sleep);
15401 }
15402 
15403 /*
15404 ** Scalar function "shell_escape_crnl" used by the .recover command.
15405 ** The argument passed to this function is the output of built-in
15406 ** function quote(). If the first character of the input is "'",
15407 ** indicating that the value passed to quote() was a text value,
15408 ** then this function searches the input for "\n" and "\r" characters
15409 ** and adds a wrapper similar to the following:
15410 **
15411 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
15412 **
15413 ** Or, if the first character of the input is not "'", then a copy
15414 ** of the input is returned.
15415 */
shellEscapeCrnl(sqlite3_context * context,int argc,sqlite3_value ** argv)15416 static void shellEscapeCrnl(
15417   sqlite3_context *context,
15418   int argc,
15419   sqlite3_value **argv
15420 ){
15421   const char *zText = (const char*)sqlite3_value_text(argv[0]);
15422   UNUSED_PARAMETER(argc);
15423   if( zText[0]=='\'' ){
15424     int nText = sqlite3_value_bytes(argv[0]);
15425     int i;
15426     char zBuf1[20];
15427     char zBuf2[20];
15428     const char *zNL = 0;
15429     const char *zCR = 0;
15430     int nCR = 0;
15431     int nNL = 0;
15432 
15433     for(i=0; zText[i]; i++){
15434       if( zNL==0 && zText[i]=='\n' ){
15435         zNL = unused_string(zText, "\\n", "\\012", zBuf1);
15436         nNL = (int)strlen(zNL);
15437       }
15438       if( zCR==0 && zText[i]=='\r' ){
15439         zCR = unused_string(zText, "\\r", "\\015", zBuf2);
15440         nCR = (int)strlen(zCR);
15441       }
15442     }
15443 
15444     if( zNL || zCR ){
15445       int iOut = 0;
15446       i64 nMax = (nNL > nCR) ? nNL : nCR;
15447       i64 nAlloc = nMax * nText + (nMax+64)*2;
15448       char *zOut = (char*)sqlite3_malloc64(nAlloc);
15449       if( zOut==0 ){
15450         sqlite3_result_error_nomem(context);
15451         return;
15452       }
15453 
15454       if( zNL && zCR ){
15455         memcpy(&zOut[iOut], "replace(replace(", 16);
15456         iOut += 16;
15457       }else{
15458         memcpy(&zOut[iOut], "replace(", 8);
15459         iOut += 8;
15460       }
15461       for(i=0; zText[i]; i++){
15462         if( zText[i]=='\n' ){
15463           memcpy(&zOut[iOut], zNL, nNL);
15464           iOut += nNL;
15465         }else if( zText[i]=='\r' ){
15466           memcpy(&zOut[iOut], zCR, nCR);
15467           iOut += nCR;
15468         }else{
15469           zOut[iOut] = zText[i];
15470           iOut++;
15471         }
15472       }
15473 
15474       if( zNL ){
15475         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
15476         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
15477         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
15478       }
15479       if( zCR ){
15480         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
15481         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
15482         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
15483       }
15484 
15485       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
15486       sqlite3_free(zOut);
15487       return;
15488     }
15489   }
15490 
15491   sqlite3_result_value(context, argv[0]);
15492 }
15493 
15494 /* Flags for open_db().
15495 **
15496 ** The default behavior of open_db() is to exit(1) if the database fails to
15497 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
15498 ** but still returns without calling exit.
15499 **
15500 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
15501 ** ZIP archive if the file does not exist or is empty and its name matches
15502 ** the *.zip pattern.
15503 */
15504 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
15505 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
15506 
15507 /*
15508 ** Make sure the database is open.  If it is not, then open it.  If
15509 ** the database fails to open, print an error message and exit.
15510 */
open_db(ShellState * p,int openFlags)15511 static void open_db(ShellState *p, int openFlags){
15512   if( p->db==0 ){
15513     if( p->openMode==SHELL_OPEN_UNSPEC ){
15514       if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
15515         p->openMode = SHELL_OPEN_NORMAL;
15516       }else{
15517         p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
15518                              (openFlags & OPEN_DB_ZIPFILE)!=0);
15519       }
15520     }
15521     switch( p->openMode ){
15522       case SHELL_OPEN_APPENDVFS: {
15523         sqlite3_open_v2(p->zDbFilename, &p->db,
15524            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
15525         break;
15526       }
15527       case SHELL_OPEN_HEXDB:
15528       case SHELL_OPEN_DESERIALIZE: {
15529         sqlite3_open(0, &p->db);
15530         break;
15531       }
15532       case SHELL_OPEN_ZIPFILE: {
15533         sqlite3_open(":memory:", &p->db);
15534         break;
15535       }
15536       case SHELL_OPEN_READONLY: {
15537         sqlite3_open_v2(p->zDbFilename, &p->db,
15538             SQLITE_OPEN_READONLY|p->openFlags, 0);
15539         break;
15540       }
15541       case SHELL_OPEN_UNSPEC:
15542       case SHELL_OPEN_NORMAL: {
15543         sqlite3_open_v2(p->zDbFilename, &p->db,
15544            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
15545         break;
15546       }
15547     }
15548     globalDb = p->db;
15549     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
15550       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
15551           p->zDbFilename, sqlite3_errmsg(p->db));
15552       if( openFlags & OPEN_DB_KEEPALIVE ){
15553         sqlite3_open(":memory:", &p->db);
15554         return;
15555       }
15556       exit(1);
15557     }
15558 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15559     sqlite3_enable_load_extension(p->db, 1);
15560 #endif
15561     sqlite3_fileio_init(p->db, 0, 0);
15562     sqlite3_shathree_init(p->db, 0, 0);
15563     sqlite3_completion_init(p->db, 0, 0);
15564     sqlite3_uint_init(p->db, 0, 0);
15565     sqlite3_decimal_init(p->db, 0, 0);
15566     sqlite3_regexp_init(p->db, 0, 0);
15567     sqlite3_ieee_init(p->db, 0, 0);
15568     sqlite3_series_init(p->db, 0, 0);
15569 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15570     sqlite3_dbdata_init(p->db, 0, 0);
15571 #endif
15572 #ifdef SQLITE_HAVE_ZLIB
15573     sqlite3_zipfile_init(p->db, 0, 0);
15574     sqlite3_sqlar_init(p->db, 0, 0);
15575 #endif
15576     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
15577                             shellAddSchemaName, 0, 0);
15578     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
15579                             shellModuleSchema, 0, 0);
15580     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
15581                             shellPutsFunc, 0, 0);
15582     sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
15583                             shellEscapeCrnl, 0, 0);
15584     sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
15585                             shellInt32, 0, 0);
15586     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
15587                             shellIdQuote, 0, 0);
15588     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
15589                             shellUSleepFunc, 0, 0);
15590 #ifndef SQLITE_NOHAVE_SYSTEM
15591     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
15592                             editFunc, 0, 0);
15593     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
15594                             editFunc, 0, 0);
15595 #endif
15596     if( p->openMode==SHELL_OPEN_ZIPFILE ){
15597       char *zSql = sqlite3_mprintf(
15598          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
15599       sqlite3_exec(p->db, zSql, 0, 0, 0);
15600       sqlite3_free(zSql);
15601     }
15602 #ifndef SQLITE_OMIT_DESERIALIZE
15603     else
15604     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
15605       int rc;
15606       int nData = 0;
15607       unsigned char *aData;
15608       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
15609         aData = (unsigned char*)readFile(p->zDbFilename, &nData);
15610       }else{
15611         aData = readHexDb(p, &nData);
15612         if( aData==0 ){
15613           return;
15614         }
15615       }
15616       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
15617                    SQLITE_DESERIALIZE_RESIZEABLE |
15618                    SQLITE_DESERIALIZE_FREEONCLOSE);
15619       if( rc ){
15620         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
15621       }
15622       if( p->szMax>0 ){
15623         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
15624       }
15625     }
15626 #endif
15627   }
15628 }
15629 
15630 /*
15631 ** Attempt to close the databaes connection.  Report errors.
15632 */
close_db(sqlite3 * db)15633 void close_db(sqlite3 *db){
15634   int rc = sqlite3_close(db);
15635   if( rc ){
15636     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
15637         rc, sqlite3_errmsg(db));
15638   }
15639 }
15640 
15641 #if HAVE_READLINE || HAVE_EDITLINE
15642 /*
15643 ** Readline completion callbacks
15644 */
readline_completion_generator(const char * text,int state)15645 static char *readline_completion_generator(const char *text, int state){
15646   static sqlite3_stmt *pStmt = 0;
15647   char *zRet;
15648   if( state==0 ){
15649     char *zSql;
15650     sqlite3_finalize(pStmt);
15651     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
15652                            "  FROM completion(%Q) ORDER BY 1", text);
15653     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
15654     sqlite3_free(zSql);
15655   }
15656   if( sqlite3_step(pStmt)==SQLITE_ROW ){
15657     zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
15658   }else{
15659     sqlite3_finalize(pStmt);
15660     pStmt = 0;
15661     zRet = 0;
15662   }
15663   return zRet;
15664 }
readline_completion(const char * zText,int iStart,int iEnd)15665 static char **readline_completion(const char *zText, int iStart, int iEnd){
15666   rl_attempted_completion_over = 1;
15667   return rl_completion_matches(zText, readline_completion_generator);
15668 }
15669 
15670 #elif HAVE_LINENOISE
15671 /*
15672 ** Linenoise completion callback
15673 */
linenoise_completion(const char * zLine,linenoiseCompletions * lc)15674 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
15675   int nLine = strlen30(zLine);
15676   int i, iStart;
15677   sqlite3_stmt *pStmt = 0;
15678   char *zSql;
15679   char zBuf[1000];
15680 
15681   if( nLine>sizeof(zBuf)-30 ) return;
15682   if( zLine[0]=='.' || zLine[0]=='#') return;
15683   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
15684   if( i==nLine-1 ) return;
15685   iStart = i+1;
15686   memcpy(zBuf, zLine, iStart);
15687   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
15688                          "  FROM completion(%Q,%Q) ORDER BY 1",
15689                          &zLine[iStart], zLine);
15690   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
15691   sqlite3_free(zSql);
15692   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
15693   while( sqlite3_step(pStmt)==SQLITE_ROW ){
15694     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
15695     int nCompletion = sqlite3_column_bytes(pStmt, 0);
15696     if( iStart+nCompletion < sizeof(zBuf)-1 ){
15697       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
15698       linenoiseAddCompletion(lc, zBuf);
15699     }
15700   }
15701   sqlite3_finalize(pStmt);
15702 }
15703 #endif
15704 
15705 /*
15706 ** Do C-language style dequoting.
15707 **
15708 **    \a    -> alarm
15709 **    \b    -> backspace
15710 **    \t    -> tab
15711 **    \n    -> newline
15712 **    \v    -> vertical tab
15713 **    \f    -> form feed
15714 **    \r    -> carriage return
15715 **    \s    -> space
15716 **    \"    -> "
15717 **    \'    -> '
15718 **    \\    -> backslash
15719 **    \NNN  -> ascii character NNN in octal
15720 */
resolve_backslashes(char * z)15721 static void resolve_backslashes(char *z){
15722   int i, j;
15723   char c;
15724   while( *z && *z!='\\' ) z++;
15725   for(i=j=0; (c = z[i])!=0; i++, j++){
15726     if( c=='\\' && z[i+1]!=0 ){
15727       c = z[++i];
15728       if( c=='a' ){
15729         c = '\a';
15730       }else if( c=='b' ){
15731         c = '\b';
15732       }else if( c=='t' ){
15733         c = '\t';
15734       }else if( c=='n' ){
15735         c = '\n';
15736       }else if( c=='v' ){
15737         c = '\v';
15738       }else if( c=='f' ){
15739         c = '\f';
15740       }else if( c=='r' ){
15741         c = '\r';
15742       }else if( c=='"' ){
15743         c = '"';
15744       }else if( c=='\'' ){
15745         c = '\'';
15746       }else if( c=='\\' ){
15747         c = '\\';
15748       }else if( c>='0' && c<='7' ){
15749         c -= '0';
15750         if( z[i+1]>='0' && z[i+1]<='7' ){
15751           i++;
15752           c = (c<<3) + z[i] - '0';
15753           if( z[i+1]>='0' && z[i+1]<='7' ){
15754             i++;
15755             c = (c<<3) + z[i] - '0';
15756           }
15757         }
15758       }
15759     }
15760     z[j] = c;
15761   }
15762   if( j<i ) z[j] = 0;
15763 }
15764 
15765 /*
15766 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
15767 ** for TRUE and FALSE.  Return the integer value if appropriate.
15768 */
booleanValue(const char * zArg)15769 static int booleanValue(const char *zArg){
15770   int i;
15771   if( zArg[0]=='0' && zArg[1]=='x' ){
15772     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
15773   }else{
15774     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
15775   }
15776   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
15777   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
15778     return 1;
15779   }
15780   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
15781     return 0;
15782   }
15783   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
15784           zArg);
15785   return 0;
15786 }
15787 
15788 /*
15789 ** Set or clear a shell flag according to a boolean value.
15790 */
setOrClearFlag(ShellState * p,unsigned mFlag,const char * zArg)15791 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
15792   if( booleanValue(zArg) ){
15793     ShellSetFlag(p, mFlag);
15794   }else{
15795     ShellClearFlag(p, mFlag);
15796   }
15797 }
15798 
15799 /*
15800 ** Close an output file, assuming it is not stderr or stdout
15801 */
output_file_close(FILE * f)15802 static void output_file_close(FILE *f){
15803   if( f && f!=stdout && f!=stderr ) fclose(f);
15804 }
15805 
15806 /*
15807 ** Try to open an output file.   The names "stdout" and "stderr" are
15808 ** recognized and do the right thing.  NULL is returned if the output
15809 ** filename is "off".
15810 */
output_file_open(const char * zFile,int bTextMode)15811 static FILE *output_file_open(const char *zFile, int bTextMode){
15812   FILE *f;
15813   if( strcmp(zFile,"stdout")==0 ){
15814     f = stdout;
15815   }else if( strcmp(zFile, "stderr")==0 ){
15816     f = stderr;
15817   }else if( strcmp(zFile, "off")==0 ){
15818     f = 0;
15819   }else{
15820     f = fopen(zFile, bTextMode ? "w" : "wb");
15821     if( f==0 ){
15822       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
15823     }
15824   }
15825   return f;
15826 }
15827 
15828 #ifndef SQLITE_OMIT_TRACE
15829 /*
15830 ** A routine for handling output from sqlite3_trace().
15831 */
sql_trace_callback(unsigned mType,void * pArg,void * pP,void * pX)15832 static int sql_trace_callback(
15833   unsigned mType,         /* The trace type */
15834   void *pArg,             /* The ShellState pointer */
15835   void *pP,               /* Usually a pointer to sqlite_stmt */
15836   void *pX                /* Auxiliary output */
15837 ){
15838   ShellState *p = (ShellState*)pArg;
15839   sqlite3_stmt *pStmt;
15840   const char *zSql;
15841   int nSql;
15842   if( p->traceOut==0 ) return 0;
15843   if( mType==SQLITE_TRACE_CLOSE ){
15844     utf8_printf(p->traceOut, "-- closing database connection\n");
15845     return 0;
15846   }
15847   if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
15848     zSql = (const char*)pX;
15849   }else{
15850     pStmt = (sqlite3_stmt*)pP;
15851     switch( p->eTraceType ){
15852       case SHELL_TRACE_EXPANDED: {
15853         zSql = sqlite3_expanded_sql(pStmt);
15854         break;
15855       }
15856 #ifdef SQLITE_ENABLE_NORMALIZE
15857       case SHELL_TRACE_NORMALIZED: {
15858         zSql = sqlite3_normalized_sql(pStmt);
15859         break;
15860       }
15861 #endif
15862       default: {
15863         zSql = sqlite3_sql(pStmt);
15864         break;
15865       }
15866     }
15867   }
15868   if( zSql==0 ) return 0;
15869   nSql = strlen30(zSql);
15870   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
15871   switch( mType ){
15872     case SQLITE_TRACE_ROW:
15873     case SQLITE_TRACE_STMT: {
15874       utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
15875       break;
15876     }
15877     case SQLITE_TRACE_PROFILE: {
15878       sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
15879       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
15880       break;
15881     }
15882   }
15883   return 0;
15884 }
15885 #endif
15886 
15887 /*
15888 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
15889 ** a useful spot to set a debugger breakpoint.
15890 */
test_breakpoint(void)15891 static void test_breakpoint(void){
15892   static int nCall = 0;
15893   nCall++;
15894 }
15895 
15896 /*
15897 ** An object used to read a CSV and other files for import.
15898 */
15899 typedef struct ImportCtx ImportCtx;
15900 struct ImportCtx {
15901   const char *zFile;  /* Name of the input file */
15902   FILE *in;           /* Read the CSV text from this input stream */
15903   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
15904   char *z;            /* Accumulated text for a field */
15905   int n;              /* Number of bytes in z */
15906   int nAlloc;         /* Space allocated for z[] */
15907   int nLine;          /* Current line number */
15908   int nRow;           /* Number of rows imported */
15909   int nErr;           /* Number of errors encountered */
15910   int bNotFirst;      /* True if one or more bytes already read */
15911   int cTerm;          /* Character that terminated the most recent field */
15912   int cColSep;        /* The column separator character.  (Usually ",") */
15913   int cRowSep;        /* The row separator character.  (Usually "\n") */
15914 };
15915 
15916 /* Clean up resourced used by an ImportCtx */
import_cleanup(ImportCtx * p)15917 static void import_cleanup(ImportCtx *p){
15918   if( p->in!=0 && p->xCloser!=0 ){
15919     p->xCloser(p->in);
15920     p->in = 0;
15921   }
15922   sqlite3_free(p->z);
15923   p->z = 0;
15924 }
15925 
15926 /* Append a single byte to z[] */
import_append_char(ImportCtx * p,int c)15927 static void import_append_char(ImportCtx *p, int c){
15928   if( p->n+1>=p->nAlloc ){
15929     p->nAlloc += p->nAlloc + 100;
15930     p->z = sqlite3_realloc64(p->z, p->nAlloc);
15931     if( p->z==0 ) shell_out_of_memory();
15932   }
15933   p->z[p->n++] = (char)c;
15934 }
15935 
15936 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
15937 ** with the option of having a separator other than ",".
15938 **
15939 **   +  Input comes from p->in.
15940 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
15941 **      from sqlite3_malloc64().
15942 **   +  Use p->cSep as the column separator.  The default is ",".
15943 **   +  Use p->rSep as the row separator.  The default is "\n".
15944 **   +  Keep track of the line number in p->nLine.
15945 **   +  Store the character that terminates the field in p->cTerm.  Store
15946 **      EOF on end-of-file.
15947 **   +  Report syntax errors on stderr
15948 */
csv_read_one_field(ImportCtx * p)15949 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
15950   int c;
15951   int cSep = p->cColSep;
15952   int rSep = p->cRowSep;
15953   p->n = 0;
15954   c = fgetc(p->in);
15955   if( c==EOF || seenInterrupt ){
15956     p->cTerm = EOF;
15957     return 0;
15958   }
15959   if( c=='"' ){
15960     int pc, ppc;
15961     int startLine = p->nLine;
15962     int cQuote = c;
15963     pc = ppc = 0;
15964     while( 1 ){
15965       c = fgetc(p->in);
15966       if( c==rSep ) p->nLine++;
15967       if( c==cQuote ){
15968         if( pc==cQuote ){
15969           pc = 0;
15970           continue;
15971         }
15972       }
15973       if( (c==cSep && pc==cQuote)
15974        || (c==rSep && pc==cQuote)
15975        || (c==rSep && pc=='\r' && ppc==cQuote)
15976        || (c==EOF && pc==cQuote)
15977       ){
15978         do{ p->n--; }while( p->z[p->n]!=cQuote );
15979         p->cTerm = c;
15980         break;
15981       }
15982       if( pc==cQuote && c!='\r' ){
15983         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
15984                 p->zFile, p->nLine, cQuote);
15985       }
15986       if( c==EOF ){
15987         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
15988                 p->zFile, startLine, cQuote);
15989         p->cTerm = c;
15990         break;
15991       }
15992       import_append_char(p, c);
15993       ppc = pc;
15994       pc = c;
15995     }
15996   }else{
15997     /* If this is the first field being parsed and it begins with the
15998     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
15999     if( (c&0xff)==0xef && p->bNotFirst==0 ){
16000       import_append_char(p, c);
16001       c = fgetc(p->in);
16002       if( (c&0xff)==0xbb ){
16003         import_append_char(p, c);
16004         c = fgetc(p->in);
16005         if( (c&0xff)==0xbf ){
16006           p->bNotFirst = 1;
16007           p->n = 0;
16008           return csv_read_one_field(p);
16009         }
16010       }
16011     }
16012     while( c!=EOF && c!=cSep && c!=rSep ){
16013       import_append_char(p, c);
16014       c = fgetc(p->in);
16015     }
16016     if( c==rSep ){
16017       p->nLine++;
16018       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
16019     }
16020     p->cTerm = c;
16021   }
16022   if( p->z ) p->z[p->n] = 0;
16023   p->bNotFirst = 1;
16024   return p->z;
16025 }
16026 
16027 /* Read a single field of ASCII delimited text.
16028 **
16029 **   +  Input comes from p->in.
16030 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
16031 **      from sqlite3_malloc64().
16032 **   +  Use p->cSep as the column separator.  The default is "\x1F".
16033 **   +  Use p->rSep as the row separator.  The default is "\x1E".
16034 **   +  Keep track of the row number in p->nLine.
16035 **   +  Store the character that terminates the field in p->cTerm.  Store
16036 **      EOF on end-of-file.
16037 **   +  Report syntax errors on stderr
16038 */
ascii_read_one_field(ImportCtx * p)16039 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
16040   int c;
16041   int cSep = p->cColSep;
16042   int rSep = p->cRowSep;
16043   p->n = 0;
16044   c = fgetc(p->in);
16045   if( c==EOF || seenInterrupt ){
16046     p->cTerm = EOF;
16047     return 0;
16048   }
16049   while( c!=EOF && c!=cSep && c!=rSep ){
16050     import_append_char(p, c);
16051     c = fgetc(p->in);
16052   }
16053   if( c==rSep ){
16054     p->nLine++;
16055   }
16056   p->cTerm = c;
16057   if( p->z ) p->z[p->n] = 0;
16058   return p->z;
16059 }
16060 
16061 /*
16062 ** Try to transfer data for table zTable.  If an error is seen while
16063 ** moving forward, try to go backwards.  The backwards movement won't
16064 ** work for WITHOUT ROWID tables.
16065 */
tryToCloneData(ShellState * p,sqlite3 * newDb,const char * zTable)16066 static void tryToCloneData(
16067   ShellState *p,
16068   sqlite3 *newDb,
16069   const char *zTable
16070 ){
16071   sqlite3_stmt *pQuery = 0;
16072   sqlite3_stmt *pInsert = 0;
16073   char *zQuery = 0;
16074   char *zInsert = 0;
16075   int rc;
16076   int i, j, n;
16077   int nTable = strlen30(zTable);
16078   int k = 0;
16079   int cnt = 0;
16080   const int spinRate = 10000;
16081 
16082   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
16083   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16084   if( rc ){
16085     utf8_printf(stderr, "Error %d: %s on [%s]\n",
16086             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
16087             zQuery);
16088     goto end_data_xfer;
16089   }
16090   n = sqlite3_column_count(pQuery);
16091   zInsert = sqlite3_malloc64(200 + nTable + n*3);
16092   if( zInsert==0 ) shell_out_of_memory();
16093   sqlite3_snprintf(200+nTable,zInsert,
16094                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
16095   i = strlen30(zInsert);
16096   for(j=1; j<n; j++){
16097     memcpy(zInsert+i, ",?", 2);
16098     i += 2;
16099   }
16100   memcpy(zInsert+i, ");", 3);
16101   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
16102   if( rc ){
16103     utf8_printf(stderr, "Error %d: %s on [%s]\n",
16104             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
16105             zQuery);
16106     goto end_data_xfer;
16107   }
16108   for(k=0; k<2; k++){
16109     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
16110       for(i=0; i<n; i++){
16111         switch( sqlite3_column_type(pQuery, i) ){
16112           case SQLITE_NULL: {
16113             sqlite3_bind_null(pInsert, i+1);
16114             break;
16115           }
16116           case SQLITE_INTEGER: {
16117             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
16118             break;
16119           }
16120           case SQLITE_FLOAT: {
16121             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
16122             break;
16123           }
16124           case SQLITE_TEXT: {
16125             sqlite3_bind_text(pInsert, i+1,
16126                              (const char*)sqlite3_column_text(pQuery,i),
16127                              -1, SQLITE_STATIC);
16128             break;
16129           }
16130           case SQLITE_BLOB: {
16131             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
16132                                             sqlite3_column_bytes(pQuery,i),
16133                                             SQLITE_STATIC);
16134             break;
16135           }
16136         }
16137       } /* End for */
16138       rc = sqlite3_step(pInsert);
16139       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
16140         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
16141                         sqlite3_errmsg(newDb));
16142       }
16143       sqlite3_reset(pInsert);
16144       cnt++;
16145       if( (cnt%spinRate)==0 ){
16146         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
16147         fflush(stdout);
16148       }
16149     } /* End while */
16150     if( rc==SQLITE_DONE ) break;
16151     sqlite3_finalize(pQuery);
16152     sqlite3_free(zQuery);
16153     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
16154                              zTable);
16155     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16156     if( rc ){
16157       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
16158       break;
16159     }
16160   } /* End for(k=0...) */
16161 
16162 end_data_xfer:
16163   sqlite3_finalize(pQuery);
16164   sqlite3_finalize(pInsert);
16165   sqlite3_free(zQuery);
16166   sqlite3_free(zInsert);
16167 }
16168 
16169 
16170 /*
16171 ** Try to transfer all rows of the schema that match zWhere.  For
16172 ** each row, invoke xForEach() on the object defined by that row.
16173 ** If an error is encountered while moving forward through the
16174 ** sqlite_schema table, try again moving backwards.
16175 */
tryToCloneSchema(ShellState * p,sqlite3 * newDb,const char * zWhere,void (* xForEach)(ShellState *,sqlite3 *,const char *))16176 static void tryToCloneSchema(
16177   ShellState *p,
16178   sqlite3 *newDb,
16179   const char *zWhere,
16180   void (*xForEach)(ShellState*,sqlite3*,const char*)
16181 ){
16182   sqlite3_stmt *pQuery = 0;
16183   char *zQuery = 0;
16184   int rc;
16185   const unsigned char *zName;
16186   const unsigned char *zSql;
16187   char *zErrMsg = 0;
16188 
16189   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
16190                            " WHERE %s", zWhere);
16191   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16192   if( rc ){
16193     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
16194                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
16195                     zQuery);
16196     goto end_schema_xfer;
16197   }
16198   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
16199     zName = sqlite3_column_text(pQuery, 0);
16200     zSql = sqlite3_column_text(pQuery, 1);
16201     printf("%s... ", zName); fflush(stdout);
16202     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
16203     if( zErrMsg ){
16204       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
16205       sqlite3_free(zErrMsg);
16206       zErrMsg = 0;
16207     }
16208     if( xForEach ){
16209       xForEach(p, newDb, (const char*)zName);
16210     }
16211     printf("done\n");
16212   }
16213   if( rc!=SQLITE_DONE ){
16214     sqlite3_finalize(pQuery);
16215     sqlite3_free(zQuery);
16216     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
16217                              " WHERE %s ORDER BY rowid DESC", zWhere);
16218     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16219     if( rc ){
16220       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
16221                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
16222                       zQuery);
16223       goto end_schema_xfer;
16224     }
16225     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
16226       zName = sqlite3_column_text(pQuery, 0);
16227       zSql = sqlite3_column_text(pQuery, 1);
16228       printf("%s... ", zName); fflush(stdout);
16229       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
16230       if( zErrMsg ){
16231         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
16232         sqlite3_free(zErrMsg);
16233         zErrMsg = 0;
16234       }
16235       if( xForEach ){
16236         xForEach(p, newDb, (const char*)zName);
16237       }
16238       printf("done\n");
16239     }
16240   }
16241 end_schema_xfer:
16242   sqlite3_finalize(pQuery);
16243   sqlite3_free(zQuery);
16244 }
16245 
16246 /*
16247 ** Open a new database file named "zNewDb".  Try to recover as much information
16248 ** as possible out of the main database (which might be corrupt) and write it
16249 ** into zNewDb.
16250 */
tryToClone(ShellState * p,const char * zNewDb)16251 static void tryToClone(ShellState *p, const char *zNewDb){
16252   int rc;
16253   sqlite3 *newDb = 0;
16254   if( access(zNewDb,0)==0 ){
16255     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
16256     return;
16257   }
16258   rc = sqlite3_open(zNewDb, &newDb);
16259   if( rc ){
16260     utf8_printf(stderr, "Cannot create output database: %s\n",
16261             sqlite3_errmsg(newDb));
16262   }else{
16263     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
16264     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
16265     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
16266     tryToCloneSchema(p, newDb, "type!='table'", 0);
16267     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
16268     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
16269   }
16270   close_db(newDb);
16271 }
16272 
16273 /*
16274 ** Change the output file back to stdout.
16275 **
16276 ** If the p->doXdgOpen flag is set, that means the output was being
16277 ** redirected to a temporary file named by p->zTempFile.  In that case,
16278 ** launch start/open/xdg-open on that temporary file.
16279 */
output_reset(ShellState * p)16280 static void output_reset(ShellState *p){
16281   if( p->outfile[0]=='|' ){
16282 #ifndef SQLITE_OMIT_POPEN
16283     pclose(p->out);
16284 #endif
16285   }else{
16286     output_file_close(p->out);
16287 #ifndef SQLITE_NOHAVE_SYSTEM
16288     if( p->doXdgOpen ){
16289       const char *zXdgOpenCmd =
16290 #if defined(_WIN32)
16291       "start";
16292 #elif defined(__APPLE__)
16293       "open";
16294 #else
16295       "xdg-open";
16296 #endif
16297       char *zCmd;
16298       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
16299       if( system(zCmd) ){
16300         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
16301       }else{
16302         /* Give the start/open/xdg-open command some time to get
16303         ** going before we continue, and potential delete the
16304         ** p->zTempFile data file out from under it */
16305         sqlite3_sleep(2000);
16306       }
16307       sqlite3_free(zCmd);
16308       outputModePop(p);
16309       p->doXdgOpen = 0;
16310     }
16311 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
16312   }
16313   p->outfile[0] = 0;
16314   p->out = stdout;
16315 }
16316 
16317 /*
16318 ** Run an SQL command and return the single integer result.
16319 */
db_int(ShellState * p,const char * zSql)16320 static int db_int(ShellState *p, const char *zSql){
16321   sqlite3_stmt *pStmt;
16322   int res = 0;
16323   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
16324   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
16325     res = sqlite3_column_int(pStmt,0);
16326   }
16327   sqlite3_finalize(pStmt);
16328   return res;
16329 }
16330 
16331 /*
16332 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
16333 */
get2byteInt(unsigned char * a)16334 static unsigned int get2byteInt(unsigned char *a){
16335   return (a[0]<<8) + a[1];
16336 }
get4byteInt(unsigned char * a)16337 static unsigned int get4byteInt(unsigned char *a){
16338   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
16339 }
16340 
16341 /*
16342 ** Implementation of the ".dbinfo" command.
16343 **
16344 ** Return 1 on error, 2 to exit, and 0 otherwise.
16345 */
shell_dbinfo_command(ShellState * p,int nArg,char ** azArg)16346 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
16347   static const struct { const char *zName; int ofst; } aField[] = {
16348      { "file change counter:",  24  },
16349      { "database page count:",  28  },
16350      { "freelist page count:",  36  },
16351      { "schema cookie:",        40  },
16352      { "schema format:",        44  },
16353      { "default cache size:",   48  },
16354      { "autovacuum top root:",  52  },
16355      { "incremental vacuum:",   64  },
16356      { "text encoding:",        56  },
16357      { "user version:",         60  },
16358      { "application id:",       68  },
16359      { "software version:",     96  },
16360   };
16361   static const struct { const char *zName; const char *zSql; } aQuery[] = {
16362      { "number of tables:",
16363        "SELECT count(*) FROM %s WHERE type='table'" },
16364      { "number of indexes:",
16365        "SELECT count(*) FROM %s WHERE type='index'" },
16366      { "number of triggers:",
16367        "SELECT count(*) FROM %s WHERE type='trigger'" },
16368      { "number of views:",
16369        "SELECT count(*) FROM %s WHERE type='view'" },
16370      { "schema size:",
16371        "SELECT total(length(sql)) FROM %s" },
16372   };
16373   int i, rc;
16374   unsigned iDataVersion;
16375   char *zSchemaTab;
16376   char *zDb = nArg>=2 ? azArg[1] : "main";
16377   sqlite3_stmt *pStmt = 0;
16378   unsigned char aHdr[100];
16379   open_db(p, 0);
16380   if( p->db==0 ) return 1;
16381   rc = sqlite3_prepare_v2(p->db,
16382              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
16383              -1, &pStmt, 0);
16384   if( rc ){
16385     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
16386     sqlite3_finalize(pStmt);
16387     return 1;
16388   }
16389   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
16390   if( sqlite3_step(pStmt)==SQLITE_ROW
16391    && sqlite3_column_bytes(pStmt,0)>100
16392   ){
16393     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
16394     sqlite3_finalize(pStmt);
16395   }else{
16396     raw_printf(stderr, "unable to read database header\n");
16397     sqlite3_finalize(pStmt);
16398     return 1;
16399   }
16400   i = get2byteInt(aHdr+16);
16401   if( i==1 ) i = 65536;
16402   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
16403   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
16404   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
16405   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
16406   for(i=0; i<ArraySize(aField); i++){
16407     int ofst = aField[i].ofst;
16408     unsigned int val = get4byteInt(aHdr + ofst);
16409     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
16410     switch( ofst ){
16411       case 56: {
16412         if( val==1 ) raw_printf(p->out, " (utf8)");
16413         if( val==2 ) raw_printf(p->out, " (utf16le)");
16414         if( val==3 ) raw_printf(p->out, " (utf16be)");
16415       }
16416     }
16417     raw_printf(p->out, "\n");
16418   }
16419   if( zDb==0 ){
16420     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
16421   }else if( strcmp(zDb,"temp")==0 ){
16422     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
16423   }else{
16424     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
16425   }
16426   for(i=0; i<ArraySize(aQuery); i++){
16427     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
16428     int val = db_int(p, zSql);
16429     sqlite3_free(zSql);
16430     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
16431   }
16432   sqlite3_free(zSchemaTab);
16433   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
16434   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
16435   return 0;
16436 }
16437 
16438 /*
16439 ** Print the current sqlite3_errmsg() value to stderr and return 1.
16440 */
shellDatabaseError(sqlite3 * db)16441 static int shellDatabaseError(sqlite3 *db){
16442   const char *zErr = sqlite3_errmsg(db);
16443   utf8_printf(stderr, "Error: %s\n", zErr);
16444   return 1;
16445 }
16446 
16447 /*
16448 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
16449 ** if they match and FALSE (0) if they do not match.
16450 **
16451 ** Globbing rules:
16452 **
16453 **      '*'       Matches any sequence of zero or more characters.
16454 **
16455 **      '?'       Matches exactly one character.
16456 **
16457 **     [...]      Matches one character from the enclosed list of
16458 **                characters.
16459 **
16460 **     [^...]     Matches one character not in the enclosed list.
16461 **
16462 **      '#'       Matches any sequence of one or more digits with an
16463 **                optional + or - sign in front
16464 **
16465 **      ' '       Any span of whitespace matches any other span of
16466 **                whitespace.
16467 **
16468 ** Extra whitespace at the end of z[] is ignored.
16469 */
testcase_glob(const char * zGlob,const char * z)16470 static int testcase_glob(const char *zGlob, const char *z){
16471   int c, c2;
16472   int invert;
16473   int seen;
16474 
16475   while( (c = (*(zGlob++)))!=0 ){
16476     if( IsSpace(c) ){
16477       if( !IsSpace(*z) ) return 0;
16478       while( IsSpace(*zGlob) ) zGlob++;
16479       while( IsSpace(*z) ) z++;
16480     }else if( c=='*' ){
16481       while( (c=(*(zGlob++))) == '*' || c=='?' ){
16482         if( c=='?' && (*(z++))==0 ) return 0;
16483       }
16484       if( c==0 ){
16485         return 1;
16486       }else if( c=='[' ){
16487         while( *z && testcase_glob(zGlob-1,z)==0 ){
16488           z++;
16489         }
16490         return (*z)!=0;
16491       }
16492       while( (c2 = (*(z++)))!=0 ){
16493         while( c2!=c ){
16494           c2 = *(z++);
16495           if( c2==0 ) return 0;
16496         }
16497         if( testcase_glob(zGlob,z) ) return 1;
16498       }
16499       return 0;
16500     }else if( c=='?' ){
16501       if( (*(z++))==0 ) return 0;
16502     }else if( c=='[' ){
16503       int prior_c = 0;
16504       seen = 0;
16505       invert = 0;
16506       c = *(z++);
16507       if( c==0 ) return 0;
16508       c2 = *(zGlob++);
16509       if( c2=='^' ){
16510         invert = 1;
16511         c2 = *(zGlob++);
16512       }
16513       if( c2==']' ){
16514         if( c==']' ) seen = 1;
16515         c2 = *(zGlob++);
16516       }
16517       while( c2 && c2!=']' ){
16518         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
16519           c2 = *(zGlob++);
16520           if( c>=prior_c && c<=c2 ) seen = 1;
16521           prior_c = 0;
16522         }else{
16523           if( c==c2 ){
16524             seen = 1;
16525           }
16526           prior_c = c2;
16527         }
16528         c2 = *(zGlob++);
16529       }
16530       if( c2==0 || (seen ^ invert)==0 ) return 0;
16531     }else if( c=='#' ){
16532       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
16533       if( !IsDigit(z[0]) ) return 0;
16534       z++;
16535       while( IsDigit(z[0]) ){ z++; }
16536     }else{
16537       if( c!=(*(z++)) ) return 0;
16538     }
16539   }
16540   while( IsSpace(*z) ){ z++; }
16541   return *z==0;
16542 }
16543 
16544 
16545 /*
16546 ** Compare the string as a command-line option with either one or two
16547 ** initial "-" characters.
16548 */
optionMatch(const char * zStr,const char * zOpt)16549 static int optionMatch(const char *zStr, const char *zOpt){
16550   if( zStr[0]!='-' ) return 0;
16551   zStr++;
16552   if( zStr[0]=='-' ) zStr++;
16553   return strcmp(zStr, zOpt)==0;
16554 }
16555 
16556 /*
16557 ** Delete a file.
16558 */
shellDeleteFile(const char * zFilename)16559 int shellDeleteFile(const char *zFilename){
16560   int rc;
16561 #ifdef _WIN32
16562   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
16563   rc = _wunlink(z);
16564   sqlite3_free(z);
16565 #else
16566   rc = unlink(zFilename);
16567 #endif
16568   return rc;
16569 }
16570 
16571 /*
16572 ** Try to delete the temporary file (if there is one) and free the
16573 ** memory used to hold the name of the temp file.
16574 */
clearTempFile(ShellState * p)16575 static void clearTempFile(ShellState *p){
16576   if( p->zTempFile==0 ) return;
16577   if( p->doXdgOpen ) return;
16578   if( shellDeleteFile(p->zTempFile) ) return;
16579   sqlite3_free(p->zTempFile);
16580   p->zTempFile = 0;
16581 }
16582 
16583 /*
16584 ** Create a new temp file name with the given suffix.
16585 */
newTempFile(ShellState * p,const char * zSuffix)16586 static void newTempFile(ShellState *p, const char *zSuffix){
16587   clearTempFile(p);
16588   sqlite3_free(p->zTempFile);
16589   p->zTempFile = 0;
16590   if( p->db ){
16591     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
16592   }
16593   if( p->zTempFile==0 ){
16594     /* If p->db is an in-memory database then the TEMPFILENAME file-control
16595     ** will not work and we will need to fallback to guessing */
16596     char *zTemp;
16597     sqlite3_uint64 r;
16598     sqlite3_randomness(sizeof(r), &r);
16599     zTemp = getenv("TEMP");
16600     if( zTemp==0 ) zTemp = getenv("TMP");
16601     if( zTemp==0 ){
16602 #ifdef _WIN32
16603       zTemp = "\\tmp";
16604 #else
16605       zTemp = "/tmp";
16606 #endif
16607     }
16608     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
16609   }else{
16610     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
16611   }
16612   if( p->zTempFile==0 ){
16613     raw_printf(stderr, "out of memory\n");
16614     exit(1);
16615   }
16616 }
16617 
16618 
16619 /*
16620 ** The implementation of SQL scalar function fkey_collate_clause(), used
16621 ** by the ".lint fkey-indexes" command. This scalar function is always
16622 ** called with four arguments - the parent table name, the parent column name,
16623 ** the child table name and the child column name.
16624 **
16625 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
16626 **
16627 ** If either of the named tables or columns do not exist, this function
16628 ** returns an empty string. An empty string is also returned if both tables
16629 ** and columns exist but have the same default collation sequence. Or,
16630 ** if both exist but the default collation sequences are different, this
16631 ** function returns the string " COLLATE <parent-collation>", where
16632 ** <parent-collation> is the default collation sequence of the parent column.
16633 */
shellFkeyCollateClause(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)16634 static void shellFkeyCollateClause(
16635   sqlite3_context *pCtx,
16636   int nVal,
16637   sqlite3_value **apVal
16638 ){
16639   sqlite3 *db = sqlite3_context_db_handle(pCtx);
16640   const char *zParent;
16641   const char *zParentCol;
16642   const char *zParentSeq;
16643   const char *zChild;
16644   const char *zChildCol;
16645   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
16646   int rc;
16647 
16648   assert( nVal==4 );
16649   zParent = (const char*)sqlite3_value_text(apVal[0]);
16650   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
16651   zChild = (const char*)sqlite3_value_text(apVal[2]);
16652   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
16653 
16654   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
16655   rc = sqlite3_table_column_metadata(
16656       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
16657   );
16658   if( rc==SQLITE_OK ){
16659     rc = sqlite3_table_column_metadata(
16660         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
16661     );
16662   }
16663 
16664   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
16665     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
16666     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
16667     sqlite3_free(z);
16668   }
16669 }
16670 
16671 
16672 /*
16673 ** The implementation of dot-command ".lint fkey-indexes".
16674 */
lintFkeyIndexes(ShellState * pState,char ** azArg,int nArg)16675 static int lintFkeyIndexes(
16676   ShellState *pState,             /* Current shell tool state */
16677   char **azArg,                   /* Array of arguments passed to dot command */
16678   int nArg                        /* Number of entries in azArg[] */
16679 ){
16680   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
16681   FILE *out = pState->out;        /* Stream to write non-error output to */
16682   int bVerbose = 0;               /* If -verbose is present */
16683   int bGroupByParent = 0;         /* If -groupbyparent is present */
16684   int i;                          /* To iterate through azArg[] */
16685   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
16686   int rc;                         /* Return code */
16687   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
16688 
16689   /*
16690   ** This SELECT statement returns one row for each foreign key constraint
16691   ** in the schema of the main database. The column values are:
16692   **
16693   ** 0. The text of an SQL statement similar to:
16694   **
16695   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
16696   **
16697   **    This SELECT is similar to the one that the foreign keys implementation
16698   **    needs to run internally on child tables. If there is an index that can
16699   **    be used to optimize this query, then it can also be used by the FK
16700   **    implementation to optimize DELETE or UPDATE statements on the parent
16701   **    table.
16702   **
16703   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
16704   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
16705   **    contains an index that can be used to optimize the query.
16706   **
16707   ** 2. Human readable text that describes the child table and columns. e.g.
16708   **
16709   **       "child_table(child_key1, child_key2)"
16710   **
16711   ** 3. Human readable text that describes the parent table and columns. e.g.
16712   **
16713   **       "parent_table(parent_key1, parent_key2)"
16714   **
16715   ** 4. A full CREATE INDEX statement for an index that could be used to
16716   **    optimize DELETE or UPDATE statements on the parent table. e.g.
16717   **
16718   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
16719   **
16720   ** 5. The name of the parent table.
16721   **
16722   ** These six values are used by the C logic below to generate the report.
16723   */
16724   const char *zSql =
16725   "SELECT "
16726     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
16727     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
16728     "  || fkey_collate_clause("
16729     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
16730     ", "
16731     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
16732     "  || group_concat('*=?', ' AND ') || ')'"
16733     ", "
16734     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
16735     ", "
16736     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
16737     ", "
16738     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
16739     "  || ' ON ' || quote(s.name) || '('"
16740     "  || group_concat(quote(f.[from]) ||"
16741     "        fkey_collate_clause("
16742     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
16743     "  || ');'"
16744     ", "
16745     "     f.[table] "
16746     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
16747     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
16748     "GROUP BY s.name, f.id "
16749     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
16750   ;
16751   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
16752 
16753   for(i=2; i<nArg; i++){
16754     int n = strlen30(azArg[i]);
16755     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
16756       bVerbose = 1;
16757     }
16758     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
16759       bGroupByParent = 1;
16760       zIndent = "    ";
16761     }
16762     else{
16763       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
16764           azArg[0], azArg[1]
16765       );
16766       return SQLITE_ERROR;
16767     }
16768   }
16769 
16770   /* Register the fkey_collate_clause() SQL function */
16771   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
16772       0, shellFkeyCollateClause, 0, 0
16773   );
16774 
16775 
16776   if( rc==SQLITE_OK ){
16777     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
16778   }
16779   if( rc==SQLITE_OK ){
16780     sqlite3_bind_int(pSql, 1, bGroupByParent);
16781   }
16782 
16783   if( rc==SQLITE_OK ){
16784     int rc2;
16785     char *zPrev = 0;
16786     while( SQLITE_ROW==sqlite3_step(pSql) ){
16787       int res = -1;
16788       sqlite3_stmt *pExplain = 0;
16789       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
16790       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
16791       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
16792       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
16793       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
16794       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
16795 
16796       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
16797       if( rc!=SQLITE_OK ) break;
16798       if( SQLITE_ROW==sqlite3_step(pExplain) ){
16799         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
16800         res = (
16801               0==sqlite3_strglob(zGlob, zPlan)
16802            || 0==sqlite3_strglob(zGlobIPK, zPlan)
16803         );
16804       }
16805       rc = sqlite3_finalize(pExplain);
16806       if( rc!=SQLITE_OK ) break;
16807 
16808       if( res<0 ){
16809         raw_printf(stderr, "Error: internal error");
16810         break;
16811       }else{
16812         if( bGroupByParent
16813         && (bVerbose || res==0)
16814         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
16815         ){
16816           raw_printf(out, "-- Parent table %s\n", zParent);
16817           sqlite3_free(zPrev);
16818           zPrev = sqlite3_mprintf("%s", zParent);
16819         }
16820 
16821         if( res==0 ){
16822           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
16823         }else if( bVerbose ){
16824           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
16825               zIndent, zFrom, zTarget
16826           );
16827         }
16828       }
16829     }
16830     sqlite3_free(zPrev);
16831 
16832     if( rc!=SQLITE_OK ){
16833       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
16834     }
16835 
16836     rc2 = sqlite3_finalize(pSql);
16837     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
16838       rc = rc2;
16839       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
16840     }
16841   }else{
16842     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
16843   }
16844 
16845   return rc;
16846 }
16847 
16848 /*
16849 ** Implementation of ".lint" dot command.
16850 */
lintDotCommand(ShellState * pState,char ** azArg,int nArg)16851 static int lintDotCommand(
16852   ShellState *pState,             /* Current shell tool state */
16853   char **azArg,                   /* Array of arguments passed to dot command */
16854   int nArg                        /* Number of entries in azArg[] */
16855 ){
16856   int n;
16857   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
16858   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
16859   return lintFkeyIndexes(pState, azArg, nArg);
16860 
16861  usage:
16862   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
16863   raw_printf(stderr, "Where sub-commands are:\n");
16864   raw_printf(stderr, "    fkey-indexes\n");
16865   return SQLITE_ERROR;
16866 }
16867 
16868 #if !defined SQLITE_OMIT_VIRTUALTABLE
shellPrepare(sqlite3 * db,int * pRc,const char * zSql,sqlite3_stmt ** ppStmt)16869 static void shellPrepare(
16870   sqlite3 *db,
16871   int *pRc,
16872   const char *zSql,
16873   sqlite3_stmt **ppStmt
16874 ){
16875   *ppStmt = 0;
16876   if( *pRc==SQLITE_OK ){
16877     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
16878     if( rc!=SQLITE_OK ){
16879       raw_printf(stderr, "sql error: %s (%d)\n",
16880           sqlite3_errmsg(db), sqlite3_errcode(db)
16881       );
16882       *pRc = rc;
16883     }
16884   }
16885 }
16886 
16887 /*
16888 ** Create a prepared statement using printf-style arguments for the SQL.
16889 **
16890 ** This routine is could be marked "static".  But it is not always used,
16891 ** depending on compile-time options.  By omitting the "static", we avoid
16892 ** nuisance compiler warnings about "defined but not used".
16893 */
shellPreparePrintf(sqlite3 * db,int * pRc,sqlite3_stmt ** ppStmt,const char * zFmt,...)16894 void shellPreparePrintf(
16895   sqlite3 *db,
16896   int *pRc,
16897   sqlite3_stmt **ppStmt,
16898   const char *zFmt,
16899   ...
16900 ){
16901   *ppStmt = 0;
16902   if( *pRc==SQLITE_OK ){
16903     va_list ap;
16904     char *z;
16905     va_start(ap, zFmt);
16906     z = sqlite3_vmprintf(zFmt, ap);
16907     va_end(ap);
16908     if( z==0 ){
16909       *pRc = SQLITE_NOMEM;
16910     }else{
16911       shellPrepare(db, pRc, z, ppStmt);
16912       sqlite3_free(z);
16913     }
16914   }
16915 }
16916 
16917 /* Finalize the prepared statement created using shellPreparePrintf().
16918 **
16919 ** This routine is could be marked "static".  But it is not always used,
16920 ** depending on compile-time options.  By omitting the "static", we avoid
16921 ** nuisance compiler warnings about "defined but not used".
16922 */
shellFinalize(int * pRc,sqlite3_stmt * pStmt)16923 void shellFinalize(
16924   int *pRc,
16925   sqlite3_stmt *pStmt
16926 ){
16927   if( pStmt ){
16928     sqlite3 *db = sqlite3_db_handle(pStmt);
16929     int rc = sqlite3_finalize(pStmt);
16930     if( *pRc==SQLITE_OK ){
16931       if( rc!=SQLITE_OK ){
16932         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
16933       }
16934       *pRc = rc;
16935     }
16936   }
16937 }
16938 
16939 /* Reset the prepared statement created using shellPreparePrintf().
16940 **
16941 ** This routine is could be marked "static".  But it is not always used,
16942 ** depending on compile-time options.  By omitting the "static", we avoid
16943 ** nuisance compiler warnings about "defined but not used".
16944 */
shellReset(int * pRc,sqlite3_stmt * pStmt)16945 void shellReset(
16946   int *pRc,
16947   sqlite3_stmt *pStmt
16948 ){
16949   int rc = sqlite3_reset(pStmt);
16950   if( *pRc==SQLITE_OK ){
16951     if( rc!=SQLITE_OK ){
16952       sqlite3 *db = sqlite3_db_handle(pStmt);
16953       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
16954     }
16955     *pRc = rc;
16956   }
16957 }
16958 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
16959 
16960 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16961 /******************************************************************************
16962 ** The ".archive" or ".ar" command.
16963 */
16964 /*
16965 ** Structure representing a single ".ar" command.
16966 */
16967 typedef struct ArCommand ArCommand;
16968 struct ArCommand {
16969   u8 eCmd;                        /* An AR_CMD_* value */
16970   u8 bVerbose;                    /* True if --verbose */
16971   u8 bZip;                        /* True if the archive is a ZIP */
16972   u8 bDryRun;                     /* True if --dry-run */
16973   u8 bAppend;                     /* True if --append */
16974   u8 fromCmdLine;                 /* Run from -A instead of .archive */
16975   int nArg;                       /* Number of command arguments */
16976   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
16977   const char *zFile;              /* --file argument, or NULL */
16978   const char *zDir;               /* --directory argument, or NULL */
16979   char **azArg;                   /* Array of command arguments */
16980   ShellState *p;                  /* Shell state */
16981   sqlite3 *db;                    /* Database containing the archive */
16982 };
16983 
16984 /*
16985 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
16986 */
arUsage(FILE * f)16987 static int arUsage(FILE *f){
16988   showHelp(f,"archive");
16989   return SQLITE_ERROR;
16990 }
16991 
16992 /*
16993 ** Print an error message for the .ar command to stderr and return
16994 ** SQLITE_ERROR.
16995 */
arErrorMsg(ArCommand * pAr,const char * zFmt,...)16996 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
16997   va_list ap;
16998   char *z;
16999   va_start(ap, zFmt);
17000   z = sqlite3_vmprintf(zFmt, ap);
17001   va_end(ap);
17002   utf8_printf(stderr, "Error: %s\n", z);
17003   if( pAr->fromCmdLine ){
17004     utf8_printf(stderr, "Use \"-A\" for more help\n");
17005   }else{
17006     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
17007   }
17008   sqlite3_free(z);
17009   return SQLITE_ERROR;
17010 }
17011 
17012 /*
17013 ** Values for ArCommand.eCmd.
17014 */
17015 #define AR_CMD_CREATE       1
17016 #define AR_CMD_UPDATE       2
17017 #define AR_CMD_INSERT       3
17018 #define AR_CMD_EXTRACT      4
17019 #define AR_CMD_LIST         5
17020 #define AR_CMD_HELP         6
17021 
17022 /*
17023 ** Other (non-command) switches.
17024 */
17025 #define AR_SWITCH_VERBOSE     7
17026 #define AR_SWITCH_FILE        8
17027 #define AR_SWITCH_DIRECTORY   9
17028 #define AR_SWITCH_APPEND     10
17029 #define AR_SWITCH_DRYRUN     11
17030 
arProcessSwitch(ArCommand * pAr,int eSwitch,const char * zArg)17031 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
17032   switch( eSwitch ){
17033     case AR_CMD_CREATE:
17034     case AR_CMD_EXTRACT:
17035     case AR_CMD_LIST:
17036     case AR_CMD_UPDATE:
17037     case AR_CMD_INSERT:
17038     case AR_CMD_HELP:
17039       if( pAr->eCmd ){
17040         return arErrorMsg(pAr, "multiple command options");
17041       }
17042       pAr->eCmd = eSwitch;
17043       break;
17044 
17045     case AR_SWITCH_DRYRUN:
17046       pAr->bDryRun = 1;
17047       break;
17048     case AR_SWITCH_VERBOSE:
17049       pAr->bVerbose = 1;
17050       break;
17051     case AR_SWITCH_APPEND:
17052       pAr->bAppend = 1;
17053       /* Fall thru into --file */
17054     case AR_SWITCH_FILE:
17055       pAr->zFile = zArg;
17056       break;
17057     case AR_SWITCH_DIRECTORY:
17058       pAr->zDir = zArg;
17059       break;
17060   }
17061 
17062   return SQLITE_OK;
17063 }
17064 
17065 /*
17066 ** Parse the command line for an ".ar" command. The results are written into
17067 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
17068 ** successfully, otherwise an error message is written to stderr and
17069 ** SQLITE_ERROR returned.
17070 */
arParseCommand(char ** azArg,int nArg,ArCommand * pAr)17071 static int arParseCommand(
17072   char **azArg,                   /* Array of arguments passed to dot command */
17073   int nArg,                       /* Number of entries in azArg[] */
17074   ArCommand *pAr                  /* Populate this object */
17075 ){
17076   struct ArSwitch {
17077     const char *zLong;
17078     char cShort;
17079     u8 eSwitch;
17080     u8 bArg;
17081   } aSwitch[] = {
17082     { "create",    'c', AR_CMD_CREATE,       0 },
17083     { "extract",   'x', AR_CMD_EXTRACT,      0 },
17084     { "insert",    'i', AR_CMD_INSERT,       0 },
17085     { "list",      't', AR_CMD_LIST,         0 },
17086     { "update",    'u', AR_CMD_UPDATE,       0 },
17087     { "help",      'h', AR_CMD_HELP,         0 },
17088     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
17089     { "file",      'f', AR_SWITCH_FILE,      1 },
17090     { "append",    'a', AR_SWITCH_APPEND,    1 },
17091     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
17092     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
17093   };
17094   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
17095   struct ArSwitch *pEnd = &aSwitch[nSwitch];
17096 
17097   if( nArg<=1 ){
17098     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
17099     return arUsage(stderr);
17100   }else{
17101     char *z = azArg[1];
17102     if( z[0]!='-' ){
17103       /* Traditional style [tar] invocation */
17104       int i;
17105       int iArg = 2;
17106       for(i=0; z[i]; i++){
17107         const char *zArg = 0;
17108         struct ArSwitch *pOpt;
17109         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
17110           if( z[i]==pOpt->cShort ) break;
17111         }
17112         if( pOpt==pEnd ){
17113           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
17114         }
17115         if( pOpt->bArg ){
17116           if( iArg>=nArg ){
17117             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
17118           }
17119           zArg = azArg[iArg++];
17120         }
17121         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
17122       }
17123       pAr->nArg = nArg-iArg;
17124       if( pAr->nArg>0 ){
17125         pAr->azArg = &azArg[iArg];
17126       }
17127     }else{
17128       /* Non-traditional invocation */
17129       int iArg;
17130       for(iArg=1; iArg<nArg; iArg++){
17131         int n;
17132         z = azArg[iArg];
17133         if( z[0]!='-' ){
17134           /* All remaining command line words are command arguments. */
17135           pAr->azArg = &azArg[iArg];
17136           pAr->nArg = nArg-iArg;
17137           break;
17138         }
17139         n = strlen30(z);
17140 
17141         if( z[1]!='-' ){
17142           int i;
17143           /* One or more short options */
17144           for(i=1; i<n; i++){
17145             const char *zArg = 0;
17146             struct ArSwitch *pOpt;
17147             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
17148               if( z[i]==pOpt->cShort ) break;
17149             }
17150             if( pOpt==pEnd ){
17151               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
17152             }
17153             if( pOpt->bArg ){
17154               if( i<(n-1) ){
17155                 zArg = &z[i+1];
17156                 i = n;
17157               }else{
17158                 if( iArg>=(nArg-1) ){
17159                   return arErrorMsg(pAr, "option requires an argument: %c",
17160                                     z[i]);
17161                 }
17162                 zArg = azArg[++iArg];
17163               }
17164             }
17165             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
17166           }
17167         }else if( z[2]=='\0' ){
17168           /* A -- option, indicating that all remaining command line words
17169           ** are command arguments.  */
17170           pAr->azArg = &azArg[iArg+1];
17171           pAr->nArg = nArg-iArg-1;
17172           break;
17173         }else{
17174           /* A long option */
17175           const char *zArg = 0;             /* Argument for option, if any */
17176           struct ArSwitch *pMatch = 0;      /* Matching option */
17177           struct ArSwitch *pOpt;            /* Iterator */
17178           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
17179             const char *zLong = pOpt->zLong;
17180             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
17181               if( pMatch ){
17182                 return arErrorMsg(pAr, "ambiguous option: %s",z);
17183               }else{
17184                 pMatch = pOpt;
17185               }
17186             }
17187           }
17188 
17189           if( pMatch==0 ){
17190             return arErrorMsg(pAr, "unrecognized option: %s", z);
17191           }
17192           if( pMatch->bArg ){
17193             if( iArg>=(nArg-1) ){
17194               return arErrorMsg(pAr, "option requires an argument: %s", z);
17195             }
17196             zArg = azArg[++iArg];
17197           }
17198           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
17199         }
17200       }
17201     }
17202   }
17203 
17204   return SQLITE_OK;
17205 }
17206 
17207 /*
17208 ** This function assumes that all arguments within the ArCommand.azArg[]
17209 ** array refer to archive members, as for the --extract or --list commands.
17210 ** It checks that each of them are present. If any specified file is not
17211 ** present in the archive, an error is printed to stderr and an error
17212 ** code returned. Otherwise, if all specified arguments are present in
17213 ** the archive, SQLITE_OK is returned.
17214 **
17215 ** This function strips any trailing '/' characters from each argument.
17216 ** This is consistent with the way the [tar] command seems to work on
17217 ** Linux.
17218 */
arCheckEntries(ArCommand * pAr)17219 static int arCheckEntries(ArCommand *pAr){
17220   int rc = SQLITE_OK;
17221   if( pAr->nArg ){
17222     int i, j;
17223     sqlite3_stmt *pTest = 0;
17224 
17225     shellPreparePrintf(pAr->db, &rc, &pTest,
17226         "SELECT name FROM %s WHERE name=$name",
17227         pAr->zSrcTable
17228     );
17229     j = sqlite3_bind_parameter_index(pTest, "$name");
17230     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
17231       char *z = pAr->azArg[i];
17232       int n = strlen30(z);
17233       int bOk = 0;
17234       while( n>0 && z[n-1]=='/' ) n--;
17235       z[n] = '\0';
17236       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
17237       if( SQLITE_ROW==sqlite3_step(pTest) ){
17238         bOk = 1;
17239       }
17240       shellReset(&rc, pTest);
17241       if( rc==SQLITE_OK && bOk==0 ){
17242         utf8_printf(stderr, "not found in archive: %s\n", z);
17243         rc = SQLITE_ERROR;
17244       }
17245     }
17246     shellFinalize(&rc, pTest);
17247   }
17248   return rc;
17249 }
17250 
17251 /*
17252 ** Format a WHERE clause that can be used against the "sqlar" table to
17253 ** identify all archive members that match the command arguments held
17254 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
17255 ** The caller is responsible for eventually calling sqlite3_free() on
17256 ** any non-NULL (*pzWhere) value.
17257 */
arWhereClause(int * pRc,ArCommand * pAr,char ** pzWhere)17258 static void arWhereClause(
17259   int *pRc,
17260   ArCommand *pAr,
17261   char **pzWhere                  /* OUT: New WHERE clause */
17262 ){
17263   char *zWhere = 0;
17264   if( *pRc==SQLITE_OK ){
17265     if( pAr->nArg==0 ){
17266       zWhere = sqlite3_mprintf("1");
17267     }else{
17268       int i;
17269       const char *zSep = "";
17270       for(i=0; i<pAr->nArg; i++){
17271         const char *z = pAr->azArg[i];
17272         zWhere = sqlite3_mprintf(
17273           "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
17274           zWhere, zSep, z, strlen30(z)+1, z
17275         );
17276         if( zWhere==0 ){
17277           *pRc = SQLITE_NOMEM;
17278           break;
17279         }
17280         zSep = " OR ";
17281       }
17282     }
17283   }
17284   *pzWhere = zWhere;
17285 }
17286 
17287 /*
17288 ** Implementation of .ar "lisT" command.
17289 */
arListCommand(ArCommand * pAr)17290 static int arListCommand(ArCommand *pAr){
17291   const char *zSql = "SELECT %s FROM %s WHERE %s";
17292   const char *azCols[] = {
17293     "name",
17294     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
17295   };
17296 
17297   char *zWhere = 0;
17298   sqlite3_stmt *pSql = 0;
17299   int rc;
17300 
17301   rc = arCheckEntries(pAr);
17302   arWhereClause(&rc, pAr, &zWhere);
17303 
17304   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
17305                      pAr->zSrcTable, zWhere);
17306   if( pAr->bDryRun ){
17307     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
17308   }else{
17309     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
17310       if( pAr->bVerbose ){
17311         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
17312             sqlite3_column_text(pSql, 0),
17313             sqlite3_column_int(pSql, 1),
17314             sqlite3_column_text(pSql, 2),
17315             sqlite3_column_text(pSql, 3)
17316         );
17317       }else{
17318         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
17319       }
17320     }
17321   }
17322   shellFinalize(&rc, pSql);
17323   sqlite3_free(zWhere);
17324   return rc;
17325 }
17326 
17327 
17328 /*
17329 ** Implementation of .ar "eXtract" command.
17330 */
arExtractCommand(ArCommand * pAr)17331 static int arExtractCommand(ArCommand *pAr){
17332   const char *zSql1 =
17333     "SELECT "
17334     " ($dir || name),"
17335     " writefile(($dir || name), %s, mode, mtime) "
17336     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
17337     " AND name NOT GLOB '*..[/\\]*'";
17338 
17339   const char *azExtraArg[] = {
17340     "sqlar_uncompress(data, sz)",
17341     "data"
17342   };
17343 
17344   sqlite3_stmt *pSql = 0;
17345   int rc = SQLITE_OK;
17346   char *zDir = 0;
17347   char *zWhere = 0;
17348   int i, j;
17349 
17350   /* If arguments are specified, check that they actually exist within
17351   ** the archive before proceeding. And formulate a WHERE clause to
17352   ** match them.  */
17353   rc = arCheckEntries(pAr);
17354   arWhereClause(&rc, pAr, &zWhere);
17355 
17356   if( rc==SQLITE_OK ){
17357     if( pAr->zDir ){
17358       zDir = sqlite3_mprintf("%s/", pAr->zDir);
17359     }else{
17360       zDir = sqlite3_mprintf("");
17361     }
17362     if( zDir==0 ) rc = SQLITE_NOMEM;
17363   }
17364 
17365   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
17366       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
17367   );
17368 
17369   if( rc==SQLITE_OK ){
17370     j = sqlite3_bind_parameter_index(pSql, "$dir");
17371     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
17372 
17373     /* Run the SELECT statement twice. The first time, writefile() is called
17374     ** for all archive members that should be extracted. The second time,
17375     ** only for the directories. This is because the timestamps for
17376     ** extracted directories must be reset after they are populated (as
17377     ** populating them changes the timestamp).  */
17378     for(i=0; i<2; i++){
17379       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
17380       sqlite3_bind_int(pSql, j, i);
17381       if( pAr->bDryRun ){
17382         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
17383       }else{
17384         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
17385           if( i==0 && pAr->bVerbose ){
17386             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
17387           }
17388         }
17389       }
17390       shellReset(&rc, pSql);
17391     }
17392     shellFinalize(&rc, pSql);
17393   }
17394 
17395   sqlite3_free(zDir);
17396   sqlite3_free(zWhere);
17397   return rc;
17398 }
17399 
17400 /*
17401 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
17402 */
arExecSql(ArCommand * pAr,const char * zSql)17403 static int arExecSql(ArCommand *pAr, const char *zSql){
17404   int rc;
17405   if( pAr->bDryRun ){
17406     utf8_printf(pAr->p->out, "%s\n", zSql);
17407     rc = SQLITE_OK;
17408   }else{
17409     char *zErr = 0;
17410     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
17411     if( zErr ){
17412       utf8_printf(stdout, "ERROR: %s\n", zErr);
17413       sqlite3_free(zErr);
17414     }
17415   }
17416   return rc;
17417 }
17418 
17419 
17420 /*
17421 ** Implementation of .ar "create", "insert", and "update" commands.
17422 **
17423 **     create    ->     Create a new SQL archive
17424 **     insert    ->     Insert or reinsert all files listed
17425 **     update    ->     Insert files that have changed or that were not
17426 **                      previously in the archive
17427 **
17428 ** Create the "sqlar" table in the database if it does not already exist.
17429 ** Then add each file in the azFile[] array to the archive. Directories
17430 ** are added recursively. If argument bVerbose is non-zero, a message is
17431 ** printed on stdout for each file archived.
17432 **
17433 ** The create command is the same as update, except that it drops
17434 ** any existing "sqlar" table before beginning.  The "insert" command
17435 ** always overwrites every file named on the command-line, where as
17436 ** "update" only overwrites if the size or mtime or mode has changed.
17437 */
arCreateOrUpdateCommand(ArCommand * pAr,int bUpdate,int bOnlyIfChanged)17438 static int arCreateOrUpdateCommand(
17439   ArCommand *pAr,                 /* Command arguments and options */
17440   int bUpdate,                    /* true for a --create. */
17441   int bOnlyIfChanged              /* Only update if file has changed */
17442 ){
17443   const char *zCreate =
17444       "CREATE TABLE IF NOT EXISTS sqlar(\n"
17445       "  name TEXT PRIMARY KEY,  -- name of the file\n"
17446       "  mode INT,               -- access permissions\n"
17447       "  mtime INT,              -- last modification time\n"
17448       "  sz INT,                 -- original file size\n"
17449       "  data BLOB               -- compressed content\n"
17450       ")";
17451   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
17452   const char *zInsertFmt[2] = {
17453      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
17454      "  SELECT\n"
17455      "    %s,\n"
17456      "    mode,\n"
17457      "    mtime,\n"
17458      "    CASE substr(lsmode(mode),1,1)\n"
17459      "      WHEN '-' THEN length(data)\n"
17460      "      WHEN 'd' THEN 0\n"
17461      "      ELSE -1 END,\n"
17462      "    sqlar_compress(data)\n"
17463      "  FROM fsdir(%Q,%Q) AS disk\n"
17464      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
17465      ,
17466      "REPLACE INTO %s(name,mode,mtime,data)\n"
17467      "  SELECT\n"
17468      "    %s,\n"
17469      "    mode,\n"
17470      "    mtime,\n"
17471      "    data\n"
17472      "  FROM fsdir(%Q,%Q) AS disk\n"
17473      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
17474   };
17475   int i;                          /* For iterating through azFile[] */
17476   int rc;                         /* Return code */
17477   const char *zTab = 0;           /* SQL table into which to insert */
17478   char *zSql;
17479   char zTemp[50];
17480   char *zExists = 0;
17481 
17482   arExecSql(pAr, "PRAGMA page_size=512");
17483   rc = arExecSql(pAr, "SAVEPOINT ar;");
17484   if( rc!=SQLITE_OK ) return rc;
17485   zTemp[0] = 0;
17486   if( pAr->bZip ){
17487     /* Initialize the zipfile virtual table, if necessary */
17488     if( pAr->zFile ){
17489       sqlite3_uint64 r;
17490       sqlite3_randomness(sizeof(r),&r);
17491       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
17492       zTab = zTemp;
17493       zSql = sqlite3_mprintf(
17494          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
17495          zTab, pAr->zFile
17496       );
17497       rc = arExecSql(pAr, zSql);
17498       sqlite3_free(zSql);
17499     }else{
17500       zTab = "zip";
17501     }
17502   }else{
17503     /* Initialize the table for an SQLAR */
17504     zTab = "sqlar";
17505     if( bUpdate==0 ){
17506       rc = arExecSql(pAr, zDrop);
17507       if( rc!=SQLITE_OK ) goto end_ar_transaction;
17508     }
17509     rc = arExecSql(pAr, zCreate);
17510   }
17511   if( bOnlyIfChanged ){
17512     zExists = sqlite3_mprintf(
17513       " AND NOT EXISTS("
17514           "SELECT 1 FROM %s AS mem"
17515           " WHERE mem.name=disk.name"
17516           " AND mem.mtime=disk.mtime"
17517           " AND mem.mode=disk.mode)", zTab);
17518   }else{
17519     zExists = sqlite3_mprintf("");
17520   }
17521   if( zExists==0 ) rc = SQLITE_NOMEM;
17522   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
17523     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
17524         pAr->bVerbose ? "shell_putsnl(name)" : "name",
17525         pAr->azArg[i], pAr->zDir, zExists);
17526     rc = arExecSql(pAr, zSql2);
17527     sqlite3_free(zSql2);
17528   }
17529 end_ar_transaction:
17530   if( rc!=SQLITE_OK ){
17531     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
17532   }else{
17533     rc = arExecSql(pAr, "RELEASE ar;");
17534     if( pAr->bZip && pAr->zFile ){
17535       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
17536       arExecSql(pAr, zSql);
17537       sqlite3_free(zSql);
17538     }
17539   }
17540   sqlite3_free(zExists);
17541   return rc;
17542 }
17543 
17544 /*
17545 ** Implementation of ".ar" dot command.
17546 */
arDotCommand(ShellState * pState,int fromCmdLine,char ** azArg,int nArg)17547 static int arDotCommand(
17548   ShellState *pState,          /* Current shell tool state */
17549   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
17550   char **azArg,                /* Array of arguments passed to dot command */
17551   int nArg                     /* Number of entries in azArg[] */
17552 ){
17553   ArCommand cmd;
17554   int rc;
17555   memset(&cmd, 0, sizeof(cmd));
17556   cmd.fromCmdLine = fromCmdLine;
17557   rc = arParseCommand(azArg, nArg, &cmd);
17558   if( rc==SQLITE_OK ){
17559     int eDbType = SHELL_OPEN_UNSPEC;
17560     cmd.p = pState;
17561     cmd.db = pState->db;
17562     if( cmd.zFile ){
17563       eDbType = deduceDatabaseType(cmd.zFile, 1);
17564     }else{
17565       eDbType = pState->openMode;
17566     }
17567     if( eDbType==SHELL_OPEN_ZIPFILE ){
17568       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
17569         if( cmd.zFile==0 ){
17570           cmd.zSrcTable = sqlite3_mprintf("zip");
17571         }else{
17572           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
17573         }
17574       }
17575       cmd.bZip = 1;
17576     }else if( cmd.zFile ){
17577       int flags;
17578       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
17579       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
17580            || cmd.eCmd==AR_CMD_UPDATE ){
17581         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
17582       }else{
17583         flags = SQLITE_OPEN_READONLY;
17584       }
17585       cmd.db = 0;
17586       if( cmd.bDryRun ){
17587         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
17588              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
17589       }
17590       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
17591              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
17592       if( rc!=SQLITE_OK ){
17593         utf8_printf(stderr, "cannot open file: %s (%s)\n",
17594             cmd.zFile, sqlite3_errmsg(cmd.db)
17595         );
17596         goto end_ar_command;
17597       }
17598       sqlite3_fileio_init(cmd.db, 0, 0);
17599       sqlite3_sqlar_init(cmd.db, 0, 0);
17600       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
17601                               shellPutsFunc, 0, 0);
17602 
17603     }
17604     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
17605       if( cmd.eCmd!=AR_CMD_CREATE
17606        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
17607       ){
17608         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
17609         rc = SQLITE_ERROR;
17610         goto end_ar_command;
17611       }
17612       cmd.zSrcTable = sqlite3_mprintf("sqlar");
17613     }
17614 
17615     switch( cmd.eCmd ){
17616       case AR_CMD_CREATE:
17617         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
17618         break;
17619 
17620       case AR_CMD_EXTRACT:
17621         rc = arExtractCommand(&cmd);
17622         break;
17623 
17624       case AR_CMD_LIST:
17625         rc = arListCommand(&cmd);
17626         break;
17627 
17628       case AR_CMD_HELP:
17629         arUsage(pState->out);
17630         break;
17631 
17632       case AR_CMD_INSERT:
17633         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
17634         break;
17635 
17636       default:
17637         assert( cmd.eCmd==AR_CMD_UPDATE );
17638         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
17639         break;
17640     }
17641   }
17642 end_ar_command:
17643   if( cmd.db!=pState->db ){
17644     close_db(cmd.db);
17645   }
17646   sqlite3_free(cmd.zSrcTable);
17647 
17648   return rc;
17649 }
17650 /* End of the ".archive" or ".ar" command logic
17651 *******************************************************************************/
17652 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
17653 
17654 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
17655 /*
17656 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
17657 ** Otherwise, the SQL statement or statements in zSql are executed using
17658 ** database connection db and the error code written to *pRc before
17659 ** this function returns.
17660 */
shellExec(sqlite3 * db,int * pRc,const char * zSql)17661 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
17662   int rc = *pRc;
17663   if( rc==SQLITE_OK ){
17664     char *zErr = 0;
17665     rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
17666     if( rc!=SQLITE_OK ){
17667       raw_printf(stderr, "SQL error: %s\n", zErr);
17668     }
17669     sqlite3_free(zErr);
17670     *pRc = rc;
17671   }
17672 }
17673 
17674 /*
17675 ** Like shellExec(), except that zFmt is a printf() style format string.
17676 */
shellExecPrintf(sqlite3 * db,int * pRc,const char * zFmt,...)17677 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
17678   char *z = 0;
17679   if( *pRc==SQLITE_OK ){
17680     va_list ap;
17681     va_start(ap, zFmt);
17682     z = sqlite3_vmprintf(zFmt, ap);
17683     va_end(ap);
17684     if( z==0 ){
17685       *pRc = SQLITE_NOMEM;
17686     }else{
17687       shellExec(db, pRc, z);
17688     }
17689     sqlite3_free(z);
17690   }
17691 }
17692 
17693 /*
17694 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
17695 ** Otherwise, an attempt is made to allocate, zero and return a pointer
17696 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
17697 ** to SQLITE_NOMEM and NULL returned.
17698 */
shellMalloc(int * pRc,sqlite3_int64 nByte)17699 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
17700   void *pRet = 0;
17701   if( *pRc==SQLITE_OK ){
17702     pRet = sqlite3_malloc64(nByte);
17703     if( pRet==0 ){
17704       *pRc = SQLITE_NOMEM;
17705     }else{
17706       memset(pRet, 0, nByte);
17707     }
17708   }
17709   return pRet;
17710 }
17711 
17712 /*
17713 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
17714 ** Otherwise, zFmt is treated as a printf() style string. The result of
17715 ** formatting it along with any trailing arguments is written into a
17716 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
17717 ** It is the responsibility of the caller to eventually free this buffer
17718 ** using a call to sqlite3_free().
17719 **
17720 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
17721 ** pointer returned.
17722 */
shellMPrintf(int * pRc,const char * zFmt,...)17723 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
17724   char *z = 0;
17725   if( *pRc==SQLITE_OK ){
17726     va_list ap;
17727     va_start(ap, zFmt);
17728     z = sqlite3_vmprintf(zFmt, ap);
17729     va_end(ap);
17730     if( z==0 ){
17731       *pRc = SQLITE_NOMEM;
17732     }
17733   }
17734   return z;
17735 }
17736 
17737 /*
17738 ** When running the ".recover" command, each output table, and the special
17739 ** orphaned row table if it is required, is represented by an instance
17740 ** of the following struct.
17741 */
17742 typedef struct RecoverTable RecoverTable;
17743 struct RecoverTable {
17744   char *zQuoted;                  /* Quoted version of table name */
17745   int nCol;                       /* Number of columns in table */
17746   char **azlCol;                  /* Array of column lists */
17747   int iPk;                        /* Index of IPK column */
17748 };
17749 
17750 /*
17751 ** Free a RecoverTable object allocated by recoverFindTable() or
17752 ** recoverOrphanTable().
17753 */
recoverFreeTable(RecoverTable * pTab)17754 static void recoverFreeTable(RecoverTable *pTab){
17755   if( pTab ){
17756     sqlite3_free(pTab->zQuoted);
17757     if( pTab->azlCol ){
17758       int i;
17759       for(i=0; i<=pTab->nCol; i++){
17760         sqlite3_free(pTab->azlCol[i]);
17761       }
17762       sqlite3_free(pTab->azlCol);
17763     }
17764     sqlite3_free(pTab);
17765   }
17766 }
17767 
17768 /*
17769 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
17770 ** Otherwise, it allocates and returns a RecoverTable object based on the
17771 ** final four arguments passed to this function. It is the responsibility
17772 ** of the caller to eventually free the returned object using
17773 ** recoverFreeTable().
17774 */
recoverNewTable(int * pRc,const char * zName,const char * zSql,int bIntkey,int nCol)17775 static RecoverTable *recoverNewTable(
17776   int *pRc,                       /* IN/OUT: Error code */
17777   const char *zName,              /* Name of table */
17778   const char *zSql,               /* CREATE TABLE statement */
17779   int bIntkey,
17780   int nCol
17781 ){
17782   sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
17783   int rc = *pRc;
17784   RecoverTable *pTab = 0;
17785 
17786   pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
17787   if( rc==SQLITE_OK ){
17788     int nSqlCol = 0;
17789     int bSqlIntkey = 0;
17790     sqlite3_stmt *pStmt = 0;
17791 
17792     rc = sqlite3_open("", &dbtmp);
17793     if( rc==SQLITE_OK ){
17794       sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
17795                               shellIdQuote, 0, 0);
17796     }
17797     if( rc==SQLITE_OK ){
17798       rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
17799     }
17800     if( rc==SQLITE_OK ){
17801       rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
17802       if( rc==SQLITE_ERROR ){
17803         rc = SQLITE_OK;
17804         goto finished;
17805       }
17806     }
17807     shellPreparePrintf(dbtmp, &rc, &pStmt,
17808         "SELECT count(*) FROM pragma_table_info(%Q)", zName
17809     );
17810     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17811       nSqlCol = sqlite3_column_int(pStmt, 0);
17812     }
17813     shellFinalize(&rc, pStmt);
17814 
17815     if( rc!=SQLITE_OK || nSqlCol<nCol ){
17816       goto finished;
17817     }
17818 
17819     shellPreparePrintf(dbtmp, &rc, &pStmt,
17820       "SELECT ("
17821       "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
17822       ") FROM sqlite_schema WHERE name = %Q", zName
17823     );
17824     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17825       bSqlIntkey = sqlite3_column_int(pStmt, 0);
17826     }
17827     shellFinalize(&rc, pStmt);
17828 
17829     if( bIntkey==bSqlIntkey ){
17830       int i;
17831       const char *zPk = "_rowid_";
17832       sqlite3_stmt *pPkFinder = 0;
17833 
17834       /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
17835       ** set zPk to the name of the PK column, and pTab->iPk to the index
17836       ** of the column, where columns are 0-numbered from left to right.
17837       ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
17838       ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
17839       pTab->iPk = -2;
17840       if( bIntkey ){
17841         shellPreparePrintf(dbtmp, &rc, &pPkFinder,
17842           "SELECT cid, name FROM pragma_table_info(%Q) "
17843           "  WHERE pk=1 AND type='integer' COLLATE nocase"
17844           "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
17845           , zName, zName
17846         );
17847         if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
17848           pTab->iPk = sqlite3_column_int(pPkFinder, 0);
17849           zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
17850         }
17851       }
17852 
17853       pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
17854       pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
17855       pTab->nCol = nSqlCol;
17856 
17857       if( bIntkey ){
17858         pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
17859       }else{
17860         pTab->azlCol[0] = shellMPrintf(&rc, "");
17861       }
17862       i = 1;
17863       shellPreparePrintf(dbtmp, &rc, &pStmt,
17864           "SELECT %Q || group_concat(shell_idquote(name), ', ') "
17865           "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
17866           "FROM pragma_table_info(%Q)",
17867           bIntkey ? ", " : "", pTab->iPk,
17868           bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
17869           zName
17870       );
17871       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17872         const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
17873         pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
17874         i++;
17875       }
17876       shellFinalize(&rc, pStmt);
17877 
17878       shellFinalize(&rc, pPkFinder);
17879     }
17880   }
17881 
17882  finished:
17883   sqlite3_close(dbtmp);
17884   *pRc = rc;
17885   if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
17886     recoverFreeTable(pTab);
17887     pTab = 0;
17888   }
17889   return pTab;
17890 }
17891 
17892 /*
17893 ** This function is called to search the schema recovered from the
17894 ** sqlite_schema table of the (possibly) corrupt database as part
17895 ** of a ".recover" command. Specifically, for a table with root page
17896 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
17897 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
17898 ** those.
17899 **
17900 ** If a table is found, a (RecoverTable*) object is returned. Or, if
17901 ** no such table is found, but bIntkey is false and iRoot is the
17902 ** root page of an index in the recovered schema, then (*pbNoop) is
17903 ** set to true and NULL returned. Or, if there is no such table or
17904 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
17905 ** the caller should write data to the orphans table.
17906 */
recoverFindTable(ShellState * pState,int * pRc,int iRoot,int bIntkey,int nCol,int * pbNoop)17907 static RecoverTable *recoverFindTable(
17908   ShellState *pState,             /* Shell state object */
17909   int *pRc,                       /* IN/OUT: Error code */
17910   int iRoot,                      /* Root page of table */
17911   int bIntkey,                    /* True for an intkey table */
17912   int nCol,                       /* Number of columns in table */
17913   int *pbNoop                     /* OUT: True if iRoot is root of index */
17914 ){
17915   sqlite3_stmt *pStmt = 0;
17916   RecoverTable *pRet = 0;
17917   int bNoop = 0;
17918   const char *zSql = 0;
17919   const char *zName = 0;
17920 
17921   /* Search the recovered schema for an object with root page iRoot. */
17922   shellPreparePrintf(pState->db, pRc, &pStmt,
17923       "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
17924   );
17925   while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17926     const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
17927     if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
17928       bNoop = 1;
17929       break;
17930     }
17931     if( sqlite3_stricmp(zType, "table")==0 ){
17932       zName = (const char*)sqlite3_column_text(pStmt, 1);
17933       zSql = (const char*)sqlite3_column_text(pStmt, 2);
17934       pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
17935       break;
17936     }
17937   }
17938 
17939   shellFinalize(pRc, pStmt);
17940   *pbNoop = bNoop;
17941   return pRet;
17942 }
17943 
17944 /*
17945 ** Return a RecoverTable object representing the orphans table.
17946 */
recoverOrphanTable(ShellState * pState,int * pRc,const char * zLostAndFound,int nCol)17947 static RecoverTable *recoverOrphanTable(
17948   ShellState *pState,             /* Shell state object */
17949   int *pRc,                       /* IN/OUT: Error code */
17950   const char *zLostAndFound,      /* Base name for orphans table */
17951   int nCol                        /* Number of user data columns */
17952 ){
17953   RecoverTable *pTab = 0;
17954   if( nCol>=0 && *pRc==SQLITE_OK ){
17955     int i;
17956 
17957     /* This block determines the name of the orphan table. The prefered
17958     ** name is zLostAndFound. But if that clashes with another name
17959     ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
17960     ** and so on until a non-clashing name is found.  */
17961     int iTab = 0;
17962     char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
17963     sqlite3_stmt *pTest = 0;
17964     shellPrepare(pState->db, pRc,
17965         "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
17966     );
17967     if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
17968     while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
17969       shellReset(pRc, pTest);
17970       sqlite3_free(zTab);
17971       zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
17972       sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
17973     }
17974     shellFinalize(pRc, pTest);
17975 
17976     pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
17977     if( pTab ){
17978       pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
17979       pTab->nCol = nCol;
17980       pTab->iPk = -2;
17981       if( nCol>0 ){
17982         pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
17983         if( pTab->azlCol ){
17984           pTab->azlCol[nCol] = shellMPrintf(pRc, "");
17985           for(i=nCol-1; i>=0; i--){
17986             pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
17987           }
17988         }
17989       }
17990 
17991       if( *pRc!=SQLITE_OK ){
17992         recoverFreeTable(pTab);
17993         pTab = 0;
17994       }else{
17995         raw_printf(pState->out,
17996             "CREATE TABLE %s(rootpgno INTEGER, "
17997             "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
17998         );
17999         for(i=0; i<nCol; i++){
18000           raw_printf(pState->out, ", c%d", i);
18001         }
18002         raw_printf(pState->out, ");\n");
18003       }
18004     }
18005     sqlite3_free(zTab);
18006   }
18007   return pTab;
18008 }
18009 
18010 /*
18011 ** This function is called to recover data from the database. A script
18012 ** to construct a new database containing all recovered data is output
18013 ** on stream pState->out.
18014 */
recoverDatabaseCmd(ShellState * pState,int nArg,char ** azArg)18015 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
18016   int rc = SQLITE_OK;
18017   sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
18018   sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
18019   sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
18020   const char *zRecoveryDb = "";   /* Name of "recovery" database */
18021   const char *zLostAndFound = "lost_and_found";
18022   int i;
18023   int nOrphan = -1;
18024   RecoverTable *pOrphan = 0;
18025 
18026   int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
18027   int bRowids = 1;                /* 0 if --no-rowids */
18028   for(i=1; i<nArg; i++){
18029     char *z = azArg[i];
18030     int n;
18031     if( z[0]=='-' && z[1]=='-' ) z++;
18032     n = strlen30(z);
18033     if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
18034       bFreelist = 0;
18035     }else
18036     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
18037       i++;
18038       zRecoveryDb = azArg[i];
18039     }else
18040     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
18041       i++;
18042       zLostAndFound = azArg[i];
18043     }else
18044     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
18045       bRowids = 0;
18046     }
18047     else{
18048       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
18049       showHelp(pState->out, azArg[0]);
18050       return 1;
18051     }
18052   }
18053 
18054   shellExecPrintf(pState->db, &rc,
18055     /* Attach an in-memory database named 'recovery'. Create an indexed
18056     ** cache of the sqlite_dbptr virtual table. */
18057     "PRAGMA writable_schema = on;"
18058     "ATTACH %Q AS recovery;"
18059     "DROP TABLE IF EXISTS recovery.dbptr;"
18060     "DROP TABLE IF EXISTS recovery.freelist;"
18061     "DROP TABLE IF EXISTS recovery.map;"
18062     "DROP TABLE IF EXISTS recovery.schema;"
18063     "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
18064   );
18065 
18066   if( bFreelist ){
18067     shellExec(pState->db, &rc,
18068       "WITH trunk(pgno) AS ("
18069       "  SELECT shell_int32("
18070       "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
18071       "      WHERE x>0"
18072       "    UNION"
18073       "  SELECT shell_int32("
18074       "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
18075       "      FROM trunk WHERE x>0"
18076       "),"
18077       "freelist(data, n, freepgno) AS ("
18078       "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
18079       "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
18080       "    UNION ALL"
18081       "  SELECT data, n-1, shell_int32(data, 2+n) "
18082       "      FROM freelist WHERE n>=0"
18083       ")"
18084       "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
18085     );
18086   }
18087 
18088   /* If this is an auto-vacuum database, add all pointer-map pages to
18089   ** the freelist table. Do this regardless of whether or not
18090   ** --freelist-corrupt was specified.  */
18091   shellExec(pState->db, &rc,
18092     "WITH ptrmap(pgno) AS ("
18093     "  SELECT 2 WHERE shell_int32("
18094     "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
18095     "  )"
18096     "    UNION ALL "
18097     "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
18098     "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
18099     ")"
18100     "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
18101   );
18102 
18103   shellExec(pState->db, &rc,
18104     "CREATE TABLE recovery.dbptr("
18105     "      pgno, child, PRIMARY KEY(child, pgno)"
18106     ") WITHOUT ROWID;"
18107     "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
18108     "    SELECT * FROM sqlite_dbptr"
18109     "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
18110 
18111     /* Delete any pointer to page 1. This ensures that page 1 is considered
18112     ** a root page, regardless of how corrupt the db is. */
18113     "DELETE FROM recovery.dbptr WHERE child = 1;"
18114 
18115     /* Delete all pointers to any pages that have more than one pointer
18116     ** to them. Such pages will be treated as root pages when recovering
18117     ** data.  */
18118     "DELETE FROM recovery.dbptr WHERE child IN ("
18119     "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
18120     ");"
18121 
18122     /* Create the "map" table that will (eventually) contain instructions
18123     ** for dealing with each page in the db that contains one or more
18124     ** records. */
18125     "CREATE TABLE recovery.map("
18126       "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
18127     ");"
18128 
18129     /* Populate table [map]. If there are circular loops of pages in the
18130     ** database, the following adds all pages in such a loop to the map
18131     ** as individual root pages. This could be handled better.  */
18132     "WITH pages(i, maxlen) AS ("
18133     "  SELECT page_count, ("
18134     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
18135     "  ) FROM pragma_page_count WHERE page_count>0"
18136     "    UNION ALL"
18137     "  SELECT i-1, ("
18138     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
18139     "  ) FROM pages WHERE i>=2"
18140     ")"
18141     "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
18142     "  SELECT i, maxlen, NULL, ("
18143     "    WITH p(orig, pgno, parent) AS ("
18144     "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
18145     "        UNION "
18146     "      SELECT i, p.parent, "
18147     "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
18148     "    )"
18149     "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
18150     ") "
18151     "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
18152     "UPDATE recovery.map AS o SET intkey = ("
18153     "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
18154     ");"
18155 
18156     /* Extract data from page 1 and any linked pages into table
18157     ** recovery.schema. With the same schema as an sqlite_schema table.  */
18158     "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
18159     "INSERT INTO recovery.schema SELECT "
18160     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
18161     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
18162     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
18163     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
18164     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
18165     "FROM sqlite_dbdata WHERE pgno IN ("
18166     "  SELECT pgno FROM recovery.map WHERE root=1"
18167     ")"
18168     "GROUP BY pgno, cell;"
18169     "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
18170   );
18171 
18172   /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
18173   ** CREATE TABLE statements that extracted from the existing schema.  */
18174   if( rc==SQLITE_OK ){
18175     sqlite3_stmt *pStmt = 0;
18176     /* ".recover" might output content in an order which causes immediate
18177     ** foreign key constraints to be violated. So disable foreign-key
18178     ** constraint enforcement to prevent problems when running the output
18179     ** script. */
18180     raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
18181     raw_printf(pState->out, "BEGIN;\n");
18182     raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
18183     shellPrepare(pState->db, &rc,
18184         "SELECT sql FROM recovery.schema "
18185         "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
18186     );
18187     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18188       const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
18189       raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
18190           &zCreateTable[12]
18191       );
18192     }
18193     shellFinalize(&rc, pStmt);
18194   }
18195 
18196   /* Figure out if an orphan table will be required. And if so, how many
18197   ** user columns it should contain */
18198   shellPrepare(pState->db, &rc,
18199       "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
18200       , &pLoop
18201   );
18202   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
18203     nOrphan = sqlite3_column_int(pLoop, 0);
18204   }
18205   shellFinalize(&rc, pLoop);
18206   pLoop = 0;
18207 
18208   shellPrepare(pState->db, &rc,
18209       "SELECT pgno FROM recovery.map WHERE root=?", &pPages
18210   );
18211 
18212   shellPrepare(pState->db, &rc,
18213       "SELECT max(field), group_concat(shell_escape_crnl(quote"
18214       "(case when (? AND field<0) then NULL else value end)"
18215       "), ', ')"
18216       ", min(field) "
18217       "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
18218       "GROUP BY cell", &pCells
18219   );
18220 
18221   /* Loop through each root page. */
18222   shellPrepare(pState->db, &rc,
18223       "SELECT root, intkey, max(maxlen) FROM recovery.map"
18224       " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
18225       "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
18226       ")", &pLoop
18227   );
18228   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
18229     int iRoot = sqlite3_column_int(pLoop, 0);
18230     int bIntkey = sqlite3_column_int(pLoop, 1);
18231     int nCol = sqlite3_column_int(pLoop, 2);
18232     int bNoop = 0;
18233     RecoverTable *pTab;
18234 
18235     assert( bIntkey==0 || bIntkey==1 );
18236     pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
18237     if( bNoop || rc ) continue;
18238     if( pTab==0 ){
18239       if( pOrphan==0 ){
18240         pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
18241       }
18242       pTab = pOrphan;
18243       if( pTab==0 ) break;
18244     }
18245 
18246     if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
18247       raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
18248     }
18249     sqlite3_bind_int(pPages, 1, iRoot);
18250     if( bRowids==0 && pTab->iPk<0 ){
18251       sqlite3_bind_int(pCells, 1, 1);
18252     }else{
18253       sqlite3_bind_int(pCells, 1, 0);
18254     }
18255     sqlite3_bind_int(pCells, 3, pTab->iPk);
18256 
18257     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
18258       int iPgno = sqlite3_column_int(pPages, 0);
18259       sqlite3_bind_int(pCells, 2, iPgno);
18260       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
18261         int nField = sqlite3_column_int(pCells, 0);
18262         int iMin = sqlite3_column_int(pCells, 2);
18263         const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
18264 
18265         RecoverTable *pTab2 = pTab;
18266         if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
18267           if( pOrphan==0 ){
18268             pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
18269           }
18270           pTab2 = pOrphan;
18271           if( pTab2==0 ) break;
18272         }
18273 
18274         nField = nField+1;
18275         if( pTab2==pOrphan ){
18276           raw_printf(pState->out,
18277               "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
18278               pTab2->zQuoted, iRoot, iPgno, nField,
18279               iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
18280           );
18281         }else{
18282           raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
18283               pTab2->zQuoted, pTab2->azlCol[nField], zVal
18284           );
18285         }
18286       }
18287       shellReset(&rc, pCells);
18288     }
18289     shellReset(&rc, pPages);
18290     if( pTab!=pOrphan ) recoverFreeTable(pTab);
18291   }
18292   shellFinalize(&rc, pLoop);
18293   shellFinalize(&rc, pPages);
18294   shellFinalize(&rc, pCells);
18295   recoverFreeTable(pOrphan);
18296 
18297   /* The rest of the schema */
18298   if( rc==SQLITE_OK ){
18299     sqlite3_stmt *pStmt = 0;
18300     shellPrepare(pState->db, &rc,
18301         "SELECT sql, name FROM recovery.schema "
18302         "WHERE sql NOT LIKE 'create table%'", &pStmt
18303     );
18304     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18305       const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
18306       if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
18307         const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
18308         char *zPrint = shellMPrintf(&rc,
18309           "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
18310           zName, zName, zSql
18311         );
18312         raw_printf(pState->out, "%s;\n", zPrint);
18313         sqlite3_free(zPrint);
18314       }else{
18315         raw_printf(pState->out, "%s;\n", zSql);
18316       }
18317     }
18318     shellFinalize(&rc, pStmt);
18319   }
18320 
18321   if( rc==SQLITE_OK ){
18322     raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
18323     raw_printf(pState->out, "COMMIT;\n");
18324   }
18325   sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
18326   return rc;
18327 }
18328 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
18329 
18330 
18331 /*
18332 ** If an input line begins with "." then invoke this routine to
18333 ** process that line.
18334 **
18335 ** Return 1 on error, 2 to exit, and 0 otherwise.
18336 */
do_meta_command(char * zLine,ShellState * p)18337 static int do_meta_command(char *zLine, ShellState *p){
18338   int h = 1;
18339   int nArg = 0;
18340   int n, c;
18341   int rc = 0;
18342   char *azArg[52];
18343 
18344 #ifndef SQLITE_OMIT_VIRTUALTABLE
18345   if( p->expert.pExpert ){
18346     expertFinish(p, 1, 0);
18347   }
18348 #endif
18349 
18350   /* Parse the input line into tokens.
18351   */
18352   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
18353     while( IsSpace(zLine[h]) ){ h++; }
18354     if( zLine[h]==0 ) break;
18355     if( zLine[h]=='\'' || zLine[h]=='"' ){
18356       int delim = zLine[h++];
18357       azArg[nArg++] = &zLine[h];
18358       while( zLine[h] && zLine[h]!=delim ){
18359         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
18360         h++;
18361       }
18362       if( zLine[h]==delim ){
18363         zLine[h++] = 0;
18364       }
18365       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
18366     }else{
18367       azArg[nArg++] = &zLine[h];
18368       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
18369       if( zLine[h] ) zLine[h++] = 0;
18370       resolve_backslashes(azArg[nArg-1]);
18371     }
18372   }
18373   azArg[nArg] = 0;
18374 
18375   /* Process the input line.
18376   */
18377   if( nArg==0 ) return 0; /* no tokens, no error */
18378   n = strlen30(azArg[0]);
18379   c = azArg[0][0];
18380   clearTempFile(p);
18381 
18382 #ifndef SQLITE_OMIT_AUTHORIZATION
18383   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
18384     if( nArg!=2 ){
18385       raw_printf(stderr, "Usage: .auth ON|OFF\n");
18386       rc = 1;
18387       goto meta_command_exit;
18388     }
18389     open_db(p, 0);
18390     if( booleanValue(azArg[1]) ){
18391       sqlite3_set_authorizer(p->db, shellAuth, p);
18392     }else{
18393       sqlite3_set_authorizer(p->db, 0, 0);
18394     }
18395   }else
18396 #endif
18397 
18398 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
18399   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
18400     open_db(p, 0);
18401     rc = arDotCommand(p, 0, azArg, nArg);
18402   }else
18403 #endif
18404 
18405   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
18406    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
18407   ){
18408     const char *zDestFile = 0;
18409     const char *zDb = 0;
18410     sqlite3 *pDest;
18411     sqlite3_backup *pBackup;
18412     int j;
18413     int bAsync = 0;
18414     const char *zVfs = 0;
18415     for(j=1; j<nArg; j++){
18416       const char *z = azArg[j];
18417       if( z[0]=='-' ){
18418         if( z[1]=='-' ) z++;
18419         if( strcmp(z, "-append")==0 ){
18420           zVfs = "apndvfs";
18421         }else
18422         if( strcmp(z, "-async")==0 ){
18423           bAsync = 1;
18424         }else
18425         {
18426           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
18427           return 1;
18428         }
18429       }else if( zDestFile==0 ){
18430         zDestFile = azArg[j];
18431       }else if( zDb==0 ){
18432         zDb = zDestFile;
18433         zDestFile = azArg[j];
18434       }else{
18435         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
18436         return 1;
18437       }
18438     }
18439     if( zDestFile==0 ){
18440       raw_printf(stderr, "missing FILENAME argument on .backup\n");
18441       return 1;
18442     }
18443     if( zDb==0 ) zDb = "main";
18444     rc = sqlite3_open_v2(zDestFile, &pDest,
18445                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
18446     if( rc!=SQLITE_OK ){
18447       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
18448       close_db(pDest);
18449       return 1;
18450     }
18451     if( bAsync ){
18452       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
18453                    0, 0, 0);
18454     }
18455     open_db(p, 0);
18456     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
18457     if( pBackup==0 ){
18458       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
18459       close_db(pDest);
18460       return 1;
18461     }
18462     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
18463     sqlite3_backup_finish(pBackup);
18464     if( rc==SQLITE_DONE ){
18465       rc = 0;
18466     }else{
18467       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
18468       rc = 1;
18469     }
18470     close_db(pDest);
18471   }else
18472 
18473   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
18474     if( nArg==2 ){
18475       bail_on_error = booleanValue(azArg[1]);
18476     }else{
18477       raw_printf(stderr, "Usage: .bail on|off\n");
18478       rc = 1;
18479     }
18480   }else
18481 
18482   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
18483     if( nArg==2 ){
18484       if( booleanValue(azArg[1]) ){
18485         setBinaryMode(p->out, 1);
18486       }else{
18487         setTextMode(p->out, 1);
18488       }
18489     }else{
18490       raw_printf(stderr, "Usage: .binary on|off\n");
18491       rc = 1;
18492     }
18493   }else
18494 
18495   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
18496     if( nArg==2 ){
18497 #if defined(_WIN32) || defined(WIN32)
18498       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
18499       rc = !SetCurrentDirectoryW(z);
18500       sqlite3_free(z);
18501 #else
18502       rc = chdir(azArg[1]);
18503 #endif
18504       if( rc ){
18505         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
18506         rc = 1;
18507       }
18508     }else{
18509       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
18510       rc = 1;
18511     }
18512   }else
18513 
18514   /* The undocumented ".breakpoint" command causes a call to the no-op
18515   ** routine named test_breakpoint().
18516   */
18517   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
18518     test_breakpoint();
18519   }else
18520 
18521   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
18522     if( nArg==2 ){
18523       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
18524     }else{
18525       raw_printf(stderr, "Usage: .changes on|off\n");
18526       rc = 1;
18527     }
18528   }else
18529 
18530   /* Cancel output redirection, if it is currently set (by .testcase)
18531   ** Then read the content of the testcase-out.txt file and compare against
18532   ** azArg[1].  If there are differences, report an error and exit.
18533   */
18534   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
18535     char *zRes = 0;
18536     output_reset(p);
18537     if( nArg!=2 ){
18538       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
18539       rc = 2;
18540     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
18541       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
18542       rc = 2;
18543     }else if( testcase_glob(azArg[1],zRes)==0 ){
18544       utf8_printf(stderr,
18545                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
18546                  p->zTestcase, azArg[1], zRes);
18547       rc = 1;
18548     }else{
18549       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
18550       p->nCheck++;
18551     }
18552     sqlite3_free(zRes);
18553   }else
18554 
18555   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
18556     if( nArg==2 ){
18557       tryToClone(p, azArg[1]);
18558     }else{
18559       raw_printf(stderr, "Usage: .clone FILENAME\n");
18560       rc = 1;
18561     }
18562   }else
18563 
18564   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
18565     char **azName = 0;
18566     int nName = 0;
18567     sqlite3_stmt *pStmt;
18568     int i;
18569     open_db(p, 0);
18570     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
18571     if( rc ){
18572       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
18573       rc = 1;
18574     }else{
18575       while( sqlite3_step(pStmt)==SQLITE_ROW ){
18576         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
18577         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
18578         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
18579         if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
18580         azName[nName*2] = strdup(zSchema);
18581         azName[nName*2+1] = strdup(zFile);
18582         nName++;
18583       }
18584     }
18585     sqlite3_finalize(pStmt);
18586     for(i=0; i<nName; i++){
18587       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
18588       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
18589       const char *z = azName[i*2+1];
18590       utf8_printf(p->out, "%s: %s %s%s\n",
18591          azName[i*2],
18592          z && z[0] ? z : "\"\"",
18593          bRdonly ? "r/o" : "r/w",
18594          eTxn==SQLITE_TXN_NONE ? "" :
18595             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
18596       free(azName[i*2]);
18597       free(azName[i*2+1]);
18598     }
18599     sqlite3_free(azName);
18600   }else
18601 
18602   if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
18603     static const struct DbConfigChoices {
18604       const char *zName;
18605       int op;
18606     } aDbConfig[] = {
18607         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
18608         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
18609         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
18610         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
18611         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
18612         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
18613         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
18614         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
18615         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
18616         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
18617         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
18618         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
18619         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
18620         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
18621         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
18622         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
18623     };
18624     int ii, v;
18625     open_db(p, 0);
18626     for(ii=0; ii<ArraySize(aDbConfig); ii++){
18627       if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
18628       if( nArg>=3 ){
18629         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
18630       }
18631       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
18632       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
18633       if( nArg>1 ) break;
18634     }
18635     if( nArg>1 && ii==ArraySize(aDbConfig) ){
18636       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
18637       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
18638     }
18639   }else
18640 
18641   if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
18642     rc = shell_dbinfo_command(p, nArg, azArg);
18643   }else
18644 
18645 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
18646   if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
18647     open_db(p, 0);
18648     rc = recoverDatabaseCmd(p, nArg, azArg);
18649   }else
18650 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
18651 
18652   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
18653     char *zLike = 0;
18654     char *zSql;
18655     int i;
18656     int savedShowHeader = p->showHeader;
18657     int savedShellFlags = p->shellFlgs;
18658     ShellClearFlag(p,
18659        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
18660        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
18661     for(i=1; i<nArg; i++){
18662       if( azArg[i][0]=='-' ){
18663         const char *z = azArg[i]+1;
18664         if( z[0]=='-' ) z++;
18665         if( strcmp(z,"preserve-rowids")==0 ){
18666 #ifdef SQLITE_OMIT_VIRTUALTABLE
18667           raw_printf(stderr, "The --preserve-rowids option is not compatible"
18668                              " with SQLITE_OMIT_VIRTUALTABLE\n");
18669           rc = 1;
18670           sqlite3_free(zLike);
18671           goto meta_command_exit;
18672 #else
18673           ShellSetFlag(p, SHFLG_PreserveRowid);
18674 #endif
18675         }else
18676         if( strcmp(z,"newlines")==0 ){
18677           ShellSetFlag(p, SHFLG_Newlines);
18678         }else
18679         if( strcmp(z,"data-only")==0 ){
18680           ShellSetFlag(p, SHFLG_DumpDataOnly);
18681         }else
18682         if( strcmp(z,"nosys")==0 ){
18683           ShellSetFlag(p, SHFLG_DumpNoSys);
18684         }else
18685         {
18686           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
18687           rc = 1;
18688           sqlite3_free(zLike);
18689           goto meta_command_exit;
18690         }
18691       }else{
18692         /* azArg[i] contains a LIKE pattern. This ".dump" request should
18693         ** only dump data for tables for which either the table name matches
18694         ** the LIKE pattern, or the table appears to be a shadow table of
18695         ** a virtual table for which the name matches the LIKE pattern.
18696         */
18697         char *zExpr = sqlite3_mprintf(
18698             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
18699             "  SELECT 1 FROM sqlite_schema WHERE "
18700             "    name LIKE %Q ESCAPE '\\' AND"
18701             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
18702             "    substr(o.name, 1, length(name)+1) == (name||'_')"
18703             ")", azArg[i], azArg[i]
18704         );
18705 
18706         if( zLike ){
18707           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
18708         }else{
18709           zLike = zExpr;
18710         }
18711       }
18712     }
18713 
18714     open_db(p, 0);
18715 
18716     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
18717       /* When playing back a "dump", the content might appear in an order
18718       ** which causes immediate foreign key constraints to be violated.
18719       ** So disable foreign-key constraint enforcement to prevent problems. */
18720       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
18721       raw_printf(p->out, "BEGIN TRANSACTION;\n");
18722     }
18723     p->writableSchema = 0;
18724     p->showHeader = 0;
18725     /* Set writable_schema=ON since doing so forces SQLite to initialize
18726     ** as much of the schema as it can even if the sqlite_schema table is
18727     ** corrupt. */
18728     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
18729     p->nErr = 0;
18730     if( zLike==0 ) zLike = sqlite3_mprintf("true");
18731     zSql = sqlite3_mprintf(
18732       "SELECT name, type, sql FROM sqlite_schema AS o "
18733       "WHERE (%s) AND type=='table'"
18734       "  AND sql NOT NULL"
18735       " ORDER BY tbl_name='sqlite_sequence', rowid",
18736       zLike
18737     );
18738     run_schema_dump_query(p,zSql);
18739     sqlite3_free(zSql);
18740     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
18741       zSql = sqlite3_mprintf(
18742         "SELECT sql FROM sqlite_schema AS o "
18743         "WHERE (%s) AND sql NOT NULL"
18744         "  AND type IN ('index','trigger','view')",
18745         zLike
18746       );
18747       run_table_dump_query(p, zSql);
18748       sqlite3_free(zSql);
18749     }
18750     sqlite3_free(zLike);
18751     if( p->writableSchema ){
18752       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
18753       p->writableSchema = 0;
18754     }
18755     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
18756     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
18757     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
18758       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
18759     }
18760     p->showHeader = savedShowHeader;
18761     p->shellFlgs = savedShellFlags;
18762   }else
18763 
18764   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
18765     if( nArg==2 ){
18766       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
18767     }else{
18768       raw_printf(stderr, "Usage: .echo on|off\n");
18769       rc = 1;
18770     }
18771   }else
18772 
18773   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
18774     if( nArg==2 ){
18775       p->autoEQPtest = 0;
18776       if( p->autoEQPtrace ){
18777         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
18778         p->autoEQPtrace = 0;
18779       }
18780       if( strcmp(azArg[1],"full")==0 ){
18781         p->autoEQP = AUTOEQP_full;
18782       }else if( strcmp(azArg[1],"trigger")==0 ){
18783         p->autoEQP = AUTOEQP_trigger;
18784 #ifdef SQLITE_DEBUG
18785       }else if( strcmp(azArg[1],"test")==0 ){
18786         p->autoEQP = AUTOEQP_on;
18787         p->autoEQPtest = 1;
18788       }else if( strcmp(azArg[1],"trace")==0 ){
18789         p->autoEQP = AUTOEQP_full;
18790         p->autoEQPtrace = 1;
18791         open_db(p, 0);
18792         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
18793         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
18794 #endif
18795       }else{
18796         p->autoEQP = (u8)booleanValue(azArg[1]);
18797       }
18798     }else{
18799       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
18800       rc = 1;
18801     }
18802   }else
18803 
18804   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
18805     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
18806     rc = 2;
18807   }else
18808 
18809   /* The ".explain" command is automatic now.  It is largely pointless.  It
18810   ** retained purely for backwards compatibility */
18811   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
18812     int val = 1;
18813     if( nArg>=2 ){
18814       if( strcmp(azArg[1],"auto")==0 ){
18815         val = 99;
18816       }else{
18817         val =  booleanValue(azArg[1]);
18818       }
18819     }
18820     if( val==1 && p->mode!=MODE_Explain ){
18821       p->normalMode = p->mode;
18822       p->mode = MODE_Explain;
18823       p->autoExplain = 0;
18824     }else if( val==0 ){
18825       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
18826       p->autoExplain = 0;
18827     }else if( val==99 ){
18828       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
18829       p->autoExplain = 1;
18830     }
18831   }else
18832 
18833 #ifndef SQLITE_OMIT_VIRTUALTABLE
18834   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
18835     open_db(p, 0);
18836     expertDotCommand(p, azArg, nArg);
18837   }else
18838 #endif
18839 
18840   if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
18841     static const struct {
18842        const char *zCtrlName;   /* Name of a test-control option */
18843        int ctrlCode;            /* Integer code for that option */
18844        const char *zUsage;      /* Usage notes */
18845     } aCtrl[] = {
18846       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
18847       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
18848       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
18849       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
18850       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
18851    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
18852       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
18853       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
18854       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
18855       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
18856    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
18857     };
18858     int filectrl = -1;
18859     int iCtrl = -1;
18860     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
18861     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
18862     int n2, i;
18863     const char *zCmd = 0;
18864     const char *zSchema = 0;
18865 
18866     open_db(p, 0);
18867     zCmd = nArg>=2 ? azArg[1] : "help";
18868 
18869     if( zCmd[0]=='-'
18870      && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
18871      && nArg>=4
18872     ){
18873       zSchema = azArg[2];
18874       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
18875       nArg -= 2;
18876       zCmd = azArg[1];
18877     }
18878 
18879     /* The argument can optionally begin with "-" or "--" */
18880     if( zCmd[0]=='-' && zCmd[1] ){
18881       zCmd++;
18882       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
18883     }
18884 
18885     /* --help lists all file-controls */
18886     if( strcmp(zCmd,"help")==0 ){
18887       utf8_printf(p->out, "Available file-controls:\n");
18888       for(i=0; i<ArraySize(aCtrl); i++){
18889         utf8_printf(p->out, "  .filectrl %s %s\n",
18890                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
18891       }
18892       rc = 1;
18893       goto meta_command_exit;
18894     }
18895 
18896     /* convert filectrl text option to value. allow any unique prefix
18897     ** of the option name, or a numerical value. */
18898     n2 = strlen30(zCmd);
18899     for(i=0; i<ArraySize(aCtrl); i++){
18900       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
18901         if( filectrl<0 ){
18902           filectrl = aCtrl[i].ctrlCode;
18903           iCtrl = i;
18904         }else{
18905           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
18906                               "Use \".filectrl --help\" for help\n", zCmd);
18907           rc = 1;
18908           goto meta_command_exit;
18909         }
18910       }
18911     }
18912     if( filectrl<0 ){
18913       utf8_printf(stderr,"Error: unknown file-control: %s\n"
18914                          "Use \".filectrl --help\" for help\n", zCmd);
18915     }else{
18916       switch(filectrl){
18917         case SQLITE_FCNTL_SIZE_LIMIT: {
18918           if( nArg!=2 && nArg!=3 ) break;
18919           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
18920           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
18921           isOk = 1;
18922           break;
18923         }
18924         case SQLITE_FCNTL_LOCK_TIMEOUT:
18925         case SQLITE_FCNTL_CHUNK_SIZE: {
18926           int x;
18927           if( nArg!=3 ) break;
18928           x = (int)integerValue(azArg[2]);
18929           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18930           isOk = 2;
18931           break;
18932         }
18933         case SQLITE_FCNTL_PERSIST_WAL:
18934         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
18935           int x;
18936           if( nArg!=2 && nArg!=3 ) break;
18937           x = nArg==3 ? booleanValue(azArg[2]) : -1;
18938           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18939           iRes = x;
18940           isOk = 1;
18941           break;
18942         }
18943         case SQLITE_FCNTL_DATA_VERSION:
18944         case SQLITE_FCNTL_HAS_MOVED: {
18945           int x;
18946           if( nArg!=2 ) break;
18947           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18948           iRes = x;
18949           isOk = 1;
18950           break;
18951         }
18952         case SQLITE_FCNTL_TEMPFILENAME: {
18953           char *z = 0;
18954           if( nArg!=2 ) break;
18955           sqlite3_file_control(p->db, zSchema, filectrl, &z);
18956           if( z ){
18957             utf8_printf(p->out, "%s\n", z);
18958             sqlite3_free(z);
18959           }
18960           isOk = 2;
18961           break;
18962         }
18963         case SQLITE_FCNTL_RESERVE_BYTES: {
18964           int x;
18965           if( nArg>=3 ){
18966             x = atoi(azArg[2]);
18967             sqlite3_file_control(p->db, zSchema, filectrl, &x);
18968           }
18969           x = -1;
18970           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18971           utf8_printf(p->out,"%d\n", x);
18972           isOk = 2;
18973           break;
18974         }
18975       }
18976     }
18977     if( isOk==0 && iCtrl>=0 ){
18978       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
18979       rc = 1;
18980     }else if( isOk==1 ){
18981       char zBuf[100];
18982       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
18983       raw_printf(p->out, "%s\n", zBuf);
18984     }
18985   }else
18986 
18987   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
18988     ShellState data;
18989     int doStats = 0;
18990     memcpy(&data, p, sizeof(data));
18991     data.showHeader = 0;
18992     data.cMode = data.mode = MODE_Semi;
18993     if( nArg==2 && optionMatch(azArg[1], "indent") ){
18994       data.cMode = data.mode = MODE_Pretty;
18995       nArg = 1;
18996     }
18997     if( nArg!=1 ){
18998       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
18999       rc = 1;
19000       goto meta_command_exit;
19001     }
19002     open_db(p, 0);
19003     rc = sqlite3_exec(p->db,
19004        "SELECT sql FROM"
19005        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
19006        "     FROM sqlite_schema UNION ALL"
19007        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
19008        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
19009        "ORDER BY rowid",
19010        callback, &data, 0
19011     );
19012     if( rc==SQLITE_OK ){
19013       sqlite3_stmt *pStmt;
19014       rc = sqlite3_prepare_v2(p->db,
19015                "SELECT rowid FROM sqlite_schema"
19016                " WHERE name GLOB 'sqlite_stat[134]'",
19017                -1, &pStmt, 0);
19018       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
19019       sqlite3_finalize(pStmt);
19020     }
19021     if( doStats==0 ){
19022       raw_printf(p->out, "/* No STAT tables available */\n");
19023     }else{
19024       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
19025       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'",
19026                    callback, &data, 0);
19027       data.cMode = data.mode = MODE_Insert;
19028       data.zDestTable = "sqlite_stat1";
19029       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
19030       data.zDestTable = "sqlite_stat4";
19031       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
19032       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
19033     }
19034   }else
19035 
19036   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
19037     if( nArg==2 ){
19038       p->showHeader = booleanValue(azArg[1]);
19039       p->shellFlgs |= SHFLG_HeaderSet;
19040     }else{
19041       raw_printf(stderr, "Usage: .headers on|off\n");
19042       rc = 1;
19043     }
19044   }else
19045 
19046   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
19047     if( nArg>=2 ){
19048       n = showHelp(p->out, azArg[1]);
19049       if( n==0 ){
19050         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
19051       }
19052     }else{
19053       showHelp(p->out, 0);
19054     }
19055   }else
19056 
19057   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
19058     char *zTable = 0;           /* Insert data into this table */
19059     char *zFile = 0;            /* Name of file to extra content from */
19060     sqlite3_stmt *pStmt = NULL; /* A statement */
19061     int nCol;                   /* Number of columns in the table */
19062     int nByte;                  /* Number of bytes in an SQL string */
19063     int i, j;                   /* Loop counters */
19064     int needCommit;             /* True to COMMIT or ROLLBACK at end */
19065     int nSep;                   /* Number of bytes in p->colSeparator[] */
19066     char *zSql;                 /* An SQL statement */
19067     ImportCtx sCtx;             /* Reader context */
19068     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
19069     int eVerbose = 0;           /* Larger for more console output */
19070     int nSkip = 0;              /* Initial lines to skip */
19071     int useOutputMode = 1;      /* Use output mode to determine separators */
19072 
19073     memset(&sCtx, 0, sizeof(sCtx));
19074     if( p->mode==MODE_Ascii ){
19075       xRead = ascii_read_one_field;
19076     }else{
19077       xRead = csv_read_one_field;
19078     }
19079     for(i=1; i<nArg; i++){
19080       char *z = azArg[i];
19081       if( z[0]=='-' && z[1]=='-' ) z++;
19082       if( z[0]!='-' ){
19083         if( zFile==0 ){
19084           zFile = z;
19085         }else if( zTable==0 ){
19086           zTable = z;
19087         }else{
19088           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
19089           showHelp(p->out, "import");
19090           rc = 1;
19091           goto meta_command_exit;
19092         }
19093       }else if( strcmp(z,"-v")==0 ){
19094         eVerbose++;
19095       }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
19096         nSkip = integerValue(azArg[++i]);
19097       }else if( strcmp(z,"-ascii")==0 ){
19098         sCtx.cColSep = SEP_Unit[0];
19099         sCtx.cRowSep = SEP_Record[0];
19100         xRead = ascii_read_one_field;
19101         useOutputMode = 0;
19102       }else if( strcmp(z,"-csv")==0 ){
19103         sCtx.cColSep = ',';
19104         sCtx.cRowSep = '\n';
19105         xRead = csv_read_one_field;
19106         useOutputMode = 0;
19107       }else{
19108         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
19109         showHelp(p->out, "import");
19110         rc = 1;
19111         goto meta_command_exit;
19112       }
19113     }
19114     if( zTable==0 ){
19115       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
19116                   zFile==0 ? "FILE" : "TABLE");
19117       showHelp(p->out, "import");
19118       rc = 1;
19119       goto meta_command_exit;
19120     }
19121     seenInterrupt = 0;
19122     open_db(p, 0);
19123     if( useOutputMode ){
19124       /* If neither the --csv or --ascii options are specified, then set
19125       ** the column and row separator characters from the output mode. */
19126       nSep = strlen30(p->colSeparator);
19127       if( nSep==0 ){
19128         raw_printf(stderr,
19129                    "Error: non-null column separator required for import\n");
19130         rc = 1;
19131         goto meta_command_exit;
19132       }
19133       if( nSep>1 ){
19134         raw_printf(stderr,
19135               "Error: multi-character column separators not allowed"
19136               " for import\n");
19137         rc = 1;
19138         goto meta_command_exit;
19139       }
19140       nSep = strlen30(p->rowSeparator);
19141       if( nSep==0 ){
19142         raw_printf(stderr,
19143             "Error: non-null row separator required for import\n");
19144         rc = 1;
19145         goto meta_command_exit;
19146       }
19147       if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
19148         /* When importing CSV (only), if the row separator is set to the
19149         ** default output row separator, change it to the default input
19150         ** row separator.  This avoids having to maintain different input
19151         ** and output row separators. */
19152         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
19153         nSep = strlen30(p->rowSeparator);
19154       }
19155       if( nSep>1 ){
19156         raw_printf(stderr, "Error: multi-character row separators not allowed"
19157                            " for import\n");
19158         rc = 1;
19159         goto meta_command_exit;
19160       }
19161       sCtx.cColSep = p->colSeparator[0];
19162       sCtx.cRowSep = p->rowSeparator[0];
19163     }
19164     sCtx.zFile = zFile;
19165     sCtx.nLine = 1;
19166     if( sCtx.zFile[0]=='|' ){
19167 #ifdef SQLITE_OMIT_POPEN
19168       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
19169       rc = 1;
19170       goto meta_command_exit;
19171 #else
19172       sCtx.in = popen(sCtx.zFile+1, "r");
19173       sCtx.zFile = "<pipe>";
19174       sCtx.xCloser = pclose;
19175 #endif
19176     }else{
19177       sCtx.in = fopen(sCtx.zFile, "rb");
19178       sCtx.xCloser = fclose;
19179     }
19180     if( sCtx.in==0 ){
19181       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
19182       rc = 1;
19183       goto meta_command_exit;
19184     }
19185     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
19186       char zSep[2];
19187       zSep[1] = 0;
19188       zSep[0] = sCtx.cColSep;
19189       utf8_printf(p->out, "Column separator ");
19190       output_c_string(p->out, zSep);
19191       utf8_printf(p->out, ", row separator ");
19192       zSep[0] = sCtx.cRowSep;
19193       output_c_string(p->out, zSep);
19194       utf8_printf(p->out, "\n");
19195     }
19196     while( (nSkip--)>0 ){
19197       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
19198     }
19199     zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
19200     if( zSql==0 ){
19201       import_cleanup(&sCtx);
19202       shell_out_of_memory();
19203     }
19204     nByte = strlen30(zSql);
19205     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19206     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
19207     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
19208       char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
19209       char cSep = '(';
19210       while( xRead(&sCtx) ){
19211         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
19212         cSep = ',';
19213         if( sCtx.cTerm!=sCtx.cColSep ) break;
19214       }
19215       if( cSep=='(' ){
19216         sqlite3_free(zCreate);
19217         import_cleanup(&sCtx);
19218         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
19219         rc = 1;
19220         goto meta_command_exit;
19221       }
19222       zCreate = sqlite3_mprintf("%z\n)", zCreate);
19223       if( eVerbose>=1 ){
19224         utf8_printf(p->out, "%s\n", zCreate);
19225       }
19226       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
19227       sqlite3_free(zCreate);
19228       if( rc ){
19229         utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
19230                 sqlite3_errmsg(p->db));
19231         import_cleanup(&sCtx);
19232         rc = 1;
19233         goto meta_command_exit;
19234       }
19235       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19236     }
19237     sqlite3_free(zSql);
19238     if( rc ){
19239       if (pStmt) sqlite3_finalize(pStmt);
19240       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
19241       import_cleanup(&sCtx);
19242       rc = 1;
19243       goto meta_command_exit;
19244     }
19245     nCol = sqlite3_column_count(pStmt);
19246     sqlite3_finalize(pStmt);
19247     pStmt = 0;
19248     if( nCol==0 ) return 0; /* no columns, no error */
19249     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
19250     if( zSql==0 ){
19251       import_cleanup(&sCtx);
19252       shell_out_of_memory();
19253     }
19254     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
19255     j = strlen30(zSql);
19256     for(i=1; i<nCol; i++){
19257       zSql[j++] = ',';
19258       zSql[j++] = '?';
19259     }
19260     zSql[j++] = ')';
19261     zSql[j] = 0;
19262     if( eVerbose>=2 ){
19263       utf8_printf(p->out, "Insert using: %s\n", zSql);
19264     }
19265     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19266     sqlite3_free(zSql);
19267     if( rc ){
19268       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19269       if (pStmt) sqlite3_finalize(pStmt);
19270       import_cleanup(&sCtx);
19271       rc = 1;
19272       goto meta_command_exit;
19273     }
19274     needCommit = sqlite3_get_autocommit(p->db);
19275     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
19276     do{
19277       int startLine = sCtx.nLine;
19278       for(i=0; i<nCol; i++){
19279         char *z = xRead(&sCtx);
19280         /*
19281         ** Did we reach end-of-file before finding any columns?
19282         ** If so, stop instead of NULL filling the remaining columns.
19283         */
19284         if( z==0 && i==0 ) break;
19285         /*
19286         ** Did we reach end-of-file OR end-of-line before finding any
19287         ** columns in ASCII mode?  If so, stop instead of NULL filling
19288         ** the remaining columns.
19289         */
19290         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
19291         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
19292         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
19293           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
19294                           "filling the rest with NULL\n",
19295                           sCtx.zFile, startLine, nCol, i+1);
19296           i += 2;
19297           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
19298         }
19299       }
19300       if( sCtx.cTerm==sCtx.cColSep ){
19301         do{
19302           xRead(&sCtx);
19303           i++;
19304         }while( sCtx.cTerm==sCtx.cColSep );
19305         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
19306                         "extras ignored\n",
19307                         sCtx.zFile, startLine, nCol, i);
19308       }
19309       if( i>=nCol ){
19310         sqlite3_step(pStmt);
19311         rc = sqlite3_reset(pStmt);
19312         if( rc!=SQLITE_OK ){
19313           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
19314                       startLine, sqlite3_errmsg(p->db));
19315           sCtx.nErr++;
19316         }else{
19317           sCtx.nRow++;
19318         }
19319       }
19320     }while( sCtx.cTerm!=EOF );
19321 
19322     import_cleanup(&sCtx);
19323     sqlite3_finalize(pStmt);
19324     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
19325     if( eVerbose>0 ){
19326       utf8_printf(p->out,
19327           "Added %d rows with %d errors using %d lines of input\n",
19328           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
19329     }
19330   }else
19331 
19332 #ifndef SQLITE_UNTESTABLE
19333   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
19334     char *zSql;
19335     char *zCollist = 0;
19336     sqlite3_stmt *pStmt;
19337     int tnum = 0;
19338     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
19339     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
19340     int i;
19341     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
19342       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
19343                           "       .imposter off\n");
19344       /* Also allowed, but not documented:
19345       **
19346       **    .imposter TABLE IMPOSTER
19347       **
19348       ** where TABLE is a WITHOUT ROWID table.  In that case, the
19349       ** imposter is another WITHOUT ROWID table with the columns in
19350       ** storage order. */
19351       rc = 1;
19352       goto meta_command_exit;
19353     }
19354     open_db(p, 0);
19355     if( nArg==2 ){
19356       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
19357       goto meta_command_exit;
19358     }
19359     zSql = sqlite3_mprintf(
19360       "SELECT rootpage, 0 FROM sqlite_schema"
19361       " WHERE name='%q' AND type='index'"
19362       "UNION ALL "
19363       "SELECT rootpage, 1 FROM sqlite_schema"
19364       " WHERE name='%q' AND type='table'"
19365       "   AND sql LIKE '%%without%%rowid%%'",
19366       azArg[1], azArg[1]
19367     );
19368     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19369     sqlite3_free(zSql);
19370     if( sqlite3_step(pStmt)==SQLITE_ROW ){
19371       tnum = sqlite3_column_int(pStmt, 0);
19372       isWO = sqlite3_column_int(pStmt, 1);
19373     }
19374     sqlite3_finalize(pStmt);
19375     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
19376     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19377     sqlite3_free(zSql);
19378     i = 0;
19379     while( sqlite3_step(pStmt)==SQLITE_ROW ){
19380       char zLabel[20];
19381       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
19382       i++;
19383       if( zCol==0 ){
19384         if( sqlite3_column_int(pStmt,1)==-1 ){
19385           zCol = "_ROWID_";
19386         }else{
19387           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
19388           zCol = zLabel;
19389         }
19390       }
19391       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
19392         lenPK = (int)strlen(zCollist);
19393       }
19394       if( zCollist==0 ){
19395         zCollist = sqlite3_mprintf("\"%w\"", zCol);
19396       }else{
19397         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
19398       }
19399     }
19400     sqlite3_finalize(pStmt);
19401     if( i==0 || tnum==0 ){
19402       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
19403       rc = 1;
19404       sqlite3_free(zCollist);
19405       goto meta_command_exit;
19406     }
19407     if( lenPK==0 ) lenPK = 100000;
19408     zSql = sqlite3_mprintf(
19409           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
19410           azArg[2], zCollist, lenPK, zCollist);
19411     sqlite3_free(zCollist);
19412     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
19413     if( rc==SQLITE_OK ){
19414       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
19415       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
19416       if( rc ){
19417         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
19418       }else{
19419         utf8_printf(stdout, "%s;\n", zSql);
19420         raw_printf(stdout,
19421           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
19422           azArg[1], isWO ? "table" : "index"
19423         );
19424       }
19425     }else{
19426       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
19427       rc = 1;
19428     }
19429     sqlite3_free(zSql);
19430   }else
19431 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
19432 
19433 #ifdef SQLITE_ENABLE_IOTRACE
19434   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
19435     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
19436     if( iotrace && iotrace!=stdout ) fclose(iotrace);
19437     iotrace = 0;
19438     if( nArg<2 ){
19439       sqlite3IoTrace = 0;
19440     }else if( strcmp(azArg[1], "-")==0 ){
19441       sqlite3IoTrace = iotracePrintf;
19442       iotrace = stdout;
19443     }else{
19444       iotrace = fopen(azArg[1], "w");
19445       if( iotrace==0 ){
19446         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
19447         sqlite3IoTrace = 0;
19448         rc = 1;
19449       }else{
19450         sqlite3IoTrace = iotracePrintf;
19451       }
19452     }
19453   }else
19454 #endif
19455 
19456   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
19457     static const struct {
19458        const char *zLimitName;   /* Name of a limit */
19459        int limitCode;            /* Integer code for that limit */
19460     } aLimit[] = {
19461       { "length",                SQLITE_LIMIT_LENGTH                    },
19462       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
19463       { "column",                SQLITE_LIMIT_COLUMN                    },
19464       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
19465       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
19466       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
19467       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
19468       { "attached",              SQLITE_LIMIT_ATTACHED                  },
19469       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
19470       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
19471       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
19472       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
19473     };
19474     int i, n2;
19475     open_db(p, 0);
19476     if( nArg==1 ){
19477       for(i=0; i<ArraySize(aLimit); i++){
19478         printf("%20s %d\n", aLimit[i].zLimitName,
19479                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
19480       }
19481     }else if( nArg>3 ){
19482       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
19483       rc = 1;
19484       goto meta_command_exit;
19485     }else{
19486       int iLimit = -1;
19487       n2 = strlen30(azArg[1]);
19488       for(i=0; i<ArraySize(aLimit); i++){
19489         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
19490           if( iLimit<0 ){
19491             iLimit = i;
19492           }else{
19493             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
19494             rc = 1;
19495             goto meta_command_exit;
19496           }
19497         }
19498       }
19499       if( iLimit<0 ){
19500         utf8_printf(stderr, "unknown limit: \"%s\"\n"
19501                         "enter \".limits\" with no arguments for a list.\n",
19502                          azArg[1]);
19503         rc = 1;
19504         goto meta_command_exit;
19505       }
19506       if( nArg==3 ){
19507         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
19508                       (int)integerValue(azArg[2]));
19509       }
19510       printf("%20s %d\n", aLimit[iLimit].zLimitName,
19511              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
19512     }
19513   }else
19514 
19515   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
19516     open_db(p, 0);
19517     lintDotCommand(p, azArg, nArg);
19518   }else
19519 
19520 #ifndef SQLITE_OMIT_LOAD_EXTENSION
19521   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
19522     const char *zFile, *zProc;
19523     char *zErrMsg = 0;
19524     if( nArg<2 ){
19525       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
19526       rc = 1;
19527       goto meta_command_exit;
19528     }
19529     zFile = azArg[1];
19530     zProc = nArg>=3 ? azArg[2] : 0;
19531     open_db(p, 0);
19532     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
19533     if( rc!=SQLITE_OK ){
19534       utf8_printf(stderr, "Error: %s\n", zErrMsg);
19535       sqlite3_free(zErrMsg);
19536       rc = 1;
19537     }
19538   }else
19539 #endif
19540 
19541   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
19542     if( nArg!=2 ){
19543       raw_printf(stderr, "Usage: .log FILENAME\n");
19544       rc = 1;
19545     }else{
19546       const char *zFile = azArg[1];
19547       output_file_close(p->pLog);
19548       p->pLog = output_file_open(zFile, 0);
19549     }
19550   }else
19551 
19552   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
19553     const char *zMode = nArg>=2 ? azArg[1] : "";
19554     int n2 = strlen30(zMode);
19555     int c2 = zMode[0];
19556     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
19557       p->mode = MODE_Line;
19558       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
19559     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
19560       p->mode = MODE_Column;
19561       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
19562         p->showHeader = 1;
19563       }
19564       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
19565     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
19566       p->mode = MODE_List;
19567       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
19568       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
19569     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
19570       p->mode = MODE_Html;
19571     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
19572       p->mode = MODE_Tcl;
19573       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
19574       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
19575     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
19576       p->mode = MODE_Csv;
19577       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
19578       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
19579     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
19580       p->mode = MODE_List;
19581       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
19582     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
19583       p->mode = MODE_Insert;
19584       set_table_name(p, nArg>=3 ? azArg[2] : "table");
19585     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
19586       p->mode = MODE_Quote;
19587       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
19588       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
19589     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
19590       p->mode = MODE_Ascii;
19591       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
19592       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
19593     }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
19594       p->mode = MODE_Markdown;
19595     }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
19596       p->mode = MODE_Table;
19597     }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
19598       p->mode = MODE_Box;
19599     }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
19600       p->mode = MODE_Json;
19601     }else if( nArg==1 ){
19602       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
19603     }else{
19604       raw_printf(stderr, "Error: mode should be one of: "
19605          "ascii box column csv html insert json line list markdown "
19606          "quote table tabs tcl\n");
19607       rc = 1;
19608     }
19609     p->cMode = p->mode;
19610   }else
19611 
19612   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
19613     if( nArg==2 ){
19614       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
19615                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
19616     }else{
19617       raw_printf(stderr, "Usage: .nullvalue STRING\n");
19618       rc = 1;
19619     }
19620   }else
19621 
19622 #ifdef SQLITE_DEBUG
19623   if( c=='o' && strcmp(azArg[0],"oom")==0 ){
19624     int i;
19625     for(i=1; i<nArg; i++){
19626       const char *z = azArg[i];
19627       if( z[0]=='-' && z[1]=='-' ) z++;
19628       if( strcmp(z,"-repeat")==0 ){
19629         if( i==nArg-1 ){
19630           raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
19631           rc = 1;
19632         }else{
19633           oomRepeat = (int)integerValue(azArg[++i]);
19634         }
19635       }else if( IsDigit(z[0]) ){
19636         oomCounter = (int)integerValue(azArg[i]);
19637       }else{
19638         raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
19639         raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
19640         rc = 1;
19641       }
19642     }
19643     if( rc==0 ){
19644       raw_printf(p->out, "oomCounter = %d\n", oomCounter);
19645       raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
19646     }
19647   }else
19648 #endif /* SQLITE_DEBUG */
19649 
19650   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
19651     char *zNewFilename = 0;  /* Name of the database file to open */
19652     int iName = 1;           /* Index in azArg[] of the filename */
19653     int newFlag = 0;         /* True to delete file before opening */
19654     /* Close the existing database */
19655     session_close_all(p);
19656     close_db(p->db);
19657     p->db = 0;
19658     p->zDbFilename = 0;
19659     sqlite3_free(p->zFreeOnClose);
19660     p->zFreeOnClose = 0;
19661     p->openMode = SHELL_OPEN_UNSPEC;
19662     p->openFlags = 0;
19663     p->szMax = 0;
19664     /* Check for command-line arguments */
19665     for(iName=1; iName<nArg; iName++){
19666       const char *z = azArg[iName];
19667       if( optionMatch(z,"new") ){
19668         newFlag = 1;
19669 #ifdef SQLITE_HAVE_ZLIB
19670       }else if( optionMatch(z, "zip") ){
19671         p->openMode = SHELL_OPEN_ZIPFILE;
19672 #endif
19673       }else if( optionMatch(z, "append") ){
19674         p->openMode = SHELL_OPEN_APPENDVFS;
19675       }else if( optionMatch(z, "readonly") ){
19676         p->openMode = SHELL_OPEN_READONLY;
19677       }else if( optionMatch(z, "nofollow") ){
19678         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
19679 #ifndef SQLITE_OMIT_DESERIALIZE
19680       }else if( optionMatch(z, "deserialize") ){
19681         p->openMode = SHELL_OPEN_DESERIALIZE;
19682       }else if( optionMatch(z, "hexdb") ){
19683         p->openMode = SHELL_OPEN_HEXDB;
19684       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
19685         p->szMax = integerValue(azArg[++iName]);
19686 #endif /* SQLITE_OMIT_DESERIALIZE */
19687       }else if( z[0]=='-' ){
19688         utf8_printf(stderr, "unknown option: %s\n", z);
19689         rc = 1;
19690         goto meta_command_exit;
19691       }else if( zNewFilename ){
19692         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
19693         rc = 1;
19694         goto meta_command_exit;
19695       }else{
19696         zNewFilename = sqlite3_mprintf("%s", z);
19697       }
19698     }
19699     /* If a filename is specified, try to open it first */
19700     if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
19701       if( newFlag ) shellDeleteFile(zNewFilename);
19702       p->zDbFilename = zNewFilename;
19703       open_db(p, OPEN_DB_KEEPALIVE);
19704       if( p->db==0 ){
19705         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
19706         sqlite3_free(zNewFilename);
19707       }else{
19708         p->zFreeOnClose = zNewFilename;
19709       }
19710     }
19711     if( p->db==0 ){
19712       /* As a fall-back open a TEMP database */
19713       p->zDbFilename = 0;
19714       open_db(p, 0);
19715     }
19716   }else
19717 
19718   if( (c=='o'
19719         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
19720    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
19721   ){
19722     char *zFile = 0;
19723     int bTxtMode = 0;
19724     int i;
19725     int eMode = 0;
19726     int bBOM = 0;
19727     int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
19728 
19729     if( c=='e' ){
19730       eMode = 'x';
19731       bOnce = 2;
19732     }else if( strncmp(azArg[0],"once",n)==0 ){
19733       bOnce = 1;
19734     }
19735     for(i=1; i<nArg; i++){
19736       char *z = azArg[i];
19737       if( z[0]=='-' ){
19738         if( z[1]=='-' ) z++;
19739         if( strcmp(z,"-bom")==0 ){
19740           bBOM = 1;
19741         }else if( c!='e' && strcmp(z,"-x")==0 ){
19742           eMode = 'x';  /* spreadsheet */
19743         }else if( c!='e' && strcmp(z,"-e")==0 ){
19744           eMode = 'e';  /* text editor */
19745         }else{
19746           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
19747                       azArg[i]);
19748           showHelp(p->out, azArg[0]);
19749           rc = 1;
19750           goto meta_command_exit;
19751         }
19752       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
19753         zFile = sqlite3_mprintf("%s", z);
19754         if( zFile[0]=='|' ){
19755           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
19756           break;
19757         }
19758       }else{
19759         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
19760                     azArg[i]);
19761         showHelp(p->out, azArg[0]);
19762         rc = 1;
19763         sqlite3_free(zFile);
19764         goto meta_command_exit;
19765       }
19766     }
19767     if( zFile==0 ) zFile = sqlite3_mprintf("stdout");
19768     if( bOnce ){
19769       p->outCount = 2;
19770     }else{
19771       p->outCount = 0;
19772     }
19773     output_reset(p);
19774 #ifndef SQLITE_NOHAVE_SYSTEM
19775     if( eMode=='e' || eMode=='x' ){
19776       p->doXdgOpen = 1;
19777       outputModePush(p);
19778       if( eMode=='x' ){
19779         /* spreadsheet mode.  Output as CSV. */
19780         newTempFile(p, "csv");
19781         ShellClearFlag(p, SHFLG_Echo);
19782         p->mode = MODE_Csv;
19783         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
19784         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
19785       }else{
19786         /* text editor mode */
19787         newTempFile(p, "txt");
19788         bTxtMode = 1;
19789       }
19790       sqlite3_free(zFile);
19791       zFile = sqlite3_mprintf("%s", p->zTempFile);
19792     }
19793 #endif /* SQLITE_NOHAVE_SYSTEM */
19794     if( zFile[0]=='|' ){
19795 #ifdef SQLITE_OMIT_POPEN
19796       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
19797       rc = 1;
19798       p->out = stdout;
19799 #else
19800       p->out = popen(zFile + 1, "w");
19801       if( p->out==0 ){
19802         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
19803         p->out = stdout;
19804         rc = 1;
19805       }else{
19806         if( bBOM ) fprintf(p->out,"\357\273\277");
19807         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
19808       }
19809 #endif
19810     }else{
19811       p->out = output_file_open(zFile, bTxtMode);
19812       if( p->out==0 ){
19813         if( strcmp(zFile,"off")!=0 ){
19814           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
19815         }
19816         p->out = stdout;
19817         rc = 1;
19818       } else {
19819         if( bBOM ) fprintf(p->out,"\357\273\277");
19820         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
19821       }
19822     }
19823     sqlite3_free(zFile);
19824   }else
19825 
19826   if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
19827     open_db(p,0);
19828     if( nArg<=1 ) goto parameter_syntax_error;
19829 
19830     /* .parameter clear
19831     ** Clear all bind parameters by dropping the TEMP table that holds them.
19832     */
19833     if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
19834       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
19835                    0, 0, 0);
19836     }else
19837 
19838     /* .parameter list
19839     ** List all bind parameters.
19840     */
19841     if( nArg==2 && strcmp(azArg[1],"list")==0 ){
19842       sqlite3_stmt *pStmt = 0;
19843       int rx;
19844       int len = 0;
19845       rx = sqlite3_prepare_v2(p->db,
19846              "SELECT max(length(key)) "
19847              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
19848       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
19849         len = sqlite3_column_int(pStmt, 0);
19850         if( len>40 ) len = 40;
19851       }
19852       sqlite3_finalize(pStmt);
19853       pStmt = 0;
19854       if( len ){
19855         rx = sqlite3_prepare_v2(p->db,
19856              "SELECT key, quote(value) "
19857              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
19858         while( sqlite3_step(pStmt)==SQLITE_ROW ){
19859           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
19860                       sqlite3_column_text(pStmt,1));
19861         }
19862         sqlite3_finalize(pStmt);
19863       }
19864     }else
19865 
19866     /* .parameter init
19867     ** Make sure the TEMP table used to hold bind parameters exists.
19868     ** Create it if necessary.
19869     */
19870     if( nArg==2 && strcmp(azArg[1],"init")==0 ){
19871       bind_table_init(p);
19872     }else
19873 
19874     /* .parameter set NAME VALUE
19875     ** Set or reset a bind parameter.  NAME should be the full parameter
19876     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
19877     ** VALUE can be in either SQL literal notation, or if not it will be
19878     ** understood to be a text string.
19879     */
19880     if( nArg==4 && strcmp(azArg[1],"set")==0 ){
19881       int rx;
19882       char *zSql;
19883       sqlite3_stmt *pStmt;
19884       const char *zKey = azArg[2];
19885       const char *zValue = azArg[3];
19886       bind_table_init(p);
19887       zSql = sqlite3_mprintf(
19888                   "REPLACE INTO temp.sqlite_parameters(key,value)"
19889                   "VALUES(%Q,%s);", zKey, zValue);
19890       if( zSql==0 ) shell_out_of_memory();
19891       pStmt = 0;
19892       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19893       sqlite3_free(zSql);
19894       if( rx!=SQLITE_OK ){
19895         sqlite3_finalize(pStmt);
19896         pStmt = 0;
19897         zSql = sqlite3_mprintf(
19898                    "REPLACE INTO temp.sqlite_parameters(key,value)"
19899                    "VALUES(%Q,%Q);", zKey, zValue);
19900         if( zSql==0 ) shell_out_of_memory();
19901         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19902         sqlite3_free(zSql);
19903         if( rx!=SQLITE_OK ){
19904           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
19905           sqlite3_finalize(pStmt);
19906           pStmt = 0;
19907           rc = 1;
19908         }
19909       }
19910       sqlite3_step(pStmt);
19911       sqlite3_finalize(pStmt);
19912     }else
19913 
19914     /* .parameter unset NAME
19915     ** Remove the NAME binding from the parameter binding table, if it
19916     ** exists.
19917     */
19918     if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
19919       char *zSql = sqlite3_mprintf(
19920           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
19921       if( zSql==0 ) shell_out_of_memory();
19922       sqlite3_exec(p->db, zSql, 0, 0, 0);
19923       sqlite3_free(zSql);
19924     }else
19925     /* If no command name matches, show a syntax error */
19926     parameter_syntax_error:
19927     showHelp(p->out, "parameter");
19928   }else
19929 
19930   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
19931     int i;
19932     for(i=1; i<nArg; i++){
19933       if( i>1 ) raw_printf(p->out, " ");
19934       utf8_printf(p->out, "%s", azArg[i]);
19935     }
19936     raw_printf(p->out, "\n");
19937   }else
19938 
19939 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19940   if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
19941     int i;
19942     int nn = 0;
19943     p->flgProgress = 0;
19944     p->mxProgress = 0;
19945     p->nProgress = 0;
19946     for(i=1; i<nArg; i++){
19947       const char *z = azArg[i];
19948       if( z[0]=='-' ){
19949         z++;
19950         if( z[0]=='-' ) z++;
19951         if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
19952           p->flgProgress |= SHELL_PROGRESS_QUIET;
19953           continue;
19954         }
19955         if( strcmp(z,"reset")==0 ){
19956           p->flgProgress |= SHELL_PROGRESS_RESET;
19957           continue;
19958         }
19959         if( strcmp(z,"once")==0 ){
19960           p->flgProgress |= SHELL_PROGRESS_ONCE;
19961           continue;
19962         }
19963         if( strcmp(z,"limit")==0 ){
19964           if( i+1>=nArg ){
19965             utf8_printf(stderr, "Error: missing argument on --limit\n");
19966             rc = 1;
19967             goto meta_command_exit;
19968           }else{
19969             p->mxProgress = (int)integerValue(azArg[++i]);
19970           }
19971           continue;
19972         }
19973         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
19974         rc = 1;
19975         goto meta_command_exit;
19976       }else{
19977         nn = (int)integerValue(z);
19978       }
19979     }
19980     open_db(p, 0);
19981     sqlite3_progress_handler(p->db, nn, progress_handler, p);
19982   }else
19983 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
19984 
19985   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
19986     if( nArg >= 2) {
19987       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
19988     }
19989     if( nArg >= 3) {
19990       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
19991     }
19992   }else
19993 
19994   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
19995     rc = 2;
19996   }else
19997 
19998   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
19999     FILE *inSaved = p->in;
20000     int savedLineno = p->lineno;
20001     if( nArg!=2 ){
20002       raw_printf(stderr, "Usage: .read FILE\n");
20003       rc = 1;
20004       goto meta_command_exit;
20005     }
20006     if( azArg[1][0]=='|' ){
20007 #ifdef SQLITE_OMIT_POPEN
20008       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
20009       rc = 1;
20010       p->out = stdout;
20011 #else
20012       p->in = popen(azArg[1]+1, "r");
20013       if( p->in==0 ){
20014         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
20015         rc = 1;
20016       }else{
20017         rc = process_input(p);
20018         pclose(p->in);
20019       }
20020 #endif
20021     }else if( notNormalFile(azArg[1]) || (p->in = fopen(azArg[1], "rb"))==0 ){
20022       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
20023       rc = 1;
20024     }else{
20025       rc = process_input(p);
20026       fclose(p->in);
20027     }
20028     p->in = inSaved;
20029     p->lineno = savedLineno;
20030   }else
20031 
20032   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
20033     const char *zSrcFile;
20034     const char *zDb;
20035     sqlite3 *pSrc;
20036     sqlite3_backup *pBackup;
20037     int nTimeout = 0;
20038 
20039     if( nArg==2 ){
20040       zSrcFile = azArg[1];
20041       zDb = "main";
20042     }else if( nArg==3 ){
20043       zSrcFile = azArg[2];
20044       zDb = azArg[1];
20045     }else{
20046       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
20047       rc = 1;
20048       goto meta_command_exit;
20049     }
20050     rc = sqlite3_open(zSrcFile, &pSrc);
20051     if( rc!=SQLITE_OK ){
20052       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
20053       close_db(pSrc);
20054       return 1;
20055     }
20056     open_db(p, 0);
20057     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
20058     if( pBackup==0 ){
20059       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
20060       close_db(pSrc);
20061       return 1;
20062     }
20063     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
20064           || rc==SQLITE_BUSY  ){
20065       if( rc==SQLITE_BUSY ){
20066         if( nTimeout++ >= 3 ) break;
20067         sqlite3_sleep(100);
20068       }
20069     }
20070     sqlite3_backup_finish(pBackup);
20071     if( rc==SQLITE_DONE ){
20072       rc = 0;
20073     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
20074       raw_printf(stderr, "Error: source database is busy\n");
20075       rc = 1;
20076     }else{
20077       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
20078       rc = 1;
20079     }
20080     close_db(pSrc);
20081   }else
20082 
20083   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
20084     if( nArg==2 ){
20085       p->scanstatsOn = (u8)booleanValue(azArg[1]);
20086 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
20087       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
20088 #endif
20089     }else{
20090       raw_printf(stderr, "Usage: .scanstats on|off\n");
20091       rc = 1;
20092     }
20093   }else
20094 
20095   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
20096     ShellText sSelect;
20097     ShellState data;
20098     char *zErrMsg = 0;
20099     const char *zDiv = "(";
20100     const char *zName = 0;
20101     int iSchema = 0;
20102     int bDebug = 0;
20103     int bNoSystemTabs = 0;
20104     int ii;
20105 
20106     open_db(p, 0);
20107     memcpy(&data, p, sizeof(data));
20108     data.showHeader = 0;
20109     data.cMode = data.mode = MODE_Semi;
20110     initText(&sSelect);
20111     for(ii=1; ii<nArg; ii++){
20112       if( optionMatch(azArg[ii],"indent") ){
20113         data.cMode = data.mode = MODE_Pretty;
20114       }else if( optionMatch(azArg[ii],"debug") ){
20115         bDebug = 1;
20116       }else if( optionMatch(azArg[ii],"nosys") ){
20117         bNoSystemTabs = 1;
20118       }else if( azArg[ii][0]=='-' ){
20119         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
20120         rc = 1;
20121         goto meta_command_exit;
20122       }else if( zName==0 ){
20123         zName = azArg[ii];
20124       }else{
20125         raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
20126         rc = 1;
20127         goto meta_command_exit;
20128       }
20129     }
20130     if( zName!=0 ){
20131       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
20132                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
20133                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
20134                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
20135       if( isSchema ){
20136         char *new_argv[2], *new_colv[2];
20137         new_argv[0] = sqlite3_mprintf(
20138                       "CREATE TABLE %s (\n"
20139                       "  type text,\n"
20140                       "  name text,\n"
20141                       "  tbl_name text,\n"
20142                       "  rootpage integer,\n"
20143                       "  sql text\n"
20144                       ")", zName);
20145         new_argv[1] = 0;
20146         new_colv[0] = "sql";
20147         new_colv[1] = 0;
20148         callback(&data, 1, new_argv, new_colv);
20149         sqlite3_free(new_argv[0]);
20150       }
20151     }
20152     if( zDiv ){
20153       sqlite3_stmt *pStmt = 0;
20154       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
20155                               -1, &pStmt, 0);
20156       if( rc ){
20157         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
20158         sqlite3_finalize(pStmt);
20159         rc = 1;
20160         goto meta_command_exit;
20161       }
20162       appendText(&sSelect, "SELECT sql FROM", 0);
20163       iSchema = 0;
20164       while( sqlite3_step(pStmt)==SQLITE_ROW ){
20165         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
20166         char zScNum[30];
20167         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
20168         appendText(&sSelect, zDiv, 0);
20169         zDiv = " UNION ALL ";
20170         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
20171         if( sqlite3_stricmp(zDb, "main")!=0 ){
20172           appendText(&sSelect, zDb, '\'');
20173         }else{
20174           appendText(&sSelect, "NULL", 0);
20175         }
20176         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
20177         appendText(&sSelect, zScNum, 0);
20178         appendText(&sSelect, " AS snum, ", 0);
20179         appendText(&sSelect, zDb, '\'');
20180         appendText(&sSelect, " AS sname FROM ", 0);
20181         appendText(&sSelect, zDb, quoteChar(zDb));
20182         appendText(&sSelect, ".sqlite_schema", 0);
20183       }
20184       sqlite3_finalize(pStmt);
20185 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
20186       if( zName ){
20187         appendText(&sSelect,
20188            " UNION ALL SELECT shell_module_schema(name),"
20189            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
20190         0);
20191       }
20192 #endif
20193       appendText(&sSelect, ") WHERE ", 0);
20194       if( zName ){
20195         char *zQarg = sqlite3_mprintf("%Q", zName);
20196         int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
20197                     strchr(zName, '[') != 0;
20198         if( strchr(zName, '.') ){
20199           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
20200         }else{
20201           appendText(&sSelect, "lower(tbl_name)", 0);
20202         }
20203         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
20204         appendText(&sSelect, zQarg, 0);
20205         if( !bGlob ){
20206           appendText(&sSelect, " ESCAPE '\\' ", 0);
20207         }
20208         appendText(&sSelect, " AND ", 0);
20209         sqlite3_free(zQarg);
20210       }
20211       if( bNoSystemTabs ){
20212         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
20213       }
20214       appendText(&sSelect, "sql IS NOT NULL"
20215                            " ORDER BY snum, rowid", 0);
20216       if( bDebug ){
20217         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
20218       }else{
20219         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
20220       }
20221       freeText(&sSelect);
20222     }
20223     if( zErrMsg ){
20224       utf8_printf(stderr,"Error: %s\n", zErrMsg);
20225       sqlite3_free(zErrMsg);
20226       rc = 1;
20227     }else if( rc != SQLITE_OK ){
20228       raw_printf(stderr,"Error: querying schema information\n");
20229       rc = 1;
20230     }else{
20231       rc = 0;
20232     }
20233   }else
20234 
20235   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
20236     unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
20237     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
20238   }else
20239 
20240 #if defined(SQLITE_ENABLE_SESSION)
20241   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
20242     OpenSession *pSession = &p->aSession[0];
20243     char **azCmd = &azArg[1];
20244     int iSes = 0;
20245     int nCmd = nArg - 1;
20246     int i;
20247     if( nArg<=1 ) goto session_syntax_error;
20248     open_db(p, 0);
20249     if( nArg>=3 ){
20250       for(iSes=0; iSes<p->nSession; iSes++){
20251         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
20252       }
20253       if( iSes<p->nSession ){
20254         pSession = &p->aSession[iSes];
20255         azCmd++;
20256         nCmd--;
20257       }else{
20258         pSession = &p->aSession[0];
20259         iSes = 0;
20260       }
20261     }
20262 
20263     /* .session attach TABLE
20264     ** Invoke the sqlite3session_attach() interface to attach a particular
20265     ** table so that it is never filtered.
20266     */
20267     if( strcmp(azCmd[0],"attach")==0 ){
20268       if( nCmd!=2 ) goto session_syntax_error;
20269       if( pSession->p==0 ){
20270         session_not_open:
20271         raw_printf(stderr, "ERROR: No sessions are open\n");
20272       }else{
20273         rc = sqlite3session_attach(pSession->p, azCmd[1]);
20274         if( rc ){
20275           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
20276           rc = 0;
20277         }
20278       }
20279     }else
20280 
20281     /* .session changeset FILE
20282     ** .session patchset FILE
20283     ** Write a changeset or patchset into a file.  The file is overwritten.
20284     */
20285     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
20286       FILE *out = 0;
20287       if( nCmd!=2 ) goto session_syntax_error;
20288       if( pSession->p==0 ) goto session_not_open;
20289       out = fopen(azCmd[1], "wb");
20290       if( out==0 ){
20291         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
20292                     azCmd[1]);
20293       }else{
20294         int szChng;
20295         void *pChng;
20296         if( azCmd[0][0]=='c' ){
20297           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
20298         }else{
20299           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
20300         }
20301         if( rc ){
20302           printf("Error: error code %d\n", rc);
20303           rc = 0;
20304         }
20305         if( pChng
20306           && fwrite(pChng, szChng, 1, out)!=1 ){
20307           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
20308                   szChng);
20309         }
20310         sqlite3_free(pChng);
20311         fclose(out);
20312       }
20313     }else
20314 
20315     /* .session close
20316     ** Close the identified session
20317     */
20318     if( strcmp(azCmd[0], "close")==0 ){
20319       if( nCmd!=1 ) goto session_syntax_error;
20320       if( p->nSession ){
20321         session_close(pSession);
20322         p->aSession[iSes] = p->aSession[--p->nSession];
20323       }
20324     }else
20325 
20326     /* .session enable ?BOOLEAN?
20327     ** Query or set the enable flag
20328     */
20329     if( strcmp(azCmd[0], "enable")==0 ){
20330       int ii;
20331       if( nCmd>2 ) goto session_syntax_error;
20332       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
20333       if( p->nSession ){
20334         ii = sqlite3session_enable(pSession->p, ii);
20335         utf8_printf(p->out, "session %s enable flag = %d\n",
20336                     pSession->zName, ii);
20337       }
20338     }else
20339 
20340     /* .session filter GLOB ....
20341     ** Set a list of GLOB patterns of table names to be excluded.
20342     */
20343     if( strcmp(azCmd[0], "filter")==0 ){
20344       int ii, nByte;
20345       if( nCmd<2 ) goto session_syntax_error;
20346       if( p->nSession ){
20347         for(ii=0; ii<pSession->nFilter; ii++){
20348           sqlite3_free(pSession->azFilter[ii]);
20349         }
20350         sqlite3_free(pSession->azFilter);
20351         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
20352         pSession->azFilter = sqlite3_malloc( nByte );
20353         if( pSession->azFilter==0 ){
20354           raw_printf(stderr, "Error: out or memory\n");
20355           exit(1);
20356         }
20357         for(ii=1; ii<nCmd; ii++){
20358           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
20359         }
20360         pSession->nFilter = ii-1;
20361       }
20362     }else
20363 
20364     /* .session indirect ?BOOLEAN?
20365     ** Query or set the indirect flag
20366     */
20367     if( strcmp(azCmd[0], "indirect")==0 ){
20368       int ii;
20369       if( nCmd>2 ) goto session_syntax_error;
20370       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
20371       if( p->nSession ){
20372         ii = sqlite3session_indirect(pSession->p, ii);
20373         utf8_printf(p->out, "session %s indirect flag = %d\n",
20374                     pSession->zName, ii);
20375       }
20376     }else
20377 
20378     /* .session isempty
20379     ** Determine if the session is empty
20380     */
20381     if( strcmp(azCmd[0], "isempty")==0 ){
20382       int ii;
20383       if( nCmd!=1 ) goto session_syntax_error;
20384       if( p->nSession ){
20385         ii = sqlite3session_isempty(pSession->p);
20386         utf8_printf(p->out, "session %s isempty flag = %d\n",
20387                     pSession->zName, ii);
20388       }
20389     }else
20390 
20391     /* .session list
20392     ** List all currently open sessions
20393     */
20394     if( strcmp(azCmd[0],"list")==0 ){
20395       for(i=0; i<p->nSession; i++){
20396         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
20397       }
20398     }else
20399 
20400     /* .session open DB NAME
20401     ** Open a new session called NAME on the attached database DB.
20402     ** DB is normally "main".
20403     */
20404     if( strcmp(azCmd[0],"open")==0 ){
20405       char *zName;
20406       if( nCmd!=3 ) goto session_syntax_error;
20407       zName = azCmd[2];
20408       if( zName[0]==0 ) goto session_syntax_error;
20409       for(i=0; i<p->nSession; i++){
20410         if( strcmp(p->aSession[i].zName,zName)==0 ){
20411           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
20412           goto meta_command_exit;
20413         }
20414       }
20415       if( p->nSession>=ArraySize(p->aSession) ){
20416         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
20417         goto meta_command_exit;
20418       }
20419       pSession = &p->aSession[p->nSession];
20420       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
20421       if( rc ){
20422         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
20423         rc = 0;
20424         goto meta_command_exit;
20425       }
20426       pSession->nFilter = 0;
20427       sqlite3session_table_filter(pSession->p, session_filter, pSession);
20428       p->nSession++;
20429       pSession->zName = sqlite3_mprintf("%s", zName);
20430     }else
20431     /* If no command name matches, show a syntax error */
20432     session_syntax_error:
20433     showHelp(p->out, "session");
20434   }else
20435 #endif
20436 
20437 #ifdef SQLITE_DEBUG
20438   /* Undocumented commands for internal testing.  Subject to change
20439   ** without notice. */
20440   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
20441     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
20442       int i, v;
20443       for(i=1; i<nArg; i++){
20444         v = booleanValue(azArg[i]);
20445         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
20446       }
20447     }
20448     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
20449       int i; sqlite3_int64 v;
20450       for(i=1; i<nArg; i++){
20451         char zBuf[200];
20452         v = integerValue(azArg[i]);
20453         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
20454         utf8_printf(p->out, "%s", zBuf);
20455       }
20456     }
20457   }else
20458 #endif
20459 
20460   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
20461     int bIsInit = 0;         /* True to initialize the SELFTEST table */
20462     int bVerbose = 0;        /* Verbose output */
20463     int bSelftestExists;     /* True if SELFTEST already exists */
20464     int i, k;                /* Loop counters */
20465     int nTest = 0;           /* Number of tests runs */
20466     int nErr = 0;            /* Number of errors seen */
20467     ShellText str;           /* Answer for a query */
20468     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
20469 
20470     open_db(p,0);
20471     for(i=1; i<nArg; i++){
20472       const char *z = azArg[i];
20473       if( z[0]=='-' && z[1]=='-' ) z++;
20474       if( strcmp(z,"-init")==0 ){
20475         bIsInit = 1;
20476       }else
20477       if( strcmp(z,"-v")==0 ){
20478         bVerbose++;
20479       }else
20480       {
20481         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
20482                     azArg[i], azArg[0]);
20483         raw_printf(stderr, "Should be one of: --init -v\n");
20484         rc = 1;
20485         goto meta_command_exit;
20486       }
20487     }
20488     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
20489            != SQLITE_OK ){
20490       bSelftestExists = 0;
20491     }else{
20492       bSelftestExists = 1;
20493     }
20494     if( bIsInit ){
20495       createSelftestTable(p);
20496       bSelftestExists = 1;
20497     }
20498     initText(&str);
20499     appendText(&str, "x", 0);
20500     for(k=bSelftestExists; k>=0; k--){
20501       if( k==1 ){
20502         rc = sqlite3_prepare_v2(p->db,
20503             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
20504             -1, &pStmt, 0);
20505       }else{
20506         rc = sqlite3_prepare_v2(p->db,
20507           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
20508           "      (1,'run','PRAGMA integrity_check','ok')",
20509           -1, &pStmt, 0);
20510       }
20511       if( rc ){
20512         raw_printf(stderr, "Error querying the selftest table\n");
20513         rc = 1;
20514         sqlite3_finalize(pStmt);
20515         goto meta_command_exit;
20516       }
20517       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
20518         int tno = sqlite3_column_int(pStmt, 0);
20519         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
20520         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
20521         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
20522 
20523         k = 0;
20524         if( bVerbose>0 ){
20525           char *zQuote = sqlite3_mprintf("%q", zSql);
20526           printf("%d: %s %s\n", tno, zOp, zSql);
20527           sqlite3_free(zQuote);
20528         }
20529         if( strcmp(zOp,"memo")==0 ){
20530           utf8_printf(p->out, "%s\n", zSql);
20531         }else
20532         if( strcmp(zOp,"run")==0 ){
20533           char *zErrMsg = 0;
20534           str.n = 0;
20535           str.z[0] = 0;
20536           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
20537           nTest++;
20538           if( bVerbose ){
20539             utf8_printf(p->out, "Result: %s\n", str.z);
20540           }
20541           if( rc || zErrMsg ){
20542             nErr++;
20543             rc = 1;
20544             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
20545             sqlite3_free(zErrMsg);
20546           }else if( strcmp(zAns,str.z)!=0 ){
20547             nErr++;
20548             rc = 1;
20549             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
20550             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
20551           }
20552         }else
20553         {
20554           utf8_printf(stderr,
20555             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
20556           rc = 1;
20557           break;
20558         }
20559       } /* End loop over rows of content from SELFTEST */
20560       sqlite3_finalize(pStmt);
20561     } /* End loop over k */
20562     freeText(&str);
20563     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
20564   }else
20565 
20566   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
20567     if( nArg<2 || nArg>3 ){
20568       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
20569       rc = 1;
20570     }
20571     if( nArg>=2 ){
20572       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
20573                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
20574     }
20575     if( nArg>=3 ){
20576       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
20577                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
20578     }
20579   }else
20580 
20581   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
20582     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
20583     int i;                   /* Loop counter */
20584     int bSchema = 0;         /* Also hash the schema */
20585     int bSeparate = 0;       /* Hash each table separately */
20586     int iSize = 224;         /* Hash algorithm to use */
20587     int bDebug = 0;          /* Only show the query that would have run */
20588     sqlite3_stmt *pStmt;     /* For querying tables names */
20589     char *zSql;              /* SQL to be run */
20590     char *zSep;              /* Separator */
20591     ShellText sSql;          /* Complete SQL for the query to run the hash */
20592     ShellText sQuery;        /* Set of queries used to read all content */
20593     open_db(p, 0);
20594     for(i=1; i<nArg; i++){
20595       const char *z = azArg[i];
20596       if( z[0]=='-' ){
20597         z++;
20598         if( z[0]=='-' ) z++;
20599         if( strcmp(z,"schema")==0 ){
20600           bSchema = 1;
20601         }else
20602         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
20603          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
20604         ){
20605           iSize = atoi(&z[5]);
20606         }else
20607         if( strcmp(z,"debug")==0 ){
20608           bDebug = 1;
20609         }else
20610         {
20611           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
20612                       azArg[i], azArg[0]);
20613           showHelp(p->out, azArg[0]);
20614           rc = 1;
20615           goto meta_command_exit;
20616         }
20617       }else if( zLike ){
20618         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
20619         rc = 1;
20620         goto meta_command_exit;
20621       }else{
20622         zLike = z;
20623         bSeparate = 1;
20624         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
20625       }
20626     }
20627     if( bSchema ){
20628       zSql = "SELECT lower(name) FROM sqlite_schema"
20629              " WHERE type='table' AND coalesce(rootpage,0)>1"
20630              " UNION ALL SELECT 'sqlite_schema'"
20631              " ORDER BY 1 collate nocase";
20632     }else{
20633       zSql = "SELECT lower(name) FROM sqlite_schema"
20634              " WHERE type='table' AND coalesce(rootpage,0)>1"
20635              " AND name NOT LIKE 'sqlite_%'"
20636              " ORDER BY 1 collate nocase";
20637     }
20638     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20639     initText(&sQuery);
20640     initText(&sSql);
20641     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
20642     zSep = "VALUES(";
20643     while( SQLITE_ROW==sqlite3_step(pStmt) ){
20644       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
20645       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
20646       if( strncmp(zTab, "sqlite_",7)!=0 ){
20647         appendText(&sQuery,"SELECT * FROM ", 0);
20648         appendText(&sQuery,zTab,'"');
20649         appendText(&sQuery," NOT INDEXED;", 0);
20650       }else if( strcmp(zTab, "sqlite_schema")==0 ){
20651         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
20652                            " ORDER BY name;", 0);
20653       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
20654         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
20655                            " ORDER BY name;", 0);
20656       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
20657         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
20658                            " ORDER BY tbl,idx;", 0);
20659       }else if( strcmp(zTab, "sqlite_stat4")==0 ){
20660         appendText(&sQuery, "SELECT * FROM ", 0);
20661         appendText(&sQuery, zTab, 0);
20662         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
20663       }
20664       appendText(&sSql, zSep, 0);
20665       appendText(&sSql, sQuery.z, '\'');
20666       sQuery.n = 0;
20667       appendText(&sSql, ",", 0);
20668       appendText(&sSql, zTab, '\'');
20669       zSep = "),(";
20670     }
20671     sqlite3_finalize(pStmt);
20672     if( bSeparate ){
20673       zSql = sqlite3_mprintf(
20674           "%s))"
20675           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
20676           "   FROM [sha3sum$query]",
20677           sSql.z, iSize);
20678     }else{
20679       zSql = sqlite3_mprintf(
20680           "%s))"
20681           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
20682           "   FROM [sha3sum$query]",
20683           sSql.z, iSize);
20684     }
20685     freeText(&sQuery);
20686     freeText(&sSql);
20687     if( bDebug ){
20688       utf8_printf(p->out, "%s\n", zSql);
20689     }else{
20690       shell_exec(p, zSql, 0);
20691     }
20692     sqlite3_free(zSql);
20693   }else
20694 
20695 #ifndef SQLITE_NOHAVE_SYSTEM
20696   if( c=='s'
20697    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
20698   ){
20699     char *zCmd;
20700     int i, x;
20701     if( nArg<2 ){
20702       raw_printf(stderr, "Usage: .system COMMAND\n");
20703       rc = 1;
20704       goto meta_command_exit;
20705     }
20706     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
20707     for(i=2; i<nArg; i++){
20708       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
20709                              zCmd, azArg[i]);
20710     }
20711     x = system(zCmd);
20712     sqlite3_free(zCmd);
20713     if( x ) raw_printf(stderr, "System command returns %d\n", x);
20714   }else
20715 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
20716 
20717   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
20718     static const char *azBool[] = { "off", "on", "trigger", "full"};
20719     const char *zOut;
20720     int i;
20721     if( nArg!=1 ){
20722       raw_printf(stderr, "Usage: .show\n");
20723       rc = 1;
20724       goto meta_command_exit;
20725     }
20726     utf8_printf(p->out, "%12.12s: %s\n","echo",
20727                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
20728     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
20729     utf8_printf(p->out, "%12.12s: %s\n","explain",
20730          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
20731     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
20732     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
20733     utf8_printf(p->out, "%12.12s: ", "nullvalue");
20734       output_c_string(p->out, p->nullValue);
20735       raw_printf(p->out, "\n");
20736     utf8_printf(p->out,"%12.12s: %s\n","output",
20737             strlen30(p->outfile) ? p->outfile : "stdout");
20738     utf8_printf(p->out,"%12.12s: ", "colseparator");
20739       output_c_string(p->out, p->colSeparator);
20740       raw_printf(p->out, "\n");
20741     utf8_printf(p->out,"%12.12s: ", "rowseparator");
20742       output_c_string(p->out, p->rowSeparator);
20743       raw_printf(p->out, "\n");
20744     switch( p->statsOn ){
20745       case 0:  zOut = "off";     break;
20746       default: zOut = "on";      break;
20747       case 2:  zOut = "stmt";    break;
20748       case 3:  zOut = "vmstep";  break;
20749     }
20750     utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
20751     utf8_printf(p->out, "%12.12s: ", "width");
20752     for (i=0;i<p->nWidth;i++) {
20753       raw_printf(p->out, "%d ", p->colWidth[i]);
20754     }
20755     raw_printf(p->out, "\n");
20756     utf8_printf(p->out, "%12.12s: %s\n", "filename",
20757                 p->zDbFilename ? p->zDbFilename : "");
20758   }else
20759 
20760   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
20761     if( nArg==2 ){
20762       if( strcmp(azArg[1],"stmt")==0 ){
20763         p->statsOn = 2;
20764       }else if( strcmp(azArg[1],"vmstep")==0 ){
20765         p->statsOn = 3;
20766       }else{
20767         p->statsOn = (u8)booleanValue(azArg[1]);
20768       }
20769     }else if( nArg==1 ){
20770       display_stats(p->db, p, 0);
20771     }else{
20772       raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
20773       rc = 1;
20774     }
20775   }else
20776 
20777   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
20778    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
20779                  || strncmp(azArg[0], "indexes", n)==0) )
20780   ){
20781     sqlite3_stmt *pStmt;
20782     char **azResult;
20783     int nRow, nAlloc;
20784     int ii;
20785     ShellText s;
20786     initText(&s);
20787     open_db(p, 0);
20788     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
20789     if( rc ){
20790       sqlite3_finalize(pStmt);
20791       return shellDatabaseError(p->db);
20792     }
20793 
20794     if( nArg>2 && c=='i' ){
20795       /* It is an historical accident that the .indexes command shows an error
20796       ** when called with the wrong number of arguments whereas the .tables
20797       ** command does not. */
20798       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
20799       rc = 1;
20800       sqlite3_finalize(pStmt);
20801       goto meta_command_exit;
20802     }
20803     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
20804       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
20805       if( zDbName==0 ) continue;
20806       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
20807       if( sqlite3_stricmp(zDbName, "main")==0 ){
20808         appendText(&s, "SELECT name FROM ", 0);
20809       }else{
20810         appendText(&s, "SELECT ", 0);
20811         appendText(&s, zDbName, '\'');
20812         appendText(&s, "||'.'||name FROM ", 0);
20813       }
20814       appendText(&s, zDbName, '"');
20815       appendText(&s, ".sqlite_schema ", 0);
20816       if( c=='t' ){
20817         appendText(&s," WHERE type IN ('table','view')"
20818                       "   AND name NOT LIKE 'sqlite_%'"
20819                       "   AND name LIKE ?1", 0);
20820       }else{
20821         appendText(&s," WHERE type='index'"
20822                       "   AND tbl_name LIKE ?1", 0);
20823       }
20824     }
20825     rc = sqlite3_finalize(pStmt);
20826     appendText(&s, " ORDER BY 1", 0);
20827     rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
20828     freeText(&s);
20829     if( rc ) return shellDatabaseError(p->db);
20830 
20831     /* Run the SQL statement prepared by the above block. Store the results
20832     ** as an array of nul-terminated strings in azResult[].  */
20833     nRow = nAlloc = 0;
20834     azResult = 0;
20835     if( nArg>1 ){
20836       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
20837     }else{
20838       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
20839     }
20840     while( sqlite3_step(pStmt)==SQLITE_ROW ){
20841       if( nRow>=nAlloc ){
20842         char **azNew;
20843         int n2 = nAlloc*2 + 10;
20844         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
20845         if( azNew==0 ) shell_out_of_memory();
20846         nAlloc = n2;
20847         azResult = azNew;
20848       }
20849       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
20850       if( 0==azResult[nRow] ) shell_out_of_memory();
20851       nRow++;
20852     }
20853     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
20854       rc = shellDatabaseError(p->db);
20855     }
20856 
20857     /* Pretty-print the contents of array azResult[] to the output */
20858     if( rc==0 && nRow>0 ){
20859       int len, maxlen = 0;
20860       int i, j;
20861       int nPrintCol, nPrintRow;
20862       for(i=0; i<nRow; i++){
20863         len = strlen30(azResult[i]);
20864         if( len>maxlen ) maxlen = len;
20865       }
20866       nPrintCol = 80/(maxlen+2);
20867       if( nPrintCol<1 ) nPrintCol = 1;
20868       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
20869       for(i=0; i<nPrintRow; i++){
20870         for(j=i; j<nRow; j+=nPrintRow){
20871           char *zSp = j<nPrintRow ? "" : "  ";
20872           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
20873                       azResult[j] ? azResult[j]:"");
20874         }
20875         raw_printf(p->out, "\n");
20876       }
20877     }
20878 
20879     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
20880     sqlite3_free(azResult);
20881   }else
20882 
20883   /* Begin redirecting output to the file "testcase-out.txt" */
20884   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
20885     output_reset(p);
20886     p->out = output_file_open("testcase-out.txt", 0);
20887     if( p->out==0 ){
20888       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
20889     }
20890     if( nArg>=2 ){
20891       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
20892     }else{
20893       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
20894     }
20895   }else
20896 
20897 #ifndef SQLITE_UNTESTABLE
20898   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
20899     static const struct {
20900        const char *zCtrlName;   /* Name of a test-control option */
20901        int ctrlCode;            /* Integer code for that option */
20902        const char *zUsage;      /* Usage notes */
20903     } aCtrl[] = {
20904       { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"        },
20905       { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"        },
20906     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""       },*/
20907     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""             },*/
20908       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""               },
20909       { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
20910     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
20911       { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
20912       { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
20913       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
20914       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
20915       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
20916 #ifdef YYCOVERAGE
20917       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""             },
20918 #endif
20919       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "       },
20920       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
20921       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
20922       { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
20923       { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,    ""               },
20924       { "tune",               SQLITE_TESTCTRL_TUNE,          "ID VALUE"       },
20925     };
20926     int testctrl = -1;
20927     int iCtrl = -1;
20928     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
20929     int isOk = 0;
20930     int i, n2;
20931     const char *zCmd = 0;
20932 
20933     open_db(p, 0);
20934     zCmd = nArg>=2 ? azArg[1] : "help";
20935 
20936     /* The argument can optionally begin with "-" or "--" */
20937     if( zCmd[0]=='-' && zCmd[1] ){
20938       zCmd++;
20939       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
20940     }
20941 
20942     /* --help lists all test-controls */
20943     if( strcmp(zCmd,"help")==0 ){
20944       utf8_printf(p->out, "Available test-controls:\n");
20945       for(i=0; i<ArraySize(aCtrl); i++){
20946         utf8_printf(p->out, "  .testctrl %s %s\n",
20947                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
20948       }
20949       rc = 1;
20950       goto meta_command_exit;
20951     }
20952 
20953     /* convert testctrl text option to value. allow any unique prefix
20954     ** of the option name, or a numerical value. */
20955     n2 = strlen30(zCmd);
20956     for(i=0; i<ArraySize(aCtrl); i++){
20957       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
20958         if( testctrl<0 ){
20959           testctrl = aCtrl[i].ctrlCode;
20960           iCtrl = i;
20961         }else{
20962           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
20963                               "Use \".testctrl --help\" for help\n", zCmd);
20964           rc = 1;
20965           goto meta_command_exit;
20966         }
20967       }
20968     }
20969     if( testctrl<0 ){
20970       utf8_printf(stderr,"Error: unknown test-control: %s\n"
20971                          "Use \".testctrl --help\" for help\n", zCmd);
20972     }else{
20973       switch(testctrl){
20974 
20975         /* sqlite3_test_control(int, db, int) */
20976         case SQLITE_TESTCTRL_OPTIMIZATIONS:
20977           if( nArg==3 ){
20978             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
20979             rc2 = sqlite3_test_control(testctrl, p->db, opt);
20980             isOk = 3;
20981           }
20982           break;
20983 
20984         /* sqlite3_test_control(int) */
20985         case SQLITE_TESTCTRL_PRNG_SAVE:
20986         case SQLITE_TESTCTRL_PRNG_RESTORE:
20987         case SQLITE_TESTCTRL_BYTEORDER:
20988           if( nArg==2 ){
20989             rc2 = sqlite3_test_control(testctrl);
20990             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
20991           }
20992           break;
20993 
20994         /* sqlite3_test_control(int, uint) */
20995         case SQLITE_TESTCTRL_PENDING_BYTE:
20996           if( nArg==3 ){
20997             unsigned int opt = (unsigned int)integerValue(azArg[2]);
20998             rc2 = sqlite3_test_control(testctrl, opt);
20999             isOk = 3;
21000           }
21001           break;
21002 
21003         /* sqlite3_test_control(int, int, sqlite3*) */
21004         case SQLITE_TESTCTRL_PRNG_SEED:
21005           if( nArg==3 || nArg==4 ){
21006             int ii = (int)integerValue(azArg[2]);
21007             sqlite3 *db;
21008             if( ii==0 && strcmp(azArg[2],"random")==0 ){
21009               sqlite3_randomness(sizeof(ii),&ii);
21010               printf("-- random seed: %d\n", ii);
21011             }
21012             if( nArg==3 ){
21013               db = 0;
21014             }else{
21015               db = p->db;
21016               /* Make sure the schema has been loaded */
21017               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
21018             }
21019             rc2 = sqlite3_test_control(testctrl, ii, db);
21020             isOk = 3;
21021           }
21022           break;
21023 
21024         /* sqlite3_test_control(int, int) */
21025         case SQLITE_TESTCTRL_ASSERT:
21026         case SQLITE_TESTCTRL_ALWAYS:
21027           if( nArg==3 ){
21028             int opt = booleanValue(azArg[2]);
21029             rc2 = sqlite3_test_control(testctrl, opt);
21030             isOk = 1;
21031           }
21032           break;
21033 
21034         /* sqlite3_test_control(int, int) */
21035         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
21036         case SQLITE_TESTCTRL_NEVER_CORRUPT:
21037           if( nArg==3 ){
21038             int opt = booleanValue(azArg[2]);
21039             rc2 = sqlite3_test_control(testctrl, opt);
21040             isOk = 3;
21041           }
21042           break;
21043 
21044         /* sqlite3_test_control(sqlite3*) */
21045         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
21046           rc2 = sqlite3_test_control(testctrl, p->db);
21047           isOk = 3;
21048           break;
21049 
21050         case SQLITE_TESTCTRL_IMPOSTER:
21051           if( nArg==5 ){
21052             rc2 = sqlite3_test_control(testctrl, p->db,
21053                           azArg[2],
21054                           integerValue(azArg[3]),
21055                           integerValue(azArg[4]));
21056             isOk = 3;
21057           }
21058           break;
21059 
21060         case SQLITE_TESTCTRL_SEEK_COUNT: {
21061           u64 x = 0;
21062           rc2 = sqlite3_test_control(testctrl, p->db, &x);
21063           utf8_printf(p->out, "%llu\n", x);
21064           isOk = 3;
21065           break;
21066         }
21067 
21068 #ifdef YYCOVERAGE
21069         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
21070           if( nArg==2 ){
21071             sqlite3_test_control(testctrl, p->out);
21072             isOk = 3;
21073           }
21074           break;
21075         }
21076 #endif
21077 #ifdef SQLITE_DEBUG
21078         case SQLITE_TESTCTRL_TUNE: {
21079           if( nArg==4 ){
21080             int id = (int)integerValue(azArg[2]);
21081             int val = (int)integerValue(azArg[3]);
21082             sqlite3_test_control(testctrl, id, &val);
21083             isOk = 3;
21084           }else if( nArg==3 ){
21085             int id = (int)integerValue(azArg[2]);
21086             sqlite3_test_control(testctrl, -id, &rc2);
21087             isOk = 1;
21088           }else if( nArg==2 ){
21089             int id = 1;
21090             while(1){
21091               int val = 0;
21092               rc2 = sqlite3_test_control(testctrl, -id, &val);
21093               if( rc2!=SQLITE_OK ) break;
21094               if( id>1 ) utf8_printf(p->out, "  ");
21095               utf8_printf(p->out, "%d: %d", id, val);
21096               id++;
21097             }
21098             if( id>1 ) utf8_printf(p->out, "\n");
21099             isOk = 3;
21100           }
21101           break;
21102         }
21103 #endif
21104       }
21105     }
21106     if( isOk==0 && iCtrl>=0 ){
21107       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
21108       rc = 1;
21109     }else if( isOk==1 ){
21110       raw_printf(p->out, "%d\n", rc2);
21111     }else if( isOk==2 ){
21112       raw_printf(p->out, "0x%08x\n", rc2);
21113     }
21114   }else
21115 #endif /* !defined(SQLITE_UNTESTABLE) */
21116 
21117   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
21118     open_db(p, 0);
21119     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
21120   }else
21121 
21122   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
21123     if( nArg==2 ){
21124       enableTimer = booleanValue(azArg[1]);
21125       if( enableTimer && !HAS_TIMER ){
21126         raw_printf(stderr, "Error: timer not available on this system.\n");
21127         enableTimer = 0;
21128       }
21129     }else{
21130       raw_printf(stderr, "Usage: .timer on|off\n");
21131       rc = 1;
21132     }
21133   }else
21134 
21135 #ifndef SQLITE_OMIT_TRACE
21136   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
21137     int mType = 0;
21138     int jj;
21139     open_db(p, 0);
21140     for(jj=1; jj<nArg; jj++){
21141       const char *z = azArg[jj];
21142       if( z[0]=='-' ){
21143         if( optionMatch(z, "expanded") ){
21144           p->eTraceType = SHELL_TRACE_EXPANDED;
21145         }
21146 #ifdef SQLITE_ENABLE_NORMALIZE
21147         else if( optionMatch(z, "normalized") ){
21148           p->eTraceType = SHELL_TRACE_NORMALIZED;
21149         }
21150 #endif
21151         else if( optionMatch(z, "plain") ){
21152           p->eTraceType = SHELL_TRACE_PLAIN;
21153         }
21154         else if( optionMatch(z, "profile") ){
21155           mType |= SQLITE_TRACE_PROFILE;
21156         }
21157         else if( optionMatch(z, "row") ){
21158           mType |= SQLITE_TRACE_ROW;
21159         }
21160         else if( optionMatch(z, "stmt") ){
21161           mType |= SQLITE_TRACE_STMT;
21162         }
21163         else if( optionMatch(z, "close") ){
21164           mType |= SQLITE_TRACE_CLOSE;
21165         }
21166         else {
21167           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
21168           rc = 1;
21169           goto meta_command_exit;
21170         }
21171       }else{
21172         output_file_close(p->traceOut);
21173         p->traceOut = output_file_open(azArg[1], 0);
21174       }
21175     }
21176     if( p->traceOut==0 ){
21177       sqlite3_trace_v2(p->db, 0, 0, 0);
21178     }else{
21179       if( mType==0 ) mType = SQLITE_TRACE_STMT;
21180       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
21181     }
21182   }else
21183 #endif /* !defined(SQLITE_OMIT_TRACE) */
21184 
21185 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
21186   if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
21187     int ii;
21188     int lenOpt;
21189     char *zOpt;
21190     if( nArg<2 ){
21191       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
21192       rc = 1;
21193       goto meta_command_exit;
21194     }
21195     open_db(p, 0);
21196     zOpt = azArg[1];
21197     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
21198     lenOpt = (int)strlen(zOpt);
21199     if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
21200       assert( azArg[nArg]==0 );
21201       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
21202     }else{
21203       for(ii=1; ii<nArg; ii++){
21204         sqlite3_create_module(p->db, azArg[ii], 0, 0);
21205       }
21206     }
21207   }else
21208 #endif
21209 
21210 #if SQLITE_USER_AUTHENTICATION
21211   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
21212     if( nArg<2 ){
21213       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
21214       rc = 1;
21215       goto meta_command_exit;
21216     }
21217     open_db(p, 0);
21218     if( strcmp(azArg[1],"login")==0 ){
21219       if( nArg!=4 ){
21220         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
21221         rc = 1;
21222         goto meta_command_exit;
21223       }
21224       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
21225                                      strlen30(azArg[3]));
21226       if( rc ){
21227         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
21228         rc = 1;
21229       }
21230     }else if( strcmp(azArg[1],"add")==0 ){
21231       if( nArg!=5 ){
21232         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
21233         rc = 1;
21234         goto meta_command_exit;
21235       }
21236       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
21237                             booleanValue(azArg[4]));
21238       if( rc ){
21239         raw_printf(stderr, "User-Add failed: %d\n", rc);
21240         rc = 1;
21241       }
21242     }else if( strcmp(azArg[1],"edit")==0 ){
21243       if( nArg!=5 ){
21244         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
21245         rc = 1;
21246         goto meta_command_exit;
21247       }
21248       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
21249                               booleanValue(azArg[4]));
21250       if( rc ){
21251         raw_printf(stderr, "User-Edit failed: %d\n", rc);
21252         rc = 1;
21253       }
21254     }else if( strcmp(azArg[1],"delete")==0 ){
21255       if( nArg!=3 ){
21256         raw_printf(stderr, "Usage: .user delete USER\n");
21257         rc = 1;
21258         goto meta_command_exit;
21259       }
21260       rc = sqlite3_user_delete(p->db, azArg[2]);
21261       if( rc ){
21262         raw_printf(stderr, "User-Delete failed: %d\n", rc);
21263         rc = 1;
21264       }
21265     }else{
21266       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
21267       rc = 1;
21268       goto meta_command_exit;
21269     }
21270   }else
21271 #endif /* SQLITE_USER_AUTHENTICATION */
21272 
21273   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
21274     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
21275         sqlite3_libversion(), sqlite3_sourceid());
21276 #if SQLITE_HAVE_ZLIB
21277     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
21278 #endif
21279 #define CTIMEOPT_VAL_(opt) #opt
21280 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
21281 #if defined(__clang__) && defined(__clang_major__)
21282     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
21283                     CTIMEOPT_VAL(__clang_minor__) "."
21284                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
21285 #elif defined(_MSC_VER)
21286     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
21287 #elif defined(__GNUC__) && defined(__VERSION__)
21288     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
21289 #endif
21290   }else
21291 
21292   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
21293     const char *zDbName = nArg==2 ? azArg[1] : "main";
21294     sqlite3_vfs *pVfs = 0;
21295     if( p->db ){
21296       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
21297       if( pVfs ){
21298         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
21299         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
21300         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
21301         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
21302       }
21303     }
21304   }else
21305 
21306   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
21307     sqlite3_vfs *pVfs;
21308     sqlite3_vfs *pCurrent = 0;
21309     if( p->db ){
21310       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
21311     }
21312     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
21313       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
21314            pVfs==pCurrent ? "  <--- CURRENT" : "");
21315       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
21316       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
21317       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
21318       if( pVfs->pNext ){
21319         raw_printf(p->out, "-----------------------------------\n");
21320       }
21321     }
21322   }else
21323 
21324   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
21325     const char *zDbName = nArg==2 ? azArg[1] : "main";
21326     char *zVfsName = 0;
21327     if( p->db ){
21328       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
21329       if( zVfsName ){
21330         utf8_printf(p->out, "%s\n", zVfsName);
21331         sqlite3_free(zVfsName);
21332       }
21333     }
21334   }else
21335 
21336   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
21337     unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
21338     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
21339   }else
21340 
21341   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
21342     int j;
21343     assert( nArg<=ArraySize(azArg) );
21344     p->nWidth = nArg-1;
21345     p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
21346     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
21347     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
21348     for(j=1; j<nArg; j++){
21349       p->colWidth[j-1] = (int)integerValue(azArg[j]);
21350     }
21351   }else
21352 
21353   {
21354     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
21355       " \"%s\". Enter \".help\" for help\n", azArg[0]);
21356     rc = 1;
21357   }
21358 
21359 meta_command_exit:
21360   if( p->outCount ){
21361     p->outCount--;
21362     if( p->outCount==0 ) output_reset(p);
21363   }
21364   return rc;
21365 }
21366 
21367 /*
21368 ** Return TRUE if a semicolon occurs anywhere in the first N characters
21369 ** of string z[].
21370 */
line_contains_semicolon(const char * z,int N)21371 static int line_contains_semicolon(const char *z, int N){
21372   int i;
21373   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
21374   return 0;
21375 }
21376 
21377 /*
21378 ** Test to see if a line consists entirely of whitespace.
21379 */
_all_whitespace(const char * z)21380 static int _all_whitespace(const char *z){
21381   for(; *z; z++){
21382     if( IsSpace(z[0]) ) continue;
21383     if( *z=='/' && z[1]=='*' ){
21384       z += 2;
21385       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
21386       if( *z==0 ) return 0;
21387       z++;
21388       continue;
21389     }
21390     if( *z=='-' && z[1]=='-' ){
21391       z += 2;
21392       while( *z && *z!='\n' ){ z++; }
21393       if( *z==0 ) return 1;
21394       continue;
21395     }
21396     return 0;
21397   }
21398   return 1;
21399 }
21400 
21401 /*
21402 ** Return TRUE if the line typed in is an SQL command terminator other
21403 ** than a semi-colon.  The SQL Server style "go" command is understood
21404 ** as is the Oracle "/".
21405 */
line_is_command_terminator(const char * zLine)21406 static int line_is_command_terminator(const char *zLine){
21407   while( IsSpace(zLine[0]) ){ zLine++; };
21408   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
21409     return 1;  /* Oracle */
21410   }
21411   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
21412          && _all_whitespace(&zLine[2]) ){
21413     return 1;  /* SQL Server */
21414   }
21415   return 0;
21416 }
21417 
21418 /*
21419 ** We need a default sqlite3_complete() implementation to use in case
21420 ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
21421 ** any arbitrary text is a complete SQL statement.  This is not very
21422 ** user-friendly, but it does seem to work.
21423 */
21424 #ifdef SQLITE_OMIT_COMPLETE
21425 #define sqlite3_complete(x) 1
21426 #endif
21427 
21428 /*
21429 ** Return true if zSql is a complete SQL statement.  Return false if it
21430 ** ends in the middle of a string literal or C-style comment.
21431 */
line_is_complete(char * zSql,int nSql)21432 static int line_is_complete(char *zSql, int nSql){
21433   int rc;
21434   if( zSql==0 ) return 1;
21435   zSql[nSql] = ';';
21436   zSql[nSql+1] = 0;
21437   rc = sqlite3_complete(zSql);
21438   zSql[nSql] = 0;
21439   return rc;
21440 }
21441 
21442 /*
21443 ** Run a single line of SQL.  Return the number of errors.
21444 */
runOneSqlLine(ShellState * p,char * zSql,FILE * in,int startline)21445 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
21446   int rc;
21447   char *zErrMsg = 0;
21448 
21449   open_db(p, 0);
21450   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
21451   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
21452   BEGIN_TIMER;
21453   rc = shell_exec(p, zSql, &zErrMsg);
21454   END_TIMER;
21455   if( rc || zErrMsg ){
21456     char zPrefix[100];
21457     if( in!=0 || !stdin_is_interactive ){
21458       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
21459                        "Error: near line %d:", startline);
21460     }else{
21461       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
21462     }
21463     if( zErrMsg!=0 ){
21464       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
21465       sqlite3_free(zErrMsg);
21466       zErrMsg = 0;
21467     }else{
21468       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
21469     }
21470     return 1;
21471   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
21472     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
21473             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
21474   }
21475   return 0;
21476 }
21477 
21478 
21479 /*
21480 ** Read input from *in and process it.  If *in==0 then input
21481 ** is interactive - the user is typing it it.  Otherwise, input
21482 ** is coming from a file or device.  A prompt is issued and history
21483 ** is saved only if input is interactive.  An interrupt signal will
21484 ** cause this routine to exit immediately, unless input is interactive.
21485 **
21486 ** Return the number of errors.
21487 */
process_input(ShellState * p)21488 static int process_input(ShellState *p){
21489   char *zLine = 0;          /* A single input line */
21490   char *zSql = 0;           /* Accumulated SQL text */
21491   int nLine;                /* Length of current line */
21492   int nSql = 0;             /* Bytes of zSql[] used */
21493   int nAlloc = 0;           /* Allocated zSql[] space */
21494   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
21495   int rc;                   /* Error code */
21496   int errCnt = 0;           /* Number of errors seen */
21497   int startline = 0;        /* Line number for start of current input */
21498 
21499   p->lineno = 0;
21500   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
21501     fflush(p->out);
21502     zLine = one_input_line(p->in, zLine, nSql>0);
21503     if( zLine==0 ){
21504       /* End of input */
21505       if( p->in==0 && stdin_is_interactive ) printf("\n");
21506       break;
21507     }
21508     if( seenInterrupt ){
21509       if( p->in!=0 ) break;
21510       seenInterrupt = 0;
21511     }
21512     p->lineno++;
21513     if( nSql==0 && _all_whitespace(zLine) ){
21514       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
21515       continue;
21516     }
21517     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
21518       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
21519       if( zLine[0]=='.' ){
21520         rc = do_meta_command(zLine, p);
21521         if( rc==2 ){ /* exit requested */
21522           break;
21523         }else if( rc ){
21524           errCnt++;
21525         }
21526       }
21527       continue;
21528     }
21529     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
21530       memcpy(zLine,";",2);
21531     }
21532     nLine = strlen30(zLine);
21533     if( nSql+nLine+2>=nAlloc ){
21534       nAlloc = nSql+nLine+100;
21535       zSql = realloc(zSql, nAlloc);
21536       if( zSql==0 ) shell_out_of_memory();
21537     }
21538     nSqlPrior = nSql;
21539     if( nSql==0 ){
21540       int i;
21541       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
21542       assert( nAlloc>0 && zSql!=0 );
21543       memcpy(zSql, zLine+i, nLine+1-i);
21544       startline = p->lineno;
21545       nSql = nLine-i;
21546     }else{
21547       zSql[nSql++] = '\n';
21548       memcpy(zSql+nSql, zLine, nLine+1);
21549       nSql += nLine;
21550     }
21551     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
21552                 && sqlite3_complete(zSql) ){
21553       errCnt += runOneSqlLine(p, zSql, p->in, startline);
21554       nSql = 0;
21555       if( p->outCount ){
21556         output_reset(p);
21557         p->outCount = 0;
21558       }else{
21559         clearTempFile(p);
21560       }
21561     }else if( nSql && _all_whitespace(zSql) ){
21562       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
21563       nSql = 0;
21564     }
21565   }
21566   if( nSql && !_all_whitespace(zSql) ){
21567     errCnt += runOneSqlLine(p, zSql, p->in, startline);
21568   }
21569   free(zSql);
21570   free(zLine);
21571   return errCnt>0;
21572 }
21573 
21574 /*
21575 ** Return a pathname which is the user's home directory.  A
21576 ** 0 return indicates an error of some kind.
21577 */
find_home_dir(int clearFlag)21578 static char *find_home_dir(int clearFlag){
21579   static char *home_dir = NULL;
21580   if( clearFlag ){
21581     free(home_dir);
21582     home_dir = 0;
21583     return 0;
21584   }
21585   if( home_dir ) return home_dir;
21586 
21587 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
21588      && !defined(__RTP__) && !defined(_WRS_KERNEL)
21589   {
21590     struct passwd *pwent;
21591     uid_t uid = getuid();
21592     if( (pwent=getpwuid(uid)) != NULL) {
21593       home_dir = pwent->pw_dir;
21594     }
21595   }
21596 #endif
21597 
21598 #if defined(_WIN32_WCE)
21599   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
21600    */
21601   home_dir = "/";
21602 #else
21603 
21604 #if defined(_WIN32) || defined(WIN32)
21605   if (!home_dir) {
21606     home_dir = getenv("USERPROFILE");
21607   }
21608 #endif
21609 
21610   if (!home_dir) {
21611     home_dir = getenv("HOME");
21612   }
21613 
21614 #if defined(_WIN32) || defined(WIN32)
21615   if (!home_dir) {
21616     char *zDrive, *zPath;
21617     int n;
21618     zDrive = getenv("HOMEDRIVE");
21619     zPath = getenv("HOMEPATH");
21620     if( zDrive && zPath ){
21621       n = strlen30(zDrive) + strlen30(zPath) + 1;
21622       home_dir = malloc( n );
21623       if( home_dir==0 ) return 0;
21624       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
21625       return home_dir;
21626     }
21627     home_dir = "c:\\";
21628   }
21629 #endif
21630 
21631 #endif /* !_WIN32_WCE */
21632 
21633   if( home_dir ){
21634     int n = strlen30(home_dir) + 1;
21635     char *z = malloc( n );
21636     if( z ) memcpy(z, home_dir, n);
21637     home_dir = z;
21638   }
21639 
21640   return home_dir;
21641 }
21642 
21643 /*
21644 ** Read input from the file given by sqliterc_override.  Or if that
21645 ** parameter is NULL, take input from ~/.sqliterc
21646 **
21647 ** Returns the number of errors.
21648 */
process_sqliterc(ShellState * p,const char * sqliterc_override)21649 static void process_sqliterc(
21650   ShellState *p,                  /* Configuration data */
21651   const char *sqliterc_override   /* Name of config file. NULL to use default */
21652 ){
21653   char *home_dir = NULL;
21654   const char *sqliterc = sqliterc_override;
21655   char *zBuf = 0;
21656   FILE *inSaved = p->in;
21657   int savedLineno = p->lineno;
21658 
21659   if (sqliterc == NULL) {
21660     home_dir = find_home_dir(0);
21661     if( home_dir==0 ){
21662       raw_printf(stderr, "-- warning: cannot find home directory;"
21663                       " cannot read ~/.sqliterc\n");
21664       return;
21665     }
21666     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
21667     sqliterc = zBuf;
21668   }
21669   p->in = fopen(sqliterc,"rb");
21670   if( p->in ){
21671     if( stdin_is_interactive ){
21672       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
21673     }
21674     if( process_input(p) && bail_on_error ) exit(1);
21675     fclose(p->in);
21676   }else if( sqliterc_override!=0 ){
21677     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
21678     if( bail_on_error ) exit(1);
21679   }
21680   p->in = inSaved;
21681   p->lineno = savedLineno;
21682   sqlite3_free(zBuf);
21683 }
21684 
21685 /*
21686 ** Show available command line options
21687 */
21688 static const char zOptions[] =
21689 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
21690   "   -A ARGS...           run \".archive ARGS\" and exit\n"
21691 #endif
21692   "   -append              append the database to the end of the file\n"
21693   "   -ascii               set output mode to 'ascii'\n"
21694   "   -bail                stop after hitting an error\n"
21695   "   -batch               force batch I/O\n"
21696   "   -box                 set output mode to 'box'\n"
21697   "   -column              set output mode to 'column'\n"
21698   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
21699   "   -csv                 set output mode to 'csv'\n"
21700 #if !defined(SQLITE_OMIT_DESERIALIZE)
21701   "   -deserialize         open the database using sqlite3_deserialize()\n"
21702 #endif
21703   "   -echo                print commands before execution\n"
21704   "   -init FILENAME       read/process named file\n"
21705   "   -[no]header          turn headers on or off\n"
21706 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
21707   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
21708 #endif
21709   "   -help                show this message\n"
21710   "   -html                set output mode to HTML\n"
21711   "   -interactive         force interactive I/O\n"
21712   "   -json                set output mode to 'json'\n"
21713   "   -line                set output mode to 'line'\n"
21714   "   -list                set output mode to 'list'\n"
21715   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
21716   "   -markdown            set output mode to 'markdown'\n"
21717 #if !defined(SQLITE_OMIT_DESERIALIZE)
21718   "   -maxsize N           maximum size for a --deserialize database\n"
21719 #endif
21720   "   -memtrace            trace all memory allocations and deallocations\n"
21721   "   -mmap N              default mmap size set to N\n"
21722 #ifdef SQLITE_ENABLE_MULTIPLEX
21723   "   -multiplex           enable the multiplexor VFS\n"
21724 #endif
21725   "   -newline SEP         set output row separator. Default: '\\n'\n"
21726   "   -nofollow            refuse to open symbolic links to database files\n"
21727   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
21728   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
21729   "   -quote               set output mode to 'quote'\n"
21730   "   -readonly            open the database read-only\n"
21731   "   -separator SEP       set output column separator. Default: '|'\n"
21732 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
21733   "   -sorterref SIZE      sorter references threshold size\n"
21734 #endif
21735   "   -stats               print memory stats before each finalize\n"
21736   "   -table               set output mode to 'table'\n"
21737   "   -tabs                set output mode to 'tabs'\n"
21738   "   -version             show SQLite version\n"
21739   "   -vfs NAME            use NAME as the default VFS\n"
21740 #ifdef SQLITE_ENABLE_VFSTRACE
21741   "   -vfstrace            enable tracing of all VFS calls\n"
21742 #endif
21743 #ifdef SQLITE_HAVE_ZLIB
21744   "   -zip                 open the file as a ZIP Archive\n"
21745 #endif
21746 ;
usage(int showDetail)21747 static void usage(int showDetail){
21748   utf8_printf(stderr,
21749       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
21750       "FILENAME is the name of an SQLite database. A new database is created\n"
21751       "if the file does not previously exist.\n", Argv0);
21752   if( showDetail ){
21753     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
21754   }else{
21755     raw_printf(stderr, "Use the -help option for additional information\n");
21756   }
21757   exit(1);
21758 }
21759 
21760 /*
21761 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
21762 ** error message if it is initialized.
21763 */
verify_uninitialized(void)21764 static void verify_uninitialized(void){
21765   if( sqlite3_config(-1)==SQLITE_MISUSE ){
21766     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
21767                         " initialization.\n");
21768   }
21769 }
21770 
21771 /*
21772 ** Initialize the state information in data
21773 */
main_init(ShellState * data)21774 static void main_init(ShellState *data) {
21775   memset(data, 0, sizeof(*data));
21776   data->normalMode = data->cMode = data->mode = MODE_List;
21777   data->autoExplain = 1;
21778   memcpy(data->colSeparator,SEP_Column, 2);
21779   memcpy(data->rowSeparator,SEP_Row, 2);
21780   data->showHeader = 0;
21781   data->shellFlgs = SHFLG_Lookaside;
21782   verify_uninitialized();
21783   sqlite3_config(SQLITE_CONFIG_URI, 1);
21784   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
21785   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
21786   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
21787   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
21788 }
21789 
21790 /*
21791 ** Output text to the console in a font that attracts extra attention.
21792 */
21793 #ifdef _WIN32
printBold(const char * zText)21794 static void printBold(const char *zText){
21795 #if !SQLITE_OS_WINRT
21796   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
21797   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
21798   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
21799   SetConsoleTextAttribute(out,
21800          FOREGROUND_RED|FOREGROUND_INTENSITY
21801   );
21802 #endif
21803   printf("%s", zText);
21804 #if !SQLITE_OS_WINRT
21805   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
21806 #endif
21807 }
21808 #else
printBold(const char * zText)21809 static void printBold(const char *zText){
21810   printf("\033[1m%s\033[0m", zText);
21811 }
21812 #endif
21813 
21814 /*
21815 ** Get the argument to an --option.  Throw an error and die if no argument
21816 ** is available.
21817 */
cmdline_option_value(int argc,char ** argv,int i)21818 static char *cmdline_option_value(int argc, char **argv, int i){
21819   if( i==argc ){
21820     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
21821             argv[0], argv[argc-1]);
21822     exit(1);
21823   }
21824   return argv[i];
21825 }
21826 
21827 #ifndef SQLITE_SHELL_IS_UTF8
21828 #  if (defined(_WIN32) || defined(WIN32)) \
21829    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
21830 #    define SQLITE_SHELL_IS_UTF8          (0)
21831 #  else
21832 #    define SQLITE_SHELL_IS_UTF8          (1)
21833 #  endif
21834 #endif
21835 
21836 #if SQLITE_SHELL_IS_UTF8
main(int argc,char ** argv)21837 int SQLITE_CDECL main(int argc, char **argv){
21838 #else
21839 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
21840   char **argv;
21841 #endif
21842   char *zErrMsg = 0;
21843   ShellState data;
21844   const char *zInitFile = 0;
21845   int i;
21846   int rc = 0;
21847   int warnInmemoryDb = 0;
21848   int readStdin = 1;
21849   int nCmd = 0;
21850   char **azCmd = 0;
21851   const char *zVfs = 0;           /* Value of -vfs command-line option */
21852 #if !SQLITE_SHELL_IS_UTF8
21853   char **argvToFree = 0;
21854   int argcToFree = 0;
21855 #endif
21856 
21857   setBinaryMode(stdin, 0);
21858   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
21859   stdin_is_interactive = isatty(0);
21860   stdout_is_console = isatty(1);
21861 
21862 #ifdef SQLITE_DEBUG
21863   registerOomSimulator();
21864 #endif
21865 
21866 #if !defined(_WIN32_WCE)
21867   if( getenv("SQLITE_DEBUG_BREAK") ){
21868     if( isatty(0) && isatty(2) ){
21869       fprintf(stderr,
21870           "attach debugger to process %d and press any key to continue.\n",
21871           GETPID());
21872       fgetc(stdin);
21873     }else{
21874 #if defined(_WIN32) || defined(WIN32)
21875 #if SQLITE_OS_WINRT
21876       __debugbreak();
21877 #else
21878       DebugBreak();
21879 #endif
21880 #elif defined(SIGTRAP)
21881       raise(SIGTRAP);
21882 #endif
21883     }
21884   }
21885 #endif
21886 
21887 #if USE_SYSTEM_SQLITE+0!=1
21888   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
21889     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
21890             sqlite3_sourceid(), SQLITE_SOURCE_ID);
21891     exit(1);
21892   }
21893 #endif
21894   main_init(&data);
21895 
21896   /* On Windows, we must translate command-line arguments into UTF-8.
21897   ** The SQLite memory allocator subsystem has to be enabled in order to
21898   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
21899   ** subsequent sqlite3_config() calls will work.  So copy all results into
21900   ** memory that does not come from the SQLite memory allocator.
21901   */
21902 #if !SQLITE_SHELL_IS_UTF8
21903   sqlite3_initialize();
21904   argvToFree = malloc(sizeof(argv[0])*argc*2);
21905   argcToFree = argc;
21906   argv = argvToFree + argc;
21907   if( argv==0 ) shell_out_of_memory();
21908   for(i=0; i<argc; i++){
21909     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
21910     int n;
21911     if( z==0 ) shell_out_of_memory();
21912     n = (int)strlen(z);
21913     argv[i] = malloc( n+1 );
21914     if( argv[i]==0 ) shell_out_of_memory();
21915     memcpy(argv[i], z, n+1);
21916     argvToFree[i] = argv[i];
21917     sqlite3_free(z);
21918   }
21919   sqlite3_shutdown();
21920 #endif
21921 
21922   assert( argc>=1 && argv && argv[0] );
21923   Argv0 = argv[0];
21924 
21925   /* Make sure we have a valid signal handler early, before anything
21926   ** else is done.
21927   */
21928 #ifdef SIGINT
21929   signal(SIGINT, interrupt_handler);
21930 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
21931   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
21932 #endif
21933 
21934 #ifdef SQLITE_SHELL_DBNAME_PROC
21935   {
21936     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
21937     ** of a C-function that will provide the name of the database file.  Use
21938     ** this compile-time option to embed this shell program in larger
21939     ** applications. */
21940     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
21941     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
21942     warnInmemoryDb = 0;
21943   }
21944 #endif
21945 
21946   /* Do an initial pass through the command-line argument to locate
21947   ** the name of the database file, the name of the initialization file,
21948   ** the size of the alternative malloc heap,
21949   ** and the first command to execute.
21950   */
21951   verify_uninitialized();
21952   for(i=1; i<argc; i++){
21953     char *z;
21954     z = argv[i];
21955     if( z[0]!='-' ){
21956       if( data.zDbFilename==0 ){
21957         data.zDbFilename = z;
21958       }else{
21959         /* Excesss arguments are interpreted as SQL (or dot-commands) and
21960         ** mean that nothing is read from stdin */
21961         readStdin = 0;
21962         nCmd++;
21963         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
21964         if( azCmd==0 ) shell_out_of_memory();
21965         azCmd[nCmd-1] = z;
21966       }
21967     }
21968     if( z[1]=='-' ) z++;
21969     if( strcmp(z,"-separator")==0
21970      || strcmp(z,"-nullvalue")==0
21971      || strcmp(z,"-newline")==0
21972      || strcmp(z,"-cmd")==0
21973     ){
21974       (void)cmdline_option_value(argc, argv, ++i);
21975     }else if( strcmp(z,"-init")==0 ){
21976       zInitFile = cmdline_option_value(argc, argv, ++i);
21977     }else if( strcmp(z,"-batch")==0 ){
21978       /* Need to check for batch mode here to so we can avoid printing
21979       ** informational messages (like from process_sqliterc) before
21980       ** we do the actual processing of arguments later in a second pass.
21981       */
21982       stdin_is_interactive = 0;
21983     }else if( strcmp(z,"-heap")==0 ){
21984 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
21985       const char *zSize;
21986       sqlite3_int64 szHeap;
21987 
21988       zSize = cmdline_option_value(argc, argv, ++i);
21989       szHeap = integerValue(zSize);
21990       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
21991       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
21992 #else
21993       (void)cmdline_option_value(argc, argv, ++i);
21994 #endif
21995     }else if( strcmp(z,"-pagecache")==0 ){
21996       sqlite3_int64 n, sz;
21997       sz = integerValue(cmdline_option_value(argc,argv,++i));
21998       if( sz>70000 ) sz = 70000;
21999       if( sz<0 ) sz = 0;
22000       n = integerValue(cmdline_option_value(argc,argv,++i));
22001       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
22002         n = 0xffffffffffffLL/sz;
22003       }
22004       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
22005                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
22006       data.shellFlgs |= SHFLG_Pagecache;
22007     }else if( strcmp(z,"-lookaside")==0 ){
22008       int n, sz;
22009       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
22010       if( sz<0 ) sz = 0;
22011       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
22012       if( n<0 ) n = 0;
22013       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
22014       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
22015 #ifdef SQLITE_ENABLE_VFSTRACE
22016     }else if( strcmp(z,"-vfstrace")==0 ){
22017       extern int vfstrace_register(
22018          const char *zTraceName,
22019          const char *zOldVfsName,
22020          int (*xOut)(const char*,void*),
22021          void *pOutArg,
22022          int makeDefault
22023       );
22024       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
22025 #endif
22026 #ifdef SQLITE_ENABLE_MULTIPLEX
22027     }else if( strcmp(z,"-multiplex")==0 ){
22028       extern int sqlite3_multiple_initialize(const char*,int);
22029       sqlite3_multiplex_initialize(0, 1);
22030 #endif
22031     }else if( strcmp(z,"-mmap")==0 ){
22032       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
22033       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
22034 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
22035     }else if( strcmp(z,"-sorterref")==0 ){
22036       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
22037       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
22038 #endif
22039     }else if( strcmp(z,"-vfs")==0 ){
22040       zVfs = cmdline_option_value(argc, argv, ++i);
22041 #ifdef SQLITE_HAVE_ZLIB
22042     }else if( strcmp(z,"-zip")==0 ){
22043       data.openMode = SHELL_OPEN_ZIPFILE;
22044 #endif
22045     }else if( strcmp(z,"-append")==0 ){
22046       data.openMode = SHELL_OPEN_APPENDVFS;
22047 #ifndef SQLITE_OMIT_DESERIALIZE
22048     }else if( strcmp(z,"-deserialize")==0 ){
22049       data.openMode = SHELL_OPEN_DESERIALIZE;
22050     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
22051       data.szMax = integerValue(argv[++i]);
22052 #endif
22053     }else if( strcmp(z,"-readonly")==0 ){
22054       data.openMode = SHELL_OPEN_READONLY;
22055     }else if( strcmp(z,"-nofollow")==0 ){
22056       data.openFlags = SQLITE_OPEN_NOFOLLOW;
22057 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
22058     }else if( strncmp(z, "-A",2)==0 ){
22059       /* All remaining command-line arguments are passed to the ".archive"
22060       ** command, so ignore them */
22061       break;
22062 #endif
22063     }else if( strcmp(z, "-memtrace")==0 ){
22064       sqlite3MemTraceActivate(stderr);
22065     }else if( strcmp(z,"-bail")==0 ){
22066       bail_on_error = 1;
22067     }
22068   }
22069   verify_uninitialized();
22070 
22071 
22072 #ifdef SQLITE_SHELL_INIT_PROC
22073   {
22074     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
22075     ** of a C-function that will perform initialization actions on SQLite that
22076     ** occur just before or after sqlite3_initialize(). Use this compile-time
22077     ** option to embed this shell program in larger applications. */
22078     extern void SQLITE_SHELL_INIT_PROC(void);
22079     SQLITE_SHELL_INIT_PROC();
22080   }
22081 #else
22082   /* All the sqlite3_config() calls have now been made. So it is safe
22083   ** to call sqlite3_initialize() and process any command line -vfs option. */
22084   sqlite3_initialize();
22085 #endif
22086 
22087   if( zVfs ){
22088     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
22089     if( pVfs ){
22090       sqlite3_vfs_register(pVfs, 1);
22091     }else{
22092       utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
22093       exit(1);
22094     }
22095   }
22096 
22097   if( data.zDbFilename==0 ){
22098 #ifndef SQLITE_OMIT_MEMORYDB
22099     data.zDbFilename = ":memory:";
22100     warnInmemoryDb = argc==1;
22101 #else
22102     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
22103     return 1;
22104 #endif
22105   }
22106   data.out = stdout;
22107   sqlite3_appendvfs_init(0,0,0);
22108 
22109   /* Go ahead and open the database file if it already exists.  If the
22110   ** file does not exist, delay opening it.  This prevents empty database
22111   ** files from being created if a user mistypes the database name argument
22112   ** to the sqlite command-line tool.
22113   */
22114   if( access(data.zDbFilename, 0)==0 ){
22115     open_db(&data, 0);
22116   }
22117 
22118   /* Process the initialization file if there is one.  If no -init option
22119   ** is given on the command line, look for a file named ~/.sqliterc and
22120   ** try to process it.
22121   */
22122   process_sqliterc(&data,zInitFile);
22123 
22124   /* Make a second pass through the command-line argument and set
22125   ** options.  This second pass is delayed until after the initialization
22126   ** file is processed so that the command-line arguments will override
22127   ** settings in the initialization file.
22128   */
22129   for(i=1; i<argc; i++){
22130     char *z = argv[i];
22131     if( z[0]!='-' ) continue;
22132     if( z[1]=='-' ){ z++; }
22133     if( strcmp(z,"-init")==0 ){
22134       i++;
22135     }else if( strcmp(z,"-html")==0 ){
22136       data.mode = MODE_Html;
22137     }else if( strcmp(z,"-list")==0 ){
22138       data.mode = MODE_List;
22139     }else if( strcmp(z,"-quote")==0 ){
22140       data.mode = MODE_Quote;
22141       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
22142       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
22143     }else if( strcmp(z,"-line")==0 ){
22144       data.mode = MODE_Line;
22145     }else if( strcmp(z,"-column")==0 ){
22146       data.mode = MODE_Column;
22147     }else if( strcmp(z,"-json")==0 ){
22148       data.mode = MODE_Json;
22149     }else if( strcmp(z,"-markdown")==0 ){
22150       data.mode = MODE_Markdown;
22151     }else if( strcmp(z,"-table")==0 ){
22152       data.mode = MODE_Table;
22153     }else if( strcmp(z,"-box")==0 ){
22154       data.mode = MODE_Box;
22155     }else if( strcmp(z,"-csv")==0 ){
22156       data.mode = MODE_Csv;
22157       memcpy(data.colSeparator,",",2);
22158 #ifdef SQLITE_HAVE_ZLIB
22159     }else if( strcmp(z,"-zip")==0 ){
22160       data.openMode = SHELL_OPEN_ZIPFILE;
22161 #endif
22162     }else if( strcmp(z,"-append")==0 ){
22163       data.openMode = SHELL_OPEN_APPENDVFS;
22164 #ifndef SQLITE_OMIT_DESERIALIZE
22165     }else if( strcmp(z,"-deserialize")==0 ){
22166       data.openMode = SHELL_OPEN_DESERIALIZE;
22167     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
22168       data.szMax = integerValue(argv[++i]);
22169 #endif
22170     }else if( strcmp(z,"-readonly")==0 ){
22171       data.openMode = SHELL_OPEN_READONLY;
22172     }else if( strcmp(z,"-nofollow")==0 ){
22173       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
22174     }else if( strcmp(z,"-ascii")==0 ){
22175       data.mode = MODE_Ascii;
22176       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
22177       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
22178     }else if( strcmp(z,"-tabs")==0 ){
22179       data.mode = MODE_List;
22180       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
22181       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
22182     }else if( strcmp(z,"-separator")==0 ){
22183       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
22184                        "%s",cmdline_option_value(argc,argv,++i));
22185     }else if( strcmp(z,"-newline")==0 ){
22186       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
22187                        "%s",cmdline_option_value(argc,argv,++i));
22188     }else if( strcmp(z,"-nullvalue")==0 ){
22189       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
22190                        "%s",cmdline_option_value(argc,argv,++i));
22191     }else if( strcmp(z,"-header")==0 ){
22192       data.showHeader = 1;
22193     }else if( strcmp(z,"-noheader")==0 ){
22194       data.showHeader = 0;
22195     }else if( strcmp(z,"-echo")==0 ){
22196       ShellSetFlag(&data, SHFLG_Echo);
22197     }else if( strcmp(z,"-eqp")==0 ){
22198       data.autoEQP = AUTOEQP_on;
22199     }else if( strcmp(z,"-eqpfull")==0 ){
22200       data.autoEQP = AUTOEQP_full;
22201     }else if( strcmp(z,"-stats")==0 ){
22202       data.statsOn = 1;
22203     }else if( strcmp(z,"-scanstats")==0 ){
22204       data.scanstatsOn = 1;
22205     }else if( strcmp(z,"-backslash")==0 ){
22206       /* Undocumented command-line option: -backslash
22207       ** Causes C-style backslash escapes to be evaluated in SQL statements
22208       ** prior to sending the SQL into SQLite.  Useful for injecting
22209       ** crazy bytes in the middle of SQL statements for testing and debugging.
22210       */
22211       ShellSetFlag(&data, SHFLG_Backslash);
22212     }else if( strcmp(z,"-bail")==0 ){
22213       /* No-op.  The bail_on_error flag should already be set. */
22214     }else if( strcmp(z,"-version")==0 ){
22215       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
22216       return 0;
22217     }else if( strcmp(z,"-interactive")==0 ){
22218       stdin_is_interactive = 1;
22219     }else if( strcmp(z,"-batch")==0 ){
22220       stdin_is_interactive = 0;
22221     }else if( strcmp(z,"-heap")==0 ){
22222       i++;
22223     }else if( strcmp(z,"-pagecache")==0 ){
22224       i+=2;
22225     }else if( strcmp(z,"-lookaside")==0 ){
22226       i+=2;
22227     }else if( strcmp(z,"-mmap")==0 ){
22228       i++;
22229     }else if( strcmp(z,"-memtrace")==0 ){
22230       i++;
22231 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
22232     }else if( strcmp(z,"-sorterref")==0 ){
22233       i++;
22234 #endif
22235     }else if( strcmp(z,"-vfs")==0 ){
22236       i++;
22237 #ifdef SQLITE_ENABLE_VFSTRACE
22238     }else if( strcmp(z,"-vfstrace")==0 ){
22239       i++;
22240 #endif
22241 #ifdef SQLITE_ENABLE_MULTIPLEX
22242     }else if( strcmp(z,"-multiplex")==0 ){
22243       i++;
22244 #endif
22245     }else if( strcmp(z,"-help")==0 ){
22246       usage(1);
22247     }else if( strcmp(z,"-cmd")==0 ){
22248       /* Run commands that follow -cmd first and separately from commands
22249       ** that simply appear on the command-line.  This seems goofy.  It would
22250       ** be better if all commands ran in the order that they appear.  But
22251       ** we retain the goofy behavior for historical compatibility. */
22252       if( i==argc-1 ) break;
22253       z = cmdline_option_value(argc,argv,++i);
22254       if( z[0]=='.' ){
22255         rc = do_meta_command(z, &data);
22256         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
22257       }else{
22258         open_db(&data, 0);
22259         rc = shell_exec(&data, z, &zErrMsg);
22260         if( zErrMsg!=0 ){
22261           utf8_printf(stderr,"Error: %s\n", zErrMsg);
22262           if( bail_on_error ) return rc!=0 ? rc : 1;
22263         }else if( rc!=0 ){
22264           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
22265           if( bail_on_error ) return rc;
22266         }
22267       }
22268 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
22269     }else if( strncmp(z, "-A", 2)==0 ){
22270       if( nCmd>0 ){
22271         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
22272                             " with \"%s\"\n", z);
22273         return 1;
22274       }
22275       open_db(&data, OPEN_DB_ZIPFILE);
22276       if( z[2] ){
22277         argv[i] = &z[2];
22278         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
22279       }else{
22280         arDotCommand(&data, 1, argv+i, argc-i);
22281       }
22282       readStdin = 0;
22283       break;
22284 #endif
22285     }else{
22286       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
22287       raw_printf(stderr,"Use -help for a list of options.\n");
22288       return 1;
22289     }
22290     data.cMode = data.mode;
22291   }
22292 
22293   if( !readStdin ){
22294     /* Run all arguments that do not begin with '-' as if they were separate
22295     ** command-line inputs, except for the argToSkip argument which contains
22296     ** the database filename.
22297     */
22298     for(i=0; i<nCmd; i++){
22299       if( azCmd[i][0]=='.' ){
22300         rc = do_meta_command(azCmd[i], &data);
22301         if( rc ){
22302           free(azCmd);
22303           return rc==2 ? 0 : rc;
22304         }
22305       }else{
22306         open_db(&data, 0);
22307         rc = shell_exec(&data, azCmd[i], &zErrMsg);
22308         if( zErrMsg || rc ){
22309           if( zErrMsg!=0 ){
22310             utf8_printf(stderr,"Error: %s\n", zErrMsg);
22311           }else{
22312             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
22313           }
22314           sqlite3_free(zErrMsg);
22315           free(azCmd);
22316           return rc!=0 ? rc : 1;
22317         }
22318       }
22319     }
22320   }else{
22321     /* Run commands received from standard input
22322     */
22323     if( stdin_is_interactive ){
22324       char *zHome;
22325       char *zHistory;
22326       int nHistory;
22327       printf(
22328         "SQLite version %s %.19s\n" /*extra-version-info*/
22329         "Enter \".help\" for usage hints.\n",
22330         sqlite3_libversion(), sqlite3_sourceid()
22331       );
22332       if( warnInmemoryDb ){
22333         printf("Connected to a ");
22334         printBold("transient in-memory database");
22335         printf(".\nUse \".open FILENAME\" to reopen on a "
22336                "persistent database.\n");
22337       }
22338       zHistory = getenv("SQLITE_HISTORY");
22339       if( zHistory ){
22340         zHistory = strdup(zHistory);
22341       }else if( (zHome = find_home_dir(0))!=0 ){
22342         nHistory = strlen30(zHome) + 20;
22343         if( (zHistory = malloc(nHistory))!=0 ){
22344           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
22345         }
22346       }
22347       if( zHistory ){ shell_read_history(zHistory); }
22348 #if HAVE_READLINE || HAVE_EDITLINE
22349       rl_attempted_completion_function = readline_completion;
22350 #elif HAVE_LINENOISE
22351       linenoiseSetCompletionCallback(linenoise_completion);
22352 #endif
22353       data.in = 0;
22354       rc = process_input(&data);
22355       if( zHistory ){
22356         shell_stifle_history(2000);
22357         shell_write_history(zHistory);
22358         free(zHistory);
22359       }
22360     }else{
22361       data.in = stdin;
22362       rc = process_input(&data);
22363     }
22364   }
22365   free(azCmd);
22366   set_table_name(&data, 0);
22367   if( data.db ){
22368     session_close_all(&data);
22369     close_db(data.db);
22370   }
22371   sqlite3_free(data.zFreeOnClose);
22372   find_home_dir(1);
22373   output_reset(&data);
22374   data.doXdgOpen = 0;
22375   clearTempFile(&data);
22376 #if !SQLITE_SHELL_IS_UTF8
22377   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
22378   free(argvToFree);
22379 #endif
22380   free(data.colWidth);
22381   /* Clear the global data structure so that valgrind will detect memory
22382   ** leaks */
22383   memset(&data, 0, sizeof(data));
22384   return rc;
22385 }
22386