xref: /freebsd/contrib/sqlite3/shell.c (revision 17f0f75308f287efea825457364e2a4de2e107d4)
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37 typedef unsigned int u32;
38 typedef unsigned short int u16;
39 
40 /*
41 ** Optionally #include a user-defined header, whereby compilation options
42 ** may be set prior to where they take effect, but after platform setup.
43 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
44 ** file. Note that this macro has a like effect on sqlite3.c compilation.
45 */
46 # define SHELL_STRINGIFY_(f) #f
47 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
48 #ifdef SQLITE_CUSTOM_INCLUDE
49 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
50 #endif
51 
52 /*
53 ** Determine if we are dealing with WinRT, which provides only a subset of
54 ** the full Win32 API.
55 */
56 #if !defined(SQLITE_OS_WINRT)
57 # define SQLITE_OS_WINRT 0
58 #endif
59 
60 /*
61 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
62 ** somewhat for use as a WASM module in a web browser. This flag
63 ** should only be used when building the "fiddle" web application, as
64 ** the browser-mode build has much different user input requirements
65 ** and this build mode rewires the user input subsystem to account for
66 ** that.
67 */
68 
69 /*
70 ** Warning pragmas copied from msvc.h in the core.
71 */
72 #if defined(_MSC_VER)
73 #pragma warning(disable : 4054)
74 #pragma warning(disable : 4055)
75 #pragma warning(disable : 4100)
76 #pragma warning(disable : 4127)
77 #pragma warning(disable : 4130)
78 #pragma warning(disable : 4152)
79 #pragma warning(disable : 4189)
80 #pragma warning(disable : 4206)
81 #pragma warning(disable : 4210)
82 #pragma warning(disable : 4232)
83 #pragma warning(disable : 4244)
84 #pragma warning(disable : 4305)
85 #pragma warning(disable : 4306)
86 #pragma warning(disable : 4702)
87 #pragma warning(disable : 4706)
88 #endif /* defined(_MSC_VER) */
89 
90 /*
91 ** No support for loadable extensions in VxWorks.
92 */
93 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
94 # define SQLITE_OMIT_LOAD_EXTENSION 1
95 #endif
96 
97 /*
98 ** Enable large-file support for fopen() and friends on unix.
99 */
100 #ifndef SQLITE_DISABLE_LFS
101 # define _LARGE_FILE       1
102 # ifndef _FILE_OFFSET_BITS
103 #   define _FILE_OFFSET_BITS 64
104 # endif
105 # define _LARGEFILE_SOURCE 1
106 #endif
107 
108 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
109 /*
110 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
111 ** to expose strdup().
112 */
113 # define _POSIX_SOURCE
114 #endif
115 
116 #include <stdlib.h>
117 #include <string.h>
118 #include <stdio.h>
119 #include <assert.h>
120 #include <math.h>
121 #include "sqlite3.h"
122 typedef sqlite3_int64 i64;
123 typedef sqlite3_uint64 u64;
124 typedef unsigned char u8;
125 #include <ctype.h>
126 #include <stdarg.h>
127 
128 #if !defined(_WIN32) && !defined(WIN32)
129 # include <signal.h>
130 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
131 #  include <pwd.h>
132 # endif
133 #endif
134 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
135 # include <unistd.h>
136 # include <dirent.h>
137 # define GETPID getpid
138 # if defined(__MINGW32__)
139 #  define DIRENT dirent
140 #  ifndef S_ISLNK
141 #   define S_ISLNK(mode) (0)
142 #  endif
143 # endif
144 #else
145 # define GETPID (int)GetCurrentProcessId
146 #endif
147 #include <sys/types.h>
148 #include <sys/stat.h>
149 
150 #if HAVE_READLINE
151 # include <readline/readline.h>
152 # include <readline/history.h>
153 #endif
154 
155 #if HAVE_EDITLINE
156 # include <editline/readline.h>
157 #endif
158 
159 #if HAVE_EDITLINE || HAVE_READLINE
160 
161 # define shell_add_history(X) add_history(X)
162 # define shell_read_history(X) read_history(X)
163 # define shell_write_history(X) write_history(X)
164 # define shell_stifle_history(X) stifle_history(X)
165 # define shell_readline(X) readline(X)
166 
167 #elif HAVE_LINENOISE
168 
169 # include "linenoise.h"
170 # define shell_add_history(X) linenoiseHistoryAdd(X)
171 # define shell_read_history(X) linenoiseHistoryLoad(X)
172 # define shell_write_history(X) linenoiseHistorySave(X)
173 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
174 # define shell_readline(X) linenoise(X)
175 
176 #else
177 
178 # define shell_read_history(X)
179 # define shell_write_history(X)
180 # define shell_stifle_history(X)
181 
182 # define SHELL_USE_LOCAL_GETLINE 1
183 #endif
184 
185 #ifndef deliberate_fall_through
186 /* Quiet some compilers about some of our intentional code. */
187 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
188 #  define deliberate_fall_through __attribute__((fallthrough));
189 # else
190 #  define deliberate_fall_through
191 # endif
192 #endif
193 
194 #if defined(_WIN32) || defined(WIN32)
195 # if SQLITE_OS_WINRT
196 #  define SQLITE_OMIT_POPEN 1
197 # else
198 #  include <io.h>
199 #  include <fcntl.h>
200 #  define isatty(h) _isatty(h)
201 #  ifndef access
202 #   define access(f,m) _access((f),(m))
203 #  endif
204 #  ifndef unlink
205 #   define unlink _unlink
206 #  endif
207 #  ifndef strdup
208 #   define strdup _strdup
209 #  endif
210 #  undef pclose
211 #  define pclose _pclose
212 # endif
213 #else
214  /* Make sure isatty() has a prototype. */
215  extern int isatty(int);
216 
217 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
218   /* popen and pclose are not C89 functions and so are
219   ** sometimes omitted from the <stdio.h> header */
220    extern FILE *popen(const char*,const char*);
221    extern int pclose(FILE*);
222 # else
223 #  define SQLITE_OMIT_POPEN 1
224 # endif
225 #endif
226 
227 #if defined(_WIN32_WCE)
228 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
229  * thus we always assume that we have a console. That can be
230  * overridden with the -batch command line option.
231  */
232 #define isatty(x) 1
233 #endif
234 
235 /* ctype macros that work with signed characters */
236 #define IsSpace(X)  isspace((unsigned char)X)
237 #define IsDigit(X)  isdigit((unsigned char)X)
238 #define ToLower(X)  (char)tolower((unsigned char)X)
239 #define IsAlnum(X)  isalnum((unsigned char)X)
240 #define IsAlpha(X)  isalpha((unsigned char)X)
241 
242 #if defined(_WIN32) || defined(WIN32)
243 #if SQLITE_OS_WINRT
244 #include <intrin.h>
245 #endif
246 #undef WIN32_LEAN_AND_MEAN
247 #define WIN32_LEAN_AND_MEAN
248 #include <windows.h>
249 
250 /* string conversion routines only needed on Win32 */
251 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
252 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
253 #endif
254 
255 /************************* Begin ../ext/misc/sqlite3_stdio.h ******************/
256 /*
257 ** 2024-09-24
258 **
259 ** The author disclaims copyright to this source code.  In place of
260 ** a legal notice, here is a blessing:
261 **
262 **    May you do good and not evil.
263 **    May you find forgiveness for yourself and forgive others.
264 **    May you share freely, never taking more than you give.
265 **
266 *************************************************************************
267 **
268 ** This header file contains definitions of interfaces that provide
269 ** cross-platform I/O for UTF-8 content.
270 **
271 ** On most platforms, the interfaces definitions in this file are
272 ** just #defines.  For example sqlite3_fopen() is a macro that resolves
273 ** to the standard fopen() in the C-library.
274 **
275 ** But Windows does not have a standard C-library, at least not one that
276 ** can handle UTF-8.  So for windows build, the interfaces resolve to new
277 ** C-language routines contained in the separate sqlite3_stdio.c source file.
278 **
279 ** So on all non-Windows platforms, simply #include this header file and
280 ** use the interfaces defined herein.  Then to run your application on Windows,
281 ** also link in the accompanying sqlite3_stdio.c source file when compiling
282 ** to get compatible interfaces.
283 */
284 #ifndef _SQLITE3_STDIO_H_
285 #define _SQLITE3_STDIO_H_ 1
286 #ifdef _WIN32
287 /**** Definitions For Windows ****/
288 #include <stdio.h>
289 #include <windows.h>
290 
291 FILE *sqlite3_fopen(const char *zFilename, const char *zMode);
292 FILE *sqlite3_popen(const char *zCommand, const char *type);
293 char *sqlite3_fgets(char *s, int size, FILE *stream);
294 int sqlite3_fputs(const char *s, FILE *stream);
295 int sqlite3_fprintf(FILE *stream, const char *format, ...);
296 void sqlite3_fsetmode(FILE *stream, int mode);
297 
298 
299 #else
300 /**** Definitions For All Other Platforms ****/
301 #include <stdio.h>
302 #define sqlite3_fopen     fopen
303 #define sqlite3_popen     popen
304 #define sqlite3_fgets     fgets
305 #define sqlite3_fputs     fputs
306 #define sqlite3_fprintf   fprintf
307 #define sqlite3_fsetmode(F,X)   /*no-op*/
308 
309 #endif
310 #endif /* _SQLITE3_STDIO_H_ */
311 
312 /************************* End ../ext/misc/sqlite3_stdio.h ********************/
313 /************************* Begin ../ext/misc/sqlite3_stdio.c ******************/
314 /*
315 ** 2024-09-24
316 **
317 ** The author disclaims copyright to this source code.  In place of
318 ** a legal notice, here is a blessing:
319 **
320 **    May you do good and not evil.
321 **    May you find forgiveness for yourself and forgive others.
322 **    May you share freely, never taking more than you give.
323 **
324 *************************************************************************
325 **
326 ** Implementation of standard I/O interfaces for UTF-8 that are missing
327 ** on Windows.
328 */
329 #ifdef _WIN32  /* This file is a no-op on all platforms except Windows */
330 #ifndef _SQLITE3_STDIO_H_
331 /* #include "sqlite3_stdio.h" */
332 #endif
333 #undef WIN32_LEAN_AND_MEAN
334 #define WIN32_LEAN_AND_MEAN
335 #include <windows.h>
336 #include <stdlib.h>
337 #include <string.h>
338 #include <stdio.h>
339 #include <assert.h>
340 /* #include "sqlite3.h" */
341 #include <ctype.h>
342 #include <stdarg.h>
343 #include <io.h>
344 #include <fcntl.h>
345 
346 /*
347 ** If the SQLITE_U8TEXT_ONLY option is defined, then use O_U8TEXT
348 ** when appropriate on all output.  (Sometimes use O_BINARY when
349 ** rendering ASCII text in cases where NL-to-CRLF expansion would
350 ** not be correct.)
351 **
352 ** If the SQLITE_U8TEXT_STDIO option is defined, then use O_U8TEXT
353 ** when appropriate when writing to stdout or stderr.  Use O_BINARY
354 ** or O_TEXT (depending on things like the .mode and the .crlf setting
355 ** in the CLI, or other context clues in other applications) for all
356 ** other output channels.
357 **
358 ** The default behavior, if neither of the above is defined is to
359 ** use O_U8TEXT when writing to the Windows console (or anything
360 ** else for which _isatty() returns true) and to use O_BINARY or O_TEXT
361 ** for all other output channels.
362 **
363 ** The SQLITE_USE_W32_FOR_CONSOLE_IO macro is also available.  If
364 ** defined, it forces the use of Win32 APIs for all console I/O, both
365 ** input and output.  This is necessary for some non-Microsoft run-times
366 ** that implement stdio differently from Microsoft/Visual-Studio.
367 */
368 #if defined(SQLITE_U8TEXT_ONLY)
369 # define UseWtextForOutput(fd) 1
370 # define UseWtextForInput(fd)  1
371 # define IsConsole(fd)         _isatty(_fileno(fd))
372 #elif defined(SQLITE_U8TEXT_STDIO)
373 # define UseWtextForOutput(fd) ((fd)==stdout || (fd)==stderr)
374 # define UseWtextForInput(fd)  ((fd)==stdin)
375 # define IsConsole(fd)         _isatty(_fileno(fd))
376 #else
377 # define UseWtextForOutput(fd) _isatty(_fileno(fd))
378 # define UseWtextForInput(fd)  _isatty(_fileno(fd))
379 # define IsConsole(fd)         1
380 #endif
381 
382 /*
383 ** Global variables determine if simulated O_BINARY mode is to be
384 ** used for stdout or other, respectively.  Simulated O_BINARY mode
385 ** means the mode is usually O_BINARY, but switches to O_U8TEXT for
386 ** unicode characters U+0080 or greater (any character that has a
387 ** multi-byte representation in UTF-8).  This is the only way we
388 ** have found to render Unicode characters on a Windows console while
389 ** at the same time avoiding undesirable \n to \r\n translation.
390 */
391 static int simBinaryStdout = 0;
392 static int simBinaryOther = 0;
393 
394 
395 /*
396 ** Determine if simulated binary mode should be used for output to fd
397 */
UseBinaryWText(FILE * fd)398 static int UseBinaryWText(FILE *fd){
399   if( fd==stdout || fd==stderr ){
400     return simBinaryStdout;
401   }else{
402     return simBinaryOther;
403   }
404 }
405 
406 
407 /*
408 ** Work-alike for the fopen() routine from the standard C library.
409 */
sqlite3_fopen(const char * zFilename,const char * zMode)410 FILE *sqlite3_fopen(const char *zFilename, const char *zMode){
411   FILE *fp = 0;
412   wchar_t *b1, *b2;
413   int sz1, sz2;
414 
415   sz1 = (int)strlen(zFilename);
416   sz2 = (int)strlen(zMode);
417   b1 = sqlite3_malloc( (sz1+1)*sizeof(b1[0]) );
418   b2 = sqlite3_malloc( (sz2+1)*sizeof(b1[0]) );
419   if( b1 && b2 ){
420     sz1 = MultiByteToWideChar(CP_UTF8, 0, zFilename, sz1, b1, sz1);
421     b1[sz1] = 0;
422     sz2 = MultiByteToWideChar(CP_UTF8, 0, zMode, sz2, b2, sz2);
423     b2[sz2] = 0;
424     fp = _wfopen(b1, b2);
425   }
426   sqlite3_free(b1);
427   sqlite3_free(b2);
428   simBinaryOther = 0;
429   return fp;
430 }
431 
432 
433 /*
434 ** Work-alike for the popen() routine from the standard C library.
435 */
sqlite3_popen(const char * zCommand,const char * zMode)436 FILE *sqlite3_popen(const char *zCommand, const char *zMode){
437   FILE *fp = 0;
438   wchar_t *b1, *b2;
439   int sz1, sz2;
440 
441   sz1 = (int)strlen(zCommand);
442   sz2 = (int)strlen(zMode);
443   b1 = sqlite3_malloc( (sz1+1)*sizeof(b1[0]) );
444   b2 = sqlite3_malloc( (sz2+1)*sizeof(b1[0]) );
445   if( b1 && b2 ){
446     sz1 = MultiByteToWideChar(CP_UTF8, 0, zCommand, sz1, b1, sz1);
447     b1[sz1] = 0;
448     sz2 = MultiByteToWideChar(CP_UTF8, 0, zMode, sz2, b2, sz2);
449     b2[sz2] = 0;
450     fp = _wpopen(b1, b2);
451   }
452   sqlite3_free(b1);
453   sqlite3_free(b2);
454   return fp;
455 }
456 
457 /*
458 ** Work-alike for fgets() from the standard C library.
459 */
sqlite3_fgets(char * buf,int sz,FILE * in)460 char *sqlite3_fgets(char *buf, int sz, FILE *in){
461   if( UseWtextForInput(in) ){
462     /* When reading from the command-prompt in Windows, it is necessary
463     ** to use _O_WTEXT input mode to read UTF-16 characters, then translate
464     ** that into UTF-8.  Otherwise, non-ASCII characters all get translated
465     ** into '?'.
466     */
467     wchar_t *b1 = sqlite3_malloc( sz*sizeof(wchar_t) );
468     if( b1==0 ) return 0;
469 #ifdef SQLITE_USE_W32_FOR_CONSOLE_IO
470     DWORD nRead = 0;
471     if( IsConsole(in)
472      && ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), b1, sz-1, &nRead, 0)
473     ){
474       b1[nRead] = 0;
475     }else
476 #endif
477     {
478       _setmode(_fileno(in), IsConsole(in) ? _O_WTEXT : _O_U8TEXT);
479       if( fgetws(b1, sz/4, in)==0 ){
480         sqlite3_free(b1);
481         return 0;
482       }
483     }
484     WideCharToMultiByte(CP_UTF8, 0, b1, -1, buf, sz, 0, 0);
485     sqlite3_free(b1);
486     return buf;
487   }else{
488     /* Reading from a file or other input source, just read bytes without
489     ** any translation. */
490     return fgets(buf, sz, in);
491   }
492 }
493 
494 /*
495 ** Send ASCII text as O_BINARY.  But for Unicode characters U+0080 and
496 ** greater, switch to O_U8TEXT.
497 */
piecemealOutput(wchar_t * b1,int sz,FILE * out)498 static void piecemealOutput(wchar_t *b1, int sz, FILE *out){
499   int i;
500   wchar_t c;
501   while( sz>0 ){
502     for(i=0; i<sz && b1[i]>=0x80; i++){}
503     if( i>0 ){
504       c = b1[i];
505       b1[i] = 0;
506       fflush(out);
507       _setmode(_fileno(out), _O_U8TEXT);
508       fputws(b1, out);
509       fflush(out);
510       b1 += i;
511       b1[0] = c;
512       sz -= i;
513     }else{
514       fflush(out);
515       _setmode(_fileno(out), _O_TEXT);
516       _setmode(_fileno(out), _O_BINARY);
517       fwrite(&b1[0], 1, 1, out);
518       for(i=1; i<sz && b1[i]<0x80; i++){
519         fwrite(&b1[i], 1, 1, out);
520       }
521       fflush(out);
522       _setmode(_fileno(out), _O_U8TEXT);
523       b1 += i;
524       sz -= i;
525     }
526   }
527 }
528 
529 /*
530 ** Work-alike for fputs() from the standard C library.
531 */
sqlite3_fputs(const char * z,FILE * out)532 int sqlite3_fputs(const char *z, FILE *out){
533   if( !UseWtextForOutput(out) ){
534     /* Writing to a file or other destination, just write bytes without
535     ** any translation. */
536     return fputs(z, out);
537   }else{
538     /* One must use UTF16 in order to get unicode support when writing
539     ** to the console on Windows.
540     */
541     int sz = (int)strlen(z);
542     wchar_t *b1 = sqlite3_malloc( (sz+1)*sizeof(wchar_t) );
543     if( b1==0 ) return 0;
544     sz = MultiByteToWideChar(CP_UTF8, 0, z, sz, b1, sz);
545     b1[sz] = 0;
546 
547 #ifdef SQLITE_USE_W32_FOR_CONSOLE_IO
548     DWORD nWr = 0;
549     if( IsConsole(out)
550       && WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),b1,sz,&nWr,0)
551     ){
552       /* If writing to the console, then the WriteConsoleW() is all we
553       ** need to do. */
554     }else
555 #endif
556     {
557       /* As long as SQLITE_USE_W32_FOR_CONSOLE_IO is not defined, or for
558       ** non-console I/O even if that macro is defined, write using the
559       ** standard library. */
560       _setmode(_fileno(out), _O_U8TEXT);
561       if( UseBinaryWText(out) ){
562         piecemealOutput(b1, sz, out);
563       }else{
564         fputws(b1, out);
565       }
566     }
567     sqlite3_free(b1);
568     return 0;
569   }
570 }
571 
572 
573 /*
574 ** Work-alike for fprintf() from the standard C library.
575 */
sqlite3_fprintf(FILE * out,const char * zFormat,...)576 int sqlite3_fprintf(FILE *out, const char *zFormat, ...){
577   int rc;
578   if( UseWtextForOutput(out) ){
579     /* When writing to the command-prompt in Windows, it is necessary
580     ** to use _O_WTEXT input mode and write UTF-16 characters.
581     */
582     char *z;
583     va_list ap;
584 
585     va_start(ap, zFormat);
586     z = sqlite3_vmprintf(zFormat, ap);
587     va_end(ap);
588     sqlite3_fputs(z, out);
589     rc = (int)strlen(z);
590     sqlite3_free(z);
591   }else{
592     /* Writing to a file or other destination, just write bytes without
593     ** any translation. */
594     va_list ap;
595     va_start(ap, zFormat);
596     rc = vfprintf(out, zFormat, ap);
597     va_end(ap);
598   }
599   return rc;
600 }
601 
602 /*
603 ** Set the mode for an output stream.  mode argument is typically _O_BINARY or
604 ** _O_TEXT.
605 */
sqlite3_fsetmode(FILE * fp,int mode)606 void sqlite3_fsetmode(FILE *fp, int mode){
607   if( !UseWtextForOutput(fp) ){
608     fflush(fp);
609     _setmode(_fileno(fp), mode);
610   }else if( fp==stdout || fp==stderr ){
611     simBinaryStdout = (mode==_O_BINARY);
612   }else{
613     simBinaryOther = (mode==_O_BINARY);
614   }
615 }
616 
617 #endif /* defined(_WIN32) */
618 
619 /************************* End ../ext/misc/sqlite3_stdio.c ********************/
620 
621 /* Use console I/O package as a direct INCLUDE. */
622 #define SQLITE_INTERNAL_LINKAGE static
623 
624 #ifdef SQLITE_SHELL_FIDDLE
625 /* Deselect most features from the console I/O package for Fiddle. */
626 # define SQLITE_CIO_NO_REDIRECT
627 # define SQLITE_CIO_NO_CLASSIFY
628 # define SQLITE_CIO_NO_TRANSLATE
629 # define SQLITE_CIO_NO_SETMODE
630 # define SQLITE_CIO_NO_FLUSH
631 #endif
632 
633 #define eputz(z) sqlite3_fputs(z,stderr)
634 #define sputz(fp,z) sqlite3_fputs(z,fp)
635 
636 /* True if the timer is enabled */
637 static int enableTimer = 0;
638 
639 /* A version of strcmp() that works with NULL values */
cli_strcmp(const char * a,const char * b)640 static int cli_strcmp(const char *a, const char *b){
641   if( a==0 ) a = "";
642   if( b==0 ) b = "";
643   return strcmp(a,b);
644 }
cli_strncmp(const char * a,const char * b,size_t n)645 static int cli_strncmp(const char *a, const char *b, size_t n){
646   if( a==0 ) a = "";
647   if( b==0 ) b = "";
648   return strncmp(a,b,n);
649 }
650 
651 /* Return the current wall-clock time */
timeOfDay(void)652 static sqlite3_int64 timeOfDay(void){
653   static sqlite3_vfs *clockVfs = 0;
654   sqlite3_int64 t;
655   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
656   if( clockVfs==0 ) return 0;  /* Never actually happens */
657   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
658     clockVfs->xCurrentTimeInt64(clockVfs, &t);
659   }else{
660     double r;
661     clockVfs->xCurrentTime(clockVfs, &r);
662     t = (sqlite3_int64)(r*86400000.0);
663   }
664   return t;
665 }
666 
667 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
668 #include <sys/time.h>
669 #include <sys/resource.h>
670 
671 /* VxWorks does not support getrusage() as far as we can determine */
672 #if defined(_WRS_KERNEL) || defined(__RTP__)
673 struct rusage {
674   struct timeval ru_utime; /* user CPU time used */
675   struct timeval ru_stime; /* system CPU time used */
676 };
677 #define getrusage(A,B) memset(B,0,sizeof(*B))
678 #endif
679 
680 
681 /* Saved resource information for the beginning of an operation */
682 static struct rusage sBegin;  /* CPU time at start */
683 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
684 
685 /*
686 ** Begin timing an operation
687 */
beginTimer(void)688 static void beginTimer(void){
689   if( enableTimer ){
690     getrusage(RUSAGE_SELF, &sBegin);
691     iBegin = timeOfDay();
692   }
693 }
694 
695 /* Return the difference of two time_structs in seconds */
timeDiff(struct timeval * pStart,struct timeval * pEnd)696 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
697   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
698          (double)(pEnd->tv_sec - pStart->tv_sec);
699 }
700 
701 /*
702 ** Print the timing results.
703 */
endTimer(FILE * out)704 static void endTimer(FILE *out){
705   if( enableTimer ){
706     sqlite3_int64 iEnd = timeOfDay();
707     struct rusage sEnd;
708     getrusage(RUSAGE_SELF, &sEnd);
709     sqlite3_fprintf(out, "Run Time: real %.3f user %f sys %f\n",
710           (iEnd - iBegin)*0.001,
711           timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
712           timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
713   }
714 }
715 
716 #define BEGIN_TIMER beginTimer()
717 #define END_TIMER(X) endTimer(X)
718 #define HAS_TIMER 1
719 
720 #elif (defined(_WIN32) || defined(WIN32))
721 
722 /* Saved resource information for the beginning of an operation */
723 static HANDLE hProcess;
724 static FILETIME ftKernelBegin;
725 static FILETIME ftUserBegin;
726 static sqlite3_int64 ftWallBegin;
727 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
728                                     LPFILETIME, LPFILETIME);
729 static GETPROCTIMES getProcessTimesAddr = NULL;
730 
731 /*
732 ** Check to see if we have timer support.  Return 1 if necessary
733 ** support found (or found previously).
734 */
hasTimer(void)735 static int hasTimer(void){
736   if( getProcessTimesAddr ){
737     return 1;
738   } else {
739 #if !SQLITE_OS_WINRT
740     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
741     ** versions. See if the version we are running on has it, and if it
742     ** does, save off a pointer to it and the current process handle.
743     */
744     hProcess = GetCurrentProcess();
745     if( hProcess ){
746       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
747       if( NULL != hinstLib ){
748         getProcessTimesAddr =
749             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
750         if( NULL != getProcessTimesAddr ){
751           return 1;
752         }
753         FreeLibrary(hinstLib);
754       }
755     }
756 #endif
757   }
758   return 0;
759 }
760 
761 /*
762 ** Begin timing an operation
763 */
beginTimer(void)764 static void beginTimer(void){
765   if( enableTimer && getProcessTimesAddr ){
766     FILETIME ftCreation, ftExit;
767     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
768                         &ftKernelBegin,&ftUserBegin);
769     ftWallBegin = timeOfDay();
770   }
771 }
772 
773 /* Return the difference of two FILETIME structs in seconds */
timeDiff(FILETIME * pStart,FILETIME * pEnd)774 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
775   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
776   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
777   return (double) ((i64End - i64Start) / 10000000.0);
778 }
779 
780 /*
781 ** Print the timing results.
782 */
endTimer(FILE * out)783 static void endTimer(FILE *out){
784   if( enableTimer && getProcessTimesAddr){
785     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
786     sqlite3_int64 ftWallEnd = timeOfDay();
787     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
788     sqlite3_fprintf(out, "Run Time: real %.3f user %f sys %f\n",
789           (ftWallEnd - ftWallBegin)*0.001,
790           timeDiff(&ftUserBegin, &ftUserEnd),
791           timeDiff(&ftKernelBegin, &ftKernelEnd));
792   }
793 }
794 
795 #define BEGIN_TIMER beginTimer()
796 #define END_TIMER(X) endTimer(X)
797 #define HAS_TIMER hasTimer()
798 
799 #else
800 #define BEGIN_TIMER
801 #define END_TIMER(X)  /*no-op*/
802 #define HAS_TIMER 0
803 #endif
804 
805 /*
806 ** Used to prevent warnings about unused parameters
807 */
808 #define UNUSED_PARAMETER(x) (void)(x)
809 
810 /*
811 ** Number of elements in an array
812 */
813 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
814 
815 /*
816 ** If the following flag is set, then command execution stops
817 ** at an error if we are not interactive.
818 */
819 static int bail_on_error = 0;
820 
821 /*
822 ** Treat stdin as an interactive input if the following variable
823 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
824 */
825 static int stdin_is_interactive = 1;
826 
827 /*
828 ** On Windows systems we need to know if standard output is a console
829 ** in order to show that UTF-16 translation is done in the sign-on
830 ** banner. The following variable is true if it is the console.
831 */
832 static int stdout_is_console = 1;
833 
834 /*
835 ** The following is the open SQLite database.  We make a pointer
836 ** to this database a static variable so that it can be accessed
837 ** by the SIGINT handler to interrupt database processing.
838 */
839 static sqlite3 *globalDb = 0;
840 
841 /*
842 ** True if an interrupt (Control-C) has been received.
843 */
844 static volatile int seenInterrupt = 0;
845 
846 /*
847 ** This is the name of our program. It is set in main(), used
848 ** in a number of other places, mostly for error messages.
849 */
850 static char *Argv0;
851 
852 /*
853 ** Prompt strings. Initialized in main. Settable with
854 **   .prompt main continue
855 */
856 #define PROMPT_LEN_MAX 128
857 /* First line prompt.   default: "sqlite> " */
858 static char mainPrompt[PROMPT_LEN_MAX];
859 /* Continuation prompt. default: "   ...> " */
860 static char continuePrompt[PROMPT_LEN_MAX];
861 
862 /* This is variant of the standard-library strncpy() routine with the
863 ** one change that the destination string is always zero-terminated, even
864 ** if there is no zero-terminator in the first n-1 characters of the source
865 ** string.
866 */
shell_strncpy(char * dest,const char * src,size_t n)867 static char *shell_strncpy(char *dest, const char *src, size_t n){
868   size_t i;
869   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
870   dest[i] = 0;
871   return dest;
872 }
873 
874 /*
875 ** strcpy() workalike to squelch an unwarranted link-time warning
876 ** from OpenBSD.
877 */
shell_strcpy(char * dest,const char * src)878 static void shell_strcpy(char *dest, const char *src){
879   while( (*(dest++) = *(src++))!=0 ){}
880 }
881 
882 /*
883 ** Optionally disable dynamic continuation prompt.
884 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
885 ** or open parentheses level if non-zero, or continuation prompt as set.
886 ** This facility interacts with the scanner and process_input() where the
887 ** below 5 macros are used.
888 */
889 #ifdef SQLITE_OMIT_DYNAPROMPT
890 # define CONTINUATION_PROMPT continuePrompt
891 # define CONTINUE_PROMPT_RESET
892 # define CONTINUE_PROMPT_AWAITS(p,s)
893 # define CONTINUE_PROMPT_AWAITC(p,c)
894 # define CONTINUE_PAREN_INCR(p,n)
895 # define CONTINUE_PROMPT_PSTATE 0
896 typedef void *t_NoDynaPrompt;
897 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
898 #else
899 # define CONTINUATION_PROMPT dynamicContinuePrompt()
900 # define CONTINUE_PROMPT_RESET \
901   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
902 # define CONTINUE_PROMPT_AWAITS(p,s) \
903   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
904 # define CONTINUE_PROMPT_AWAITC(p,c) \
905   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
906 # define CONTINUE_PAREN_INCR(p,n) \
907   if(p && stdin_is_interactive) (trackParenLevel(p,n))
908 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
909 typedef struct DynaPrompt *t_DynaPromptRef;
910 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
911 
912 static struct DynaPrompt {
913   char dynamicPrompt[PROMPT_LEN_MAX];
914   char acAwait[2];
915   int inParenLevel;
916   char *zScannerAwaits;
917 } dynPrompt = { {0}, {0}, 0, 0 };
918 
919 /* Record parenthesis nesting level change, or force level to 0. */
trackParenLevel(struct DynaPrompt * p,int ni)920 static void trackParenLevel(struct DynaPrompt *p, int ni){
921   p->inParenLevel += ni;
922   if( ni==0 ) p->inParenLevel = 0;
923   p->zScannerAwaits = 0;
924 }
925 
926 /* Record that a lexeme is opened, or closed with args==0. */
setLexemeOpen(struct DynaPrompt * p,char * s,char c)927 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
928   if( s!=0 || c==0 ){
929     p->zScannerAwaits = s;
930     p->acAwait[0] = 0;
931   }else{
932     p->acAwait[0] = c;
933     p->zScannerAwaits = p->acAwait;
934   }
935 }
936 
937 /* Upon demand, derive the continuation prompt to display. */
dynamicContinuePrompt(void)938 static char *dynamicContinuePrompt(void){
939   if( continuePrompt[0]==0
940       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
941     return continuePrompt;
942   }else{
943     if( dynPrompt.zScannerAwaits ){
944       size_t ncp = strlen(continuePrompt);
945       size_t ndp = strlen(dynPrompt.zScannerAwaits);
946       if( ndp > ncp-3 ) return continuePrompt;
947       shell_strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
948       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
949       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
950               PROMPT_LEN_MAX-4);
951     }else{
952       if( dynPrompt.inParenLevel>9 ){
953         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
954       }else if( dynPrompt.inParenLevel<0 ){
955         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
956       }else{
957         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
958         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
959       }
960       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
961                     PROMPT_LEN_MAX-4);
962     }
963   }
964   return dynPrompt.dynamicPrompt;
965 }
966 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
967 
968 /* Indicate out-of-memory and exit. */
shell_out_of_memory(void)969 static void shell_out_of_memory(void){
970   eputz("Error: out of memory\n");
971   exit(1);
972 }
973 
974 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
975 ** out-of-memory error.
976 */
shell_check_oom(const void * p)977 static void shell_check_oom(const void *p){
978   if( p==0 ) shell_out_of_memory();
979 }
980 
981 /*
982 ** Write I/O traces to the following stream.
983 */
984 #ifdef SQLITE_ENABLE_IOTRACE
985 static FILE *iotrace = 0;
986 #endif
987 
988 /*
989 ** This routine works like printf in that its first argument is a
990 ** format string and subsequent arguments are values to be substituted
991 ** in place of % fields.  The result of formatting this string
992 ** is written to iotrace.
993 */
994 #ifdef SQLITE_ENABLE_IOTRACE
iotracePrintf(const char * zFormat,...)995 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
996   va_list ap;
997   char *z;
998   if( iotrace==0 ) return;
999   va_start(ap, zFormat);
1000   z = sqlite3_vmprintf(zFormat, ap);
1001   va_end(ap);
1002   sqlite3_fprintf(iotrace, "%s", z);
1003   sqlite3_free(z);
1004 }
1005 #endif
1006 
1007 /* Lookup table to estimate the number of columns consumed by a Unicode
1008 ** character.
1009 */
1010 static const struct {
1011   unsigned char w;    /* Width of the character in columns */
1012   int iFirst;         /* First character in a span having this width */
1013 } aUWidth[] = {
1014    /* {1, 0x00000}, */
1015   {0, 0x00300},  {1, 0x00370},  {0, 0x00483},  {1, 0x00487},  {0, 0x00488},
1016   {1, 0x0048a},  {0, 0x00591},  {1, 0x005be},  {0, 0x005bf},  {1, 0x005c0},
1017   {0, 0x005c1},  {1, 0x005c3},  {0, 0x005c4},  {1, 0x005c6},  {0, 0x005c7},
1018   {1, 0x005c8},  {0, 0x00600},  {1, 0x00604},  {0, 0x00610},  {1, 0x00616},
1019   {0, 0x0064b},  {1, 0x0065f},  {0, 0x00670},  {1, 0x00671},  {0, 0x006d6},
1020   {1, 0x006e5},  {0, 0x006e7},  {1, 0x006e9},  {0, 0x006ea},  {1, 0x006ee},
1021   {0, 0x0070f},  {1, 0x00710},  {0, 0x00711},  {1, 0x00712},  {0, 0x00730},
1022   {1, 0x0074b},  {0, 0x007a6},  {1, 0x007b1},  {0, 0x007eb},  {1, 0x007f4},
1023   {0, 0x00901},  {1, 0x00903},  {0, 0x0093c},  {1, 0x0093d},  {0, 0x00941},
1024   {1, 0x00949},  {0, 0x0094d},  {1, 0x0094e},  {0, 0x00951},  {1, 0x00955},
1025   {0, 0x00962},  {1, 0x00964},  {0, 0x00981},  {1, 0x00982},  {0, 0x009bc},
1026   {1, 0x009bd},  {0, 0x009c1},  {1, 0x009c5},  {0, 0x009cd},  {1, 0x009ce},
1027   {0, 0x009e2},  {1, 0x009e4},  {0, 0x00a01},  {1, 0x00a03},  {0, 0x00a3c},
1028   {1, 0x00a3d},  {0, 0x00a41},  {1, 0x00a43},  {0, 0x00a47},  {1, 0x00a49},
1029   {0, 0x00a4b},  {1, 0x00a4e},  {0, 0x00a70},  {1, 0x00a72},  {0, 0x00a81},
1030   {1, 0x00a83},  {0, 0x00abc},  {1, 0x00abd},  {0, 0x00ac1},  {1, 0x00ac6},
1031   {0, 0x00ac7},  {1, 0x00ac9},  {0, 0x00acd},  {1, 0x00ace},  {0, 0x00ae2},
1032   {1, 0x00ae4},  {0, 0x00b01},  {1, 0x00b02},  {0, 0x00b3c},  {1, 0x00b3d},
1033   {0, 0x00b3f},  {1, 0x00b40},  {0, 0x00b41},  {1, 0x00b44},  {0, 0x00b4d},
1034   {1, 0x00b4e},  {0, 0x00b56},  {1, 0x00b57},  {0, 0x00b82},  {1, 0x00b83},
1035   {0, 0x00bc0},  {1, 0x00bc1},  {0, 0x00bcd},  {1, 0x00bce},  {0, 0x00c3e},
1036   {1, 0x00c41},  {0, 0x00c46},  {1, 0x00c49},  {0, 0x00c4a},  {1, 0x00c4e},
1037   {0, 0x00c55},  {1, 0x00c57},  {0, 0x00cbc},  {1, 0x00cbd},  {0, 0x00cbf},
1038   {1, 0x00cc0},  {0, 0x00cc6},  {1, 0x00cc7},  {0, 0x00ccc},  {1, 0x00cce},
1039   {0, 0x00ce2},  {1, 0x00ce4},  {0, 0x00d41},  {1, 0x00d44},  {0, 0x00d4d},
1040   {1, 0x00d4e},  {0, 0x00dca},  {1, 0x00dcb},  {0, 0x00dd2},  {1, 0x00dd5},
1041   {0, 0x00dd6},  {1, 0x00dd7},  {0, 0x00e31},  {1, 0x00e32},  {0, 0x00e34},
1042   {1, 0x00e3b},  {0, 0x00e47},  {1, 0x00e4f},  {0, 0x00eb1},  {1, 0x00eb2},
1043   {0, 0x00eb4},  {1, 0x00eba},  {0, 0x00ebb},  {1, 0x00ebd},  {0, 0x00ec8},
1044   {1, 0x00ece},  {0, 0x00f18},  {1, 0x00f1a},  {0, 0x00f35},  {1, 0x00f36},
1045   {0, 0x00f37},  {1, 0x00f38},  {0, 0x00f39},  {1, 0x00f3a},  {0, 0x00f71},
1046   {1, 0x00f7f},  {0, 0x00f80},  {1, 0x00f85},  {0, 0x00f86},  {1, 0x00f88},
1047   {0, 0x00f90},  {1, 0x00f98},  {0, 0x00f99},  {1, 0x00fbd},  {0, 0x00fc6},
1048   {1, 0x00fc7},  {0, 0x0102d},  {1, 0x01031},  {0, 0x01032},  {1, 0x01033},
1049   {0, 0x01036},  {1, 0x01038},  {0, 0x01039},  {1, 0x0103a},  {0, 0x01058},
1050   {1, 0x0105a},  {2, 0x01100},  {0, 0x01160},  {1, 0x01200},  {0, 0x0135f},
1051   {1, 0x01360},  {0, 0x01712},  {1, 0x01715},  {0, 0x01732},  {1, 0x01735},
1052   {0, 0x01752},  {1, 0x01754},  {0, 0x01772},  {1, 0x01774},  {0, 0x017b4},
1053   {1, 0x017b6},  {0, 0x017b7},  {1, 0x017be},  {0, 0x017c6},  {1, 0x017c7},
1054   {0, 0x017c9},  {1, 0x017d4},  {0, 0x017dd},  {1, 0x017de},  {0, 0x0180b},
1055   {1, 0x0180e},  {0, 0x018a9},  {1, 0x018aa},  {0, 0x01920},  {1, 0x01923},
1056   {0, 0x01927},  {1, 0x01929},  {0, 0x01932},  {1, 0x01933},  {0, 0x01939},
1057   {1, 0x0193c},  {0, 0x01a17},  {1, 0x01a19},  {0, 0x01b00},  {1, 0x01b04},
1058   {0, 0x01b34},  {1, 0x01b35},  {0, 0x01b36},  {1, 0x01b3b},  {0, 0x01b3c},
1059   {1, 0x01b3d},  {0, 0x01b42},  {1, 0x01b43},  {0, 0x01b6b},  {1, 0x01b74},
1060   {0, 0x01dc0},  {1, 0x01dcb},  {0, 0x01dfe},  {1, 0x01e00},  {0, 0x0200b},
1061   {1, 0x02010},  {0, 0x0202a},  {1, 0x0202f},  {0, 0x02060},  {1, 0x02064},
1062   {0, 0x0206a},  {1, 0x02070},  {0, 0x020d0},  {1, 0x020f0},  {2, 0x02329},
1063   {1, 0x0232b},  {2, 0x02e80},  {0, 0x0302a},  {2, 0x03030},  {1, 0x0303f},
1064   {2, 0x03040},  {0, 0x03099},  {2, 0x0309b},  {1, 0x0a4d0},  {0, 0x0a806},
1065   {1, 0x0a807},  {0, 0x0a80b},  {1, 0x0a80c},  {0, 0x0a825},  {1, 0x0a827},
1066   {2, 0x0ac00},  {1, 0x0d7a4},  {2, 0x0f900},  {1, 0x0fb00},  {0, 0x0fb1e},
1067   {1, 0x0fb1f},  {0, 0x0fe00},  {2, 0x0fe10},  {1, 0x0fe1a},  {0, 0x0fe20},
1068   {1, 0x0fe24},  {2, 0x0fe30},  {1, 0x0fe70},  {0, 0x0feff},  {2, 0x0ff00},
1069   {1, 0x0ff61},  {2, 0x0ffe0},  {1, 0x0ffe7},  {0, 0x0fff9},  {1, 0x0fffc},
1070   {0, 0x10a01},  {1, 0x10a04},  {0, 0x10a05},  {1, 0x10a07},  {0, 0x10a0c},
1071   {1, 0x10a10},  {0, 0x10a38},  {1, 0x10a3b},  {0, 0x10a3f},  {1, 0x10a40},
1072   {0, 0x1d167},  {1, 0x1d16a},  {0, 0x1d173},  {1, 0x1d183},  {0, 0x1d185},
1073   {1, 0x1d18c},  {0, 0x1d1aa},  {1, 0x1d1ae},  {0, 0x1d242},  {1, 0x1d245},
1074   {2, 0x20000},  {1, 0x2fffe},  {2, 0x30000},  {1, 0x3fffe},  {0, 0xe0001},
1075   {1, 0xe0002},  {0, 0xe0020},  {1, 0xe0080},  {0, 0xe0100},  {1, 0xe01f0}
1076 };
1077 
1078 /*
1079 ** Return an estimate of the width, in columns, for the single Unicode
1080 ** character c.  For normal characters, the answer is always 1.  But the
1081 ** estimate might be 0 or 2 for zero-width and double-width characters.
1082 **
1083 ** Different display devices display unicode using different widths.  So
1084 ** it is impossible to know that true display width with 100% accuracy.
1085 ** Inaccuracies in the width estimates might cause columns to be misaligned.
1086 ** Unfortunately, there is nothing we can do about that.
1087 */
cli_wcwidth(int c)1088 int cli_wcwidth(int c){
1089   int iFirst, iLast;
1090 
1091   /* Fast path for common characters */
1092   if( c<=0x300 ) return 1;
1093 
1094   /* The general case */
1095   iFirst = 0;
1096   iLast = sizeof(aUWidth)/sizeof(aUWidth[0]) - 1;
1097   while( iFirst<iLast-1 ){
1098     int iMid = (iFirst+iLast)/2;
1099     int cMid = aUWidth[iMid].iFirst;
1100     if( cMid < c ){
1101       iFirst = iMid;
1102     }else if( cMid > c ){
1103       iLast = iMid - 1;
1104     }else{
1105       return aUWidth[iMid].w;
1106     }
1107   }
1108   if( aUWidth[iLast].iFirst > c ) return aUWidth[iFirst].w;
1109   return aUWidth[iLast].w;
1110 }
1111 
1112 /*
1113 ** Compute the value and length of a multi-byte UTF-8 character that
1114 ** begins at z[0].   Return the length.  Write the Unicode value into *pU.
1115 **
1116 ** This routine only works for *multi-byte* UTF-8 characters.
1117 */
decodeUtf8(const unsigned char * z,int * pU)1118 static int decodeUtf8(const unsigned char *z, int *pU){
1119   if( (z[0] & 0xe0)==0xc0 && (z[1] & 0xc0)==0x80 ){
1120     *pU = ((z[0] & 0x1f)<<6) | (z[1] & 0x3f);
1121     return 2;
1122   }
1123   if( (z[0] & 0xf0)==0xe0 && (z[1] & 0xc0)==0x80 && (z[2] & 0xc0)==0x80 ){
1124     *pU = ((z[0] & 0x0f)<<12) | ((z[1] & 0x3f)<<6) | (z[2] & 0x3f);
1125     return 3;
1126   }
1127   if( (z[0] & 0xf8)==0xf0 && (z[1] & 0xc0)==0x80 && (z[2] & 0xc0)==0x80
1128    && (z[3] & 0xc0)==0x80
1129   ){
1130     *pU = ((z[0] & 0x0f)<<18) | ((z[1] & 0x3f)<<12) | ((z[2] & 0x3f))<<6
1131                               | (z[4] & 0x3f);
1132     return 4;
1133   }
1134   *pU = 0;
1135   return 1;
1136 }
1137 
1138 
1139 #if 0 /* NOT USED */
1140 /*
1141 ** Return the width, in display columns, of a UTF-8 string.
1142 **
1143 ** Each normal character counts as 1.  Zero-width characters count
1144 ** as zero, and double-width characters count as 2.
1145 */
1146 int cli_wcswidth(const char *z){
1147   const unsigned char *a = (const unsigned char*)z;
1148   int n = 0;
1149   int i = 0;
1150   unsigned char c;
1151   while( (c = a[i])!=0 ){
1152     if( c>=0xc0 ){
1153       int u;
1154       int len = decodeUtf8(&a[i], &u);
1155       i += len;
1156       n += cli_wcwidth(u);
1157     }else if( c>=' ' ){
1158       n++;
1159       i++;
1160     }else{
1161       i++;
1162     }
1163   }
1164   return n;
1165 }
1166 #endif
1167 
1168 /*
1169 ** Check to see if z[] is a valid VT100 escape.  If it is, then
1170 ** return the number of bytes in the escape sequence.  Return 0 if
1171 ** z[] is not a VT100 escape.
1172 **
1173 ** This routine assumes that z[0] is \033 (ESC).
1174 */
isVt100(const unsigned char * z)1175 static int isVt100(const unsigned char *z){
1176   int i;
1177   if( z[1]!='[' ) return 0;
1178   i = 2;
1179   while( z[i]>=0x30 && z[i]<=0x3f ){ i++; }
1180   while( z[i]>=0x20 && z[i]<=0x2f ){ i++; }
1181   if( z[i]<0x40 || z[i]>0x7e ) return 0;
1182   return i+1;
1183 }
1184 
1185 /*
1186 ** Output string zUtf to stdout as w characters.  If w is negative,
1187 ** then right-justify the text.  W is the width in UTF-8 characters, not
1188 ** in bytes.  This is different from the %*.*s specification in printf
1189 ** since with %*.*s the width is measured in bytes, not characters.
1190 **
1191 ** Take into account zero-width and double-width Unicode characters.
1192 ** In other words, a zero-width character does not count toward the
1193 ** the w limit.  A double-width character counts as two.
1194 */
utf8_width_print(FILE * out,int w,const char * zUtf)1195 static void utf8_width_print(FILE *out, int w, const char *zUtf){
1196   const unsigned char *a = (const unsigned char*)zUtf;
1197   unsigned char c;
1198   int i = 0;
1199   int n = 0;
1200   int k;
1201   int aw = w<0 ? -w : w;
1202   if( zUtf==0 ) zUtf = "";
1203   while( (c = a[i])!=0 ){
1204     if( (c&0xc0)==0xc0 ){
1205       int u;
1206       int len = decodeUtf8(a+i, &u);
1207       int x = cli_wcwidth(u);
1208       if( x+n>aw ){
1209         break;
1210       }
1211       i += len;
1212       n += x;
1213     }else if( c==0x1b && (k = isVt100(&a[i]))>0 ){
1214       i += k;
1215     }else if( n>=aw ){
1216       break;
1217     }else{
1218       n++;
1219       i++;
1220     }
1221   }
1222   if( n>=aw ){
1223     sqlite3_fprintf(out, "%.*s", i, zUtf);
1224   }else if( w<0 ){
1225     sqlite3_fprintf(out, "%*s%s", aw-n, "", zUtf);
1226   }else{
1227     sqlite3_fprintf(out, "%s%*s", zUtf, aw-n, "");
1228   }
1229 }
1230 
1231 
1232 /*
1233 ** Determines if a string is a number of not.
1234 */
isNumber(const char * z,int * realnum)1235 static int isNumber(const char *z, int *realnum){
1236   if( *z=='-' || *z=='+' ) z++;
1237   if( !IsDigit(*z) ){
1238     return 0;
1239   }
1240   z++;
1241   if( realnum ) *realnum = 0;
1242   while( IsDigit(*z) ){ z++; }
1243   if( *z=='.' ){
1244     z++;
1245     if( !IsDigit(*z) ) return 0;
1246     while( IsDigit(*z) ){ z++; }
1247     if( realnum ) *realnum = 1;
1248   }
1249   if( *z=='e' || *z=='E' ){
1250     z++;
1251     if( *z=='+' || *z=='-' ) z++;
1252     if( !IsDigit(*z) ) return 0;
1253     while( IsDigit(*z) ){ z++; }
1254     if( realnum ) *realnum = 1;
1255   }
1256   return *z==0;
1257 }
1258 
1259 /*
1260 ** Compute a string length that is limited to what can be stored in
1261 ** lower 30 bits of a 32-bit signed integer.
1262 */
strlen30(const char * z)1263 static int strlen30(const char *z){
1264   const char *z2 = z;
1265   while( *z2 ){ z2++; }
1266   return 0x3fffffff & (int)(z2 - z);
1267 }
1268 
1269 /*
1270 ** Return the length of a string in characters.  Multibyte UTF8 characters
1271 ** count as a single character.
1272 */
strlenChar(const char * z)1273 static int strlenChar(const char *z){
1274   int n = 0;
1275   while( *z ){
1276     if( (0xc0&*(z++))!=0x80 ) n++;
1277   }
1278   return n;
1279 }
1280 
1281 /*
1282 ** Return open FILE * if zFile exists, can be opened for read
1283 ** and is an ordinary file or a character stream source.
1284 ** Otherwise return 0.
1285 */
openChrSource(const char * zFile)1286 static FILE * openChrSource(const char *zFile){
1287 #if defined(_WIN32) || defined(WIN32)
1288   struct __stat64 x = {0};
1289 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1290   /* On Windows, open first, then check the stream nature. This order
1291   ** is necessary because _stat() and sibs, when checking a named pipe,
1292   ** effectively break the pipe as its supplier sees it. */
1293   FILE *rv = sqlite3_fopen(zFile, "rb");
1294   if( rv==0 ) return 0;
1295   if( _fstat64(_fileno(rv), &x) != 0
1296       || !STAT_CHR_SRC(x.st_mode)){
1297     fclose(rv);
1298     rv = 0;
1299   }
1300   return rv;
1301 #else
1302   struct stat x = {0};
1303   int rc = stat(zFile, &x);
1304 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
1305   if( rc!=0 ) return 0;
1306   if( STAT_CHR_SRC(x.st_mode) ){
1307     return sqlite3_fopen(zFile, "rb");
1308   }else{
1309     return 0;
1310   }
1311 #endif
1312 #undef STAT_CHR_SRC
1313 }
1314 
1315 /*
1316 ** This routine reads a line of text from FILE in, stores
1317 ** the text in memory obtained from malloc() and returns a pointer
1318 ** to the text.  NULL is returned at end of file, or if malloc()
1319 ** fails.
1320 **
1321 ** If zLine is not NULL then it is a malloced buffer returned from
1322 ** a previous call to this routine that may be reused.
1323 */
local_getline(char * zLine,FILE * in)1324 static char *local_getline(char *zLine, FILE *in){
1325   int nLine = zLine==0 ? 0 : 100;
1326   int n = 0;
1327 
1328   while( 1 ){
1329     if( n+100>nLine ){
1330       nLine = nLine*2 + 100;
1331       zLine = realloc(zLine, nLine);
1332       shell_check_oom(zLine);
1333     }
1334     if( sqlite3_fgets(&zLine[n], nLine - n, in)==0 ){
1335       if( n==0 ){
1336         free(zLine);
1337         return 0;
1338       }
1339       zLine[n] = 0;
1340       break;
1341     }
1342     while( zLine[n] ) n++;
1343     if( n>0 && zLine[n-1]=='\n' ){
1344       n--;
1345       if( n>0 && zLine[n-1]=='\r' ) n--;
1346       zLine[n] = 0;
1347       break;
1348     }
1349   }
1350   return zLine;
1351 }
1352 
1353 /*
1354 ** Retrieve a single line of input text.
1355 **
1356 ** If in==0 then read from standard input and prompt before each line.
1357 ** If isContinuation is true, then a continuation prompt is appropriate.
1358 ** If isContinuation is zero, then the main prompt should be used.
1359 **
1360 ** If zPrior is not NULL then it is a buffer from a prior call to this
1361 ** routine that can be reused.
1362 **
1363 ** The result is stored in space obtained from malloc() and must either
1364 ** be freed by the caller or else passed back into this routine via the
1365 ** zPrior argument for reuse.
1366 */
1367 #ifndef SQLITE_SHELL_FIDDLE
one_input_line(FILE * in,char * zPrior,int isContinuation)1368 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1369   char *zPrompt;
1370   char *zResult;
1371   if( in!=0 ){
1372     zResult = local_getline(zPrior, in);
1373   }else{
1374     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1375 #if SHELL_USE_LOCAL_GETLINE
1376     sputz(stdout, zPrompt);
1377     fflush(stdout);
1378     do{
1379       zResult = local_getline(zPrior, stdin);
1380       zPrior = 0;
1381       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1382       if( zResult==0 ) sqlite3_sleep(50);
1383     }while( zResult==0 && seenInterrupt>0 );
1384 #else
1385     free(zPrior);
1386     zResult = shell_readline(zPrompt);
1387     while( zResult==0 ){
1388       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1389       sqlite3_sleep(50);
1390       if( seenInterrupt==0 ) break;
1391       zResult = shell_readline("");
1392     }
1393     if( zResult && *zResult ) shell_add_history(zResult);
1394 #endif
1395   }
1396   return zResult;
1397 }
1398 #endif /* !SQLITE_SHELL_FIDDLE */
1399 
1400 /*
1401 ** Return the value of a hexadecimal digit.  Return -1 if the input
1402 ** is not a hex digit.
1403 */
hexDigitValue(char c)1404 static int hexDigitValue(char c){
1405   if( c>='0' && c<='9' ) return c - '0';
1406   if( c>='a' && c<='f' ) return c - 'a' + 10;
1407   if( c>='A' && c<='F' ) return c - 'A' + 10;
1408   return -1;
1409 }
1410 
1411 /*
1412 ** Interpret zArg as an integer value, possibly with suffixes.
1413 */
integerValue(const char * zArg)1414 static sqlite3_int64 integerValue(const char *zArg){
1415   sqlite3_int64 v = 0;
1416   static const struct { char *zSuffix; int iMult; } aMult[] = {
1417     { "KiB", 1024 },
1418     { "MiB", 1024*1024 },
1419     { "GiB", 1024*1024*1024 },
1420     { "KB",  1000 },
1421     { "MB",  1000000 },
1422     { "GB",  1000000000 },
1423     { "K",   1000 },
1424     { "M",   1000000 },
1425     { "G",   1000000000 },
1426   };
1427   int i;
1428   int isNeg = 0;
1429   if( zArg[0]=='-' ){
1430     isNeg = 1;
1431     zArg++;
1432   }else if( zArg[0]=='+' ){
1433     zArg++;
1434   }
1435   if( zArg[0]=='0' && zArg[1]=='x' ){
1436     int x;
1437     zArg += 2;
1438     while( (x = hexDigitValue(zArg[0]))>=0 ){
1439       v = (v<<4) + x;
1440       zArg++;
1441     }
1442   }else{
1443     while( IsDigit(zArg[0]) ){
1444       v = v*10 + zArg[0] - '0';
1445       zArg++;
1446     }
1447   }
1448   for(i=0; i<ArraySize(aMult); i++){
1449     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1450       v *= aMult[i].iMult;
1451       break;
1452     }
1453   }
1454   return isNeg? -v : v;
1455 }
1456 
1457 /*
1458 ** A variable length string to which one can append text.
1459 */
1460 typedef struct ShellText ShellText;
1461 struct ShellText {
1462   char *z;
1463   int n;
1464   int nAlloc;
1465 };
1466 
1467 /*
1468 ** Initialize and destroy a ShellText object
1469 */
initText(ShellText * p)1470 static void initText(ShellText *p){
1471   memset(p, 0, sizeof(*p));
1472 }
freeText(ShellText * p)1473 static void freeText(ShellText *p){
1474   free(p->z);
1475   initText(p);
1476 }
1477 
1478 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1479 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1480 ** added to zIn, and the result returned in memory obtained from malloc().
1481 ** zIn, if it was not NULL, is freed.
1482 **
1483 ** If the third argument, quote, is not '\0', then it is used as a
1484 ** quote character for zAppend.
1485 */
appendText(ShellText * p,const char * zAppend,char quote)1486 static void appendText(ShellText *p, const char *zAppend, char quote){
1487   i64 len;
1488   i64 i;
1489   i64 nAppend = strlen30(zAppend);
1490 
1491   len = nAppend+p->n+1;
1492   if( quote ){
1493     len += 2;
1494     for(i=0; i<nAppend; i++){
1495       if( zAppend[i]==quote ) len++;
1496     }
1497   }
1498 
1499   if( p->z==0 || p->n+len>=p->nAlloc ){
1500     p->nAlloc = p->nAlloc*2 + len + 20;
1501     p->z = realloc(p->z, p->nAlloc);
1502     shell_check_oom(p->z);
1503   }
1504 
1505   if( quote ){
1506     char *zCsr = p->z+p->n;
1507     *zCsr++ = quote;
1508     for(i=0; i<nAppend; i++){
1509       *zCsr++ = zAppend[i];
1510       if( zAppend[i]==quote ) *zCsr++ = quote;
1511     }
1512     *zCsr++ = quote;
1513     p->n = (int)(zCsr - p->z);
1514     *zCsr = '\0';
1515   }else{
1516     memcpy(p->z+p->n, zAppend, nAppend);
1517     p->n += nAppend;
1518     p->z[p->n] = '\0';
1519   }
1520 }
1521 
1522 /*
1523 ** Attempt to determine if identifier zName needs to be quoted, either
1524 ** because it contains non-alphanumeric characters, or because it is an
1525 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1526 ** that quoting is required.
1527 **
1528 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1529 */
quoteChar(const char * zName)1530 static char quoteChar(const char *zName){
1531   int i;
1532   if( zName==0 ) return '"';
1533   if( !IsAlpha(zName[0]) && zName[0]!='_' ) return '"';
1534   for(i=0; zName[i]; i++){
1535     if( !IsAlnum(zName[i]) && zName[i]!='_' ) return '"';
1536   }
1537   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1538 }
1539 
1540 /*
1541 ** Construct a fake object name and column list to describe the structure
1542 ** of the view, virtual table, or table valued function zSchema.zName.
1543 */
shellFakeSchema(sqlite3 * db,const char * zSchema,const char * zName)1544 static char *shellFakeSchema(
1545   sqlite3 *db,            /* The database connection containing the vtab */
1546   const char *zSchema,    /* Schema of the database holding the vtab */
1547   const char *zName       /* The name of the virtual table */
1548 ){
1549   sqlite3_stmt *pStmt = 0;
1550   char *zSql;
1551   ShellText s;
1552   char cQuote;
1553   char *zDiv = "(";
1554   int nRow = 0;
1555 
1556   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1557                          zSchema ? zSchema : "main", zName);
1558   shell_check_oom(zSql);
1559   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1560   sqlite3_free(zSql);
1561   initText(&s);
1562   if( zSchema ){
1563     cQuote = quoteChar(zSchema);
1564     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1565     appendText(&s, zSchema, cQuote);
1566     appendText(&s, ".", 0);
1567   }
1568   cQuote = quoteChar(zName);
1569   appendText(&s, zName, cQuote);
1570   while( sqlite3_step(pStmt)==SQLITE_ROW ){
1571     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1572     nRow++;
1573     appendText(&s, zDiv, 0);
1574     zDiv = ",";
1575     if( zCol==0 ) zCol = "";
1576     cQuote = quoteChar(zCol);
1577     appendText(&s, zCol, cQuote);
1578   }
1579   appendText(&s, ")", 0);
1580   sqlite3_finalize(pStmt);
1581   if( nRow==0 ){
1582     freeText(&s);
1583     s.z = 0;
1584   }
1585   return s.z;
1586 }
1587 
1588 /*
1589 ** SQL function:  strtod(X)
1590 **
1591 ** Use the C-library strtod() function to convert string X into a double.
1592 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
1593 ** routines against the C-library.
1594 */
shellStrtod(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)1595 static void shellStrtod(
1596   sqlite3_context *pCtx,
1597   int nVal,
1598   sqlite3_value **apVal
1599 ){
1600   char *z = (char*)sqlite3_value_text(apVal[0]);
1601   UNUSED_PARAMETER(nVal);
1602   if( z==0 ) return;
1603   sqlite3_result_double(pCtx, strtod(z,0));
1604 }
1605 
1606 /*
1607 ** SQL function:  dtostr(X)
1608 **
1609 ** Use the C-library printf() function to convert real value X into a string.
1610 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
1611 ** routines against the C-library.
1612 */
shellDtostr(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)1613 static void shellDtostr(
1614   sqlite3_context *pCtx,
1615   int nVal,
1616   sqlite3_value **apVal
1617 ){
1618   double r = sqlite3_value_double(apVal[0]);
1619   int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
1620   char z[400];
1621   if( n<1 ) n = 1;
1622   if( n>350 ) n = 350;
1623   sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
1624   sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
1625 }
1626 
1627 /*
1628 ** SQL function:  shell_add_schema(S,X)
1629 **
1630 ** Add the schema name X to the CREATE statement in S and return the result.
1631 ** Examples:
1632 **
1633 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
1634 **
1635 ** Also works on
1636 **
1637 **    CREATE INDEX
1638 **    CREATE UNIQUE INDEX
1639 **    CREATE VIEW
1640 **    CREATE TRIGGER
1641 **    CREATE VIRTUAL TABLE
1642 **
1643 ** This UDF is used by the .schema command to insert the schema name of
1644 ** attached databases into the middle of the sqlite_schema.sql field.
1645 */
shellAddSchemaName(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)1646 static void shellAddSchemaName(
1647   sqlite3_context *pCtx,
1648   int nVal,
1649   sqlite3_value **apVal
1650 ){
1651   static const char *aPrefix[] = {
1652      "TABLE",
1653      "INDEX",
1654      "UNIQUE INDEX",
1655      "VIEW",
1656      "TRIGGER",
1657      "VIRTUAL TABLE"
1658   };
1659   int i = 0;
1660   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1661   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1662   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1663   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1664   UNUSED_PARAMETER(nVal);
1665   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1666     for(i=0; i<ArraySize(aPrefix); i++){
1667       int n = strlen30(aPrefix[i]);
1668       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1669         char *z = 0;
1670         char *zFake = 0;
1671         if( zSchema ){
1672           char cQuote = quoteChar(zSchema);
1673           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1674             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1675           }else{
1676             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1677           }
1678         }
1679         if( zName
1680          && aPrefix[i][0]=='V'
1681          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1682         ){
1683           if( z==0 ){
1684             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1685           }else{
1686             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1687           }
1688           free(zFake);
1689         }
1690         if( z ){
1691           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1692           return;
1693         }
1694       }
1695     }
1696   }
1697   sqlite3_result_value(pCtx, apVal[0]);
1698 }
1699 
1700 /*
1701 ** The source code for several run-time loadable extensions is inserted
1702 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1703 ** code, we need to override some macros to make the included program code
1704 ** work here in the middle of this regular program.
1705 */
1706 #define SQLITE_EXTENSION_INIT1
1707 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1708 
1709 #if defined(_WIN32) && defined(_MSC_VER)
1710 /************************* Begin test_windirent.h ******************/
1711 /*
1712 ** 2015 November 30
1713 **
1714 ** The author disclaims copyright to this source code.  In place of
1715 ** a legal notice, here is a blessing:
1716 **
1717 **    May you do good and not evil.
1718 **    May you find forgiveness for yourself and forgive others.
1719 **    May you share freely, never taking more than you give.
1720 **
1721 *************************************************************************
1722 ** This file contains declarations for most of the opendir() family of
1723 ** POSIX functions on Win32 using the MSVCRT.
1724 */
1725 
1726 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1727 #define SQLITE_WINDIRENT_H
1728 
1729 /*
1730 ** We need several data types from the Windows SDK header.
1731 */
1732 
1733 #ifndef WIN32_LEAN_AND_MEAN
1734 #define WIN32_LEAN_AND_MEAN
1735 #endif
1736 
1737 #include "windows.h"
1738 
1739 /*
1740 ** We need several support functions from the SQLite core.
1741 */
1742 
1743 /* #include "sqlite3.h" */
1744 
1745 /*
1746 ** We need several things from the ANSI and MSVCRT headers.
1747 */
1748 
1749 #include <stdio.h>
1750 #include <stdlib.h>
1751 #include <errno.h>
1752 #include <io.h>
1753 #include <limits.h>
1754 #include <sys/types.h>
1755 #include <sys/stat.h>
1756 
1757 /*
1758 ** We may need several defines that should have been in "sys/stat.h".
1759 */
1760 
1761 #ifndef S_ISREG
1762 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1763 #endif
1764 
1765 #ifndef S_ISDIR
1766 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1767 #endif
1768 
1769 #ifndef S_ISLNK
1770 #define S_ISLNK(mode) (0)
1771 #endif
1772 
1773 /*
1774 ** We may need to provide the "mode_t" type.
1775 */
1776 
1777 #ifndef MODE_T_DEFINED
1778   #define MODE_T_DEFINED
1779   typedef unsigned short mode_t;
1780 #endif
1781 
1782 /*
1783 ** We may need to provide the "ino_t" type.
1784 */
1785 
1786 #ifndef INO_T_DEFINED
1787   #define INO_T_DEFINED
1788   typedef unsigned short ino_t;
1789 #endif
1790 
1791 /*
1792 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1793 */
1794 
1795 #ifndef NAME_MAX
1796 #  ifdef FILENAME_MAX
1797 #    define NAME_MAX (FILENAME_MAX)
1798 #  else
1799 #    define NAME_MAX (260)
1800 #  endif
1801 #  define DIRENT_NAME_MAX (NAME_MAX)
1802 #endif
1803 
1804 /*
1805 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1806 */
1807 
1808 #ifndef NULL_INTPTR_T
1809 #  define NULL_INTPTR_T ((intptr_t)(0))
1810 #endif
1811 
1812 #ifndef BAD_INTPTR_T
1813 #  define BAD_INTPTR_T ((intptr_t)(-1))
1814 #endif
1815 
1816 /*
1817 ** We need to provide the necessary structures and related types.
1818 */
1819 
1820 #ifndef DIRENT_DEFINED
1821 #define DIRENT_DEFINED
1822 typedef struct DIRENT DIRENT;
1823 typedef DIRENT *LPDIRENT;
1824 struct DIRENT {
1825   ino_t d_ino;               /* Sequence number, do not use. */
1826   unsigned d_attributes;     /* Win32 file attributes. */
1827   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1828 };
1829 #endif
1830 
1831 #ifndef DIR_DEFINED
1832 #define DIR_DEFINED
1833 typedef struct DIR DIR;
1834 typedef DIR *LPDIR;
1835 struct DIR {
1836   intptr_t d_handle; /* Value returned by "_findfirst". */
1837   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1838   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1839 };
1840 #endif
1841 
1842 /*
1843 ** Provide a macro, for use by the implementation, to determine if a
1844 ** particular directory entry should be skipped over when searching for
1845 ** the next directory entry that should be returned by the readdir().
1846 */
1847 
1848 #ifndef is_filtered
1849 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1850 #endif
1851 
1852 /*
1853 ** Provide the function prototype for the POSIX compatible getenv()
1854 ** function.  This function is not thread-safe.
1855 */
1856 
1857 extern const char *windirent_getenv(const char *name);
1858 
1859 /*
1860 ** Finally, we can provide the function prototypes for the opendir(),
1861 ** readdir(), and closedir() POSIX functions.
1862 */
1863 
1864 extern LPDIR opendir(const char *dirname);
1865 extern LPDIRENT readdir(LPDIR dirp);
1866 extern INT closedir(LPDIR dirp);
1867 
1868 #endif /* defined(WIN32) && defined(_MSC_VER) */
1869 
1870 /************************* End test_windirent.h ********************/
1871 /************************* Begin test_windirent.c ******************/
1872 /*
1873 ** 2015 November 30
1874 **
1875 ** The author disclaims copyright to this source code.  In place of
1876 ** a legal notice, here is a blessing:
1877 **
1878 **    May you do good and not evil.
1879 **    May you find forgiveness for yourself and forgive others.
1880 **    May you share freely, never taking more than you give.
1881 **
1882 *************************************************************************
1883 ** This file contains code to implement most of the opendir() family of
1884 ** POSIX functions on Win32 using the MSVCRT.
1885 */
1886 
1887 #if defined(_WIN32) && defined(_MSC_VER)
1888 /* #include "test_windirent.h" */
1889 
1890 /*
1891 ** Implementation of the POSIX getenv() function using the Win32 API.
1892 ** This function is not thread-safe.
1893 */
windirent_getenv(const char * name)1894 const char *windirent_getenv(
1895   const char *name
1896 ){
1897   static char value[32768]; /* Maximum length, per MSDN */
1898   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1899   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1900 
1901   memset(value, 0, sizeof(value));
1902   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1903   if( dwRet==0 || dwRet>dwSize ){
1904     /*
1905     ** The function call to GetEnvironmentVariableA() failed -OR-
1906     ** the buffer is not large enough.  Either way, return NULL.
1907     */
1908     return 0;
1909   }else{
1910     /*
1911     ** The function call to GetEnvironmentVariableA() succeeded
1912     ** -AND- the buffer contains the entire value.
1913     */
1914     return value;
1915   }
1916 }
1917 
1918 /*
1919 ** Implementation of the POSIX opendir() function using the MSVCRT.
1920 */
opendir(const char * dirname)1921 LPDIR opendir(
1922   const char *dirname  /* Directory name, UTF8 encoding */
1923 ){
1924   struct _wfinddata_t data;
1925   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1926   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1927   wchar_t *b1;
1928   sqlite3_int64 sz;
1929 
1930   if( dirp==NULL ) return NULL;
1931   memset(dirp, 0, sizeof(DIR));
1932 
1933   /* TODO: Remove this if Unix-style root paths are not used. */
1934   if( sqlite3_stricmp(dirname, "/")==0 ){
1935     dirname = windirent_getenv("SystemDrive");
1936   }
1937 
1938   memset(&data, 0, sizeof(data));
1939   sz = strlen(dirname);
1940   b1 = sqlite3_malloc64( (sz+3)*sizeof(b1[0]) );
1941   if( b1==0 ){
1942     closedir(dirp);
1943     return NULL;
1944   }
1945   sz = MultiByteToWideChar(CP_UTF8, 0, dirname, sz, b1, sz);
1946   b1[sz++] = '\\';
1947   b1[sz++] = '*';
1948   b1[sz] = 0;
1949   if( sz+1>(sqlite3_int64)namesize ){
1950     closedir(dirp);
1951     sqlite3_free(b1);
1952     return NULL;
1953   }
1954   memcpy(data.name, b1, (sz+1)*sizeof(b1[0]));
1955   sqlite3_free(b1);
1956   dirp->d_handle = _wfindfirst(data.name, &data);
1957 
1958   if( dirp->d_handle==BAD_INTPTR_T ){
1959     closedir(dirp);
1960     return NULL;
1961   }
1962 
1963   /* TODO: Remove this block to allow hidden and/or system files. */
1964   if( is_filtered(data) ){
1965 next:
1966 
1967     memset(&data, 0, sizeof(data));
1968     if( _wfindnext(dirp->d_handle, &data)==-1 ){
1969       closedir(dirp);
1970       return NULL;
1971     }
1972 
1973     /* TODO: Remove this block to allow hidden and/or system files. */
1974     if( is_filtered(data) ) goto next;
1975   }
1976 
1977   dirp->d_first.d_attributes = data.attrib;
1978   WideCharToMultiByte(CP_UTF8, 0, data.name, -1,
1979                       dirp->d_first.d_name, DIRENT_NAME_MAX, 0, 0);
1980   return dirp;
1981 }
1982 
1983 /*
1984 ** Implementation of the POSIX readdir() function using the MSVCRT.
1985 */
readdir(LPDIR dirp)1986 LPDIRENT readdir(
1987   LPDIR dirp
1988 ){
1989   struct _wfinddata_t data;
1990 
1991   if( dirp==NULL ) return NULL;
1992 
1993   if( dirp->d_first.d_ino==0 ){
1994     dirp->d_first.d_ino++;
1995     dirp->d_next.d_ino++;
1996 
1997     return &dirp->d_first;
1998   }
1999 
2000 next:
2001 
2002   memset(&data, 0, sizeof(data));
2003   if( _wfindnext(dirp->d_handle, &data)==-1 ) return NULL;
2004 
2005   /* TODO: Remove this block to allow hidden and/or system files. */
2006   if( is_filtered(data) ) goto next;
2007 
2008   dirp->d_next.d_ino++;
2009   dirp->d_next.d_attributes = data.attrib;
2010   WideCharToMultiByte(CP_UTF8, 0, data.name, -1,
2011                       dirp->d_next.d_name, DIRENT_NAME_MAX, 0, 0);
2012   return &dirp->d_next;
2013 }
2014 
2015 /*
2016 ** Implementation of the POSIX closedir() function using the MSVCRT.
2017 */
closedir(LPDIR dirp)2018 INT closedir(
2019   LPDIR dirp
2020 ){
2021   INT result = 0;
2022 
2023   if( dirp==NULL ) return EINVAL;
2024 
2025   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
2026     result = _findclose(dirp->d_handle);
2027   }
2028 
2029   sqlite3_free(dirp);
2030   return result;
2031 }
2032 
2033 #endif /* defined(WIN32) && defined(_MSC_VER) */
2034 
2035 /************************* End test_windirent.c ********************/
2036 #define dirent DIRENT
2037 #endif
2038 /************************* Begin ../ext/misc/memtrace.c ******************/
2039 /*
2040 ** 2019-01-21
2041 **
2042 ** The author disclaims copyright to this source code.  In place of
2043 ** a legal notice, here is a blessing:
2044 **
2045 **    May you do good and not evil.
2046 **    May you find forgiveness for yourself and forgive others.
2047 **    May you share freely, never taking more than you give.
2048 **
2049 *************************************************************************
2050 **
2051 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
2052 ** mechanism to add a tracing layer on top of SQLite.  If this extension
2053 ** is registered prior to sqlite3_initialize(), it will cause all memory
2054 ** allocation activities to be logged on standard output, or to some other
2055 ** FILE specified by the initializer.
2056 **
2057 ** This file needs to be compiled into the application that uses it.
2058 **
2059 ** This extension is used to implement the --memtrace option of the
2060 ** command-line shell.
2061 */
2062 #include <assert.h>
2063 #include <string.h>
2064 #include <stdio.h>
2065 
2066 /* The original memory allocation routines */
2067 static sqlite3_mem_methods memtraceBase;
2068 static FILE *memtraceOut;
2069 
2070 /* Methods that trace memory allocations */
memtraceMalloc(int n)2071 static void *memtraceMalloc(int n){
2072   if( memtraceOut ){
2073     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
2074             memtraceBase.xRoundup(n));
2075   }
2076   return memtraceBase.xMalloc(n);
2077 }
memtraceFree(void * p)2078 static void memtraceFree(void *p){
2079   if( p==0 ) return;
2080   if( memtraceOut ){
2081     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
2082   }
2083   memtraceBase.xFree(p);
2084 }
memtraceRealloc(void * p,int n)2085 static void *memtraceRealloc(void *p, int n){
2086   if( p==0 ) return memtraceMalloc(n);
2087   if( n==0 ){
2088     memtraceFree(p);
2089     return 0;
2090   }
2091   if( memtraceOut ){
2092     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
2093             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
2094   }
2095   return memtraceBase.xRealloc(p, n);
2096 }
memtraceSize(void * p)2097 static int memtraceSize(void *p){
2098   return memtraceBase.xSize(p);
2099 }
memtraceRoundup(int n)2100 static int memtraceRoundup(int n){
2101   return memtraceBase.xRoundup(n);
2102 }
memtraceInit(void * p)2103 static int memtraceInit(void *p){
2104   return memtraceBase.xInit(p);
2105 }
memtraceShutdown(void * p)2106 static void memtraceShutdown(void *p){
2107   memtraceBase.xShutdown(p);
2108 }
2109 
2110 /* The substitute memory allocator */
2111 static sqlite3_mem_methods ersaztMethods = {
2112   memtraceMalloc,
2113   memtraceFree,
2114   memtraceRealloc,
2115   memtraceSize,
2116   memtraceRoundup,
2117   memtraceInit,
2118   memtraceShutdown,
2119   0
2120 };
2121 
2122 /* Begin tracing memory allocations to out. */
sqlite3MemTraceActivate(FILE * out)2123 int sqlite3MemTraceActivate(FILE *out){
2124   int rc = SQLITE_OK;
2125   if( memtraceBase.xMalloc==0 ){
2126     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
2127     if( rc==SQLITE_OK ){
2128       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
2129     }
2130   }
2131   memtraceOut = out;
2132   return rc;
2133 }
2134 
2135 /* Deactivate memory tracing */
sqlite3MemTraceDeactivate(void)2136 int sqlite3MemTraceDeactivate(void){
2137   int rc = SQLITE_OK;
2138   if( memtraceBase.xMalloc!=0 ){
2139     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
2140     if( rc==SQLITE_OK ){
2141       memset(&memtraceBase, 0, sizeof(memtraceBase));
2142     }
2143   }
2144   memtraceOut = 0;
2145   return rc;
2146 }
2147 
2148 /************************* End ../ext/misc/memtrace.c ********************/
2149 /************************* Begin ../ext/misc/pcachetrace.c ******************/
2150 /*
2151 ** 2023-06-21
2152 **
2153 ** The author disclaims copyright to this source code.  In place of
2154 ** a legal notice, here is a blessing:
2155 **
2156 **    May you do good and not evil.
2157 **    May you find forgiveness for yourself and forgive others.
2158 **    May you share freely, never taking more than you give.
2159 **
2160 *************************************************************************
2161 **
2162 ** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
2163 ** mechanism to add a tracing layer on top of pluggable page cache of
2164 ** SQLite.  If this extension is registered prior to sqlite3_initialize(),
2165 ** it will cause all page cache activities to be logged on standard output,
2166 ** or to some other FILE specified by the initializer.
2167 **
2168 ** This file needs to be compiled into the application that uses it.
2169 **
2170 ** This extension is used to implement the --pcachetrace option of the
2171 ** command-line shell.
2172 */
2173 #include <assert.h>
2174 #include <string.h>
2175 #include <stdio.h>
2176 
2177 /* The original page cache routines */
2178 static sqlite3_pcache_methods2 pcacheBase;
2179 static FILE *pcachetraceOut;
2180 
2181 /* Methods that trace pcache activity */
pcachetraceInit(void * pArg)2182 static int pcachetraceInit(void *pArg){
2183   int nRes;
2184   if( pcachetraceOut ){
2185     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
2186   }
2187   nRes = pcacheBase.xInit(pArg);
2188   if( pcachetraceOut ){
2189     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
2190   }
2191   return nRes;
2192 }
pcachetraceShutdown(void * pArg)2193 static void pcachetraceShutdown(void *pArg){
2194   if( pcachetraceOut ){
2195     fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
2196   }
2197   pcacheBase.xShutdown(pArg);
2198 }
pcachetraceCreate(int szPage,int szExtra,int bPurge)2199 static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
2200   sqlite3_pcache *pRes;
2201   if( pcachetraceOut ){
2202     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
2203             szPage, szExtra, bPurge);
2204   }
2205   pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
2206   if( pcachetraceOut ){
2207     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
2208             szPage, szExtra, bPurge, pRes);
2209   }
2210   return pRes;
2211 }
pcachetraceCachesize(sqlite3_pcache * p,int nCachesize)2212 static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
2213   if( pcachetraceOut ){
2214     fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
2215   }
2216   pcacheBase.xCachesize(p, nCachesize);
2217 }
pcachetracePagecount(sqlite3_pcache * p)2218 static int pcachetracePagecount(sqlite3_pcache *p){
2219   int nRes;
2220   if( pcachetraceOut ){
2221     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
2222   }
2223   nRes = pcacheBase.xPagecount(p);
2224   if( pcachetraceOut ){
2225     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
2226   }
2227   return nRes;
2228 }
pcachetraceFetch(sqlite3_pcache * p,unsigned key,int crFg)2229 static sqlite3_pcache_page *pcachetraceFetch(
2230   sqlite3_pcache *p,
2231   unsigned key,
2232   int crFg
2233 ){
2234   sqlite3_pcache_page *pRes;
2235   if( pcachetraceOut ){
2236     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
2237   }
2238   pRes = pcacheBase.xFetch(p, key, crFg);
2239   if( pcachetraceOut ){
2240     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
2241             p, key, crFg, pRes);
2242   }
2243   return pRes;
2244 }
pcachetraceUnpin(sqlite3_pcache * p,sqlite3_pcache_page * pPg,int bDiscard)2245 static void pcachetraceUnpin(
2246   sqlite3_pcache *p,
2247   sqlite3_pcache_page *pPg,
2248   int bDiscard
2249 ){
2250   if( pcachetraceOut ){
2251     fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
2252             p, pPg, bDiscard);
2253   }
2254   pcacheBase.xUnpin(p, pPg, bDiscard);
2255 }
pcachetraceRekey(sqlite3_pcache * p,sqlite3_pcache_page * pPg,unsigned oldKey,unsigned newKey)2256 static void pcachetraceRekey(
2257   sqlite3_pcache *p,
2258   sqlite3_pcache_page *pPg,
2259   unsigned oldKey,
2260   unsigned newKey
2261 ){
2262   if( pcachetraceOut ){
2263     fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
2264         p, pPg, oldKey, newKey);
2265   }
2266   pcacheBase.xRekey(p, pPg, oldKey, newKey);
2267 }
pcachetraceTruncate(sqlite3_pcache * p,unsigned n)2268 static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
2269   if( pcachetraceOut ){
2270     fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
2271   }
2272   pcacheBase.xTruncate(p, n);
2273 }
pcachetraceDestroy(sqlite3_pcache * p)2274 static void pcachetraceDestroy(sqlite3_pcache *p){
2275   if( pcachetraceOut ){
2276     fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
2277   }
2278   pcacheBase.xDestroy(p);
2279 }
pcachetraceShrink(sqlite3_pcache * p)2280 static void pcachetraceShrink(sqlite3_pcache *p){
2281   if( pcachetraceOut ){
2282     fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
2283   }
2284   pcacheBase.xShrink(p);
2285 }
2286 
2287 /* The substitute pcache methods */
2288 static sqlite3_pcache_methods2 ersaztPcacheMethods = {
2289   0,
2290   0,
2291   pcachetraceInit,
2292   pcachetraceShutdown,
2293   pcachetraceCreate,
2294   pcachetraceCachesize,
2295   pcachetracePagecount,
2296   pcachetraceFetch,
2297   pcachetraceUnpin,
2298   pcachetraceRekey,
2299   pcachetraceTruncate,
2300   pcachetraceDestroy,
2301   pcachetraceShrink
2302 };
2303 
2304 /* Begin tracing memory allocations to out. */
sqlite3PcacheTraceActivate(FILE * out)2305 int sqlite3PcacheTraceActivate(FILE *out){
2306   int rc = SQLITE_OK;
2307   if( pcacheBase.xFetch==0 ){
2308     rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
2309     if( rc==SQLITE_OK ){
2310       rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
2311     }
2312   }
2313   pcachetraceOut = out;
2314   return rc;
2315 }
2316 
2317 /* Deactivate memory tracing */
sqlite3PcacheTraceDeactivate(void)2318 int sqlite3PcacheTraceDeactivate(void){
2319   int rc = SQLITE_OK;
2320   if( pcacheBase.xFetch!=0 ){
2321     rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
2322     if( rc==SQLITE_OK ){
2323       memset(&pcacheBase, 0, sizeof(pcacheBase));
2324     }
2325   }
2326   pcachetraceOut = 0;
2327   return rc;
2328 }
2329 
2330 /************************* End ../ext/misc/pcachetrace.c ********************/
2331 /************************* Begin ../ext/misc/shathree.c ******************/
2332 /*
2333 ** 2017-03-08
2334 **
2335 ** The author disclaims copyright to this source code.  In place of
2336 ** a legal notice, here is a blessing:
2337 **
2338 **    May you do good and not evil.
2339 **    May you find forgiveness for yourself and forgive others.
2340 **    May you share freely, never taking more than you give.
2341 **
2342 ******************************************************************************
2343 **
2344 ** This SQLite extension implements functions that compute SHA3 hashes
2345 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2346 ** Three SQL functions are implemented:
2347 **
2348 **     sha3(X,SIZE)
2349 **     sha3_agg(Y,SIZE)
2350 **     sha3_query(Z,SIZE)
2351 **
2352 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
2353 ** X is NULL.  If inputs X is text, the UTF-8 rendering of that text is
2354 ** used to compute the hash.  If X is a BLOB, then the binary data of the
2355 ** blob is used to compute the hash.  If X is an integer or real number,
2356 ** then that number if converted into UTF-8 text and the hash is computed
2357 ** over the text.
2358 **
2359 ** The sha3_agg(Y) function computes the SHA3 hash of all Y inputs.  Since
2360 ** order is important for the hash, it is recommended that the Y expression
2361 ** by followed by an ORDER BY clause to guarantee that the inputs occur
2362 ** in the desired order.
2363 **
2364 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
2365 ** and returns a hash of their results.
2366 **
2367 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
2368 ** is used.  If SIZE is included it must be one of the integers 224, 256,
2369 ** 384, or 512, to determine SHA3 hash variant that is computed.
2370 **
2371 ** Because the sha3_agg() and sha3_query() functions compute a hash over
2372 ** multiple values, the values are encode to use include type information.
2373 **
2374 ** In sha3_agg(), the sequence of bytes that gets hashed for each input
2375 ** Y depends on the datatype of Y:
2376 **
2377 **    typeof(Y)='null'         A single "N" is hashed.  (One byte)
2378 **
2379 **    typeof(Y)='integer'      The data hash is the character "I" followed
2380 **                             by an 8-byte big-endian binary of the
2381 **                             64-bit signed integer.  (Nine bytes total.)
2382 **
2383 **    typeof(Y)='real'         The character "F" followed by an 8-byte
2384 **                             big-ending binary of the double.  (Nine
2385 **                             bytes total.)
2386 **
2387 **    typeof(Y)='text'         The hash is over prefix "Tnnn:" followed
2388 **                             by the UTF8 encoding of the text.  The "nnn"
2389 **                             in the prefix is the minimum-length decimal
2390 **                             representation of the octet_length of the text.
2391 **                             Notice the ":" at the end of the prefix, which
2392 **                             is needed to separate the prefix from the
2393 **                             content in cases where the content starts
2394 **                             with a digit.
2395 **
2396 **    typeof(Y)='blob'         The hash is taken over prefix "Bnnn:" followed
2397 **                             by the binary content of the blob.  The "nnn"
2398 **                             in the prefix is the minimum-length decimal
2399 **                             representation of the byte-length of the blob.
2400 **
2401 ** According to the rules above, all of the following SELECT statements
2402 ** should return TRUE:
2403 **
2404 **    SELECT sha3(1) = sha3('1');
2405 **
2406 **    SELECT sha3('hello') = sha3(x'68656c6c6f');
2407 **
2408 **    WITH a(x) AS (VALUES('xyzzy'))
2409 **      SELECT sha3_agg(x) = sha3('T5:xyzzy')            FROM a;
2410 **
2411 **    WITH a(x) AS (VALUES(x'010203'))
2412 **      SELECT sha3_agg(x) = sha3(x'42333a010203')       FROM a;
2413 **
2414 **    WITH a(x) AS (VALUES(0x123456))
2415 **      SELECT sha3_agg(x) = sha3(x'490000000000123456') FROM a;
2416 **
2417 **    WITH a(x) AS (VALUES(100.015625))
2418 **      SELECT sha3_agg(x) = sha3(x'464059010000000000') FROM a;
2419 **
2420 **    WITH a(x) AS (VALUES(NULL))
2421 **      SELECT sha3_agg(x) = sha3('N') FROM a;
2422 **
2423 **
2424 ** In sha3_query(), individual column values are encoded as with
2425 ** sha3_agg(), but with the addition that a single "R" character is
2426 ** inserted at the start of each row.
2427 **
2428 ** Note that sha3_agg() hashes rows for which Y is NULL.  Add a FILTER
2429 ** clause if NULL rows should be excluded:
2430 **
2431 **    SELECT sha3_agg(x ORDER BY rowid) FILTER(WHERE x NOT NULL) FROM t1;
2432 */
2433 /* #include "sqlite3ext.h" */
2434 SQLITE_EXTENSION_INIT1
2435 #include <assert.h>
2436 #include <string.h>
2437 #include <stdarg.h>
2438 
2439 #ifndef SQLITE_AMALGAMATION
2440 /* typedef sqlite3_uint64 u64; */
2441 #endif /* SQLITE_AMALGAMATION */
2442 
2443 /******************************************************************************
2444 ** The Hash Engine
2445 */
2446 /*
2447 ** Macros to determine whether the machine is big or little endian,
2448 ** and whether or not that determination is run-time or compile-time.
2449 **
2450 ** For best performance, an attempt is made to guess at the byte-order
2451 ** using C-preprocessor macros.  If that is unsuccessful, or if
2452 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2453 ** at run-time.
2454 */
2455 #ifndef SHA3_BYTEORDER
2456 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
2457      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
2458      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
2459      defined(__arm__)
2460 #   define SHA3_BYTEORDER    1234
2461 # elif defined(sparc)    || defined(__ppc__)
2462 #   define SHA3_BYTEORDER    4321
2463 # else
2464 #   define SHA3_BYTEORDER 0
2465 # endif
2466 #endif
2467 
2468 
2469 /*
2470 ** State structure for a SHA3 hash in progress
2471 */
2472 typedef struct SHA3Context SHA3Context;
2473 struct SHA3Context {
2474   union {
2475     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
2476     unsigned char x[1600];    /* ... or 1600 bytes */
2477   } u;
2478   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
2479   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
2480   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
2481   unsigned iSize;        /* 224, 256, 358, or 512 */
2482 };
2483 
2484 /*
2485 ** A single step of the Keccak mixing function for a 1600-bit state
2486 */
KeccakF1600Step(SHA3Context * p)2487 static void KeccakF1600Step(SHA3Context *p){
2488   int i;
2489   u64 b0, b1, b2, b3, b4;
2490   u64 c0, c1, c2, c3, c4;
2491   u64 d0, d1, d2, d3, d4;
2492   static const u64 RC[] = {
2493     0x0000000000000001ULL,  0x0000000000008082ULL,
2494     0x800000000000808aULL,  0x8000000080008000ULL,
2495     0x000000000000808bULL,  0x0000000080000001ULL,
2496     0x8000000080008081ULL,  0x8000000000008009ULL,
2497     0x000000000000008aULL,  0x0000000000000088ULL,
2498     0x0000000080008009ULL,  0x000000008000000aULL,
2499     0x000000008000808bULL,  0x800000000000008bULL,
2500     0x8000000000008089ULL,  0x8000000000008003ULL,
2501     0x8000000000008002ULL,  0x8000000000000080ULL,
2502     0x000000000000800aULL,  0x800000008000000aULL,
2503     0x8000000080008081ULL,  0x8000000000008080ULL,
2504     0x0000000080000001ULL,  0x8000000080008008ULL
2505   };
2506 # define a00 (p->u.s[0])
2507 # define a01 (p->u.s[1])
2508 # define a02 (p->u.s[2])
2509 # define a03 (p->u.s[3])
2510 # define a04 (p->u.s[4])
2511 # define a10 (p->u.s[5])
2512 # define a11 (p->u.s[6])
2513 # define a12 (p->u.s[7])
2514 # define a13 (p->u.s[8])
2515 # define a14 (p->u.s[9])
2516 # define a20 (p->u.s[10])
2517 # define a21 (p->u.s[11])
2518 # define a22 (p->u.s[12])
2519 # define a23 (p->u.s[13])
2520 # define a24 (p->u.s[14])
2521 # define a30 (p->u.s[15])
2522 # define a31 (p->u.s[16])
2523 # define a32 (p->u.s[17])
2524 # define a33 (p->u.s[18])
2525 # define a34 (p->u.s[19])
2526 # define a40 (p->u.s[20])
2527 # define a41 (p->u.s[21])
2528 # define a42 (p->u.s[22])
2529 # define a43 (p->u.s[23])
2530 # define a44 (p->u.s[24])
2531 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
2532 
2533   for(i=0; i<24; i+=4){
2534     c0 = a00^a10^a20^a30^a40;
2535     c1 = a01^a11^a21^a31^a41;
2536     c2 = a02^a12^a22^a32^a42;
2537     c3 = a03^a13^a23^a33^a43;
2538     c4 = a04^a14^a24^a34^a44;
2539     d0 = c4^ROL64(c1, 1);
2540     d1 = c0^ROL64(c2, 1);
2541     d2 = c1^ROL64(c3, 1);
2542     d3 = c2^ROL64(c4, 1);
2543     d4 = c3^ROL64(c0, 1);
2544 
2545     b0 = (a00^d0);
2546     b1 = ROL64((a11^d1), 44);
2547     b2 = ROL64((a22^d2), 43);
2548     b3 = ROL64((a33^d3), 21);
2549     b4 = ROL64((a44^d4), 14);
2550     a00 =   b0 ^((~b1)&  b2 );
2551     a00 ^= RC[i];
2552     a11 =   b1 ^((~b2)&  b3 );
2553     a22 =   b2 ^((~b3)&  b4 );
2554     a33 =   b3 ^((~b4)&  b0 );
2555     a44 =   b4 ^((~b0)&  b1 );
2556 
2557     b2 = ROL64((a20^d0), 3);
2558     b3 = ROL64((a31^d1), 45);
2559     b4 = ROL64((a42^d2), 61);
2560     b0 = ROL64((a03^d3), 28);
2561     b1 = ROL64((a14^d4), 20);
2562     a20 =   b0 ^((~b1)&  b2 );
2563     a31 =   b1 ^((~b2)&  b3 );
2564     a42 =   b2 ^((~b3)&  b4 );
2565     a03 =   b3 ^((~b4)&  b0 );
2566     a14 =   b4 ^((~b0)&  b1 );
2567 
2568     b4 = ROL64((a40^d0), 18);
2569     b0 = ROL64((a01^d1), 1);
2570     b1 = ROL64((a12^d2), 6);
2571     b2 = ROL64((a23^d3), 25);
2572     b3 = ROL64((a34^d4), 8);
2573     a40 =   b0 ^((~b1)&  b2 );
2574     a01 =   b1 ^((~b2)&  b3 );
2575     a12 =   b2 ^((~b3)&  b4 );
2576     a23 =   b3 ^((~b4)&  b0 );
2577     a34 =   b4 ^((~b0)&  b1 );
2578 
2579     b1 = ROL64((a10^d0), 36);
2580     b2 = ROL64((a21^d1), 10);
2581     b3 = ROL64((a32^d2), 15);
2582     b4 = ROL64((a43^d3), 56);
2583     b0 = ROL64((a04^d4), 27);
2584     a10 =   b0 ^((~b1)&  b2 );
2585     a21 =   b1 ^((~b2)&  b3 );
2586     a32 =   b2 ^((~b3)&  b4 );
2587     a43 =   b3 ^((~b4)&  b0 );
2588     a04 =   b4 ^((~b0)&  b1 );
2589 
2590     b3 = ROL64((a30^d0), 41);
2591     b4 = ROL64((a41^d1), 2);
2592     b0 = ROL64((a02^d2), 62);
2593     b1 = ROL64((a13^d3), 55);
2594     b2 = ROL64((a24^d4), 39);
2595     a30 =   b0 ^((~b1)&  b2 );
2596     a41 =   b1 ^((~b2)&  b3 );
2597     a02 =   b2 ^((~b3)&  b4 );
2598     a13 =   b3 ^((~b4)&  b0 );
2599     a24 =   b4 ^((~b0)&  b1 );
2600 
2601     c0 = a00^a20^a40^a10^a30;
2602     c1 = a11^a31^a01^a21^a41;
2603     c2 = a22^a42^a12^a32^a02;
2604     c3 = a33^a03^a23^a43^a13;
2605     c4 = a44^a14^a34^a04^a24;
2606     d0 = c4^ROL64(c1, 1);
2607     d1 = c0^ROL64(c2, 1);
2608     d2 = c1^ROL64(c3, 1);
2609     d3 = c2^ROL64(c4, 1);
2610     d4 = c3^ROL64(c0, 1);
2611 
2612     b0 = (a00^d0);
2613     b1 = ROL64((a31^d1), 44);
2614     b2 = ROL64((a12^d2), 43);
2615     b3 = ROL64((a43^d3), 21);
2616     b4 = ROL64((a24^d4), 14);
2617     a00 =   b0 ^((~b1)&  b2 );
2618     a00 ^= RC[i+1];
2619     a31 =   b1 ^((~b2)&  b3 );
2620     a12 =   b2 ^((~b3)&  b4 );
2621     a43 =   b3 ^((~b4)&  b0 );
2622     a24 =   b4 ^((~b0)&  b1 );
2623 
2624     b2 = ROL64((a40^d0), 3);
2625     b3 = ROL64((a21^d1), 45);
2626     b4 = ROL64((a02^d2), 61);
2627     b0 = ROL64((a33^d3), 28);
2628     b1 = ROL64((a14^d4), 20);
2629     a40 =   b0 ^((~b1)&  b2 );
2630     a21 =   b1 ^((~b2)&  b3 );
2631     a02 =   b2 ^((~b3)&  b4 );
2632     a33 =   b3 ^((~b4)&  b0 );
2633     a14 =   b4 ^((~b0)&  b1 );
2634 
2635     b4 = ROL64((a30^d0), 18);
2636     b0 = ROL64((a11^d1), 1);
2637     b1 = ROL64((a42^d2), 6);
2638     b2 = ROL64((a23^d3), 25);
2639     b3 = ROL64((a04^d4), 8);
2640     a30 =   b0 ^((~b1)&  b2 );
2641     a11 =   b1 ^((~b2)&  b3 );
2642     a42 =   b2 ^((~b3)&  b4 );
2643     a23 =   b3 ^((~b4)&  b0 );
2644     a04 =   b4 ^((~b0)&  b1 );
2645 
2646     b1 = ROL64((a20^d0), 36);
2647     b2 = ROL64((a01^d1), 10);
2648     b3 = ROL64((a32^d2), 15);
2649     b4 = ROL64((a13^d3), 56);
2650     b0 = ROL64((a44^d4), 27);
2651     a20 =   b0 ^((~b1)&  b2 );
2652     a01 =   b1 ^((~b2)&  b3 );
2653     a32 =   b2 ^((~b3)&  b4 );
2654     a13 =   b3 ^((~b4)&  b0 );
2655     a44 =   b4 ^((~b0)&  b1 );
2656 
2657     b3 = ROL64((a10^d0), 41);
2658     b4 = ROL64((a41^d1), 2);
2659     b0 = ROL64((a22^d2), 62);
2660     b1 = ROL64((a03^d3), 55);
2661     b2 = ROL64((a34^d4), 39);
2662     a10 =   b0 ^((~b1)&  b2 );
2663     a41 =   b1 ^((~b2)&  b3 );
2664     a22 =   b2 ^((~b3)&  b4 );
2665     a03 =   b3 ^((~b4)&  b0 );
2666     a34 =   b4 ^((~b0)&  b1 );
2667 
2668     c0 = a00^a40^a30^a20^a10;
2669     c1 = a31^a21^a11^a01^a41;
2670     c2 = a12^a02^a42^a32^a22;
2671     c3 = a43^a33^a23^a13^a03;
2672     c4 = a24^a14^a04^a44^a34;
2673     d0 = c4^ROL64(c1, 1);
2674     d1 = c0^ROL64(c2, 1);
2675     d2 = c1^ROL64(c3, 1);
2676     d3 = c2^ROL64(c4, 1);
2677     d4 = c3^ROL64(c0, 1);
2678 
2679     b0 = (a00^d0);
2680     b1 = ROL64((a21^d1), 44);
2681     b2 = ROL64((a42^d2), 43);
2682     b3 = ROL64((a13^d3), 21);
2683     b4 = ROL64((a34^d4), 14);
2684     a00 =   b0 ^((~b1)&  b2 );
2685     a00 ^= RC[i+2];
2686     a21 =   b1 ^((~b2)&  b3 );
2687     a42 =   b2 ^((~b3)&  b4 );
2688     a13 =   b3 ^((~b4)&  b0 );
2689     a34 =   b4 ^((~b0)&  b1 );
2690 
2691     b2 = ROL64((a30^d0), 3);
2692     b3 = ROL64((a01^d1), 45);
2693     b4 = ROL64((a22^d2), 61);
2694     b0 = ROL64((a43^d3), 28);
2695     b1 = ROL64((a14^d4), 20);
2696     a30 =   b0 ^((~b1)&  b2 );
2697     a01 =   b1 ^((~b2)&  b3 );
2698     a22 =   b2 ^((~b3)&  b4 );
2699     a43 =   b3 ^((~b4)&  b0 );
2700     a14 =   b4 ^((~b0)&  b1 );
2701 
2702     b4 = ROL64((a10^d0), 18);
2703     b0 = ROL64((a31^d1), 1);
2704     b1 = ROL64((a02^d2), 6);
2705     b2 = ROL64((a23^d3), 25);
2706     b3 = ROL64((a44^d4), 8);
2707     a10 =   b0 ^((~b1)&  b2 );
2708     a31 =   b1 ^((~b2)&  b3 );
2709     a02 =   b2 ^((~b3)&  b4 );
2710     a23 =   b3 ^((~b4)&  b0 );
2711     a44 =   b4 ^((~b0)&  b1 );
2712 
2713     b1 = ROL64((a40^d0), 36);
2714     b2 = ROL64((a11^d1), 10);
2715     b3 = ROL64((a32^d2), 15);
2716     b4 = ROL64((a03^d3), 56);
2717     b0 = ROL64((a24^d4), 27);
2718     a40 =   b0 ^((~b1)&  b2 );
2719     a11 =   b1 ^((~b2)&  b3 );
2720     a32 =   b2 ^((~b3)&  b4 );
2721     a03 =   b3 ^((~b4)&  b0 );
2722     a24 =   b4 ^((~b0)&  b1 );
2723 
2724     b3 = ROL64((a20^d0), 41);
2725     b4 = ROL64((a41^d1), 2);
2726     b0 = ROL64((a12^d2), 62);
2727     b1 = ROL64((a33^d3), 55);
2728     b2 = ROL64((a04^d4), 39);
2729     a20 =   b0 ^((~b1)&  b2 );
2730     a41 =   b1 ^((~b2)&  b3 );
2731     a12 =   b2 ^((~b3)&  b4 );
2732     a33 =   b3 ^((~b4)&  b0 );
2733     a04 =   b4 ^((~b0)&  b1 );
2734 
2735     c0 = a00^a30^a10^a40^a20;
2736     c1 = a21^a01^a31^a11^a41;
2737     c2 = a42^a22^a02^a32^a12;
2738     c3 = a13^a43^a23^a03^a33;
2739     c4 = a34^a14^a44^a24^a04;
2740     d0 = c4^ROL64(c1, 1);
2741     d1 = c0^ROL64(c2, 1);
2742     d2 = c1^ROL64(c3, 1);
2743     d3 = c2^ROL64(c4, 1);
2744     d4 = c3^ROL64(c0, 1);
2745 
2746     b0 = (a00^d0);
2747     b1 = ROL64((a01^d1), 44);
2748     b2 = ROL64((a02^d2), 43);
2749     b3 = ROL64((a03^d3), 21);
2750     b4 = ROL64((a04^d4), 14);
2751     a00 =   b0 ^((~b1)&  b2 );
2752     a00 ^= RC[i+3];
2753     a01 =   b1 ^((~b2)&  b3 );
2754     a02 =   b2 ^((~b3)&  b4 );
2755     a03 =   b3 ^((~b4)&  b0 );
2756     a04 =   b4 ^((~b0)&  b1 );
2757 
2758     b2 = ROL64((a10^d0), 3);
2759     b3 = ROL64((a11^d1), 45);
2760     b4 = ROL64((a12^d2), 61);
2761     b0 = ROL64((a13^d3), 28);
2762     b1 = ROL64((a14^d4), 20);
2763     a10 =   b0 ^((~b1)&  b2 );
2764     a11 =   b1 ^((~b2)&  b3 );
2765     a12 =   b2 ^((~b3)&  b4 );
2766     a13 =   b3 ^((~b4)&  b0 );
2767     a14 =   b4 ^((~b0)&  b1 );
2768 
2769     b4 = ROL64((a20^d0), 18);
2770     b0 = ROL64((a21^d1), 1);
2771     b1 = ROL64((a22^d2), 6);
2772     b2 = ROL64((a23^d3), 25);
2773     b3 = ROL64((a24^d4), 8);
2774     a20 =   b0 ^((~b1)&  b2 );
2775     a21 =   b1 ^((~b2)&  b3 );
2776     a22 =   b2 ^((~b3)&  b4 );
2777     a23 =   b3 ^((~b4)&  b0 );
2778     a24 =   b4 ^((~b0)&  b1 );
2779 
2780     b1 = ROL64((a30^d0), 36);
2781     b2 = ROL64((a31^d1), 10);
2782     b3 = ROL64((a32^d2), 15);
2783     b4 = ROL64((a33^d3), 56);
2784     b0 = ROL64((a34^d4), 27);
2785     a30 =   b0 ^((~b1)&  b2 );
2786     a31 =   b1 ^((~b2)&  b3 );
2787     a32 =   b2 ^((~b3)&  b4 );
2788     a33 =   b3 ^((~b4)&  b0 );
2789     a34 =   b4 ^((~b0)&  b1 );
2790 
2791     b3 = ROL64((a40^d0), 41);
2792     b4 = ROL64((a41^d1), 2);
2793     b0 = ROL64((a42^d2), 62);
2794     b1 = ROL64((a43^d3), 55);
2795     b2 = ROL64((a44^d4), 39);
2796     a40 =   b0 ^((~b1)&  b2 );
2797     a41 =   b1 ^((~b2)&  b3 );
2798     a42 =   b2 ^((~b3)&  b4 );
2799     a43 =   b3 ^((~b4)&  b0 );
2800     a44 =   b4 ^((~b0)&  b1 );
2801   }
2802 }
2803 
2804 /*
2805 ** Initialize a new hash.  iSize determines the size of the hash
2806 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
2807 ** can be zero to use the default hash size of 256 bits.
2808 */
SHA3Init(SHA3Context * p,int iSize)2809 static void SHA3Init(SHA3Context *p, int iSize){
2810   memset(p, 0, sizeof(*p));
2811   p->iSize = iSize;
2812   if( iSize>=128 && iSize<=512 ){
2813     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
2814   }else{
2815     p->nRate = (1600 - 2*256)/8;
2816   }
2817 #if SHA3_BYTEORDER==1234
2818   /* Known to be little-endian at compile-time. No-op */
2819 #elif SHA3_BYTEORDER==4321
2820   p->ixMask = 7;  /* Big-endian */
2821 #else
2822   {
2823     static unsigned int one = 1;
2824     if( 1==*(unsigned char*)&one ){
2825       /* Little endian.  No byte swapping. */
2826       p->ixMask = 0;
2827     }else{
2828       /* Big endian.  Byte swap. */
2829       p->ixMask = 7;
2830     }
2831   }
2832 #endif
2833 }
2834 
2835 /*
2836 ** Make consecutive calls to the SHA3Update function to add new content
2837 ** to the hash
2838 */
SHA3Update(SHA3Context * p,const unsigned char * aData,unsigned int nData)2839 static void SHA3Update(
2840   SHA3Context *p,
2841   const unsigned char *aData,
2842   unsigned int nData
2843 ){
2844   unsigned int i = 0;
2845   if( aData==0 ) return;
2846 #if SHA3_BYTEORDER==1234
2847   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
2848     for(; i+7<nData; i+=8){
2849       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
2850       p->nLoaded += 8;
2851       if( p->nLoaded>=p->nRate ){
2852         KeccakF1600Step(p);
2853         p->nLoaded = 0;
2854       }
2855     }
2856   }
2857 #endif
2858   for(; i<nData; i++){
2859 #if SHA3_BYTEORDER==1234
2860     p->u.x[p->nLoaded] ^= aData[i];
2861 #elif SHA3_BYTEORDER==4321
2862     p->u.x[p->nLoaded^0x07] ^= aData[i];
2863 #else
2864     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
2865 #endif
2866     p->nLoaded++;
2867     if( p->nLoaded==p->nRate ){
2868       KeccakF1600Step(p);
2869       p->nLoaded = 0;
2870     }
2871   }
2872 }
2873 
2874 /*
2875 ** After all content has been added, invoke SHA3Final() to compute
2876 ** the final hash.  The function returns a pointer to the binary
2877 ** hash value.
2878 */
SHA3Final(SHA3Context * p)2879 static unsigned char *SHA3Final(SHA3Context *p){
2880   unsigned int i;
2881   if( p->nLoaded==p->nRate-1 ){
2882     const unsigned char c1 = 0x86;
2883     SHA3Update(p, &c1, 1);
2884   }else{
2885     const unsigned char c2 = 0x06;
2886     const unsigned char c3 = 0x80;
2887     SHA3Update(p, &c2, 1);
2888     p->nLoaded = p->nRate - 1;
2889     SHA3Update(p, &c3, 1);
2890   }
2891   for(i=0; i<p->nRate; i++){
2892     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
2893   }
2894   return &p->u.x[p->nRate];
2895 }
2896 /* End of the hashing logic
2897 *****************************************************************************/
2898 
2899 /*
2900 ** Implementation of the sha3(X,SIZE) function.
2901 **
2902 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
2903 ** size is 256.  If X is a BLOB, it is hashed as is.
2904 ** For all other non-NULL types of input, X is converted into a UTF-8 string
2905 ** and the string is hashed without the trailing 0x00 terminator.  The hash
2906 ** of a NULL value is NULL.
2907 */
sha3Func(sqlite3_context * context,int argc,sqlite3_value ** argv)2908 static void sha3Func(
2909   sqlite3_context *context,
2910   int argc,
2911   sqlite3_value **argv
2912 ){
2913   SHA3Context cx;
2914   int eType = sqlite3_value_type(argv[0]);
2915   int nByte = sqlite3_value_bytes(argv[0]);
2916   int iSize;
2917   if( argc==1 ){
2918     iSize = 256;
2919   }else{
2920     iSize = sqlite3_value_int(argv[1]);
2921     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2922       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2923                                     "384 512", -1);
2924       return;
2925     }
2926   }
2927   if( eType==SQLITE_NULL ) return;
2928   SHA3Init(&cx, iSize);
2929   if( eType==SQLITE_BLOB ){
2930     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
2931   }else{
2932     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
2933   }
2934   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2935 }
2936 
2937 /* Compute a string using sqlite3_vsnprintf() with a maximum length
2938 ** of 50 bytes and add it to the hash.
2939 */
sha3_step_vformat(SHA3Context * p,const char * zFormat,...)2940 static void sha3_step_vformat(
2941   SHA3Context *p,                 /* Add content to this context */
2942   const char *zFormat,
2943   ...
2944 ){
2945   va_list ap;
2946   int n;
2947   char zBuf[50];
2948   va_start(ap, zFormat);
2949   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
2950   va_end(ap);
2951   n = (int)strlen(zBuf);
2952   SHA3Update(p, (unsigned char*)zBuf, n);
2953 }
2954 
2955 /*
2956 ** Update a SHA3Context using a single sqlite3_value.
2957 */
sha3UpdateFromValue(SHA3Context * p,sqlite3_value * pVal)2958 static void sha3UpdateFromValue(SHA3Context *p, sqlite3_value *pVal){
2959   switch( sqlite3_value_type(pVal) ){
2960     case SQLITE_NULL: {
2961       SHA3Update(p, (const unsigned char*)"N",1);
2962       break;
2963     }
2964     case SQLITE_INTEGER: {
2965       sqlite3_uint64 u;
2966       int j;
2967       unsigned char x[9];
2968       sqlite3_int64 v = sqlite3_value_int64(pVal);
2969       memcpy(&u, &v, 8);
2970       for(j=8; j>=1; j--){
2971         x[j] = u & 0xff;
2972         u >>= 8;
2973       }
2974       x[0] = 'I';
2975       SHA3Update(p, x, 9);
2976       break;
2977     }
2978     case SQLITE_FLOAT: {
2979       sqlite3_uint64 u;
2980       int j;
2981       unsigned char x[9];
2982       double r = sqlite3_value_double(pVal);
2983       memcpy(&u, &r, 8);
2984       for(j=8; j>=1; j--){
2985         x[j] = u & 0xff;
2986         u >>= 8;
2987       }
2988       x[0] = 'F';
2989       SHA3Update(p,x,9);
2990       break;
2991     }
2992     case SQLITE_TEXT: {
2993       int n2 = sqlite3_value_bytes(pVal);
2994       const unsigned char *z2 = sqlite3_value_text(pVal);
2995       sha3_step_vformat(p,"T%d:",n2);
2996       SHA3Update(p, z2, n2);
2997       break;
2998     }
2999     case SQLITE_BLOB: {
3000       int n2 = sqlite3_value_bytes(pVal);
3001       const unsigned char *z2 = sqlite3_value_blob(pVal);
3002       sha3_step_vformat(p,"B%d:",n2);
3003       SHA3Update(p, z2, n2);
3004       break;
3005     }
3006   }
3007 }
3008 
3009 /*
3010 ** Implementation of the sha3_query(SQL,SIZE) function.
3011 **
3012 ** This function compiles and runs the SQL statement(s) given in the
3013 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
3014 ** size is 256.
3015 **
3016 ** The format of the byte stream that is hashed is summarized as follows:
3017 **
3018 **       S<n>:<sql>
3019 **       R
3020 **       N
3021 **       I<int>
3022 **       F<ieee-float>
3023 **       B<size>:<bytes>
3024 **       T<size>:<text>
3025 **
3026 ** <sql> is the original SQL text for each statement run and <n> is
3027 ** the size of that text.  The SQL text is UTF-8.  A single R character
3028 ** occurs before the start of each row.  N means a NULL value.
3029 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
3030 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3031 ** B means blobs of <size> bytes.  T means text rendered as <size>
3032 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
3033 ** text integers.
3034 **
3035 ** For each SQL statement in the X input, there is one S segment.  Each
3036 ** S segment is followed by zero or more R segments, one for each row in the
3037 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
3038 ** one for each column in the result set.  Segments are concatentated directly
3039 ** with no delimiters of any kind.
3040 */
sha3QueryFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)3041 static void sha3QueryFunc(
3042   sqlite3_context *context,
3043   int argc,
3044   sqlite3_value **argv
3045 ){
3046   sqlite3 *db = sqlite3_context_db_handle(context);
3047   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
3048   sqlite3_stmt *pStmt = 0;
3049   int nCol;                   /* Number of columns in the result set */
3050   int i;                      /* Loop counter */
3051   int rc;
3052   int n;
3053   const char *z;
3054   SHA3Context cx;
3055   int iSize;
3056 
3057   if( argc==1 ){
3058     iSize = 256;
3059   }else{
3060     iSize = sqlite3_value_int(argv[1]);
3061     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3062       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3063                                     "384 512", -1);
3064       return;
3065     }
3066   }
3067   if( zSql==0 ) return;
3068   SHA3Init(&cx, iSize);
3069   while( zSql[0] ){
3070     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
3071     if( rc ){
3072       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
3073                                    zSql, sqlite3_errmsg(db));
3074       sqlite3_finalize(pStmt);
3075       sqlite3_result_error(context, zMsg, -1);
3076       sqlite3_free(zMsg);
3077       return;
3078     }
3079     if( !sqlite3_stmt_readonly(pStmt) ){
3080       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
3081       sqlite3_finalize(pStmt);
3082       sqlite3_result_error(context, zMsg, -1);
3083       sqlite3_free(zMsg);
3084       return;
3085     }
3086     nCol = sqlite3_column_count(pStmt);
3087     z = sqlite3_sql(pStmt);
3088     if( z ){
3089       n = (int)strlen(z);
3090       sha3_step_vformat(&cx,"S%d:",n);
3091       SHA3Update(&cx,(unsigned char*)z,n);
3092     }
3093 
3094     /* Compute a hash over the result of the query */
3095     while( SQLITE_ROW==sqlite3_step(pStmt) ){
3096       SHA3Update(&cx,(const unsigned char*)"R",1);
3097       for(i=0; i<nCol; i++){
3098         sha3UpdateFromValue(&cx, sqlite3_column_value(pStmt,i));
3099       }
3100     }
3101     sqlite3_finalize(pStmt);
3102   }
3103   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3104 }
3105 
3106 /*
3107 ** xStep function for sha3_agg().
3108 */
sha3AggStep(sqlite3_context * context,int argc,sqlite3_value ** argv)3109 static void sha3AggStep(
3110   sqlite3_context *context,
3111   int argc,
3112   sqlite3_value **argv
3113 ){
3114   SHA3Context *p;
3115   p = (SHA3Context*)sqlite3_aggregate_context(context, sizeof(*p));
3116   if( p==0 ) return;
3117   if( p->nRate==0 ){
3118     int sz = 256;
3119     if( argc==2 ){
3120       sz = sqlite3_value_int(argv[1]);
3121       if( sz!=224 && sz!=384 && sz!=512 ){
3122         sz = 256;
3123       }
3124     }
3125     SHA3Init(p, sz);
3126   }
3127   sha3UpdateFromValue(p, argv[0]);
3128 }
3129 
3130 
3131 /*
3132 ** xFinal function for sha3_agg().
3133 */
sha3AggFinal(sqlite3_context * context)3134 static void sha3AggFinal(sqlite3_context *context){
3135   SHA3Context *p;
3136   p = (SHA3Context*)sqlite3_aggregate_context(context, sizeof(*p));
3137   if( p==0 ) return;
3138   if( p->iSize ){
3139     sqlite3_result_blob(context, SHA3Final(p), p->iSize/8, SQLITE_TRANSIENT);
3140   }
3141 }
3142 
3143 
3144 
3145 #ifdef _WIN32
3146 
3147 #endif
sqlite3_shathree_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3148 int sqlite3_shathree_init(
3149   sqlite3 *db,
3150   char **pzErrMsg,
3151   const sqlite3_api_routines *pApi
3152 ){
3153   int rc = SQLITE_OK;
3154   SQLITE_EXTENSION_INIT2(pApi);
3155   (void)pzErrMsg;  /* Unused parameter */
3156   rc = sqlite3_create_function(db, "sha3", 1,
3157                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3158                       0, sha3Func, 0, 0);
3159   if( rc==SQLITE_OK ){
3160     rc = sqlite3_create_function(db, "sha3", 2,
3161                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3162                       0, sha3Func, 0, 0);
3163   }
3164   if( rc==SQLITE_OK ){
3165     rc = sqlite3_create_function(db, "sha3_agg", 1,
3166                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3167                       0, 0, sha3AggStep, sha3AggFinal);
3168   }
3169   if( rc==SQLITE_OK ){
3170     rc = sqlite3_create_function(db, "sha3_agg", 2,
3171                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3172                       0, 0, sha3AggStep, sha3AggFinal);
3173   }
3174   if( rc==SQLITE_OK ){
3175     rc = sqlite3_create_function(db, "sha3_query", 1,
3176                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3177                       0, sha3QueryFunc, 0, 0);
3178   }
3179   if( rc==SQLITE_OK ){
3180     rc = sqlite3_create_function(db, "sha3_query", 2,
3181                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3182                       0, sha3QueryFunc, 0, 0);
3183   }
3184   return rc;
3185 }
3186 
3187 /************************* End ../ext/misc/shathree.c ********************/
3188 /************************* Begin ../ext/misc/sha1.c ******************/
3189 /*
3190 ** 2017-01-27
3191 **
3192 ** The author disclaims copyright to this source code.  In place of
3193 ** a legal notice, here is a blessing:
3194 **
3195 **    May you do good and not evil.
3196 **    May you find forgiveness for yourself and forgive others.
3197 **    May you share freely, never taking more than you give.
3198 **
3199 ******************************************************************************
3200 **
3201 ** This SQLite extension implements functions that compute SHA1 hashes.
3202 ** Two SQL functions are implemented:
3203 **
3204 **     sha1(X)
3205 **     sha1_query(Y)
3206 **
3207 ** The sha1(X) function computes the SHA1 hash of the input X, or NULL if
3208 ** X is NULL.
3209 **
3210 ** The sha1_query(Y) function evalutes all queries in the SQL statements of Y
3211 ** and returns a hash of their results.
3212 */
3213 /* #include "sqlite3ext.h" */
3214 SQLITE_EXTENSION_INIT1
3215 #include <assert.h>
3216 #include <string.h>
3217 #include <stdarg.h>
3218 
3219 /******************************************************************************
3220 ** The Hash Engine
3221 */
3222 /* Context for the SHA1 hash */
3223 typedef struct SHA1Context SHA1Context;
3224 struct SHA1Context {
3225   unsigned int state[5];
3226   unsigned int count[2];
3227   unsigned char buffer[64];
3228 };
3229 
3230 #define SHA_ROT(x,l,r) ((x) << (l) | (x) >> (r))
3231 #define rol(x,k) SHA_ROT(x,k,32-(k))
3232 #define ror(x,k) SHA_ROT(x,32-(k),k)
3233 
3234 #define blk0le(i) (block[i] = (ror(block[i],8)&0xFF00FF00) \
3235     |(rol(block[i],8)&0x00FF00FF))
3236 #define blk0be(i) block[i]
3237 #define blk(i) (block[i&15] = rol(block[(i+13)&15]^block[(i+8)&15] \
3238     ^block[(i+2)&15]^block[i&15],1))
3239 
3240 /*
3241  * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1
3242  *
3243  * Rl0() for little-endian and Rb0() for big-endian.  Endianness is
3244  * determined at run-time.
3245  */
3246 #define Rl0(v,w,x,y,z,i) \
3247     z+=((w&(x^y))^y)+blk0le(i)+0x5A827999+rol(v,5);w=ror(w,2);
3248 #define Rb0(v,w,x,y,z,i) \
3249     z+=((w&(x^y))^y)+blk0be(i)+0x5A827999+rol(v,5);w=ror(w,2);
3250 #define R1(v,w,x,y,z,i) \
3251     z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=ror(w,2);
3252 #define R2(v,w,x,y,z,i) \
3253     z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=ror(w,2);
3254 #define R3(v,w,x,y,z,i) \
3255     z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=ror(w,2);
3256 #define R4(v,w,x,y,z,i) \
3257     z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=ror(w,2);
3258 
3259 /*
3260  * Hash a single 512-bit block. This is the core of the algorithm.
3261  */
SHA1Transform(unsigned int state[5],const unsigned char buffer[64])3262 static void SHA1Transform(unsigned int state[5], const unsigned char buffer[64]){
3263   unsigned int qq[5]; /* a, b, c, d, e; */
3264   static int one = 1;
3265   unsigned int block[16];
3266   memcpy(block, buffer, 64);
3267   memcpy(qq,state,5*sizeof(unsigned int));
3268 
3269 #define a qq[0]
3270 #define b qq[1]
3271 #define c qq[2]
3272 #define d qq[3]
3273 #define e qq[4]
3274 
3275   /* Copy p->state[] to working vars */
3276   /*
3277   a = state[0];
3278   b = state[1];
3279   c = state[2];
3280   d = state[3];
3281   e = state[4];
3282   */
3283 
3284   /* 4 rounds of 20 operations each. Loop unrolled. */
3285   if( 1 == *(unsigned char*)&one ){
3286     Rl0(a,b,c,d,e, 0); Rl0(e,a,b,c,d, 1); Rl0(d,e,a,b,c, 2); Rl0(c,d,e,a,b, 3);
3287     Rl0(b,c,d,e,a, 4); Rl0(a,b,c,d,e, 5); Rl0(e,a,b,c,d, 6); Rl0(d,e,a,b,c, 7);
3288     Rl0(c,d,e,a,b, 8); Rl0(b,c,d,e,a, 9); Rl0(a,b,c,d,e,10); Rl0(e,a,b,c,d,11);
3289     Rl0(d,e,a,b,c,12); Rl0(c,d,e,a,b,13); Rl0(b,c,d,e,a,14); Rl0(a,b,c,d,e,15);
3290   }else{
3291     Rb0(a,b,c,d,e, 0); Rb0(e,a,b,c,d, 1); Rb0(d,e,a,b,c, 2); Rb0(c,d,e,a,b, 3);
3292     Rb0(b,c,d,e,a, 4); Rb0(a,b,c,d,e, 5); Rb0(e,a,b,c,d, 6); Rb0(d,e,a,b,c, 7);
3293     Rb0(c,d,e,a,b, 8); Rb0(b,c,d,e,a, 9); Rb0(a,b,c,d,e,10); Rb0(e,a,b,c,d,11);
3294     Rb0(d,e,a,b,c,12); Rb0(c,d,e,a,b,13); Rb0(b,c,d,e,a,14); Rb0(a,b,c,d,e,15);
3295   }
3296   R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
3297   R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
3298   R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
3299   R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
3300   R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
3301   R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
3302   R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
3303   R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
3304   R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
3305   R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
3306   R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
3307   R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
3308   R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
3309   R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
3310   R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
3311   R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
3312 
3313   /* Add the working vars back into context.state[] */
3314   state[0] += a;
3315   state[1] += b;
3316   state[2] += c;
3317   state[3] += d;
3318   state[4] += e;
3319 
3320 #undef a
3321 #undef b
3322 #undef c
3323 #undef d
3324 #undef e
3325 }
3326 
3327 
3328 /* Initialize a SHA1 context */
hash_init(SHA1Context * p)3329 static void hash_init(SHA1Context *p){
3330   /* SHA1 initialization constants */
3331   p->state[0] = 0x67452301;
3332   p->state[1] = 0xEFCDAB89;
3333   p->state[2] = 0x98BADCFE;
3334   p->state[3] = 0x10325476;
3335   p->state[4] = 0xC3D2E1F0;
3336   p->count[0] = p->count[1] = 0;
3337 }
3338 
3339 /* Add new content to the SHA1 hash */
hash_step(SHA1Context * p,const unsigned char * data,unsigned int len)3340 static void hash_step(
3341   SHA1Context *p,                 /* Add content to this context */
3342   const unsigned char *data,      /* Data to be added */
3343   unsigned int len                /* Number of bytes in data */
3344 ){
3345   unsigned int i, j;
3346 
3347   j = p->count[0];
3348   if( (p->count[0] += len << 3) < j ){
3349     p->count[1] += (len>>29)+1;
3350   }
3351   j = (j >> 3) & 63;
3352   if( (j + len) > 63 ){
3353     (void)memcpy(&p->buffer[j], data, (i = 64-j));
3354     SHA1Transform(p->state, p->buffer);
3355     for(; i + 63 < len; i += 64){
3356       SHA1Transform(p->state, &data[i]);
3357     }
3358     j = 0;
3359   }else{
3360     i = 0;
3361   }
3362   (void)memcpy(&p->buffer[j], &data[i], len - i);
3363 }
3364 
3365 /* Compute a string using sqlite3_vsnprintf() and hash it */
hash_step_vformat(SHA1Context * p,const char * zFormat,...)3366 static void hash_step_vformat(
3367   SHA1Context *p,                 /* Add content to this context */
3368   const char *zFormat,
3369   ...
3370 ){
3371   va_list ap;
3372   int n;
3373   char zBuf[50];
3374   va_start(ap, zFormat);
3375   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
3376   va_end(ap);
3377   n = (int)strlen(zBuf);
3378   hash_step(p, (unsigned char*)zBuf, n);
3379 }
3380 
3381 
3382 /* Add padding and compute the message digest.  Render the
3383 ** message digest as lower-case hexadecimal and put it into
3384 ** zOut[].  zOut[] must be at least 41 bytes long. */
hash_finish(SHA1Context * p,char * zOut,int bAsBinary)3385 static void hash_finish(
3386   SHA1Context *p,           /* The SHA1 context to finish and render */
3387   char *zOut,               /* Store hex or binary hash here */
3388   int bAsBinary             /* 1 for binary hash, 0 for hex hash */
3389 ){
3390   unsigned int i;
3391   unsigned char finalcount[8];
3392   unsigned char digest[20];
3393   static const char zEncode[] = "0123456789abcdef";
3394 
3395   for (i = 0; i < 8; i++){
3396     finalcount[i] = (unsigned char)((p->count[(i >= 4 ? 0 : 1)]
3397        >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
3398   }
3399   hash_step(p, (const unsigned char *)"\200", 1);
3400   while ((p->count[0] & 504) != 448){
3401     hash_step(p, (const unsigned char *)"\0", 1);
3402   }
3403   hash_step(p, finalcount, 8);  /* Should cause a SHA1Transform() */
3404   for (i = 0; i < 20; i++){
3405     digest[i] = (unsigned char)((p->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
3406   }
3407   if( bAsBinary ){
3408     memcpy(zOut, digest, 20);
3409   }else{
3410     for(i=0; i<20; i++){
3411       zOut[i*2] = zEncode[(digest[i]>>4)&0xf];
3412       zOut[i*2+1] = zEncode[digest[i] & 0xf];
3413     }
3414     zOut[i*2]= 0;
3415   }
3416 }
3417 /* End of the hashing logic
3418 *****************************************************************************/
3419 
3420 /*
3421 ** Implementation of the sha1(X) function.
3422 **
3423 ** Return a lower-case hexadecimal rendering of the SHA1 hash of the
3424 ** argument X.  If X is a BLOB, it is hashed as is.  For all other
3425 ** types of input, X is converted into a UTF-8 string and the string
3426 ** is hash without the trailing 0x00 terminator.  The hash of a NULL
3427 ** value is NULL.
3428 */
sha1Func(sqlite3_context * context,int argc,sqlite3_value ** argv)3429 static void sha1Func(
3430   sqlite3_context *context,
3431   int argc,
3432   sqlite3_value **argv
3433 ){
3434   SHA1Context cx;
3435   int eType = sqlite3_value_type(argv[0]);
3436   int nByte = sqlite3_value_bytes(argv[0]);
3437   char zOut[44];
3438 
3439   assert( argc==1 );
3440   if( eType==SQLITE_NULL ) return;
3441   hash_init(&cx);
3442   if( eType==SQLITE_BLOB ){
3443     hash_step(&cx, sqlite3_value_blob(argv[0]), nByte);
3444   }else{
3445     hash_step(&cx, sqlite3_value_text(argv[0]), nByte);
3446   }
3447   if( sqlite3_user_data(context)!=0 ){
3448     hash_finish(&cx, zOut, 1);
3449     sqlite3_result_blob(context, zOut, 20, SQLITE_TRANSIENT);
3450   }else{
3451     hash_finish(&cx, zOut, 0);
3452     sqlite3_result_blob(context, zOut, 40, SQLITE_TRANSIENT);
3453   }
3454 }
3455 
3456 /*
3457 ** Implementation of the sha1_query(SQL) function.
3458 **
3459 ** This function compiles and runs the SQL statement(s) given in the
3460 ** argument. The results are hashed using SHA1 and that hash is returned.
3461 **
3462 ** The original SQL text is included as part of the hash.
3463 **
3464 ** The hash is not just a concatenation of the outputs.  Each query
3465 ** is delimited and each row and value within the query is delimited,
3466 ** with all values being marked with their datatypes.
3467 */
sha1QueryFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)3468 static void sha1QueryFunc(
3469   sqlite3_context *context,
3470   int argc,
3471   sqlite3_value **argv
3472 ){
3473   sqlite3 *db = sqlite3_context_db_handle(context);
3474   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
3475   sqlite3_stmt *pStmt = 0;
3476   int nCol;                   /* Number of columns in the result set */
3477   int i;                      /* Loop counter */
3478   int rc;
3479   int n;
3480   const char *z;
3481   SHA1Context cx;
3482   char zOut[44];
3483 
3484   assert( argc==1 );
3485   if( zSql==0 ) return;
3486   hash_init(&cx);
3487   while( zSql[0] ){
3488     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
3489     if( rc ){
3490       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
3491                                    zSql, sqlite3_errmsg(db));
3492       sqlite3_finalize(pStmt);
3493       sqlite3_result_error(context, zMsg, -1);
3494       sqlite3_free(zMsg);
3495       return;
3496     }
3497     if( !sqlite3_stmt_readonly(pStmt) ){
3498       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
3499       sqlite3_finalize(pStmt);
3500       sqlite3_result_error(context, zMsg, -1);
3501       sqlite3_free(zMsg);
3502       return;
3503     }
3504     nCol = sqlite3_column_count(pStmt);
3505     z = sqlite3_sql(pStmt);
3506     n = (int)strlen(z);
3507     hash_step_vformat(&cx,"S%d:",n);
3508     hash_step(&cx,(unsigned char*)z,n);
3509 
3510     /* Compute a hash over the result of the query */
3511     while( SQLITE_ROW==sqlite3_step(pStmt) ){
3512       hash_step(&cx,(const unsigned char*)"R",1);
3513       for(i=0; i<nCol; i++){
3514         switch( sqlite3_column_type(pStmt,i) ){
3515           case SQLITE_NULL: {
3516             hash_step(&cx, (const unsigned char*)"N",1);
3517             break;
3518           }
3519           case SQLITE_INTEGER: {
3520             sqlite3_uint64 u;
3521             int j;
3522             unsigned char x[9];
3523             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
3524             memcpy(&u, &v, 8);
3525             for(j=8; j>=1; j--){
3526               x[j] = u & 0xff;
3527               u >>= 8;
3528             }
3529             x[0] = 'I';
3530             hash_step(&cx, x, 9);
3531             break;
3532           }
3533           case SQLITE_FLOAT: {
3534             sqlite3_uint64 u;
3535             int j;
3536             unsigned char x[9];
3537             double r = sqlite3_column_double(pStmt,i);
3538             memcpy(&u, &r, 8);
3539             for(j=8; j>=1; j--){
3540               x[j] = u & 0xff;
3541               u >>= 8;
3542             }
3543             x[0] = 'F';
3544             hash_step(&cx,x,9);
3545             break;
3546           }
3547           case SQLITE_TEXT: {
3548             int n2 = sqlite3_column_bytes(pStmt, i);
3549             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
3550             hash_step_vformat(&cx,"T%d:",n2);
3551             hash_step(&cx, z2, n2);
3552             break;
3553           }
3554           case SQLITE_BLOB: {
3555             int n2 = sqlite3_column_bytes(pStmt, i);
3556             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
3557             hash_step_vformat(&cx,"B%d:",n2);
3558             hash_step(&cx, z2, n2);
3559             break;
3560           }
3561         }
3562       }
3563     }
3564     sqlite3_finalize(pStmt);
3565   }
3566   hash_finish(&cx, zOut, 0);
3567   sqlite3_result_text(context, zOut, 40, SQLITE_TRANSIENT);
3568 }
3569 
3570 
3571 #ifdef _WIN32
3572 
3573 #endif
sqlite3_sha_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3574 int sqlite3_sha_init(
3575   sqlite3 *db,
3576   char **pzErrMsg,
3577   const sqlite3_api_routines *pApi
3578 ){
3579   int rc = SQLITE_OK;
3580   static int one = 1;
3581   SQLITE_EXTENSION_INIT2(pApi);
3582   (void)pzErrMsg;  /* Unused parameter */
3583   rc = sqlite3_create_function(db, "sha1", 1,
3584                        SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3585                                 0, sha1Func, 0, 0);
3586   if( rc==SQLITE_OK ){
3587     rc = sqlite3_create_function(db, "sha1b", 1,
3588                        SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3589                           (void*)&one, sha1Func, 0, 0);
3590   }
3591   if( rc==SQLITE_OK ){
3592     rc = sqlite3_create_function(db, "sha1_query", 1,
3593                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3594                                  sha1QueryFunc, 0, 0);
3595   }
3596   return rc;
3597 }
3598 
3599 /************************* End ../ext/misc/sha1.c ********************/
3600 /************************* Begin ../ext/misc/uint.c ******************/
3601 /*
3602 ** 2020-04-14
3603 **
3604 ** The author disclaims copyright to this source code.  In place of
3605 ** a legal notice, here is a blessing:
3606 **
3607 **    May you do good and not evil.
3608 **    May you find forgiveness for yourself and forgive others.
3609 **    May you share freely, never taking more than you give.
3610 **
3611 ******************************************************************************
3612 **
3613 ** This SQLite extension implements the UINT collating sequence.
3614 **
3615 ** UINT works like BINARY for text, except that embedded strings
3616 ** of digits compare in numeric order.
3617 **
3618 **     *   Leading zeros are handled properly, in the sense that
3619 **         they do not mess of the magnitude comparison of embedded
3620 **         strings of digits.  "x00123y" is equal to "x123y".
3621 **
3622 **     *   Only unsigned integers are recognized.  Plus and minus
3623 **         signs are ignored.  Decimal points and exponential notation
3624 **         are ignored.
3625 **
3626 **     *   Embedded integers can be of arbitrary length.  Comparison
3627 **         is *not* limited integers that can be expressed as a
3628 **         64-bit machine integer.
3629 */
3630 /* #include "sqlite3ext.h" */
3631 SQLITE_EXTENSION_INIT1
3632 #include <assert.h>
3633 #include <string.h>
3634 #include <ctype.h>
3635 
3636 /*
3637 ** Compare text in lexicographic order, except strings of digits
3638 ** compare in numeric order.
3639 */
uintCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)3640 static int uintCollFunc(
3641   void *notUsed,
3642   int nKey1, const void *pKey1,
3643   int nKey2, const void *pKey2
3644 ){
3645   const unsigned char *zA = (const unsigned char*)pKey1;
3646   const unsigned char *zB = (const unsigned char*)pKey2;
3647   int i=0, j=0, x;
3648   (void)notUsed;
3649   while( i<nKey1 && j<nKey2 ){
3650     x = zA[i] - zB[j];
3651     if( isdigit(zA[i]) ){
3652       int k;
3653       if( !isdigit(zB[j]) ) return x;
3654       while( i<nKey1 && zA[i]=='0' ){ i++; }
3655       while( j<nKey2 && zB[j]=='0' ){ j++; }
3656       k = 0;
3657       while( i+k<nKey1 && isdigit(zA[i+k])
3658              && j+k<nKey2 && isdigit(zB[j+k]) ){
3659         k++;
3660       }
3661       if( i+k<nKey1 && isdigit(zA[i+k]) ){
3662         return +1;
3663       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
3664         return -1;
3665       }else{
3666         x = memcmp(zA+i, zB+j, k);
3667         if( x ) return x;
3668         i += k;
3669         j += k;
3670       }
3671     }else if( x ){
3672       return x;
3673     }else{
3674       i++;
3675       j++;
3676     }
3677   }
3678   return (nKey1 - i) - (nKey2 - j);
3679 }
3680 
3681 #ifdef _WIN32
3682 
3683 #endif
sqlite3_uint_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3684 int sqlite3_uint_init(
3685   sqlite3 *db,
3686   char **pzErrMsg,
3687   const sqlite3_api_routines *pApi
3688 ){
3689   SQLITE_EXTENSION_INIT2(pApi);
3690   (void)pzErrMsg;  /* Unused parameter */
3691   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
3692 }
3693 
3694 /************************* End ../ext/misc/uint.c ********************/
3695 /************************* Begin ../ext/misc/decimal.c ******************/
3696 /*
3697 ** 2020-06-22
3698 **
3699 ** The author disclaims copyright to this source code.  In place of
3700 ** a legal notice, here is a blessing:
3701 **
3702 **    May you do good and not evil.
3703 **    May you find forgiveness for yourself and forgive others.
3704 **    May you share freely, never taking more than you give.
3705 **
3706 ******************************************************************************
3707 **
3708 ** Routines to implement arbitrary-precision decimal math.
3709 **
3710 ** The focus here is on simplicity and correctness, not performance.
3711 */
3712 /* #include "sqlite3ext.h" */
3713 SQLITE_EXTENSION_INIT1
3714 #include <assert.h>
3715 #include <string.h>
3716 #include <ctype.h>
3717 #include <stdlib.h>
3718 
3719 /* Mark a function parameter as unused, to suppress nuisance compiler
3720 ** warnings. */
3721 #ifndef UNUSED_PARAMETER
3722 # define UNUSED_PARAMETER(X)  (void)(X)
3723 #endif
3724 
3725 #ifndef IsSpace
3726 #define IsSpace(X)  isspace((unsigned char)X)
3727 #endif
3728 
3729 /* A decimal object */
3730 typedef struct Decimal Decimal;
3731 struct Decimal {
3732   char sign;        /* 0 for positive, 1 for negative */
3733   char oom;         /* True if an OOM is encountered */
3734   char isNull;      /* True if holds a NULL rather than a number */
3735   char isInit;      /* True upon initialization */
3736   int nDigit;       /* Total number of digits */
3737   int nFrac;        /* Number of digits to the right of the decimal point */
3738   signed char *a;   /* Array of digits.  Most significant first. */
3739 };
3740 
3741 /*
3742 ** Release memory held by a Decimal, but do not free the object itself.
3743 */
decimal_clear(Decimal * p)3744 static void decimal_clear(Decimal *p){
3745   sqlite3_free(p->a);
3746 }
3747 
3748 /*
3749 ** Destroy a Decimal object
3750 */
decimal_free(Decimal * p)3751 static void decimal_free(Decimal *p){
3752   if( p ){
3753     decimal_clear(p);
3754     sqlite3_free(p);
3755   }
3756 }
3757 
3758 /*
3759 ** Allocate a new Decimal object initialized to the text in zIn[].
3760 ** Return NULL if any kind of error occurs.
3761 */
decimalNewFromText(const char * zIn,int n)3762 static Decimal *decimalNewFromText(const char *zIn, int n){
3763   Decimal *p = 0;
3764   int i;
3765   int iExp = 0;
3766 
3767   p = sqlite3_malloc( sizeof(*p) );
3768   if( p==0 ) goto new_from_text_failed;
3769   p->sign = 0;
3770   p->oom = 0;
3771   p->isInit = 1;
3772   p->isNull = 0;
3773   p->nDigit = 0;
3774   p->nFrac = 0;
3775   p->a = sqlite3_malloc64( n+1 );
3776   if( p->a==0 ) goto new_from_text_failed;
3777   for(i=0; IsSpace(zIn[i]); i++){}
3778   if( zIn[i]=='-' ){
3779     p->sign = 1;
3780     i++;
3781   }else if( zIn[i]=='+' ){
3782     i++;
3783   }
3784   while( i<n && zIn[i]=='0' ) i++;
3785   while( i<n ){
3786     char c = zIn[i];
3787     if( c>='0' && c<='9' ){
3788       p->a[p->nDigit++] = c - '0';
3789     }else if( c=='.' ){
3790       p->nFrac = p->nDigit + 1;
3791     }else if( c=='e' || c=='E' ){
3792       int j = i+1;
3793       int neg = 0;
3794       if( j>=n ) break;
3795       if( zIn[j]=='-' ){
3796         neg = 1;
3797         j++;
3798       }else if( zIn[j]=='+' ){
3799         j++;
3800       }
3801       while( j<n && iExp<1000000 ){
3802         if( zIn[j]>='0' && zIn[j]<='9' ){
3803           iExp = iExp*10 + zIn[j] - '0';
3804         }
3805         j++;
3806       }
3807       if( neg ) iExp = -iExp;
3808       break;
3809     }
3810     i++;
3811   }
3812   if( p->nFrac ){
3813     p->nFrac = p->nDigit - (p->nFrac - 1);
3814   }
3815   if( iExp>0 ){
3816     if( p->nFrac>0 ){
3817       if( iExp<=p->nFrac ){
3818         p->nFrac -= iExp;
3819         iExp = 0;
3820       }else{
3821         iExp -= p->nFrac;
3822         p->nFrac = 0;
3823       }
3824     }
3825     if( iExp>0 ){
3826       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3827       if( p->a==0 ) goto new_from_text_failed;
3828       memset(p->a+p->nDigit, 0, iExp);
3829       p->nDigit += iExp;
3830     }
3831   }else if( iExp<0 ){
3832     int nExtra;
3833     iExp = -iExp;
3834     nExtra = p->nDigit - p->nFrac - 1;
3835     if( nExtra ){
3836       if( nExtra>=iExp ){
3837         p->nFrac += iExp;
3838         iExp  = 0;
3839       }else{
3840         iExp -= nExtra;
3841         p->nFrac = p->nDigit - 1;
3842       }
3843     }
3844     if( iExp>0 ){
3845       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3846       if( p->a==0 ) goto new_from_text_failed;
3847       memmove(p->a+iExp, p->a, p->nDigit);
3848       memset(p->a, 0, iExp);
3849       p->nDigit += iExp;
3850       p->nFrac += iExp;
3851     }
3852   }
3853   return p;
3854 
3855 new_from_text_failed:
3856   if( p ){
3857     if( p->a ) sqlite3_free(p->a);
3858     sqlite3_free(p);
3859   }
3860   return 0;
3861 }
3862 
3863 /* Forward reference */
3864 static Decimal *decimalFromDouble(double);
3865 
3866 /*
3867 ** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
3868 ** to the new object, or NULL if there is an error.  If the pCtx argument
3869 ** is not NULL, then errors are reported on it as well.
3870 **
3871 ** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3872 ** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
3873 ** 8 bytes, the resulting double value is expanded into its decimal equivalent.
3874 ** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3875 ** then NULL is returned.
3876 */
decimal_new(sqlite3_context * pCtx,sqlite3_value * pIn,int bTextOnly)3877 static Decimal *decimal_new(
3878   sqlite3_context *pCtx,       /* Report error here, if not null */
3879   sqlite3_value *pIn,          /* Construct the decimal object from this */
3880   int bTextOnly                /* Always interpret pIn as text if true */
3881 ){
3882   Decimal *p = 0;
3883   int eType = sqlite3_value_type(pIn);
3884   if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
3885     eType = SQLITE_TEXT;
3886   }
3887   switch( eType ){
3888     case SQLITE_TEXT:
3889     case SQLITE_INTEGER: {
3890       const char *zIn = (const char*)sqlite3_value_text(pIn);
3891       int n = sqlite3_value_bytes(pIn);
3892       p = decimalNewFromText(zIn, n);
3893       if( p==0 ) goto new_failed;
3894       break;
3895     }
3896 
3897     case SQLITE_FLOAT: {
3898       p = decimalFromDouble(sqlite3_value_double(pIn));
3899       break;
3900     }
3901 
3902     case SQLITE_BLOB: {
3903       const unsigned char *x;
3904       unsigned int i;
3905       sqlite3_uint64 v = 0;
3906       double r;
3907 
3908       if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
3909       x = sqlite3_value_blob(pIn);
3910       for(i=0; i<sizeof(r); i++){
3911         v = (v<<8) | x[i];
3912       }
3913       memcpy(&r, &v, sizeof(r));
3914       p = decimalFromDouble(r);
3915       break;
3916     }
3917 
3918     case SQLITE_NULL: {
3919       break;
3920     }
3921   }
3922   return p;
3923 
3924 new_failed:
3925   if( pCtx ) sqlite3_result_error_nomem(pCtx);
3926   sqlite3_free(p);
3927   return 0;
3928 }
3929 
3930 /*
3931 ** Make the given Decimal the result.
3932 */
decimal_result(sqlite3_context * pCtx,Decimal * p)3933 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
3934   char *z;
3935   int i, j;
3936   int n;
3937   if( p==0 || p->oom ){
3938     sqlite3_result_error_nomem(pCtx);
3939     return;
3940   }
3941   if( p->isNull ){
3942     sqlite3_result_null(pCtx);
3943     return;
3944   }
3945   z = sqlite3_malloc( p->nDigit+4 );
3946   if( z==0 ){
3947     sqlite3_result_error_nomem(pCtx);
3948     return;
3949   }
3950   i = 0;
3951   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
3952     p->sign = 0;
3953   }
3954   if( p->sign ){
3955     z[0] = '-';
3956     i = 1;
3957   }
3958   n = p->nDigit - p->nFrac;
3959   if( n<=0 ){
3960     z[i++] = '0';
3961   }
3962   j = 0;
3963   while( n>1 && p->a[j]==0 ){
3964     j++;
3965     n--;
3966   }
3967   while( n>0  ){
3968     z[i++] = p->a[j] + '0';
3969     j++;
3970     n--;
3971   }
3972   if( p->nFrac ){
3973     z[i++] = '.';
3974     do{
3975       z[i++] = p->a[j] + '0';
3976       j++;
3977     }while( j<p->nDigit );
3978   }
3979   z[i] = 0;
3980   sqlite3_result_text(pCtx, z, i, sqlite3_free);
3981 }
3982 
3983 /*
3984 ** Make the given Decimal the result in an format similar to  '%+#e'.
3985 ** In other words, show exponential notation with leading and trailing
3986 ** zeros omitted.
3987 */
decimal_result_sci(sqlite3_context * pCtx,Decimal * p)3988 static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){
3989   char *z;       /* The output buffer */
3990   int i;         /* Loop counter */
3991   int nZero;     /* Number of leading zeros */
3992   int nDigit;    /* Number of digits not counting trailing zeros */
3993   int nFrac;     /* Digits to the right of the decimal point */
3994   int exp;       /* Exponent value */
3995   signed char zero;     /* Zero value */
3996   signed char *a;       /* Array of digits */
3997 
3998   if( p==0 || p->oom ){
3999     sqlite3_result_error_nomem(pCtx);
4000     return;
4001   }
4002   if( p->isNull ){
4003     sqlite3_result_null(pCtx);
4004     return;
4005   }
4006   for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){}
4007   for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
4008   nFrac = p->nFrac + (nDigit - p->nDigit);
4009   nDigit -= nZero;
4010   z = sqlite3_malloc( nDigit+20 );
4011   if( z==0 ){
4012     sqlite3_result_error_nomem(pCtx);
4013     return;
4014   }
4015   if( nDigit==0 ){
4016     zero = 0;
4017     a = &zero;
4018     nDigit = 1;
4019     nFrac = 0;
4020   }else{
4021     a = &p->a[nZero];
4022   }
4023   if( p->sign && nDigit>0 ){
4024     z[0] = '-';
4025   }else{
4026     z[0] = '+';
4027   }
4028   z[1] = a[0]+'0';
4029   z[2] = '.';
4030   if( nDigit==1 ){
4031     z[3] = '0';
4032     i = 4;
4033   }else{
4034     for(i=1; i<nDigit; i++){
4035       z[2+i] = a[i]+'0';
4036     }
4037     i = nDigit+2;
4038   }
4039   exp = nDigit - nFrac - 1;
4040   sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
4041   sqlite3_result_text(pCtx, z, -1, sqlite3_free);
4042 }
4043 
4044 /*
4045 ** Compare to Decimal objects.  Return negative, 0, or positive if the
4046 ** first object is less than, equal to, or greater than the second.
4047 **
4048 ** Preconditions for this routine:
4049 **
4050 **    pA!=0
4051 **    pA->isNull==0
4052 **    pB!=0
4053 **    pB->isNull==0
4054 */
decimal_cmp(const Decimal * pA,const Decimal * pB)4055 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4056   int nASig, nBSig, rc, n;
4057   if( pA->sign!=pB->sign ){
4058     return pA->sign ? -1 : +1;
4059   }
4060   if( pA->sign ){
4061     const Decimal *pTemp = pA;
4062     pA = pB;
4063     pB = pTemp;
4064   }
4065   nASig = pA->nDigit - pA->nFrac;
4066   nBSig = pB->nDigit - pB->nFrac;
4067   if( nASig!=nBSig ){
4068     return nASig - nBSig;
4069   }
4070   n = pA->nDigit;
4071   if( n>pB->nDigit ) n = pB->nDigit;
4072   rc = memcmp(pA->a, pB->a, n);
4073   if( rc==0 ){
4074     rc = pA->nDigit - pB->nDigit;
4075   }
4076   return rc;
4077 }
4078 
4079 /*
4080 ** SQL Function:   decimal_cmp(X, Y)
4081 **
4082 ** Return negative, zero, or positive if X is less then, equal to, or
4083 ** greater than Y.
4084 */
decimalCmpFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4085 static void decimalCmpFunc(
4086   sqlite3_context *context,
4087   int argc,
4088   sqlite3_value **argv
4089 ){
4090   Decimal *pA = 0, *pB = 0;
4091   int rc;
4092 
4093   UNUSED_PARAMETER(argc);
4094   pA = decimal_new(context, argv[0], 1);
4095   if( pA==0 || pA->isNull ) goto cmp_done;
4096   pB = decimal_new(context, argv[1], 1);
4097   if( pB==0 || pB->isNull ) goto cmp_done;
4098   rc = decimal_cmp(pA, pB);
4099   if( rc<0 ) rc = -1;
4100   else if( rc>0 ) rc = +1;
4101   sqlite3_result_int(context, rc);
4102 cmp_done:
4103   decimal_free(pA);
4104   decimal_free(pB);
4105 }
4106 
4107 /*
4108 ** Expand the Decimal so that it has a least nDigit digits and nFrac
4109 ** digits to the right of the decimal point.
4110 */
decimal_expand(Decimal * p,int nDigit,int nFrac)4111 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4112   int nAddSig;
4113   int nAddFrac;
4114   if( p==0 ) return;
4115   nAddFrac = nFrac - p->nFrac;
4116   nAddSig = (nDigit - p->nDigit) - nAddFrac;
4117   if( nAddFrac==0 && nAddSig==0 ) return;
4118   p->a = sqlite3_realloc64(p->a, nDigit+1);
4119   if( p->a==0 ){
4120     p->oom = 1;
4121     return;
4122   }
4123   if( nAddSig ){
4124     memmove(p->a+nAddSig, p->a, p->nDigit);
4125     memset(p->a, 0, nAddSig);
4126     p->nDigit += nAddSig;
4127   }
4128   if( nAddFrac ){
4129     memset(p->a+p->nDigit, 0, nAddFrac);
4130     p->nDigit += nAddFrac;
4131     p->nFrac += nAddFrac;
4132   }
4133 }
4134 
4135 /*
4136 ** Add the value pB into pA.   A := A + B.
4137 **
4138 ** Both pA and pB might become denormalized by this routine.
4139 */
decimal_add(Decimal * pA,Decimal * pB)4140 static void decimal_add(Decimal *pA, Decimal *pB){
4141   int nSig, nFrac, nDigit;
4142   int i, rc;
4143   if( pA==0 ){
4144     return;
4145   }
4146   if( pA->oom || pB==0 || pB->oom ){
4147     pA->oom = 1;
4148     return;
4149   }
4150   if( pA->isNull || pB->isNull ){
4151     pA->isNull = 1;
4152     return;
4153   }
4154   nSig = pA->nDigit - pA->nFrac;
4155   if( nSig && pA->a[0]==0 ) nSig--;
4156   if( nSig<pB->nDigit-pB->nFrac ){
4157     nSig = pB->nDigit - pB->nFrac;
4158   }
4159   nFrac = pA->nFrac;
4160   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4161   nDigit = nSig + nFrac + 1;
4162   decimal_expand(pA, nDigit, nFrac);
4163   decimal_expand(pB, nDigit, nFrac);
4164   if( pA->oom || pB->oom ){
4165     pA->oom = 1;
4166   }else{
4167     if( pA->sign==pB->sign ){
4168       int carry = 0;
4169       for(i=nDigit-1; i>=0; i--){
4170         int x = pA->a[i] + pB->a[i] + carry;
4171         if( x>=10 ){
4172           carry = 1;
4173           pA->a[i] = x - 10;
4174         }else{
4175           carry = 0;
4176           pA->a[i] = x;
4177         }
4178       }
4179     }else{
4180       signed char *aA, *aB;
4181       int borrow = 0;
4182       rc = memcmp(pA->a, pB->a, nDigit);
4183       if( rc<0 ){
4184         aA = pB->a;
4185         aB = pA->a;
4186         pA->sign = !pA->sign;
4187       }else{
4188         aA = pA->a;
4189         aB = pB->a;
4190       }
4191       for(i=nDigit-1; i>=0; i--){
4192         int x = aA[i] - aB[i] - borrow;
4193         if( x<0 ){
4194           pA->a[i] = x+10;
4195           borrow = 1;
4196         }else{
4197           pA->a[i] = x;
4198           borrow = 0;
4199         }
4200       }
4201     }
4202   }
4203 }
4204 
4205 /*
4206 ** Multiply A by B.   A := A * B
4207 **
4208 ** All significant digits after the decimal point are retained.
4209 ** Trailing zeros after the decimal point are omitted as long as
4210 ** the number of digits after the decimal point is no less than
4211 ** either the number of digits in either input.
4212 */
decimalMul(Decimal * pA,Decimal * pB)4213 static void decimalMul(Decimal *pA, Decimal *pB){
4214   signed char *acc = 0;
4215   int i, j, k;
4216   int minFrac;
4217 
4218   if( pA==0 || pA->oom || pA->isNull
4219    || pB==0 || pB->oom || pB->isNull
4220   ){
4221     goto mul_end;
4222   }
4223   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
4224   if( acc==0 ){
4225     pA->oom = 1;
4226     goto mul_end;
4227   }
4228   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
4229   minFrac = pA->nFrac;
4230   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
4231   for(i=pA->nDigit-1; i>=0; i--){
4232     signed char f = pA->a[i];
4233     int carry = 0, x;
4234     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
4235       x = acc[k] + f*pB->a[j] + carry;
4236       acc[k] = x%10;
4237       carry = x/10;
4238     }
4239     x = acc[k] + carry;
4240     acc[k] = x%10;
4241     acc[k-1] += x/10;
4242   }
4243   sqlite3_free(pA->a);
4244   pA->a = acc;
4245   acc = 0;
4246   pA->nDigit += pB->nDigit + 2;
4247   pA->nFrac += pB->nFrac;
4248   pA->sign ^= pB->sign;
4249   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
4250     pA->nFrac--;
4251     pA->nDigit--;
4252   }
4253 
4254 mul_end:
4255   sqlite3_free(acc);
4256 }
4257 
4258 /*
4259 ** Create a new Decimal object that contains an integer power of 2.
4260 */
decimalPow2(int N)4261 static Decimal *decimalPow2(int N){
4262   Decimal *pA = 0;      /* The result to be returned */
4263   Decimal *pX = 0;      /* Multiplier */
4264   if( N<-20000 || N>20000 ) goto pow2_fault;
4265   pA = decimalNewFromText("1.0", 3);
4266   if( pA==0 || pA->oom ) goto pow2_fault;
4267   if( N==0 ) return pA;
4268   if( N>0 ){
4269     pX = decimalNewFromText("2.0", 3);
4270   }else{
4271     N = -N;
4272     pX = decimalNewFromText("0.5", 3);
4273   }
4274   if( pX==0 || pX->oom ) goto pow2_fault;
4275   while( 1 /* Exit by break */ ){
4276     if( N & 1 ){
4277       decimalMul(pA, pX);
4278       if( pA->oom ) goto pow2_fault;
4279     }
4280     N >>= 1;
4281     if( N==0 ) break;
4282     decimalMul(pX, pX);
4283   }
4284   decimal_free(pX);
4285   return pA;
4286 
4287 pow2_fault:
4288   decimal_free(pA);
4289   decimal_free(pX);
4290   return 0;
4291 }
4292 
4293 /*
4294 ** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
4295 */
decimalFromDouble(double r)4296 static Decimal *decimalFromDouble(double r){
4297   sqlite3_int64 m, a;
4298   int e;
4299   int isNeg;
4300   Decimal *pA;
4301   Decimal *pX;
4302   char zNum[100];
4303   if( r<0.0 ){
4304     isNeg = 1;
4305     r = -r;
4306   }else{
4307     isNeg = 0;
4308   }
4309   memcpy(&a,&r,sizeof(a));
4310   if( a==0 ){
4311     e = 0;
4312     m = 0;
4313   }else{
4314     e = a>>52;
4315     m = a & ((((sqlite3_int64)1)<<52)-1);
4316     if( e==0 ){
4317       m <<= 1;
4318     }else{
4319       m |= ((sqlite3_int64)1)<<52;
4320     }
4321     while( e<1075 && m>0 && (m&1)==0 ){
4322       m >>= 1;
4323       e++;
4324     }
4325     if( isNeg ) m = -m;
4326     e = e - 1075;
4327     if( e>971 ){
4328       return 0;  /* A NaN or an Infinity */
4329     }
4330   }
4331 
4332   /* At this point m is the integer significand and e is the exponent */
4333   sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
4334   pA = decimalNewFromText(zNum, (int)strlen(zNum));
4335   pX = decimalPow2(e);
4336   decimalMul(pA, pX);
4337   decimal_free(pX);
4338   return pA;
4339 }
4340 
4341 /*
4342 ** SQL Function:   decimal(X)
4343 ** OR:             decimal_exp(X)
4344 **
4345 ** Convert input X into decimal and then back into text.
4346 **
4347 ** If X is originally a float, then a full decimal expansion of that floating
4348 ** point value is done.  Or if X is an 8-byte blob, it is interpreted
4349 ** as a float and similarly expanded.
4350 **
4351 ** The decimal_exp(X) function returns the result in exponential notation.
4352 ** decimal(X) returns a complete decimal, without the e+NNN at the end.
4353 */
decimalFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4354 static void decimalFunc(
4355   sqlite3_context *context,
4356   int argc,
4357   sqlite3_value **argv
4358 ){
4359   Decimal *p =  decimal_new(context, argv[0], 0);
4360   UNUSED_PARAMETER(argc);
4361   if( p ){
4362     if( sqlite3_user_data(context)!=0 ){
4363       decimal_result_sci(context, p);
4364     }else{
4365       decimal_result(context, p);
4366     }
4367     decimal_free(p);
4368   }
4369 }
4370 
4371 /*
4372 ** Compare text in decimal order.
4373 */
decimalCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)4374 static int decimalCollFunc(
4375   void *notUsed,
4376   int nKey1, const void *pKey1,
4377   int nKey2, const void *pKey2
4378 ){
4379   const unsigned char *zA = (const unsigned char*)pKey1;
4380   const unsigned char *zB = (const unsigned char*)pKey2;
4381   Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
4382   Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
4383   int rc;
4384   UNUSED_PARAMETER(notUsed);
4385   if( pA==0 || pB==0 ){
4386     rc = 0;
4387   }else{
4388     rc = decimal_cmp(pA, pB);
4389   }
4390   decimal_free(pA);
4391   decimal_free(pB);
4392   return rc;
4393 }
4394 
4395 
4396 /*
4397 ** SQL Function:   decimal_add(X, Y)
4398 **                 decimal_sub(X, Y)
4399 **
4400 ** Return the sum or difference of X and Y.
4401 */
decimalAddFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4402 static void decimalAddFunc(
4403   sqlite3_context *context,
4404   int argc,
4405   sqlite3_value **argv
4406 ){
4407   Decimal *pA = decimal_new(context, argv[0], 1);
4408   Decimal *pB = decimal_new(context, argv[1], 1);
4409   UNUSED_PARAMETER(argc);
4410   decimal_add(pA, pB);
4411   decimal_result(context, pA);
4412   decimal_free(pA);
4413   decimal_free(pB);
4414 }
decimalSubFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4415 static void decimalSubFunc(
4416   sqlite3_context *context,
4417   int argc,
4418   sqlite3_value **argv
4419 ){
4420   Decimal *pA = decimal_new(context, argv[0], 1);
4421   Decimal *pB = decimal_new(context, argv[1], 1);
4422   UNUSED_PARAMETER(argc);
4423   if( pB ){
4424     pB->sign = !pB->sign;
4425     decimal_add(pA, pB);
4426     decimal_result(context, pA);
4427   }
4428   decimal_free(pA);
4429   decimal_free(pB);
4430 }
4431 
4432 /* Aggregate function:   decimal_sum(X)
4433 **
4434 ** Works like sum() except that it uses decimal arithmetic for unlimited
4435 ** precision.
4436 */
decimalSumStep(sqlite3_context * context,int argc,sqlite3_value ** argv)4437 static void decimalSumStep(
4438   sqlite3_context *context,
4439   int argc,
4440   sqlite3_value **argv
4441 ){
4442   Decimal *p;
4443   Decimal *pArg;
4444   UNUSED_PARAMETER(argc);
4445   p = sqlite3_aggregate_context(context, sizeof(*p));
4446   if( p==0 ) return;
4447   if( !p->isInit ){
4448     p->isInit = 1;
4449     p->a = sqlite3_malloc(2);
4450     if( p->a==0 ){
4451       p->oom = 1;
4452     }else{
4453       p->a[0] = 0;
4454     }
4455     p->nDigit = 1;
4456     p->nFrac = 0;
4457   }
4458   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4459   pArg = decimal_new(context, argv[0], 1);
4460   decimal_add(p, pArg);
4461   decimal_free(pArg);
4462 }
decimalSumInverse(sqlite3_context * context,int argc,sqlite3_value ** argv)4463 static void decimalSumInverse(
4464   sqlite3_context *context,
4465   int argc,
4466   sqlite3_value **argv
4467 ){
4468   Decimal *p;
4469   Decimal *pArg;
4470   UNUSED_PARAMETER(argc);
4471   p = sqlite3_aggregate_context(context, sizeof(*p));
4472   if( p==0 ) return;
4473   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4474   pArg = decimal_new(context, argv[0], 1);
4475   if( pArg ) pArg->sign = !pArg->sign;
4476   decimal_add(p, pArg);
4477   decimal_free(pArg);
4478 }
decimalSumValue(sqlite3_context * context)4479 static void decimalSumValue(sqlite3_context *context){
4480   Decimal *p = sqlite3_aggregate_context(context, 0);
4481   if( p==0 ) return;
4482   decimal_result(context, p);
4483 }
decimalSumFinalize(sqlite3_context * context)4484 static void decimalSumFinalize(sqlite3_context *context){
4485   Decimal *p = sqlite3_aggregate_context(context, 0);
4486   if( p==0 ) return;
4487   decimal_result(context, p);
4488   decimal_clear(p);
4489 }
4490 
4491 /*
4492 ** SQL Function:   decimal_mul(X, Y)
4493 **
4494 ** Return the product of X and Y.
4495 */
decimalMulFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4496 static void decimalMulFunc(
4497   sqlite3_context *context,
4498   int argc,
4499   sqlite3_value **argv
4500 ){
4501   Decimal *pA = decimal_new(context, argv[0], 1);
4502   Decimal *pB = decimal_new(context, argv[1], 1);
4503   UNUSED_PARAMETER(argc);
4504   if( pA==0 || pA->oom || pA->isNull
4505    || pB==0 || pB->oom || pB->isNull
4506   ){
4507     goto mul_end;
4508   }
4509   decimalMul(pA, pB);
4510   if( pA->oom ){
4511     goto mul_end;
4512   }
4513   decimal_result(context, pA);
4514 
4515 mul_end:
4516   decimal_free(pA);
4517   decimal_free(pB);
4518 }
4519 
4520 /*
4521 ** SQL Function:   decimal_pow2(N)
4522 **
4523 ** Return the N-th power of 2.  N must be an integer.
4524 */
decimalPow2Func(sqlite3_context * context,int argc,sqlite3_value ** argv)4525 static void decimalPow2Func(
4526   sqlite3_context *context,
4527   int argc,
4528   sqlite3_value **argv
4529 ){
4530   UNUSED_PARAMETER(argc);
4531   if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
4532     Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
4533     decimal_result_sci(context, pA);
4534     decimal_free(pA);
4535   }
4536 }
4537 
4538 #ifdef _WIN32
4539 
4540 #endif
sqlite3_decimal_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)4541 int sqlite3_decimal_init(
4542   sqlite3 *db,
4543   char **pzErrMsg,
4544   const sqlite3_api_routines *pApi
4545 ){
4546   int rc = SQLITE_OK;
4547   static const struct {
4548     const char *zFuncName;
4549     int nArg;
4550     int iArg;
4551     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4552   } aFunc[] = {
4553     { "decimal",       1, 0,  decimalFunc        },
4554     { "decimal_exp",   1, 1,  decimalFunc        },
4555     { "decimal_cmp",   2, 0,  decimalCmpFunc     },
4556     { "decimal_add",   2, 0,  decimalAddFunc     },
4557     { "decimal_sub",   2, 0,  decimalSubFunc     },
4558     { "decimal_mul",   2, 0,  decimalMulFunc     },
4559     { "decimal_pow2",  1, 0,  decimalPow2Func    },
4560   };
4561   unsigned int i;
4562   (void)pzErrMsg;  /* Unused parameter */
4563 
4564   SQLITE_EXTENSION_INIT2(pApi);
4565 
4566   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
4567     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
4568                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4569                    aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
4570   }
4571   if( rc==SQLITE_OK ){
4572     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
4573                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
4574                    decimalSumStep, decimalSumFinalize,
4575                    decimalSumValue, decimalSumInverse, 0);
4576   }
4577   if( rc==SQLITE_OK ){
4578     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
4579                                   0, decimalCollFunc);
4580   }
4581   return rc;
4582 }
4583 
4584 /************************* End ../ext/misc/decimal.c ********************/
4585 /************************* Begin ../ext/misc/percentile.c ******************/
4586 /*
4587 ** 2013-05-28
4588 **
4589 ** The author disclaims copyright to this source code.  In place of
4590 ** a legal notice, here is a blessing:
4591 **
4592 **    May you do good and not evil.
4593 **    May you find forgiveness for yourself and forgive others.
4594 **    May you share freely, never taking more than you give.
4595 **
4596 ******************************************************************************
4597 **
4598 ** This file contains code to implement the percentile(Y,P) SQL function
4599 ** and similar as described below:
4600 **
4601 **   (1)  The percentile(Y,P) function is an aggregate function taking
4602 **        exactly two arguments.
4603 **
4604 **   (2)  If the P argument to percentile(Y,P) is not the same for every
4605 **        row in the aggregate then an error is thrown.  The word "same"
4606 **        in the previous sentence means that the value differ by less
4607 **        than 0.001.
4608 **
4609 **   (3)  If the P argument to percentile(Y,P) evaluates to anything other
4610 **        than a number in the range of 0.0 to 100.0 inclusive then an
4611 **        error is thrown.
4612 **
4613 **   (4)  If any Y argument to percentile(Y,P) evaluates to a value that
4614 **        is not NULL and is not numeric then an error is thrown.
4615 **
4616 **   (5)  If any Y argument to percentile(Y,P) evaluates to plus or minus
4617 **        infinity then an error is thrown.  (SQLite always interprets NaN
4618 **        values as NULL.)
4619 **
4620 **   (6)  Both Y and P in percentile(Y,P) can be arbitrary expressions,
4621 **        including CASE WHEN expressions.
4622 **
4623 **   (7)  The percentile(Y,P) aggregate is able to handle inputs of at least
4624 **        one million (1,000,000) rows.
4625 **
4626 **   (8)  If there are no non-NULL values for Y, then percentile(Y,P)
4627 **        returns NULL.
4628 **
4629 **   (9)  If there is exactly one non-NULL value for Y, the percentile(Y,P)
4630 **        returns the one Y value.
4631 **
4632 **  (10)  If there N non-NULL values of Y where N is two or more and
4633 **        the Y values are ordered from least to greatest and a graph is
4634 **        drawn from 0 to N-1 such that the height of the graph at J is
4635 **        the J-th Y value and such that straight lines are drawn between
4636 **        adjacent Y values, then the percentile(Y,P) function returns
4637 **        the height of the graph at P*(N-1)/100.
4638 **
4639 **  (11)  The percentile(Y,P) function always returns either a floating
4640 **        point number or NULL.
4641 **
4642 **  (12)  The percentile(Y,P) is implemented as a single C99 source-code
4643 **        file that compiles into a shared-library or DLL that can be loaded
4644 **        into SQLite using the sqlite3_load_extension() interface.
4645 **
4646 **  (13)  A separate median(Y) function is the equivalent percentile(Y,50).
4647 **
4648 **  (14)  A separate percentile_cont(Y,P) function is equivalent to
4649 **        percentile(Y,P/100.0).  In other words, the fraction value in
4650 **        the second argument is in the range of 0 to 1 instead of 0 to 100.
4651 **
4652 **  (15)  A separate percentile_disc(Y,P) function is like
4653 **        percentile_cont(Y,P) except that instead of returning the weighted
4654 **        average of the nearest two input values, it returns the next lower
4655 **        value.  So the percentile_disc(Y,P) will always return a value
4656 **        that was one of the inputs.
4657 **
4658 **  (16)  All of median(), percentile(Y,P), percentile_cont(Y,P) and
4659 **        percentile_disc(Y,P) can be used as window functions.
4660 **
4661 ** Differences from standard SQL:
4662 **
4663 **  *  The percentile_cont(X,P) function is equivalent to the following in
4664 **     standard SQL:
4665 **
4666 **         (percentile_cont(P) WITHIN GROUP (ORDER BY X))
4667 **
4668 **     The SQLite syntax is much more compact.  The standard SQL syntax
4669 **     is also supported if SQLite is compiled with the
4670 **     -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES option.
4671 **
4672 **  *  No median(X) function exists in the SQL standard.  App developers
4673 **     are expected to write "percentile_cont(0.5)WITHIN GROUP(ORDER BY X)".
4674 **
4675 **  *  No percentile(Y,P) function exists in the SQL standard.  Instead of
4676 **     percential(Y,P), developers must write this:
4677 **     "percentile_cont(P/100.0) WITHIN GROUP (ORDER BY Y)".  Note that
4678 **     the fraction parameter to percentile() goes from 0 to 100 whereas
4679 **     the fraction parameter in SQL standard percentile_cont() goes from
4680 **     0 to 1.
4681 **
4682 ** Implementation notes as of 2024-08-31:
4683 **
4684 **  *  The regular aggregate-function versions of these routines work
4685 **     by accumulating all values in an array of doubles, then sorting
4686 **     that array using quicksort before computing the answer. Thus
4687 **     the runtime is O(NlogN) where N is the number of rows of input.
4688 **
4689 **  *  For the window-function versions of these routines, the array of
4690 **     inputs is sorted as soon as the first value is computed.  Thereafter,
4691 **     the array is kept in sorted order using an insert-sort.  This
4692 **     results in O(N*K) performance where K is the size of the window.
4693 **     One can imagine alternative implementations that give O(N*logN*logK)
4694 **     performance, but they require more complex logic and data structures.
4695 **     The developers have elected to keep the asymptotically slower
4696 **     algorithm for now, for simplicity, under the theory that window
4697 **     functions are seldom used and when they are, the window size K is
4698 **     often small.  The developers might revisit that decision later,
4699 **     should the need arise.
4700 */
4701 #if defined(SQLITE3_H)
4702   /* no-op */
4703 #elif defined(SQLITE_STATIC_PERCENTILE)
4704 /* #  include "sqlite3.h" */
4705 #else
4706 /* #  include "sqlite3ext.h" */
4707    SQLITE_EXTENSION_INIT1
4708 #endif
4709 #include <assert.h>
4710 #include <string.h>
4711 #include <stdlib.h>
4712 
4713 /* The following object is the group context for a single percentile()
4714 ** aggregate.  Remember all input Y values until the very end.
4715 ** Those values are accumulated in the Percentile.a[] array.
4716 */
4717 typedef struct Percentile Percentile;
4718 struct Percentile {
4719   unsigned nAlloc;     /* Number of slots allocated for a[] */
4720   unsigned nUsed;      /* Number of slots actually used in a[] */
4721   char bSorted;        /* True if a[] is already in sorted order */
4722   char bKeepSorted;    /* True if advantageous to keep a[] sorted */
4723   char bPctValid;      /* True if rPct is valid */
4724   double rPct;         /* Fraction.  0.0 to 1.0 */
4725   double *a;           /* Array of Y values */
4726 };
4727 
4728 /* Details of each function in the percentile family */
4729 typedef struct PercentileFunc PercentileFunc;
4730 struct PercentileFunc {
4731   const char *zName;   /* Function name */
4732   char nArg;           /* Number of arguments */
4733   char mxFrac;         /* Maximum value of the "fraction" input */
4734   char bDiscrete;      /* True for percentile_disc() */
4735 };
4736 static const PercentileFunc aPercentFunc[] = {
4737   { "median",           1,   1, 0 },
4738   { "percentile",       2, 100, 0 },
4739   { "percentile_cont",  2,   1, 0 },
4740   { "percentile_disc",  2,   1, 1 },
4741 };
4742 
4743 /*
4744 ** Return TRUE if the input floating-point number is an infinity.
4745 */
percentIsInfinity(double r)4746 static int percentIsInfinity(double r){
4747   sqlite3_uint64 u;
4748   assert( sizeof(u)==sizeof(r) );
4749   memcpy(&u, &r, sizeof(u));
4750   return ((u>>52)&0x7ff)==0x7ff;
4751 }
4752 
4753 /*
4754 ** Return TRUE if two doubles differ by 0.001 or less.
4755 */
percentSameValue(double a,double b)4756 static int percentSameValue(double a, double b){
4757   a -= b;
4758   return a>=-0.001 && a<=0.001;
4759 }
4760 
4761 /*
4762 ** Search p (which must have p->bSorted) looking for an entry with
4763 ** value y.  Return the index of that entry.
4764 **
4765 ** If bExact is true, return -1 if the entry is not found.
4766 **
4767 ** If bExact is false, return the index at which a new entry with
4768 ** value y should be insert in order to keep the values in sorted
4769 ** order.  The smallest return value in this case will be 0, and
4770 ** the largest return value will be p->nUsed.
4771 */
percentBinarySearch(Percentile * p,double y,int bExact)4772 static int percentBinarySearch(Percentile *p, double y, int bExact){
4773   int iFirst = 0;              /* First element of search range */
4774   int iLast = p->nUsed - 1;    /* Last element of search range */
4775   while( iLast>=iFirst ){
4776     int iMid = (iFirst+iLast)/2;
4777     double x = p->a[iMid];
4778     if( x<y ){
4779       iFirst = iMid + 1;
4780     }else if( x>y ){
4781       iLast = iMid - 1;
4782     }else{
4783       return iMid;
4784     }
4785   }
4786   if( bExact ) return -1;
4787   return iFirst;
4788 }
4789 
4790 /*
4791 ** Generate an error for a percentile function.
4792 **
4793 ** The error format string must have exactly one occurrence of "%%s()"
4794 ** (with two '%' characters).  That substring will be replaced by the name
4795 ** of the function.
4796 */
percentError(sqlite3_context * pCtx,const char * zFormat,...)4797 static void percentError(sqlite3_context *pCtx, const char *zFormat, ...){
4798   PercentileFunc *pFunc = (PercentileFunc*)sqlite3_user_data(pCtx);
4799   char *zMsg1;
4800   char *zMsg2;
4801   va_list ap;
4802 
4803   va_start(ap, zFormat);
4804   zMsg1 = sqlite3_vmprintf(zFormat, ap);
4805   va_end(ap);
4806   zMsg2 = zMsg1 ? sqlite3_mprintf(zMsg1, pFunc->zName) : 0;
4807   sqlite3_result_error(pCtx, zMsg2, -1);
4808   sqlite3_free(zMsg1);
4809   sqlite3_free(zMsg2);
4810 }
4811 
4812 /*
4813 ** The "step" function for percentile(Y,P) is called once for each
4814 ** input row.
4815 */
percentStep(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)4816 static void percentStep(sqlite3_context *pCtx, int argc, sqlite3_value **argv){
4817   Percentile *p;
4818   double rPct;
4819   int eType;
4820   double y;
4821   assert( argc==2 || argc==1 );
4822 
4823   if( argc==1 ){
4824     /* Requirement 13:  median(Y) is the same as percentile(Y,50). */
4825     rPct = 0.5;
4826   }else{
4827     /* Requirement 3:  P must be a number between 0 and 100 */
4828     PercentileFunc *pFunc = (PercentileFunc*)sqlite3_user_data(pCtx);
4829     eType = sqlite3_value_numeric_type(argv[1]);
4830     rPct = sqlite3_value_double(argv[1])/(double)pFunc->mxFrac;
4831     if( (eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT)
4832      || rPct<0.0 || rPct>1.0
4833     ){
4834       percentError(pCtx, "the fraction argument to %%s()"
4835                         " is not between 0.0 and %.1f",
4836                         (double)pFunc->mxFrac);
4837       return;
4838     }
4839   }
4840 
4841   /* Allocate the session context. */
4842   p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p));
4843   if( p==0 ) return;
4844 
4845   /* Remember the P value.  Throw an error if the P value is different
4846   ** from any prior row, per Requirement (2). */
4847   if( !p->bPctValid ){
4848     p->rPct = rPct;
4849     p->bPctValid = 1;
4850   }else if( !percentSameValue(p->rPct,rPct) ){
4851     percentError(pCtx, "the fraction argument to %%s()"
4852                       " is not the same for all input rows");
4853     return;
4854   }
4855 
4856   /* Ignore rows for which Y is NULL */
4857   eType = sqlite3_value_type(argv[0]);
4858   if( eType==SQLITE_NULL ) return;
4859 
4860   /* If not NULL, then Y must be numeric.  Otherwise throw an error.
4861   ** Requirement 4 */
4862   if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){
4863     percentError(pCtx, "input to %%s() is not numeric");
4864     return;
4865   }
4866 
4867   /* Throw an error if the Y value is infinity or NaN */
4868   y = sqlite3_value_double(argv[0]);
4869   if( percentIsInfinity(y) ){
4870     percentError(pCtx, "Inf input to %%s()");
4871     return;
4872   }
4873 
4874   /* Allocate and store the Y */
4875   if( p->nUsed>=p->nAlloc ){
4876     unsigned n = p->nAlloc*2 + 250;
4877     double *a = sqlite3_realloc64(p->a, sizeof(double)*n);
4878     if( a==0 ){
4879       sqlite3_free(p->a);
4880       memset(p, 0, sizeof(*p));
4881       sqlite3_result_error_nomem(pCtx);
4882       return;
4883     }
4884     p->nAlloc = n;
4885     p->a = a;
4886   }
4887   if( p->nUsed==0 ){
4888     p->a[p->nUsed++] = y;
4889     p->bSorted = 1;
4890   }else if( !p->bSorted || y>=p->a[p->nUsed-1] ){
4891     p->a[p->nUsed++] = y;
4892   }else if( p->bKeepSorted ){
4893     int i;
4894     i = percentBinarySearch(p, y, 0);
4895     if( i<(int)p->nUsed ){
4896       memmove(&p->a[i+1], &p->a[i], (p->nUsed-i)*sizeof(p->a[0]));
4897     }
4898     p->a[i] = y;
4899     p->nUsed++;
4900   }else{
4901     p->a[p->nUsed++] = y;
4902     p->bSorted = 0;
4903   }
4904 }
4905 
4906 /*
4907 ** Interchange two doubles.
4908 */
4909 #define SWAP_DOUBLE(X,Y)  {double ttt=(X);(X)=(Y);(Y)=ttt;}
4910 
4911 /*
4912 ** Sort an array of doubles.
4913 **
4914 ** Algorithm: quicksort
4915 **
4916 ** This is implemented separately rather than using the qsort() routine
4917 ** from the standard library because:
4918 **
4919 **    (1)  To avoid a dependency on qsort()
4920 **    (2)  To avoid the function call to the comparison routine for each
4921 **         comparison.
4922 */
percentSort(double * a,unsigned int n)4923 static void percentSort(double *a, unsigned int n){
4924   int iLt;  /* Entries before a[iLt] are less than rPivot */
4925   int iGt;  /* Entries at or after a[iGt] are greater than rPivot */
4926   int i;         /* Loop counter */
4927   double rPivot; /* The pivot value */
4928 
4929   assert( n>=2 );
4930   if( a[0]>a[n-1] ){
4931     SWAP_DOUBLE(a[0],a[n-1])
4932   }
4933   if( n==2 ) return;
4934   iGt = n-1;
4935   i = n/2;
4936   if( a[0]>a[i] ){
4937     SWAP_DOUBLE(a[0],a[i])
4938   }else if( a[i]>a[iGt] ){
4939     SWAP_DOUBLE(a[i],a[iGt])
4940   }
4941   if( n==3 ) return;
4942   rPivot = a[i];
4943   iLt = i = 1;
4944   do{
4945     if( a[i]<rPivot ){
4946       if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
4947       iLt++;
4948       i++;
4949     }else if( a[i]>rPivot ){
4950       do{
4951         iGt--;
4952       }while( iGt>i && a[iGt]>rPivot );
4953       SWAP_DOUBLE(a[i],a[iGt])
4954     }else{
4955       i++;
4956     }
4957   }while( i<iGt );
4958   if( iLt>=2 ) percentSort(a, iLt);
4959   if( n-iGt>=2 ) percentSort(a+iGt, n-iGt);
4960 
4961 /* Uncomment for testing */
4962 #if 0
4963   for(i=0; i<n-1; i++){
4964     assert( a[i]<=a[i+1] );
4965   }
4966 #endif
4967 }
4968 
4969 
4970 /*
4971 ** The "inverse" function for percentile(Y,P) is called to remove a
4972 ** row that was previously inserted by "step".
4973 */
percentInverse(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)4974 static void percentInverse(sqlite3_context *pCtx,int argc,sqlite3_value **argv){
4975   Percentile *p;
4976   int eType;
4977   double y;
4978   int i;
4979   assert( argc==2 || argc==1 );
4980 
4981   /* Allocate the session context. */
4982   p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p));
4983   assert( p!=0 );
4984 
4985   /* Ignore rows for which Y is NULL */
4986   eType = sqlite3_value_type(argv[0]);
4987   if( eType==SQLITE_NULL ) return;
4988 
4989   /* If not NULL, then Y must be numeric.  Otherwise throw an error.
4990   ** Requirement 4 */
4991   if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){
4992     return;
4993   }
4994 
4995   /* Ignore the Y value if it is infinity or NaN */
4996   y = sqlite3_value_double(argv[0]);
4997   if( percentIsInfinity(y) ){
4998     return;
4999   }
5000   if( p->bSorted==0 ){
5001     assert( p->nUsed>1 );
5002     percentSort(p->a, p->nUsed);
5003     p->bSorted = 1;
5004   }
5005   p->bKeepSorted = 1;
5006 
5007   /* Find and remove the row */
5008   i = percentBinarySearch(p, y, 1);
5009   if( i>=0 ){
5010     p->nUsed--;
5011     if( i<(int)p->nUsed ){
5012       memmove(&p->a[i], &p->a[i+1], (p->nUsed - i)*sizeof(p->a[0]));
5013     }
5014   }
5015 }
5016 
5017 /*
5018 ** Compute the final output of percentile().  Clean up all allocated
5019 ** memory if and only if bIsFinal is true.
5020 */
percentCompute(sqlite3_context * pCtx,int bIsFinal)5021 static void percentCompute(sqlite3_context *pCtx, int bIsFinal){
5022   Percentile *p;
5023   PercentileFunc *pFunc = (PercentileFunc*)sqlite3_user_data(pCtx);
5024   unsigned i1, i2;
5025   double v1, v2;
5026   double ix, vx;
5027   p = (Percentile*)sqlite3_aggregate_context(pCtx, 0);
5028   if( p==0 ) return;
5029   if( p->a==0 ) return;
5030   if( p->nUsed ){
5031     if( p->bSorted==0 ){
5032       assert( p->nUsed>1 );
5033       percentSort(p->a, p->nUsed);
5034       p->bSorted = 1;
5035     }
5036     ix = p->rPct*(p->nUsed-1);
5037     i1 = (unsigned)ix;
5038     if( pFunc->bDiscrete ){
5039       vx = p->a[i1];
5040     }else{
5041       i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1;
5042       v1 = p->a[i1];
5043       v2 = p->a[i2];
5044       vx = v1 + (v2-v1)*(ix-i1);
5045     }
5046     sqlite3_result_double(pCtx, vx);
5047   }
5048   if( bIsFinal ){
5049     sqlite3_free(p->a);
5050     memset(p, 0, sizeof(*p));
5051   }else{
5052     p->bKeepSorted = 1;
5053   }
5054 }
percentFinal(sqlite3_context * pCtx)5055 static void percentFinal(sqlite3_context *pCtx){
5056   percentCompute(pCtx, 1);
5057 }
percentValue(sqlite3_context * pCtx)5058 static void percentValue(sqlite3_context *pCtx){
5059   percentCompute(pCtx, 0);
5060 }
5061 
5062 #if defined(_WIN32) && !defined(SQLITE3_H) && !defined(SQLITE_STATIC_PERCENTILE)
5063 
5064 #endif
sqlite3_percentile_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)5065 int sqlite3_percentile_init(
5066   sqlite3 *db,
5067   char **pzErrMsg,
5068   const sqlite3_api_routines *pApi
5069 ){
5070   int rc = SQLITE_OK;
5071   unsigned int i;
5072 #ifdef SQLITE3EXT_H
5073   SQLITE_EXTENSION_INIT2(pApi);
5074 #else
5075   (void)pApi;      /* Unused parameter */
5076 #endif
5077   (void)pzErrMsg;  /* Unused parameter */
5078   for(i=0; i<sizeof(aPercentFunc)/sizeof(aPercentFunc[0]); i++){
5079     rc = sqlite3_create_window_function(db,
5080             aPercentFunc[i].zName,
5081             aPercentFunc[i].nArg,
5082             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_SELFORDER1,
5083             (void*)&aPercentFunc[i],
5084             percentStep, percentFinal, percentValue, percentInverse, 0);
5085     if( rc ) break;
5086   }
5087   return rc;
5088 }
5089 
5090 /************************* End ../ext/misc/percentile.c ********************/
5091 #undef sqlite3_base_init
5092 #define sqlite3_base_init sqlite3_base64_init
5093 /************************* Begin ../ext/misc/base64.c ******************/
5094 /*
5095 ** 2022-11-18
5096 **
5097 ** The author disclaims copyright to this source code.  In place of
5098 ** a legal notice, here is a blessing:
5099 **
5100 **    May you do good and not evil.
5101 **    May you find forgiveness for yourself and forgive others.
5102 **    May you share freely, never taking more than you give.
5103 **
5104 *************************************************************************
5105 **
5106 ** This is a SQLite extension for converting in either direction
5107 ** between a (binary) blob and base64 text. Base64 can transit a
5108 ** sane USASCII channel unmolested. It also plays nicely in CSV or
5109 ** written as TCL brace-enclosed literals or SQL string literals,
5110 ** and can be used unmodified in XML-like documents.
5111 **
5112 ** This is an independent implementation of conversions specified in
5113 ** RFC 4648, done on the above date by the author (Larry Brasfield)
5114 ** who thereby has the right to put this into the public domain.
5115 **
5116 ** The conversions meet RFC 4648 requirements, provided that this
5117 ** C source specifies that line-feeds are included in the encoded
5118 ** data to limit visible line lengths to 72 characters and to
5119 ** terminate any encoded blob having non-zero length.
5120 **
5121 ** Length limitations are not imposed except that the runtime
5122 ** SQLite string or blob length limits are respected. Otherwise,
5123 ** any length binary sequence can be represented and recovered.
5124 ** Generated base64 sequences, with their line-feeds included,
5125 ** can be concatenated; the result converted back to binary will
5126 ** be the concatenation of the represented binary sequences.
5127 **
5128 ** This SQLite3 extension creates a function, base64(x), which
5129 ** either: converts text x containing base64 to a returned blob;
5130 ** or converts a blob x to returned text containing base64. An
5131 ** error will be thrown for other input argument types.
5132 **
5133 ** This code relies on UTF-8 encoding only with respect to the
5134 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
5135 ** It will fail miserably if somehow made to try to convert EBCDIC.
5136 ** Because it is table-driven, it could be enhanced to handle that,
5137 ** but the world and SQLite have moved on from that anachronism.
5138 **
5139 ** To build the extension:
5140 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
5141 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
5142 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
5143 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
5144 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
5145 */
5146 
5147 #include <assert.h>
5148 
5149 /* #include "sqlite3ext.h" */
5150 
5151 #ifndef deliberate_fall_through
5152 /* Quiet some compilers about some of our intentional code. */
5153 # if GCC_VERSION>=7000000
5154 #  define deliberate_fall_through __attribute__((fallthrough));
5155 # else
5156 #  define deliberate_fall_through
5157 # endif
5158 #endif
5159 
5160 SQLITE_EXTENSION_INIT1;
5161 
5162 #define PC 0x80 /* pad character */
5163 #define WS 0x81 /* whitespace */
5164 #define ND 0x82 /* Not above or digit-value */
5165 #define PAD_CHAR '='
5166 
5167 #ifndef U8_TYPEDEF
5168 /* typedef unsigned char u8; */
5169 #define U8_TYPEDEF
5170 #endif
5171 
5172 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
5173 static const u8 b64DigitValues[128] = {
5174   /*                             HT LF VT  FF CR       */
5175     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
5176   /*                                                US */
5177     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
5178   /*sp                                  +            / */
5179     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
5180   /* 0  1            5            9            =       */
5181     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
5182   /*    A                                            O */
5183     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
5184   /* P                               Z                 */
5185     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
5186   /*    a                                            o */
5187     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
5188   /* p                               z                 */
5189     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
5190 };
5191 
5192 static const char b64Numerals[64+1]
5193 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
5194 
5195 #define BX_DV_PROTO(c) \
5196   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
5197 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
5198 #define IS_BX_WS(bdp) ((bdp)==WS)
5199 #define IS_BX_PAD(bdp) ((bdp)==PC)
5200 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
5201 /* Width of base64 lines. Should be an integer multiple of 4. */
5202 #define B64_DARK_MAX 72
5203 
5204 /* Encode a byte buffer into base64 text with linefeeds appended to limit
5205 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
5206 */
toBase64(u8 * pIn,int nbIn,char * pOut)5207 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
5208   int nCol = 0;
5209   while( nbIn >= 3 ){
5210     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
5211     pOut[0] = BX_NUMERAL(pIn[0]>>2);
5212     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
5213     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
5214     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
5215     pOut += 4;
5216     nbIn -= 3;
5217     pIn += 3;
5218     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
5219       *pOut++ = '\n';
5220       nCol = 0;
5221     }
5222   }
5223   if( nbIn > 0 ){
5224     signed char nco = nbIn+1;
5225     int nbe;
5226     unsigned long qv = *pIn++;
5227     for( nbe=1; nbe<3; ++nbe ){
5228       qv <<= 8;
5229       if( nbe<nbIn ) qv |= *pIn++;
5230     }
5231     for( nbe=3; nbe>=0; --nbe ){
5232       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
5233       qv >>= 6;
5234       pOut[nbe] = ce;
5235     }
5236     pOut += 4;
5237     *pOut++ = '\n';
5238   }
5239   *pOut = 0;
5240   return pOut;
5241 }
5242 
5243 /* Skip over text which is not base64 numeral(s). */
skipNonB64(char * s,int nc)5244 static char * skipNonB64( char *s, int nc ){
5245   char c;
5246   while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
5247   return s;
5248 }
5249 
5250 /* Decode base64 text into a byte buffer. */
fromBase64(char * pIn,int ncIn,u8 * pOut)5251 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
5252   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
5253   while( ncIn>0 && *pIn!=PAD_CHAR ){
5254     static signed char nboi[] = { 0, 0, 1, 2, 3 };
5255     char *pUse = skipNonB64(pIn, ncIn);
5256     unsigned long qv = 0L;
5257     int nti, nbo, nac;
5258     ncIn -= (pUse - pIn);
5259     pIn = pUse;
5260     nti = (ncIn>4)? 4 : ncIn;
5261     ncIn -= nti;
5262     nbo = nboi[nti];
5263     if( nbo==0 ) break;
5264     for( nac=0; nac<4; ++nac ){
5265       char c = (nac<nti)? *pIn++ : b64Numerals[0];
5266       u8 bdp = BX_DV_PROTO(c);
5267       switch( bdp ){
5268       case ND:
5269         /*  Treat dark non-digits as pad, but they terminate decode too. */
5270         ncIn = 0;
5271         deliberate_fall_through; /* FALLTHRU */
5272       case WS:
5273         /* Treat whitespace as pad and terminate this group.*/
5274         nti = nac;
5275         deliberate_fall_through; /* FALLTHRU */
5276       case PC:
5277         bdp = 0;
5278         --nbo;
5279         deliberate_fall_through; /* FALLTHRU */
5280       default: /* bdp is the digit value. */
5281         qv = qv<<6 | bdp;
5282         break;
5283       }
5284     }
5285     switch( nbo ){
5286     case 3:
5287       pOut[2] = (qv) & 0xff;
5288       deliberate_fall_through; /* FALLTHRU */
5289     case 2:
5290       pOut[1] = (qv>>8) & 0xff;
5291       deliberate_fall_through; /* FALLTHRU */
5292     case 1:
5293       pOut[0] = (qv>>16) & 0xff;
5294       break;
5295     }
5296     pOut += nbo;
5297   }
5298   return pOut;
5299 }
5300 
5301 /* This function does the work for the SQLite base64(x) UDF. */
base64(sqlite3_context * context,int na,sqlite3_value * av[])5302 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
5303   int nb, nc, nv = sqlite3_value_bytes(av[0]);
5304   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
5305                             SQLITE_LIMIT_LENGTH, -1);
5306   char *cBuf;
5307   u8 *bBuf;
5308   assert(na==1);
5309   switch( sqlite3_value_type(av[0]) ){
5310   case SQLITE_BLOB:
5311     nb = nv;
5312     nc = 4*(nv+2/3); /* quads needed */
5313     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
5314     if( nvMax < nc ){
5315       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
5316       return;
5317     }
5318     bBuf = (u8*)sqlite3_value_blob(av[0]);
5319     if( !bBuf ){
5320       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5321         goto memFail;
5322       }
5323       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
5324       break;
5325     }
5326     cBuf = sqlite3_malloc(nc);
5327     if( !cBuf ) goto memFail;
5328     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
5329     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
5330     break;
5331   case SQLITE_TEXT:
5332     nc = nv;
5333     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
5334     if( nvMax < nb ){
5335       sqlite3_result_error(context, "blob from base64 may be too big", -1);
5336       return;
5337     }else if( nb<1 ){
5338       nb = 1;
5339     }
5340     cBuf = (char *)sqlite3_value_text(av[0]);
5341     if( !cBuf ){
5342       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5343         goto memFail;
5344       }
5345       sqlite3_result_zeroblob(context, 0);
5346       break;
5347     }
5348     bBuf = sqlite3_malloc(nb);
5349     if( !bBuf ) goto memFail;
5350     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
5351     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
5352     break;
5353   default:
5354     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
5355     return;
5356   }
5357   return;
5358  memFail:
5359   sqlite3_result_error(context, "base64 OOM", -1);
5360 }
5361 
5362 /*
5363 ** Establish linkage to running SQLite library.
5364 */
5365 #ifndef SQLITE_SHELL_EXTFUNCS
5366 #ifdef _WIN32
5367 
5368 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)5369 int sqlite3_base_init
5370 #else
5371 static int sqlite3_base64_init
5372 #endif
5373 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
5374   SQLITE_EXTENSION_INIT2(pApi);
5375   (void)pzErr;
5376   return sqlite3_create_function
5377     (db, "base64", 1,
5378      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
5379      0, base64, 0, 0);
5380 }
5381 
5382 /*
5383 ** Define some macros to allow this extension to be built into the shell
5384 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
5385 ** allows shell.c, as distributed, to have this extension built in.
5386 */
5387 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
5388 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
5389 
5390 /************************* End ../ext/misc/base64.c ********************/
5391 #undef sqlite3_base_init
5392 #define sqlite3_base_init sqlite3_base85_init
5393 #define OMIT_BASE85_CHECKER
5394 /************************* Begin ../ext/misc/base85.c ******************/
5395 /*
5396 ** 2022-11-16
5397 **
5398 ** The author disclaims copyright to this source code.  In place of
5399 ** a legal notice, here is a blessing:
5400 **
5401 **    May you do good and not evil.
5402 **    May you find forgiveness for yourself and forgive others.
5403 **    May you share freely, never taking more than you give.
5404 **
5405 *************************************************************************
5406 **
5407 ** This is a utility for converting binary to base85 or vice-versa.
5408 ** It can be built as a standalone program or an SQLite3 extension.
5409 **
5410 ** Much like base64 representations, base85 can be sent through a
5411 ** sane USASCII channel unmolested. It also plays nicely in CSV or
5412 ** written as TCL brace-enclosed literals or SQL string literals.
5413 ** It is not suited for unmodified use in XML-like documents.
5414 **
5415 ** The encoding used resembles Ascii85, but was devised by the author
5416 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
5417 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
5418 ** Further, this is an independent implementation of a base85 system.
5419 ** Hence, the author has rightfully put this into the public domain.
5420 **
5421 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
5422 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
5423 ** in code order representing digit values 0 to 84 (base 10.)
5424 **
5425 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
5426 ** are represented as 5-digit base85 numbers with MS to LS digit
5427 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
5428 ** still big-endian but 8-24 bit values. (Using big-endian yields
5429 ** the simplest transition to byte groups smaller than 4 bytes.
5430 ** These byte groups can also be considered base-256 numbers.)
5431 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
5432 ** No pad characters are used; Encoded base85 numeral sequence
5433 ** (aka "group") length maps 1-to-1 to the decoded binary length.
5434 **
5435 ** Any character not in the base85 numeral set delimits groups.
5436 ** When base85 is streamed or stored in containers of indefinite
5437 ** size, newline is used to separate it into sub-sequences of no
5438 ** more than 80 digits so that fgets() can be used to read it.
5439 **
5440 ** Length limitations are not imposed except that the runtime
5441 ** SQLite string or blob length limits are respected. Otherwise,
5442 ** any length binary sequence can be represented and recovered.
5443 ** Base85 sequences can be concatenated by separating them with
5444 ** a non-base85 character; the conversion to binary will then
5445 ** be the concatenation of the represented binary sequences.
5446 
5447 ** The standalone program either converts base85 on stdin to create
5448 ** a binary file or converts a binary file to base85 on stdout.
5449 ** Read or make it blurt its help for invocation details.
5450 **
5451 ** The SQLite3 extension creates a function, base85(x), which will
5452 ** either convert text base85 to a blob or a blob to text base85
5453 ** and return the result (or throw an error for other types.)
5454 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
5455 ** function, is_base85(t), which returns 1 iff the text t contains
5456 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
5457 **
5458 ** To build the extension:
5459 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
5460 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
5461 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
5462 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
5463 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
5464 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
5465 **
5466 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
5467 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
5468 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
5469 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
5470 */
5471 
5472 #include <stdio.h>
5473 #include <memory.h>
5474 #include <string.h>
5475 #include <assert.h>
5476 #ifndef OMIT_BASE85_CHECKER
5477 # include <ctype.h>
5478 #endif
5479 
5480 #ifndef BASE85_STANDALONE
5481 
5482 /* # include "sqlite3ext.h" */
5483 
5484 SQLITE_EXTENSION_INIT1;
5485 
5486 #else
5487 
5488 # ifdef _WIN32
5489 #  include <io.h>
5490 #  include <fcntl.h>
5491 # else
5492 #  define setmode(fd,m)
5493 # endif
5494 
5495 static char *zHelp =
5496   "Usage: base85 <dirFlag> <binFile>\n"
5497   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
5498   "   content to be converted to/from base85 on stdout/stdin.\n"
5499   " <binFile> names a binary file to be rendered or created.\n"
5500   "   Or, the name '-' refers to the stdin or stdout stream.\n"
5501   ;
5502 
sayHelp()5503 static void sayHelp(){
5504   printf("%s", zHelp);
5505 }
5506 #endif
5507 
5508 #ifndef U8_TYPEDEF
5509 /* typedef unsigned char u8; */
5510 #define U8_TYPEDEF
5511 #endif
5512 
5513 /* Classify c according to interval within USASCII set w.r.t. base85
5514  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
5515  */
5516 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
5517 
5518 /* Provide digitValue to b85Numeral offset as a function of above class. */
5519 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
5520 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
5521 
5522 /* Say whether c is a base85 numeral. */
5523 #define IS_B85( c ) (B85_CLASS(c) & 1)
5524 
5525 #if 0 /* Not used, */
5526 static u8 base85DigitValue( char c ){
5527   u8 dv = (u8)(c - '#');
5528   if( dv>87 ) return 0xff;
5529   return (dv > 3)? dv-3 : dv;
5530 }
5531 #endif
5532 
5533 /* Width of base64 lines. Should be an integer multiple of 5. */
5534 #define B85_DARK_MAX 80
5535 
5536 
skipNonB85(char * s,int nc)5537 static char * skipNonB85( char *s, int nc ){
5538   char c;
5539   while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
5540   return s;
5541 }
5542 
5543 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
5544  * Do not use the macro form with argument expression having a side-effect.*/
5545 #if 0
5546 static char base85Numeral( u8 b ){
5547   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
5548 }
5549 #else
5550 # define base85Numeral( dn )\
5551   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
5552 #endif
5553 
putcs(char * pc,char * s)5554 static char *putcs(char *pc, char *s){
5555   char c;
5556   while( (c = *s++)!=0 ) *pc++ = c;
5557   return pc;
5558 }
5559 
5560 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
5561 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
5562 ** or to terminate the last group (to aid concatenation.)
5563 */
toBase85(u8 * pIn,int nbIn,char * pOut,char * pSep)5564 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
5565   int nCol = 0;
5566   while( nbIn >= 4 ){
5567     int nco = 5;
5568     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
5569                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
5570     while( nco > 0 ){
5571       unsigned nqv = (unsigned)(qbv/85UL);
5572       unsigned char dv = qbv - 85UL*nqv;
5573       qbv = nqv;
5574       pOut[--nco] = base85Numeral(dv);
5575     }
5576     nbIn -= 4;
5577     pIn += 4;
5578     pOut += 5;
5579     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
5580       pOut = putcs(pOut, pSep);
5581       nCol = 0;
5582     }
5583   }
5584   if( nbIn > 0 ){
5585     int nco = nbIn + 1;
5586     unsigned long qv = *pIn++;
5587     int nbe = 1;
5588     while( nbe++ < nbIn ){
5589       qv = (qv<<8) | *pIn++;
5590     }
5591     nCol += nco;
5592     while( nco > 0 ){
5593       u8 dv = (u8)(qv % 85);
5594       qv /= 85;
5595       pOut[--nco] = base85Numeral(dv);
5596     }
5597     pOut += (nbIn+1);
5598   }
5599   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
5600   *pOut = 0;
5601   return pOut;
5602 }
5603 
5604 /* Decode base85 text into a byte buffer. */
fromBase85(char * pIn,int ncIn,u8 * pOut)5605 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
5606   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
5607   while( ncIn>0 ){
5608     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
5609     char *pUse = skipNonB85(pIn, ncIn);
5610     unsigned long qv = 0L;
5611     int nti, nbo;
5612     ncIn -= (pUse - pIn);
5613     pIn = pUse;
5614     nti = (ncIn>5)? 5 : ncIn;
5615     nbo = nboi[nti];
5616     if( nbo==0 ) break;
5617     while( nti>0 ){
5618       char c = *pIn++;
5619       u8 cdo = B85_DNOS(c);
5620       --ncIn;
5621       if( cdo==0 ) break;
5622       qv = 85 * qv + (c - cdo);
5623       --nti;
5624     }
5625     nbo -= nti; /* Adjust for early (non-digit) end of group. */
5626     switch( nbo ){
5627     case 4:
5628       *pOut++ = (qv >> 24)&0xff;
5629       /* FALLTHRU */
5630     case 3:
5631       *pOut++ = (qv >> 16)&0xff;
5632       /* FALLTHRU */
5633     case 2:
5634       *pOut++ = (qv >> 8)&0xff;
5635       /* FALLTHRU */
5636     case 1:
5637       *pOut++ = qv&0xff;
5638       /* FALLTHRU */
5639     case 0:
5640       break;
5641     }
5642   }
5643   return pOut;
5644 }
5645 
5646 #ifndef OMIT_BASE85_CHECKER
5647 /* Say whether input char sequence is all (base85 and/or whitespace).*/
allBase85(char * p,int len)5648 static int allBase85( char *p, int len ){
5649   char c;
5650   while( len-- > 0 && (c = *p++) != 0 ){
5651     if( !IS_B85(c) && !isspace(c) ) return 0;
5652   }
5653   return 1;
5654 }
5655 #endif
5656 
5657 #ifndef BASE85_STANDALONE
5658 
5659 # ifndef OMIT_BASE85_CHECKER
5660 /* This function does the work for the SQLite is_base85(t) UDF. */
is_base85(sqlite3_context * context,int na,sqlite3_value * av[])5661 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5662   assert(na==1);
5663   switch( sqlite3_value_type(av[0]) ){
5664   case SQLITE_TEXT:
5665     {
5666       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
5667                           sqlite3_value_bytes(av[0]) );
5668       sqlite3_result_int(context, rv);
5669     }
5670     break;
5671   case SQLITE_NULL:
5672     sqlite3_result_null(context);
5673     break;
5674   default:
5675     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
5676     return;
5677   }
5678 }
5679 # endif
5680 
5681 /* This function does the work for the SQLite base85(x) UDF. */
base85(sqlite3_context * context,int na,sqlite3_value * av[])5682 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5683   int nb, nc, nv = sqlite3_value_bytes(av[0]);
5684   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
5685                             SQLITE_LIMIT_LENGTH, -1);
5686   char *cBuf;
5687   u8 *bBuf;
5688   assert(na==1);
5689   switch( sqlite3_value_type(av[0]) ){
5690   case SQLITE_BLOB:
5691     nb = nv;
5692     /*    ulongs    tail   newlines  tailenc+nul*/
5693     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
5694     if( nvMax < nc ){
5695       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
5696       return;
5697     }
5698     bBuf = (u8*)sqlite3_value_blob(av[0]);
5699     if( !bBuf ){
5700       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5701         goto memFail;
5702       }
5703       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
5704       break;
5705     }
5706     cBuf = sqlite3_malloc(nc);
5707     if( !cBuf ) goto memFail;
5708     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
5709     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
5710     break;
5711   case SQLITE_TEXT:
5712     nc = nv;
5713     nb = 4*(nv/5) + nv%5; /* may overestimate */
5714     if( nvMax < nb ){
5715       sqlite3_result_error(context, "blob from base85 may be too big", -1);
5716       return;
5717     }else if( nb<1 ){
5718       nb = 1;
5719     }
5720     cBuf = (char *)sqlite3_value_text(av[0]);
5721     if( !cBuf ){
5722       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5723         goto memFail;
5724       }
5725       sqlite3_result_zeroblob(context, 0);
5726       break;
5727     }
5728     bBuf = sqlite3_malloc(nb);
5729     if( !bBuf ) goto memFail;
5730     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
5731     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
5732     break;
5733   default:
5734     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
5735     return;
5736   }
5737   return;
5738  memFail:
5739   sqlite3_result_error(context, "base85 OOM", -1);
5740 }
5741 
5742 /*
5743 ** Establish linkage to running SQLite library.
5744 */
5745 #ifndef SQLITE_SHELL_EXTFUNCS
5746 #ifdef _WIN32
5747 
5748 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)5749 int sqlite3_base_init
5750 #else
5751 static int sqlite3_base85_init
5752 #endif
5753 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
5754   SQLITE_EXTENSION_INIT2(pApi);
5755   (void)pzErr;
5756 # ifndef OMIT_BASE85_CHECKER
5757   {
5758     int rc = sqlite3_create_function
5759       (db, "is_base85", 1,
5760        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
5761        0, is_base85, 0, 0);
5762     if( rc!=SQLITE_OK ) return rc;
5763   }
5764 # endif
5765   return sqlite3_create_function
5766     (db, "base85", 1,
5767      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
5768      0, base85, 0, 0);
5769 }
5770 
5771 /*
5772 ** Define some macros to allow this extension to be built into the shell
5773 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
5774 ** allows shell.c, as distributed, to have this extension built in.
5775 */
5776 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
5777 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
5778 
5779 #else /* standalone program */
5780 
main(int na,char * av[])5781 int main(int na, char *av[]){
5782   int cin;
5783   int rc = 0;
5784   u8 bBuf[4*(B85_DARK_MAX/5)];
5785   char cBuf[5*(sizeof(bBuf)/4)+2];
5786   size_t nio;
5787 # ifndef OMIT_BASE85_CHECKER
5788   int b85Clean = 1;
5789 # endif
5790   char rw;
5791   FILE *fb = 0, *foc = 0;
5792   char fmode[3] = "xb";
5793   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
5794     sayHelp();
5795     return 0;
5796   }
5797   fmode[0] = rw;
5798   if( av[2][0]=='-' && av[2][1]==0 ){
5799     switch( rw ){
5800     case 'r':
5801       fb = stdin;
5802       setmode(fileno(stdin), O_BINARY);
5803       break;
5804     case 'w':
5805       fb = stdout;
5806       setmode(fileno(stdout), O_BINARY);
5807       break;
5808     }
5809   }else{
5810     fb = fopen(av[2], fmode);
5811     foc = fb;
5812   }
5813   if( !fb ){
5814     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
5815     rc = 1;
5816   }else{
5817     switch( rw ){
5818     case 'r':
5819       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
5820         toBase85( bBuf, (int)nio, cBuf, 0 );
5821         fprintf(stdout, "%s\n", cBuf);
5822       }
5823       break;
5824     case 'w':
5825       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
5826         int nc = strlen(cBuf);
5827         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
5828         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
5829 # ifndef OMIT_BASE85_CHECKER
5830         b85Clean &= allBase85( cBuf, nc );
5831 # endif
5832       }
5833       break;
5834     default:
5835       sayHelp();
5836       rc = 1;
5837     }
5838     if( foc ) fclose(foc);
5839   }
5840 # ifndef OMIT_BASE85_CHECKER
5841   if( !b85Clean ){
5842     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
5843   }
5844 # endif
5845   return rc;
5846 }
5847 
5848 #endif
5849 
5850 /************************* End ../ext/misc/base85.c ********************/
5851 /************************* Begin ../ext/misc/ieee754.c ******************/
5852 /*
5853 ** 2013-04-17
5854 **
5855 ** The author disclaims copyright to this source code.  In place of
5856 ** a legal notice, here is a blessing:
5857 **
5858 **    May you do good and not evil.
5859 **    May you find forgiveness for yourself and forgive others.
5860 **    May you share freely, never taking more than you give.
5861 **
5862 ******************************************************************************
5863 **
5864 ** This SQLite extension implements functions for the exact display
5865 ** and input of IEEE754 Binary64 floating-point numbers.
5866 **
5867 **   ieee754(X)
5868 **   ieee754(Y,Z)
5869 **
5870 ** In the first form, the value X should be a floating-point number.
5871 ** The function will return a string of the form 'ieee754(Y,Z)' where
5872 ** Y and Z are integers such that X==Y*pow(2,Z).
5873 **
5874 ** In the second form, Y and Z are integers which are the mantissa and
5875 ** base-2 exponent of a new floating point number.  The function returns
5876 ** a floating-point value equal to Y*pow(2,Z).
5877 **
5878 ** Examples:
5879 **
5880 **     ieee754(2.0)             ->     'ieee754(2,0)'
5881 **     ieee754(45.25)           ->     'ieee754(181,-2)'
5882 **     ieee754(2, 0)            ->     2.0
5883 **     ieee754(181, -2)         ->     45.25
5884 **
5885 ** Two additional functions break apart the one-argument ieee754()
5886 ** result into separate integer values:
5887 **
5888 **     ieee754_mantissa(45.25)  ->     181
5889 **     ieee754_exponent(45.25)  ->     -2
5890 **
5891 ** These functions convert binary64 numbers into blobs and back again.
5892 **
5893 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5894 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5895 **
5896 ** In all single-argument functions, if the argument is an 8-byte blob
5897 ** then that blob is interpreted as a big-endian binary64 value.
5898 **
5899 **
5900 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5901 ** -----------------------------------------------
5902 **
5903 ** This extension in combination with the separate 'decimal' extension
5904 ** can be used to compute the exact decimal representation of binary64
5905 ** values.  To begin, first compute a table of exponent values:
5906 **
5907 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5908 **    WITH RECURSIVE c(x,v) AS (
5909 **      VALUES(0,'1')
5910 **      UNION ALL
5911 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5912 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5913 **    WITH RECURSIVE c(x,v) AS (
5914 **      VALUES(-1,'0.5')
5915 **      UNION ALL
5916 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5917 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5918 **
5919 ** Then, to compute the exact decimal representation of a floating
5920 ** point value (the value 47.49 is used in the example) do:
5921 **
5922 **    WITH c(n) AS (VALUES(47.49))
5923 **          ---------------^^^^^---- Replace with whatever you want
5924 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5925 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5926 **
5927 ** Here is a query to show various boundry values for the binary64
5928 ** number format:
5929 **
5930 **    WITH c(name,bin) AS (VALUES
5931 **       ('minimum positive value',        x'0000000000000001'),
5932 **       ('maximum subnormal value',       x'000fffffffffffff'),
5933 **       ('minimum positive normal value', x'0010000000000000'),
5934 **       ('maximum value',                 x'7fefffffffffffff'))
5935 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5936 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5937 **
5938 */
5939 /* #include "sqlite3ext.h" */
5940 SQLITE_EXTENSION_INIT1
5941 #include <assert.h>
5942 #include <string.h>
5943 
5944 /* Mark a function parameter as unused, to suppress nuisance compiler
5945 ** warnings. */
5946 #ifndef UNUSED_PARAMETER
5947 # define UNUSED_PARAMETER(X)  (void)(X)
5948 #endif
5949 
5950 /*
5951 ** Implementation of the ieee754() function
5952 */
ieee754func(sqlite3_context * context,int argc,sqlite3_value ** argv)5953 static void ieee754func(
5954   sqlite3_context *context,
5955   int argc,
5956   sqlite3_value **argv
5957 ){
5958   if( argc==1 ){
5959     sqlite3_int64 m, a;
5960     double r;
5961     int e;
5962     int isNeg;
5963     char zResult[100];
5964     assert( sizeof(m)==sizeof(r) );
5965     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5966      && sqlite3_value_bytes(argv[0])==sizeof(r)
5967     ){
5968       const unsigned char *x = sqlite3_value_blob(argv[0]);
5969       unsigned int i;
5970       sqlite3_uint64 v = 0;
5971       for(i=0; i<sizeof(r); i++){
5972         v = (v<<8) | x[i];
5973       }
5974       memcpy(&r, &v, sizeof(r));
5975     }else{
5976       r = sqlite3_value_double(argv[0]);
5977     }
5978     if( r<0.0 ){
5979       isNeg = 1;
5980       r = -r;
5981     }else{
5982       isNeg = 0;
5983     }
5984     memcpy(&a,&r,sizeof(a));
5985     if( a==0 ){
5986       e = 0;
5987       m = 0;
5988     }else{
5989       e = a>>52;
5990       m = a & ((((sqlite3_int64)1)<<52)-1);
5991       if( e==0 ){
5992         m <<= 1;
5993       }else{
5994         m |= ((sqlite3_int64)1)<<52;
5995       }
5996       while( e<1075 && m>0 && (m&1)==0 ){
5997         m >>= 1;
5998         e++;
5999       }
6000       if( isNeg ) m = -m;
6001     }
6002     switch( *(int*)sqlite3_user_data(context) ){
6003       case 0:
6004         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
6005                          m, e-1075);
6006         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
6007         break;
6008       case 1:
6009         sqlite3_result_int64(context, m);
6010         break;
6011       case 2:
6012         sqlite3_result_int(context, e-1075);
6013         break;
6014     }
6015   }else{
6016     sqlite3_int64 m, e, a;
6017     double r;
6018     int isNeg = 0;
6019     m = sqlite3_value_int64(argv[0]);
6020     e = sqlite3_value_int64(argv[1]);
6021 
6022     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
6023     if( e>10000 ){
6024       e = 10000;
6025     }else if( e<-10000 ){
6026       e = -10000;
6027     }
6028 
6029     if( m<0 ){
6030       isNeg = 1;
6031       m = -m;
6032       if( m<0 ) return;
6033     }else if( m==0 && e>-1000 && e<1000 ){
6034       sqlite3_result_double(context, 0.0);
6035       return;
6036     }
6037     while( (m>>32)&0xffe00000 ){
6038       m >>= 1;
6039       e++;
6040     }
6041     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
6042       m <<= 1;
6043       e--;
6044     }
6045     e += 1075;
6046     if( e<=0 ){
6047       /* Subnormal */
6048       if( 1-e >= 64 ){
6049         m = 0;
6050       }else{
6051         m >>= 1-e;
6052       }
6053       e = 0;
6054     }else if( e>0x7ff ){
6055       e = 0x7ff;
6056     }
6057     a = m & ((((sqlite3_int64)1)<<52)-1);
6058     a |= e<<52;
6059     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
6060     memcpy(&r, &a, sizeof(r));
6061     sqlite3_result_double(context, r);
6062   }
6063 }
6064 
6065 /*
6066 ** Functions to convert between blobs and floats.
6067 */
ieee754func_from_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)6068 static void ieee754func_from_blob(
6069   sqlite3_context *context,
6070   int argc,
6071   sqlite3_value **argv
6072 ){
6073   UNUSED_PARAMETER(argc);
6074   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
6075    && sqlite3_value_bytes(argv[0])==sizeof(double)
6076   ){
6077     double r;
6078     const unsigned char *x = sqlite3_value_blob(argv[0]);
6079     unsigned int i;
6080     sqlite3_uint64 v = 0;
6081     for(i=0; i<sizeof(r); i++){
6082       v = (v<<8) | x[i];
6083     }
6084     memcpy(&r, &v, sizeof(r));
6085     sqlite3_result_double(context, r);
6086   }
6087 }
ieee754func_to_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)6088 static void ieee754func_to_blob(
6089   sqlite3_context *context,
6090   int argc,
6091   sqlite3_value **argv
6092 ){
6093   UNUSED_PARAMETER(argc);
6094   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
6095    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
6096   ){
6097     double r = sqlite3_value_double(argv[0]);
6098     sqlite3_uint64 v;
6099     unsigned char a[sizeof(r)];
6100     unsigned int i;
6101     memcpy(&v, &r, sizeof(r));
6102     for(i=1; i<=sizeof(r); i++){
6103       a[sizeof(r)-i] = v&0xff;
6104       v >>= 8;
6105     }
6106     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
6107   }
6108 }
6109 
6110 /*
6111 ** SQL Function:   ieee754_inc(r,N)
6112 **
6113 ** Move the floating point value r by N quantums and return the new
6114 ** values.
6115 **
6116 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
6117 ** integer, adds N, then casts the value back into float.
6118 **
6119 ** Example:  To find the smallest positive number:
6120 **
6121 **     SELECT ieee754_inc(0.0,+1);
6122 */
ieee754inc(sqlite3_context * context,int argc,sqlite3_value ** argv)6123 static void ieee754inc(
6124   sqlite3_context *context,
6125   int argc,
6126   sqlite3_value **argv
6127 ){
6128   double r;
6129   sqlite3_int64 N;
6130   sqlite3_uint64 m1, m2;
6131   double r2;
6132   UNUSED_PARAMETER(argc);
6133   r = sqlite3_value_double(argv[0]);
6134   N = sqlite3_value_int64(argv[1]);
6135   memcpy(&m1, &r, 8);
6136   m2 = m1 + N;
6137   memcpy(&r2, &m2, 8);
6138   sqlite3_result_double(context, r2);
6139 }
6140 
6141 
6142 #ifdef _WIN32
6143 
6144 #endif
sqlite3_ieee_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)6145 int sqlite3_ieee_init(
6146   sqlite3 *db,
6147   char **pzErrMsg,
6148   const sqlite3_api_routines *pApi
6149 ){
6150   static const struct {
6151     char *zFName;
6152     int nArg;
6153     int iAux;
6154     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
6155   } aFunc[] = {
6156     { "ieee754",           1,   0, ieee754func },
6157     { "ieee754",           2,   0, ieee754func },
6158     { "ieee754_mantissa",  1,   1, ieee754func },
6159     { "ieee754_exponent",  1,   2, ieee754func },
6160     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
6161     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
6162     { "ieee754_inc",       2,   0, ieee754inc  },
6163   };
6164   unsigned int i;
6165   int rc = SQLITE_OK;
6166   SQLITE_EXTENSION_INIT2(pApi);
6167   (void)pzErrMsg;  /* Unused parameter */
6168   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
6169     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
6170                                SQLITE_UTF8|SQLITE_INNOCUOUS,
6171                                (void*)&aFunc[i].iAux,
6172                                aFunc[i].xFunc, 0, 0);
6173   }
6174   return rc;
6175 }
6176 
6177 /************************* End ../ext/misc/ieee754.c ********************/
6178 /************************* Begin ../ext/misc/series.c ******************/
6179 /*
6180 ** 2015-08-18, 2023-04-28
6181 **
6182 ** The author disclaims copyright to this source code.  In place of
6183 ** a legal notice, here is a blessing:
6184 **
6185 **    May you do good and not evil.
6186 **    May you find forgiveness for yourself and forgive others.
6187 **    May you share freely, never taking more than you give.
6188 **
6189 *************************************************************************
6190 **
6191 ** This file demonstrates how to create a table-valued-function using
6192 ** a virtual table.  This demo implements the generate_series() function
6193 ** which gives the same results as the eponymous function in PostgreSQL,
6194 ** within the limitation that its arguments are signed 64-bit integers.
6195 **
6196 ** Considering its equivalents to generate_series(start,stop,step): A
6197 ** value V[n] sequence is produced for integer n ascending from 0 where
6198 **  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
6199 ** for each produced value (independent of production time ordering.)
6200 **
6201 ** All parameters must be either integer or convertable to integer.
6202 ** The start parameter is required.
6203 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
6204 ** The step parameter defaults to 1 and 0 is treated as 1.
6205 **
6206 ** Examples:
6207 **
6208 **      SELECT * FROM generate_series(0,100,5);
6209 **
6210 ** The query above returns integers from 0 through 100 counting by steps
6211 ** of 5.
6212 **
6213 **      SELECT * FROM generate_series(0,100);
6214 **
6215 ** Integers from 0 through 100 with a step size of 1.
6216 **
6217 **      SELECT * FROM generate_series(20) LIMIT 10;
6218 **
6219 ** Integers 20 through 29.
6220 **
6221 **      SELECT * FROM generate_series(0,-100,-5);
6222 **
6223 ** Integers 0 -5 -10 ... -100.
6224 **
6225 **      SELECT * FROM generate_series(0,-1);
6226 **
6227 ** Empty sequence.
6228 **
6229 ** HOW IT WORKS
6230 **
6231 ** The generate_series "function" is really a virtual table with the
6232 ** following schema:
6233 **
6234 **     CREATE TABLE generate_series(
6235 **       value,
6236 **       start HIDDEN,
6237 **       stop HIDDEN,
6238 **       step HIDDEN
6239 **     );
6240 **
6241 ** The virtual table also has a rowid which is an alias for the value.
6242 **
6243 ** Function arguments in queries against this virtual table are translated
6244 ** into equality constraints against successive hidden columns.  In other
6245 ** words, the following pairs of queries are equivalent to each other:
6246 **
6247 **    SELECT * FROM generate_series(0,100,5);
6248 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
6249 **
6250 **    SELECT * FROM generate_series(0,100);
6251 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
6252 **
6253 **    SELECT * FROM generate_series(20) LIMIT 10;
6254 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
6255 **
6256 ** The generate_series virtual table implementation leaves the xCreate method
6257 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
6258 ** TABLE command with "generate_series" as the USING argument.  Instead, there
6259 ** is a single generate_series virtual table that is always available without
6260 ** having to be created first.
6261 **
6262 ** The xBestIndex method looks for equality constraints against the hidden
6263 ** start, stop, and step columns, and if present, it uses those constraints
6264 ** to bound the sequence of generated values.  If the equality constraints
6265 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
6266 ** xBestIndex returns a small cost when both start and stop are available,
6267 ** and a very large cost if either start or stop are unavailable.  This
6268 ** encourages the query planner to order joins such that the bounds of the
6269 ** series are well-defined.
6270 **
6271 ** Update on 2024-08-22:
6272 ** xBestIndex now also looks for equality and inequality constraints against
6273 ** the value column and uses those constraints as additional bounds against
6274 ** the sequence range.  Thus, a query like this:
6275 **
6276 **     SELECT value FROM generate_series($SA,$EA)
6277 **      WHERE value BETWEEN $SB AND $EB;
6278 **
6279 ** Is logically the same as:
6280 **
6281 **     SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB));
6282 **
6283 ** Constraints on the value column can server as substitutes for constraints
6284 ** on the hidden start and stop columns.  So, the following two queries
6285 ** are equivalent:
6286 **
6287 **     SELECT value FROM generate_series($S,$E);
6288 **     SELECT value FROM generate_series WHERE value BETWEEN $S and $E;
6289 **
6290 */
6291 /* #include "sqlite3ext.h" */
6292 SQLITE_EXTENSION_INIT1
6293 #include <assert.h>
6294 #include <string.h>
6295 #include <limits.h>
6296 #include <math.h>
6297 
6298 #ifndef SQLITE_OMIT_VIRTUALTABLE
6299 /*
6300 ** Return that member of a generate_series(...) sequence whose 0-based
6301 ** index is ix. The 0th member is given by smBase. The sequence members
6302 ** progress per ix increment by smStep.
6303 */
genSeqMember(sqlite3_int64 smBase,sqlite3_int64 smStep,sqlite3_uint64 ix)6304 static sqlite3_int64 genSeqMember(
6305   sqlite3_int64 smBase,
6306   sqlite3_int64 smStep,
6307   sqlite3_uint64 ix
6308 ){
6309   static const sqlite3_uint64 mxI64 =
6310       ((sqlite3_uint64)0x7fffffff)<<32 | 0xffffffff;
6311   if( ix>=mxI64 ){
6312     /* Get ix into signed i64 range. */
6313     ix -= mxI64;
6314     /* With 2's complement ALU, this next can be 1 step, but is split into
6315      * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
6316     smBase += (mxI64/2) * smStep;
6317     smBase += (mxI64 - mxI64/2) * smStep;
6318   }
6319   /* Under UBSAN (or on 1's complement machines), must do this last term
6320    * in steps to avoid the dreaded (and harmless) signed multiply overflow. */
6321   if( ix>=2 ){
6322     sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
6323     smBase += ix2*smStep;
6324     ix -= ix2;
6325   }
6326   return smBase + ((sqlite3_int64)ix)*smStep;
6327 }
6328 
6329 /* typedef unsigned char u8; */
6330 
6331 typedef struct SequenceSpec {
6332   sqlite3_int64 iOBase;        /* Original starting value ("start") */
6333   sqlite3_int64 iOTerm;        /* Original terminal value ("stop") */
6334   sqlite3_int64 iBase;         /* Starting value to actually use */
6335   sqlite3_int64 iTerm;         /* Terminal value to actually use */
6336   sqlite3_int64 iStep;         /* Increment ("step") */
6337   sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
6338   sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
6339   sqlite3_int64 iValueNow;     /* Current value during generation */
6340   u8 isNotEOF;                 /* Sequence generation not exhausted */
6341   u8 isReversing;              /* Sequence is being reverse generated */
6342 } SequenceSpec;
6343 
6344 /*
6345 ** Prepare a SequenceSpec for use in generating an integer series
6346 ** given initialized iBase, iTerm and iStep values. Sequence is
6347 ** initialized per given isReversing. Other members are computed.
6348 */
setupSequence(SequenceSpec * pss)6349 static void setupSequence( SequenceSpec *pss ){
6350   int bSameSigns;
6351   pss->uSeqIndexMax = 0;
6352   pss->isNotEOF = 0;
6353   bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
6354   if( pss->iTerm < pss->iBase ){
6355     sqlite3_uint64 nuspan = 0;
6356     if( bSameSigns ){
6357       nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
6358     }else{
6359       /* Under UBSAN (or on 1's complement machines), must do this in steps.
6360        * In this clause, iBase>=0 and iTerm<0 . */
6361       nuspan = 1;
6362       nuspan += pss->iBase;
6363       nuspan += -(pss->iTerm+1);
6364     }
6365     if( pss->iStep<0 ){
6366       pss->isNotEOF = 1;
6367       if( nuspan==ULONG_MAX ){
6368         pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
6369       }else if( pss->iStep>LLONG_MIN ){
6370         pss->uSeqIndexMax = nuspan/-pss->iStep;
6371       }
6372     }
6373   }else if( pss->iTerm > pss->iBase ){
6374     sqlite3_uint64 puspan = 0;
6375     if( bSameSigns ){
6376       puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
6377     }else{
6378       /* Under UBSAN (or on 1's complement machines), must do this in steps.
6379        * In this clause, iTerm>=0 and iBase<0 . */
6380       puspan = 1;
6381       puspan += pss->iTerm;
6382       puspan += -(pss->iBase+1);
6383     }
6384     if( pss->iStep>0 ){
6385       pss->isNotEOF = 1;
6386       pss->uSeqIndexMax = puspan/pss->iStep;
6387     }
6388   }else if( pss->iTerm == pss->iBase ){
6389       pss->isNotEOF = 1;
6390       pss->uSeqIndexMax = 0;
6391   }
6392   pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
6393   pss->iValueNow = (pss->isReversing)
6394     ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
6395     : pss->iBase;
6396 }
6397 
6398 /*
6399 ** Progress sequence generator to yield next value, if any.
6400 ** Leave its state to either yield next value or be at EOF.
6401 ** Return whether there is a next value, or 0 at EOF.
6402 */
progressSequence(SequenceSpec * pss)6403 static int progressSequence( SequenceSpec *pss ){
6404   if( !pss->isNotEOF ) return 0;
6405   if( pss->isReversing ){
6406     if( pss->uSeqIndexNow > 0 ){
6407       pss->uSeqIndexNow--;
6408       pss->iValueNow -= pss->iStep;
6409     }else{
6410       pss->isNotEOF = 0;
6411     }
6412   }else{
6413     if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
6414       pss->uSeqIndexNow++;
6415       pss->iValueNow += pss->iStep;
6416     }else{
6417       pss->isNotEOF = 0;
6418     }
6419   }
6420   return pss->isNotEOF;
6421 }
6422 
6423 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
6424 ** serve as the underlying representation of a cursor that scans
6425 ** over rows of the result
6426 */
6427 typedef struct series_cursor series_cursor;
6428 struct series_cursor {
6429   sqlite3_vtab_cursor base;  /* Base class - must be first */
6430   SequenceSpec ss;           /* (this) Derived class data */
6431 };
6432 
6433 /*
6434 ** The seriesConnect() method is invoked to create a new
6435 ** series_vtab that describes the generate_series virtual table.
6436 **
6437 ** Think of this routine as the constructor for series_vtab objects.
6438 **
6439 ** All this routine needs to do is:
6440 **
6441 **    (1) Allocate the series_vtab object and initialize all fields.
6442 **
6443 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
6444 **        result set of queries against generate_series will look like.
6445 */
seriesConnect(sqlite3 * db,void * pUnused,int argcUnused,const char * const * argvUnused,sqlite3_vtab ** ppVtab,char ** pzErrUnused)6446 static int seriesConnect(
6447   sqlite3 *db,
6448   void *pUnused,
6449   int argcUnused, const char *const*argvUnused,
6450   sqlite3_vtab **ppVtab,
6451   char **pzErrUnused
6452 ){
6453   sqlite3_vtab *pNew;
6454   int rc;
6455 
6456 /* Column numbers */
6457 #define SERIES_COLUMN_ROWID (-1)
6458 #define SERIES_COLUMN_VALUE 0
6459 #define SERIES_COLUMN_START 1
6460 #define SERIES_COLUMN_STOP  2
6461 #define SERIES_COLUMN_STEP  3
6462 
6463   (void)pUnused;
6464   (void)argcUnused;
6465   (void)argvUnused;
6466   (void)pzErrUnused;
6467   rc = sqlite3_declare_vtab(db,
6468      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
6469   if( rc==SQLITE_OK ){
6470     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
6471     if( pNew==0 ) return SQLITE_NOMEM;
6472     memset(pNew, 0, sizeof(*pNew));
6473     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
6474   }
6475   return rc;
6476 }
6477 
6478 /*
6479 ** This method is the destructor for series_cursor objects.
6480 */
seriesDisconnect(sqlite3_vtab * pVtab)6481 static int seriesDisconnect(sqlite3_vtab *pVtab){
6482   sqlite3_free(pVtab);
6483   return SQLITE_OK;
6484 }
6485 
6486 /*
6487 ** Constructor for a new series_cursor object.
6488 */
seriesOpen(sqlite3_vtab * pUnused,sqlite3_vtab_cursor ** ppCursor)6489 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
6490   series_cursor *pCur;
6491   (void)pUnused;
6492   pCur = sqlite3_malloc( sizeof(*pCur) );
6493   if( pCur==0 ) return SQLITE_NOMEM;
6494   memset(pCur, 0, sizeof(*pCur));
6495   *ppCursor = &pCur->base;
6496   return SQLITE_OK;
6497 }
6498 
6499 /*
6500 ** Destructor for a series_cursor.
6501 */
seriesClose(sqlite3_vtab_cursor * cur)6502 static int seriesClose(sqlite3_vtab_cursor *cur){
6503   sqlite3_free(cur);
6504   return SQLITE_OK;
6505 }
6506 
6507 
6508 /*
6509 ** Advance a series_cursor to its next row of output.
6510 */
seriesNext(sqlite3_vtab_cursor * cur)6511 static int seriesNext(sqlite3_vtab_cursor *cur){
6512   series_cursor *pCur = (series_cursor*)cur;
6513   progressSequence( & pCur->ss );
6514   return SQLITE_OK;
6515 }
6516 
6517 /*
6518 ** Return values of columns for the row at which the series_cursor
6519 ** is currently pointing.
6520 */
seriesColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)6521 static int seriesColumn(
6522   sqlite3_vtab_cursor *cur,   /* The cursor */
6523   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6524   int i                       /* Which column to return */
6525 ){
6526   series_cursor *pCur = (series_cursor*)cur;
6527   sqlite3_int64 x = 0;
6528   switch( i ){
6529     case SERIES_COLUMN_START:  x = pCur->ss.iOBase;     break;
6530     case SERIES_COLUMN_STOP:   x = pCur->ss.iOTerm;     break;
6531     case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;      break;
6532     default:                   x = pCur->ss.iValueNow;  break;
6533   }
6534   sqlite3_result_int64(ctx, x);
6535   return SQLITE_OK;
6536 }
6537 
6538 #ifndef LARGEST_UINT64
6539 #define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
6540 #define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32))
6541 #define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
6542 #endif
6543 
6544 /*
6545 ** The rowid is the same as the value.
6546 */
seriesRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)6547 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
6548   series_cursor *pCur = (series_cursor*)cur;
6549   *pRowid = pCur->ss.iValueNow;
6550   return SQLITE_OK;
6551 }
6552 
6553 /*
6554 ** Return TRUE if the cursor has been moved off of the last
6555 ** row of output.
6556 */
seriesEof(sqlite3_vtab_cursor * cur)6557 static int seriesEof(sqlite3_vtab_cursor *cur){
6558   series_cursor *pCur = (series_cursor*)cur;
6559   return !pCur->ss.isNotEOF;
6560 }
6561 
6562 /* True to cause run-time checking of the start=, stop=, and/or step=
6563 ** parameters.  The only reason to do this is for testing the
6564 ** constraint checking logic for virtual tables in the SQLite core.
6565 */
6566 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
6567 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
6568 #endif
6569 
6570 /*
6571 ** This method is called to "rewind" the series_cursor object back
6572 ** to the first row of output.  This method is always called at least
6573 ** once prior to any call to seriesColumn() or seriesRowid() or
6574 ** seriesEof().
6575 **
6576 ** The query plan selected by seriesBestIndex is passed in the idxNum
6577 ** parameter.  (idxStr is not used in this implementation.)  idxNum
6578 ** is a bitmask showing which constraints are available:
6579 **
6580 **   0x0001:    start=VALUE
6581 **   0x0002:    stop=VALUE
6582 **   0x0004:    step=VALUE
6583 **   0x0008:    descending order
6584 **   0x0010:    ascending order
6585 **   0x0020:    LIMIT  VALUE
6586 **   0x0040:    OFFSET  VALUE
6587 **   0x0080:    value=VALUE
6588 **   0x0100:    value>=VALUE
6589 **   0x0200:    value>VALUE
6590 **   0x1000:    value<=VALUE
6591 **   0x2000:    value<VALUE
6592 **
6593 ** This routine should initialize the cursor and position it so that it
6594 ** is pointing at the first row, or pointing off the end of the table
6595 ** (so that seriesEof() will return true) if the table is empty.
6596 */
seriesFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStrUnused,int argc,sqlite3_value ** argv)6597 static int seriesFilter(
6598   sqlite3_vtab_cursor *pVtabCursor,
6599   int idxNum, const char *idxStrUnused,
6600   int argc, sqlite3_value **argv
6601 ){
6602   series_cursor *pCur = (series_cursor *)pVtabCursor;
6603   int i = 0;
6604   int returnNoRows = 0;
6605   sqlite3_int64 iMin = SMALLEST_INT64;
6606   sqlite3_int64 iMax = LARGEST_INT64;
6607   sqlite3_int64 iLimit = 0;
6608   sqlite3_int64 iOffset = 0;
6609 
6610   (void)idxStrUnused;
6611   if( idxNum & 0x01 ){
6612     pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
6613   }else{
6614     pCur->ss.iBase = 0;
6615   }
6616   if( idxNum & 0x02 ){
6617     pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
6618   }else{
6619     pCur->ss.iTerm = 0xffffffff;
6620   }
6621   if( idxNum & 0x04 ){
6622     pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
6623     if( pCur->ss.iStep==0 ){
6624       pCur->ss.iStep = 1;
6625     }else if( pCur->ss.iStep<0 ){
6626       if( (idxNum & 0x10)==0 ) idxNum |= 0x08;
6627     }
6628   }else{
6629     pCur->ss.iStep = 1;
6630   }
6631 
6632   /* If there are constraints on the value column but there are
6633   ** no constraints on  the start, stop, and step columns, then
6634   ** initialize the default range to be the entire range of 64-bit signed
6635   ** integers.  This range will contracted by the value column constraints
6636   ** further below.
6637   */
6638   if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
6639     pCur->ss.iBase = SMALLEST_INT64;
6640   }
6641   if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
6642     pCur->ss.iTerm = LARGEST_INT64;
6643   }
6644   pCur->ss.iOBase = pCur->ss.iBase;
6645   pCur->ss.iOTerm = pCur->ss.iTerm;
6646 
6647   /* Extract the LIMIT and OFFSET values, but do not apply them yet.
6648   ** The range must first be constrained by the limits on value.
6649   */
6650   if( idxNum & 0x20 ){
6651     iLimit = sqlite3_value_int64(argv[i++]);
6652     if( idxNum & 0x40 ){
6653       iOffset = sqlite3_value_int64(argv[i++]);
6654     }
6655   }
6656 
6657   if( idxNum & 0x3380 ){
6658     /* Extract the maximum range of output values determined by
6659     ** constraints on the "value" column.
6660     */
6661     if( idxNum & 0x0080 ){
6662       if( sqlite3_value_numeric_type(argv[i])==SQLITE_FLOAT ){
6663         double r = sqlite3_value_double(argv[i++]);
6664         if( r==ceil(r) ){
6665           iMin = iMax = (sqlite3_int64)r;
6666         }else{
6667           returnNoRows = 1;
6668         }
6669       }else{
6670         iMin = iMax = sqlite3_value_int64(argv[i++]);
6671       }
6672     }else{
6673       if( idxNum & 0x0300 ){
6674         if( sqlite3_value_numeric_type(argv[i])==SQLITE_FLOAT ){
6675           double r = sqlite3_value_double(argv[i++]);
6676           if( idxNum & 0x0200 && r==ceil(r) ){
6677             iMin = (sqlite3_int64)ceil(r+1.0);
6678           }else{
6679             iMin = (sqlite3_int64)ceil(r);
6680           }
6681         }else{
6682           iMin = sqlite3_value_int64(argv[i++]);
6683           if( idxNum & 0x0200 ){
6684             if( iMin==LARGEST_INT64 ){
6685               returnNoRows = 1;
6686             }else{
6687               iMin++;
6688             }
6689           }
6690         }
6691       }
6692       if( idxNum & 0x3000 ){
6693         if( sqlite3_value_numeric_type(argv[i])==SQLITE_FLOAT ){
6694           double r = sqlite3_value_double(argv[i++]);
6695           if( (idxNum & 0x2000)!=0 && r==floor(r) ){
6696             iMax = (sqlite3_int64)(r-1.0);
6697           }else{
6698             iMax = (sqlite3_int64)floor(r);
6699           }
6700         }else{
6701           iMax = sqlite3_value_int64(argv[i++]);
6702           if( idxNum & 0x2000 ){
6703             if( iMax==SMALLEST_INT64 ){
6704               returnNoRows = 1;
6705             }else{
6706               iMax--;
6707             }
6708           }
6709         }
6710       }
6711       if( iMin>iMax ){
6712         returnNoRows = 1;
6713       }
6714     }
6715 
6716     /* Try to reduce the range of values to be generated based on
6717     ** constraints on the "value" column.
6718     */
6719     if( pCur->ss.iStep>0 ){
6720       sqlite3_int64 szStep = pCur->ss.iStep;
6721       if( pCur->ss.iBase<iMin ){
6722         sqlite3_uint64 d = iMin - pCur->ss.iBase;
6723         pCur->ss.iBase += ((d+szStep-1)/szStep)*szStep;
6724       }
6725       if( pCur->ss.iTerm>iMax ){
6726         pCur->ss.iTerm = iMax;
6727       }
6728     }else{
6729       sqlite3_int64 szStep = -pCur->ss.iStep;
6730       assert( szStep>0 );
6731       if( pCur->ss.iBase>iMax ){
6732         sqlite3_uint64 d = pCur->ss.iBase - iMax;
6733         pCur->ss.iBase -= ((d+szStep-1)/szStep)*szStep;
6734       }
6735       if( pCur->ss.iTerm<iMin ){
6736         pCur->ss.iTerm = iMin;
6737       }
6738     }
6739   }
6740 
6741   /* Apply LIMIT and OFFSET constraints, if any */
6742   if( idxNum & 0x20 ){
6743     if( iOffset>0 ){
6744       pCur->ss.iBase += pCur->ss.iStep*iOffset;
6745     }
6746     if( iLimit>=0 ){
6747       sqlite3_int64 iTerm;
6748       iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep;
6749       if( pCur->ss.iStep<0 ){
6750         if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
6751       }else{
6752         if( iTerm<pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
6753       }
6754     }
6755   }
6756 
6757 
6758   for(i=0; i<argc; i++){
6759     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
6760       /* If any of the constraints have a NULL value, then return no rows.
6761       ** See ticket https://sqlite.org/src/info/fac496b61722daf2 */
6762       returnNoRows = 1;
6763       break;
6764     }
6765   }
6766   if( returnNoRows ){
6767     pCur->ss.iBase = 1;
6768     pCur->ss.iTerm = 0;
6769     pCur->ss.iStep = 1;
6770   }
6771   if( idxNum & 0x08 ){
6772     pCur->ss.isReversing = pCur->ss.iStep > 0;
6773   }else{
6774     pCur->ss.isReversing = pCur->ss.iStep < 0;
6775   }
6776   setupSequence( &pCur->ss );
6777   return SQLITE_OK;
6778 }
6779 
6780 /*
6781 ** SQLite will invoke this method one or more times while planning a query
6782 ** that uses the generate_series virtual table.  This routine needs to create
6783 ** a query plan for each invocation and compute an estimated cost for that
6784 ** plan.
6785 **
6786 ** In this implementation idxNum is used to represent the
6787 ** query plan.  idxStr is unused.
6788 **
6789 ** The query plan is represented by bits in idxNum:
6790 **
6791 **   0x0001  start = $num
6792 **   0x0002  stop = $num
6793 **   0x0004  step = $num
6794 **   0x0008  output is in descending order
6795 **   0x0010  output is in ascending order
6796 **   0x0020  LIMIT $num
6797 **   0x0040  OFFSET $num
6798 **   0x0080  value = $num
6799 **   0x0100  value >= $num
6800 **   0x0200  value > $num
6801 **   0x1000  value <= $num
6802 **   0x2000  value < $num
6803 **
6804 ** Only one of 0x0100 or 0x0200 will be returned.  Similarly, only
6805 ** one of 0x1000 or 0x2000 will be returned.  If the 0x0080 is set, then
6806 ** none of the 0xff00 bits will be set.
6807 **
6808 ** The order of parameters passed to xFilter is as follows:
6809 **
6810 **    * The argument to start= if bit 0x0001 is in the idxNum mask
6811 **    * The argument to stop= if bit 0x0002 is in the idxNum mask
6812 **    * The argument to step= if bit 0x0004 is in the idxNum mask
6813 **    * The argument to LIMIT if bit 0x0020 is in the idxNum mask
6814 **    * The argument to OFFSET if bit 0x0040 is in the idxNum mask
6815 **    * The argument to value=, or value>= or value> if any of
6816 **      bits 0x0380 are in the idxNum mask
6817 **    * The argument to value<= or value< if either of bits 0x3000
6818 **      are in the mask
6819 **
6820 */
seriesBestIndex(sqlite3_vtab * pVTab,sqlite3_index_info * pIdxInfo)6821 static int seriesBestIndex(
6822   sqlite3_vtab *pVTab,
6823   sqlite3_index_info *pIdxInfo
6824 ){
6825   int i, j;              /* Loop over constraints */
6826   int idxNum = 0;        /* The query plan bitmask */
6827 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6828   int bStartSeen = 0;    /* EQ constraint seen on the START column */
6829 #endif
6830   int unusableMask = 0;  /* Mask of unusable constraints */
6831   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
6832   int aIdx[7];           /* Constraints on start, stop, step, LIMIT, OFFSET,
6833                          ** and value.  aIdx[5] covers value=, value>=, and
6834                          ** value>,  aIdx[6] covers value<= and value< */
6835   const struct sqlite3_index_constraint *pConstraint;
6836 
6837   /* This implementation assumes that the start, stop, and step columns
6838   ** are the last three columns in the virtual table. */
6839   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
6840   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
6841 
6842   aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
6843   pConstraint = pIdxInfo->aConstraint;
6844   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6845     int iCol;    /* 0 for start, 1 for stop, 2 for step */
6846     int iMask;   /* bitmask for those column */
6847     int op = pConstraint->op;
6848     if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
6849      && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
6850     ){
6851       if( pConstraint->usable==0 ){
6852         /* do nothing */
6853       }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
6854         aIdx[3] = i;
6855         idxNum |= 0x20;
6856       }else{
6857         assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
6858         aIdx[4] = i;
6859         idxNum |= 0x40;
6860       }
6861       continue;
6862     }
6863     if( pConstraint->iColumn<SERIES_COLUMN_START ){
6864       if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
6865            pConstraint->iColumn==SERIES_COLUMN_ROWID)
6866        && pConstraint->usable
6867       ){
6868         switch( op ){
6869           case SQLITE_INDEX_CONSTRAINT_EQ:
6870           case SQLITE_INDEX_CONSTRAINT_IS: {
6871             idxNum |=  0x0080;
6872             idxNum &= ~0x3300;
6873             aIdx[5] = i;
6874             aIdx[6] = -1;
6875 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6876             bStartSeen = 1;
6877 #endif
6878             break;
6879           }
6880           case SQLITE_INDEX_CONSTRAINT_GE: {
6881             if( idxNum & 0x0080 ) break;
6882             idxNum |=  0x0100;
6883             idxNum &= ~0x0200;
6884             aIdx[5] = i;
6885 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6886             bStartSeen = 1;
6887 #endif
6888             break;
6889           }
6890           case SQLITE_INDEX_CONSTRAINT_GT: {
6891             if( idxNum & 0x0080 ) break;
6892             idxNum |=  0x0200;
6893             idxNum &= ~0x0100;
6894             aIdx[5] = i;
6895 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6896             bStartSeen = 1;
6897 #endif
6898             break;
6899           }
6900           case SQLITE_INDEX_CONSTRAINT_LE: {
6901             if( idxNum & 0x0080 ) break;
6902             idxNum |=  0x1000;
6903             idxNum &= ~0x2000;
6904             aIdx[6] = i;
6905             break;
6906           }
6907           case SQLITE_INDEX_CONSTRAINT_LT: {
6908             if( idxNum & 0x0080 ) break;
6909             idxNum |=  0x2000;
6910             idxNum &= ~0x1000;
6911             aIdx[6] = i;
6912             break;
6913           }
6914         }
6915       }
6916       continue;
6917     }
6918     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
6919     assert( iCol>=0 && iCol<=2 );
6920     iMask = 1 << iCol;
6921 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6922     if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
6923       bStartSeen = 1;
6924     }
6925 #endif
6926     if( pConstraint->usable==0 ){
6927       unusableMask |=  iMask;
6928       continue;
6929     }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
6930       idxNum |= iMask;
6931       aIdx[iCol] = i;
6932     }
6933   }
6934   if( aIdx[3]==0 ){
6935     /* Ignore OFFSET if LIMIT is omitted */
6936     idxNum &= ~0x60;
6937     aIdx[4] = 0;
6938   }
6939   for(i=0; i<7; i++){
6940     if( (j = aIdx[i])>=0 ){
6941       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
6942       pIdxInfo->aConstraintUsage[j].omit =
6943          !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
6944     }
6945   }
6946   /* The current generate_column() implementation requires at least one
6947   ** argument (the START value).  Legacy versions assumed START=0 if the
6948   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
6949   ** to obtain the legacy behavior */
6950 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6951   if( !bStartSeen ){
6952     sqlite3_free(pVTab->zErrMsg);
6953     pVTab->zErrMsg = sqlite3_mprintf(
6954         "first argument to \"generate_series()\" missing or unusable");
6955     return SQLITE_ERROR;
6956   }
6957 #endif
6958   if( (unusableMask & ~idxNum)!=0 ){
6959     /* The start, stop, and step columns are inputs.  Therefore if there
6960     ** are unusable constraints on any of start, stop, or step then
6961     ** this plan is unusable */
6962     return SQLITE_CONSTRAINT;
6963   }
6964   if( (idxNum & 0x03)==0x03 ){
6965     /* Both start= and stop= boundaries are available.  This is the
6966     ** the preferred case */
6967     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
6968     pIdxInfo->estimatedRows = 1000;
6969     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
6970       if( pIdxInfo->aOrderBy[0].desc ){
6971         idxNum |= 0x08;
6972       }else{
6973         idxNum |= 0x10;
6974       }
6975       pIdxInfo->orderByConsumed = 1;
6976     }
6977   }else if( (idxNum & 0x21)==0x21 ){
6978     /* We have start= and LIMIT */
6979     pIdxInfo->estimatedRows = 2500;
6980   }else{
6981     /* If either boundary is missing, we have to generate a huge span
6982     ** of numbers.  Make this case very expensive so that the query
6983     ** planner will work hard to avoid it. */
6984     pIdxInfo->estimatedRows = 2147483647;
6985   }
6986   pIdxInfo->idxNum = idxNum;
6987 #ifdef SQLITE_INDEX_SCAN_HEX
6988   pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
6989 #endif
6990   return SQLITE_OK;
6991 }
6992 
6993 /*
6994 ** This following structure defines all the methods for the
6995 ** generate_series virtual table.
6996 */
6997 static sqlite3_module seriesModule = {
6998   0,                         /* iVersion */
6999   0,                         /* xCreate */
7000   seriesConnect,             /* xConnect */
7001   seriesBestIndex,           /* xBestIndex */
7002   seriesDisconnect,          /* xDisconnect */
7003   0,                         /* xDestroy */
7004   seriesOpen,                /* xOpen - open a cursor */
7005   seriesClose,               /* xClose - close a cursor */
7006   seriesFilter,              /* xFilter - configure scan constraints */
7007   seriesNext,                /* xNext - advance a cursor */
7008   seriesEof,                 /* xEof - check for end of scan */
7009   seriesColumn,              /* xColumn - read data */
7010   seriesRowid,               /* xRowid - read data */
7011   0,                         /* xUpdate */
7012   0,                         /* xBegin */
7013   0,                         /* xSync */
7014   0,                         /* xCommit */
7015   0,                         /* xRollback */
7016   0,                         /* xFindMethod */
7017   0,                         /* xRename */
7018   0,                         /* xSavepoint */
7019   0,                         /* xRelease */
7020   0,                         /* xRollbackTo */
7021   0,                         /* xShadowName */
7022   0                          /* xIntegrity */
7023 };
7024 
7025 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7026 
7027 #ifdef _WIN32
7028 
7029 #endif
sqlite3_series_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)7030 int sqlite3_series_init(
7031   sqlite3 *db,
7032   char **pzErrMsg,
7033   const sqlite3_api_routines *pApi
7034 ){
7035   int rc = SQLITE_OK;
7036   SQLITE_EXTENSION_INIT2(pApi);
7037 #ifndef SQLITE_OMIT_VIRTUALTABLE
7038   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
7039     *pzErrMsg = sqlite3_mprintf(
7040         "generate_series() requires SQLite 3.8.12 or later");
7041     return SQLITE_ERROR;
7042   }
7043   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
7044 #endif
7045   return rc;
7046 }
7047 
7048 /************************* End ../ext/misc/series.c ********************/
7049 /************************* Begin ../ext/misc/regexp.c ******************/
7050 /*
7051 ** 2012-11-13
7052 **
7053 ** The author disclaims copyright to this source code.  In place of
7054 ** a legal notice, here is a blessing:
7055 **
7056 **    May you do good and not evil.
7057 **    May you find forgiveness for yourself and forgive others.
7058 **    May you share freely, never taking more than you give.
7059 **
7060 ******************************************************************************
7061 **
7062 ** The code in this file implements a compact but reasonably
7063 ** efficient regular-expression matcher for posix extended regular
7064 ** expressions against UTF8 text.
7065 **
7066 ** This file is an SQLite extension.  It registers a single function
7067 ** named "regexp(A,B)" where A is the regular expression and B is the
7068 ** string to be matched.  By registering this function, SQLite will also
7069 ** then implement the "B regexp A" operator.  Note that with the function
7070 ** the regular expression comes first, but with the operator it comes
7071 ** second.
7072 **
7073 **  The following regular expression syntax is supported:
7074 **
7075 **     X*      zero or more occurrences of X
7076 **     X+      one or more occurrences of X
7077 **     X?      zero or one occurrences of X
7078 **     X{p,q}  between p and q occurrences of X
7079 **     (X)     match X
7080 **     X|Y     X or Y
7081 **     ^X      X occurring at the beginning of the string
7082 **     X$      X occurring at the end of the string
7083 **     .       Match any single character
7084 **     \c      Character c where c is one of \{}()[]|*+?.
7085 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
7086 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
7087 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
7088 **     [abc]   Any single character from the set abc
7089 **     [^abc]  Any single character not in the set abc
7090 **     [a-z]   Any single character in the range a-z
7091 **     [^a-z]  Any single character not in the range a-z
7092 **     \b      Word boundary
7093 **     \w      Word character.  [A-Za-z0-9_]
7094 **     \W      Non-word character
7095 **     \d      Digit
7096 **     \D      Non-digit
7097 **     \s      Whitespace character
7098 **     \S      Non-whitespace character
7099 **
7100 ** A nondeterministic finite automaton (NFA) is used for matching, so the
7101 ** performance is bounded by O(N*M) where N is the size of the regular
7102 ** expression and M is the size of the input string.  The matcher never
7103 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
7104 ** to p copies of X following by q-p copies of X? and that the size of the
7105 ** regular expression in the O(N*M) performance bound is computed after
7106 ** this expansion.
7107 */
7108 #include <string.h>
7109 #include <stdlib.h>
7110 /* #include "sqlite3ext.h" */
7111 SQLITE_EXTENSION_INIT1
7112 
7113 /*
7114 ** The following #defines change the names of some functions implemented in
7115 ** this file to prevent name collisions with C-library functions of the
7116 ** same name.
7117 */
7118 #define re_match   sqlite3re_match
7119 #define re_compile sqlite3re_compile
7120 #define re_free    sqlite3re_free
7121 
7122 /* The end-of-input character */
7123 #define RE_EOF            0    /* End of input */
7124 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
7125 
7126 /* The NFA is implemented as sequence of opcodes taken from the following
7127 ** set.  Each opcode has a single integer argument.
7128 */
7129 #define RE_OP_MATCH       1    /* Match the one character in the argument */
7130 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
7131 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
7132 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
7133 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
7134 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
7135 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
7136 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
7137 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
7138 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
7139 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
7140 #define RE_OP_NOTWORD    12    /* Not a perl word character */
7141 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
7142 #define RE_OP_NOTDIGIT   14    /* Not a digit */
7143 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
7144 #define RE_OP_NOTSPACE   16    /* Not a digit */
7145 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
7146 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
7147 
7148 #if defined(SQLITE_DEBUG)
7149 /* Opcode names used for symbolic debugging */
7150 static const char *ReOpName[] = {
7151   "EOF",
7152   "MATCH",
7153   "ANY",
7154   "ANYSTAR",
7155   "FORK",
7156   "GOTO",
7157   "ACCEPT",
7158   "CC_INC",
7159   "CC_EXC",
7160   "CC_VALUE",
7161   "CC_RANGE",
7162   "WORD",
7163   "NOTWORD",
7164   "DIGIT",
7165   "NOTDIGIT",
7166   "SPACE",
7167   "NOTSPACE",
7168   "BOUNDARY",
7169   "ATSTART",
7170 };
7171 #endif /* SQLITE_DEBUG */
7172 
7173 
7174 /* Each opcode is a "state" in the NFA */
7175 typedef unsigned short ReStateNumber;
7176 
7177 /* Because this is an NFA and not a DFA, multiple states can be active at
7178 ** once.  An instance of the following object records all active states in
7179 ** the NFA.  The implementation is optimized for the common case where the
7180 ** number of actives states is small.
7181 */
7182 typedef struct ReStateSet {
7183   unsigned nState;            /* Number of current states */
7184   ReStateNumber *aState;      /* Current states */
7185 } ReStateSet;
7186 
7187 /* An input string read one character at a time.
7188 */
7189 typedef struct ReInput ReInput;
7190 struct ReInput {
7191   const unsigned char *z;  /* All text */
7192   int i;                   /* Next byte to read */
7193   int mx;                  /* EOF when i>=mx */
7194 };
7195 
7196 /* A compiled NFA (or an NFA that is in the process of being compiled) is
7197 ** an instance of the following object.
7198 */
7199 typedef struct ReCompiled ReCompiled;
7200 struct ReCompiled {
7201   ReInput sIn;                /* Regular expression text */
7202   const char *zErr;           /* Error message to return */
7203   char *aOp;                  /* Operators for the virtual machine */
7204   int *aArg;                  /* Arguments to each operator */
7205   unsigned (*xNextChar)(ReInput*);  /* Next character function */
7206   unsigned char zInit[12];    /* Initial text to match */
7207   int nInit;                  /* Number of bytes in zInit */
7208   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
7209   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
7210 };
7211 
7212 /* Add a state to the given state set if it is not already there */
re_add_state(ReStateSet * pSet,int newState)7213 static void re_add_state(ReStateSet *pSet, int newState){
7214   unsigned i;
7215   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
7216   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
7217 }
7218 
7219 /* Extract the next unicode character from *pzIn and return it.  Advance
7220 ** *pzIn to the first byte past the end of the character returned.  To
7221 ** be clear:  this routine converts utf8 to unicode.  This routine is
7222 ** optimized for the common case where the next character is a single byte.
7223 */
re_next_char(ReInput * p)7224 static unsigned re_next_char(ReInput *p){
7225   unsigned c;
7226   if( p->i>=p->mx ) return 0;
7227   c = p->z[p->i++];
7228   if( c>=0x80 ){
7229     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
7230       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
7231       if( c<0x80 ) c = 0xfffd;
7232     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
7233            && (p->z[p->i+1]&0xc0)==0x80 ){
7234       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
7235       p->i += 2;
7236       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
7237     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
7238            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
7239       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
7240                        | (p->z[p->i+2]&0x3f);
7241       p->i += 3;
7242       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
7243     }else{
7244       c = 0xfffd;
7245     }
7246   }
7247   return c;
7248 }
re_next_char_nocase(ReInput * p)7249 static unsigned re_next_char_nocase(ReInput *p){
7250   unsigned c = re_next_char(p);
7251   if( c>='A' && c<='Z' ) c += 'a' - 'A';
7252   return c;
7253 }
7254 
7255 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
re_word_char(int c)7256 static int re_word_char(int c){
7257   return (c>='0' && c<='9') || (c>='a' && c<='z')
7258       || (c>='A' && c<='Z') || c=='_';
7259 }
7260 
7261 /* Return true if c is a "digit" character:  [0-9] */
re_digit_char(int c)7262 static int re_digit_char(int c){
7263   return (c>='0' && c<='9');
7264 }
7265 
7266 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
re_space_char(int c)7267 static int re_space_char(int c){
7268   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
7269 }
7270 
7271 /* Run a compiled regular expression on the zero-terminated input
7272 ** string zIn[].  Return true on a match and false if there is no match.
7273 */
re_match(ReCompiled * pRe,const unsigned char * zIn,int nIn)7274 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
7275   ReStateSet aStateSet[2], *pThis, *pNext;
7276   ReStateNumber aSpace[100];
7277   ReStateNumber *pToFree;
7278   unsigned int i = 0;
7279   unsigned int iSwap = 0;
7280   int c = RE_START;
7281   int cPrev = 0;
7282   int rc = 0;
7283   ReInput in;
7284 
7285   in.z = zIn;
7286   in.i = 0;
7287   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
7288 
7289   /* Look for the initial prefix match, if there is one. */
7290   if( pRe->nInit ){
7291     unsigned char x = pRe->zInit[0];
7292     while( in.i+pRe->nInit<=in.mx
7293      && (zIn[in.i]!=x ||
7294          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
7295     ){
7296       in.i++;
7297     }
7298     if( in.i+pRe->nInit>in.mx ) return 0;
7299     c = RE_START-1;
7300   }
7301 
7302   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
7303     pToFree = 0;
7304     aStateSet[0].aState = aSpace;
7305   }else{
7306     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
7307     if( pToFree==0 ) return -1;
7308     aStateSet[0].aState = pToFree;
7309   }
7310   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
7311   pNext = &aStateSet[1];
7312   pNext->nState = 0;
7313   re_add_state(pNext, 0);
7314   while( c!=RE_EOF && pNext->nState>0 ){
7315     cPrev = c;
7316     c = pRe->xNextChar(&in);
7317     pThis = pNext;
7318     pNext = &aStateSet[iSwap];
7319     iSwap = 1 - iSwap;
7320     pNext->nState = 0;
7321     for(i=0; i<pThis->nState; i++){
7322       int x = pThis->aState[i];
7323       switch( pRe->aOp[x] ){
7324         case RE_OP_MATCH: {
7325           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
7326           break;
7327         }
7328         case RE_OP_ATSTART: {
7329           if( cPrev==RE_START ) re_add_state(pThis, x+1);
7330           break;
7331         }
7332         case RE_OP_ANY: {
7333           if( c!=0 ) re_add_state(pNext, x+1);
7334           break;
7335         }
7336         case RE_OP_WORD: {
7337           if( re_word_char(c) ) re_add_state(pNext, x+1);
7338           break;
7339         }
7340         case RE_OP_NOTWORD: {
7341           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
7342           break;
7343         }
7344         case RE_OP_DIGIT: {
7345           if( re_digit_char(c) ) re_add_state(pNext, x+1);
7346           break;
7347         }
7348         case RE_OP_NOTDIGIT: {
7349           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
7350           break;
7351         }
7352         case RE_OP_SPACE: {
7353           if( re_space_char(c) ) re_add_state(pNext, x+1);
7354           break;
7355         }
7356         case RE_OP_NOTSPACE: {
7357           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
7358           break;
7359         }
7360         case RE_OP_BOUNDARY: {
7361           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
7362           break;
7363         }
7364         case RE_OP_ANYSTAR: {
7365           re_add_state(pNext, x);
7366           re_add_state(pThis, x+1);
7367           break;
7368         }
7369         case RE_OP_FORK: {
7370           re_add_state(pThis, x+pRe->aArg[x]);
7371           re_add_state(pThis, x+1);
7372           break;
7373         }
7374         case RE_OP_GOTO: {
7375           re_add_state(pThis, x+pRe->aArg[x]);
7376           break;
7377         }
7378         case RE_OP_ACCEPT: {
7379           rc = 1;
7380           goto re_match_end;
7381         }
7382         case RE_OP_CC_EXC: {
7383           if( c==0 ) break;
7384           /* fall-through */ goto re_op_cc_inc;
7385         }
7386         case RE_OP_CC_INC: re_op_cc_inc: {
7387           int j = 1;
7388           int n = pRe->aArg[x];
7389           int hit = 0;
7390           for(j=1; j>0 && j<n; j++){
7391             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
7392               if( pRe->aArg[x+j]==c ){
7393                 hit = 1;
7394                 j = -1;
7395               }
7396             }else{
7397               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
7398                 hit = 1;
7399                 j = -1;
7400               }else{
7401                 j++;
7402               }
7403             }
7404           }
7405           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
7406           if( hit ) re_add_state(pNext, x+n);
7407           break;
7408         }
7409       }
7410     }
7411   }
7412   for(i=0; i<pNext->nState; i++){
7413     int x = pNext->aState[i];
7414     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
7415     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
7416   }
7417 re_match_end:
7418   sqlite3_free(pToFree);
7419   return rc;
7420 }
7421 
7422 /* Resize the opcode and argument arrays for an RE under construction.
7423 */
re_resize(ReCompiled * p,int N)7424 static int re_resize(ReCompiled *p, int N){
7425   char *aOp;
7426   int *aArg;
7427   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
7428   if( aOp==0 ) return 1;
7429   p->aOp = aOp;
7430   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
7431   if( aArg==0 ) return 1;
7432   p->aArg = aArg;
7433   p->nAlloc = N;
7434   return 0;
7435 }
7436 
7437 /* Insert a new opcode and argument into an RE under construction.  The
7438 ** insertion point is just prior to existing opcode iBefore.
7439 */
re_insert(ReCompiled * p,int iBefore,int op,int arg)7440 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
7441   int i;
7442   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
7443   for(i=p->nState; i>iBefore; i--){
7444     p->aOp[i] = p->aOp[i-1];
7445     p->aArg[i] = p->aArg[i-1];
7446   }
7447   p->nState++;
7448   p->aOp[iBefore] = (char)op;
7449   p->aArg[iBefore] = arg;
7450   return iBefore;
7451 }
7452 
7453 /* Append a new opcode and argument to the end of the RE under construction.
7454 */
re_append(ReCompiled * p,int op,int arg)7455 static int re_append(ReCompiled *p, int op, int arg){
7456   return re_insert(p, p->nState, op, arg);
7457 }
7458 
7459 /* Make a copy of N opcodes starting at iStart onto the end of the RE
7460 ** under construction.
7461 */
re_copy(ReCompiled * p,int iStart,int N)7462 static void re_copy(ReCompiled *p, int iStart, int N){
7463   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
7464   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
7465   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
7466   p->nState += N;
7467 }
7468 
7469 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
7470 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
7471 ** c is not a hex digit *pV is unchanged.
7472 */
re_hex(int c,int * pV)7473 static int re_hex(int c, int *pV){
7474   if( c>='0' && c<='9' ){
7475     c -= '0';
7476   }else if( c>='a' && c<='f' ){
7477     c -= 'a' - 10;
7478   }else if( c>='A' && c<='F' ){
7479     c -= 'A' - 10;
7480   }else{
7481     return 0;
7482   }
7483   *pV = (*pV)*16 + (c & 0xff);
7484   return 1;
7485 }
7486 
7487 /* A backslash character has been seen, read the next character and
7488 ** return its interpretation.
7489 */
re_esc_char(ReCompiled * p)7490 static unsigned re_esc_char(ReCompiled *p){
7491   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
7492   static const char zTrans[] = "\a\f\n\r\t\v";
7493   int i, v = 0;
7494   char c;
7495   if( p->sIn.i>=p->sIn.mx ) return 0;
7496   c = p->sIn.z[p->sIn.i];
7497   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
7498     const unsigned char *zIn = p->sIn.z + p->sIn.i;
7499     if( re_hex(zIn[1],&v)
7500      && re_hex(zIn[2],&v)
7501      && re_hex(zIn[3],&v)
7502      && re_hex(zIn[4],&v)
7503     ){
7504       p->sIn.i += 5;
7505       return v;
7506     }
7507   }
7508   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
7509     const unsigned char *zIn = p->sIn.z + p->sIn.i;
7510     if( re_hex(zIn[1],&v)
7511      && re_hex(zIn[2],&v)
7512     ){
7513       p->sIn.i += 3;
7514       return v;
7515     }
7516   }
7517   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
7518   if( zEsc[i] ){
7519     if( i<6 ) c = zTrans[i];
7520     p->sIn.i++;
7521   }else{
7522     p->zErr = "unknown \\ escape";
7523   }
7524   return c;
7525 }
7526 
7527 /* Forward declaration */
7528 static const char *re_subcompile_string(ReCompiled*);
7529 
7530 /* Peek at the next byte of input */
rePeek(ReCompiled * p)7531 static unsigned char rePeek(ReCompiled *p){
7532   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
7533 }
7534 
7535 /* Compile RE text into a sequence of opcodes.  Continue up to the
7536 ** first unmatched ")" character, then return.  If an error is found,
7537 ** return a pointer to the error message string.
7538 */
re_subcompile_re(ReCompiled * p)7539 static const char *re_subcompile_re(ReCompiled *p){
7540   const char *zErr;
7541   int iStart, iEnd, iGoto;
7542   iStart = p->nState;
7543   zErr = re_subcompile_string(p);
7544   if( zErr ) return zErr;
7545   while( rePeek(p)=='|' ){
7546     iEnd = p->nState;
7547     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
7548     iGoto = re_append(p, RE_OP_GOTO, 0);
7549     p->sIn.i++;
7550     zErr = re_subcompile_string(p);
7551     if( zErr ) return zErr;
7552     p->aArg[iGoto] = p->nState - iGoto;
7553   }
7554   return 0;
7555 }
7556 
7557 /* Compile an element of regular expression text (anything that can be
7558 ** an operand to the "|" operator).  Return NULL on success or a pointer
7559 ** to the error message if there is a problem.
7560 */
re_subcompile_string(ReCompiled * p)7561 static const char *re_subcompile_string(ReCompiled *p){
7562   int iPrev = -1;
7563   int iStart;
7564   unsigned c;
7565   const char *zErr;
7566   while( (c = p->xNextChar(&p->sIn))!=0 ){
7567     iStart = p->nState;
7568     switch( c ){
7569       case '|':
7570       case ')': {
7571         p->sIn.i--;
7572         return 0;
7573       }
7574       case '(': {
7575         zErr = re_subcompile_re(p);
7576         if( zErr ) return zErr;
7577         if( rePeek(p)!=')' ) return "unmatched '('";
7578         p->sIn.i++;
7579         break;
7580       }
7581       case '.': {
7582         if( rePeek(p)=='*' ){
7583           re_append(p, RE_OP_ANYSTAR, 0);
7584           p->sIn.i++;
7585         }else{
7586           re_append(p, RE_OP_ANY, 0);
7587         }
7588         break;
7589       }
7590       case '*': {
7591         if( iPrev<0 ) return "'*' without operand";
7592         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
7593         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
7594         break;
7595       }
7596       case '+': {
7597         if( iPrev<0 ) return "'+' without operand";
7598         re_append(p, RE_OP_FORK, iPrev - p->nState);
7599         break;
7600       }
7601       case '?': {
7602         if( iPrev<0 ) return "'?' without operand";
7603         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
7604         break;
7605       }
7606       case '$': {
7607         re_append(p, RE_OP_MATCH, RE_EOF);
7608         break;
7609       }
7610       case '^': {
7611         re_append(p, RE_OP_ATSTART, 0);
7612         break;
7613       }
7614       case '{': {
7615         int m = 0, n = 0;
7616         int sz, j;
7617         if( iPrev<0 ) return "'{m,n}' without operand";
7618         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
7619         n = m;
7620         if( c==',' ){
7621           p->sIn.i++;
7622           n = 0;
7623           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
7624         }
7625         if( c!='}' ) return "unmatched '{'";
7626         if( n>0 && n<m ) return "n less than m in '{m,n}'";
7627         p->sIn.i++;
7628         sz = p->nState - iPrev;
7629         if( m==0 ){
7630           if( n==0 ) return "both m and n are zero in '{m,n}'";
7631           re_insert(p, iPrev, RE_OP_FORK, sz+1);
7632           iPrev++;
7633           n--;
7634         }else{
7635           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
7636         }
7637         for(j=m; j<n; j++){
7638           re_append(p, RE_OP_FORK, sz+1);
7639           re_copy(p, iPrev, sz);
7640         }
7641         if( n==0 && m>0 ){
7642           re_append(p, RE_OP_FORK, -sz);
7643         }
7644         break;
7645       }
7646       case '[': {
7647         unsigned int iFirst = p->nState;
7648         if( rePeek(p)=='^' ){
7649           re_append(p, RE_OP_CC_EXC, 0);
7650           p->sIn.i++;
7651         }else{
7652           re_append(p, RE_OP_CC_INC, 0);
7653         }
7654         while( (c = p->xNextChar(&p->sIn))!=0 ){
7655           if( c=='[' && rePeek(p)==':' ){
7656             return "POSIX character classes not supported";
7657           }
7658           if( c=='\\' ) c = re_esc_char(p);
7659           if( rePeek(p)=='-' ){
7660             re_append(p, RE_OP_CC_RANGE, c);
7661             p->sIn.i++;
7662             c = p->xNextChar(&p->sIn);
7663             if( c=='\\' ) c = re_esc_char(p);
7664             re_append(p, RE_OP_CC_RANGE, c);
7665           }else{
7666             re_append(p, RE_OP_CC_VALUE, c);
7667           }
7668           if( rePeek(p)==']' ){ p->sIn.i++; break; }
7669         }
7670         if( c==0 ) return "unclosed '['";
7671         if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
7672         break;
7673       }
7674       case '\\': {
7675         int specialOp = 0;
7676         switch( rePeek(p) ){
7677           case 'b': specialOp = RE_OP_BOUNDARY;   break;
7678           case 'd': specialOp = RE_OP_DIGIT;      break;
7679           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
7680           case 's': specialOp = RE_OP_SPACE;      break;
7681           case 'S': specialOp = RE_OP_NOTSPACE;   break;
7682           case 'w': specialOp = RE_OP_WORD;       break;
7683           case 'W': specialOp = RE_OP_NOTWORD;    break;
7684         }
7685         if( specialOp ){
7686           p->sIn.i++;
7687           re_append(p, specialOp, 0);
7688         }else{
7689           c = re_esc_char(p);
7690           re_append(p, RE_OP_MATCH, c);
7691         }
7692         break;
7693       }
7694       default: {
7695         re_append(p, RE_OP_MATCH, c);
7696         break;
7697       }
7698     }
7699     iPrev = iStart;
7700   }
7701   return 0;
7702 }
7703 
7704 /* Free and reclaim all the memory used by a previously compiled
7705 ** regular expression.  Applications should invoke this routine once
7706 ** for every call to re_compile() to avoid memory leaks.
7707 */
re_free(void * p)7708 static void re_free(void *p){
7709   ReCompiled *pRe = (ReCompiled*)p;
7710   if( pRe ){
7711     sqlite3_free(pRe->aOp);
7712     sqlite3_free(pRe->aArg);
7713     sqlite3_free(pRe);
7714   }
7715 }
7716 
7717 /*
7718 ** Compile a textual regular expression in zIn[] into a compiled regular
7719 ** expression suitable for us by re_match() and return a pointer to the
7720 ** compiled regular expression in *ppRe.  Return NULL on success or an
7721 ** error message if something goes wrong.
7722 */
re_compile(ReCompiled ** ppRe,const char * zIn,int noCase)7723 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
7724   ReCompiled *pRe;
7725   const char *zErr;
7726   int i, j;
7727 
7728   *ppRe = 0;
7729   pRe = sqlite3_malloc( sizeof(*pRe) );
7730   if( pRe==0 ){
7731     return "out of memory";
7732   }
7733   memset(pRe, 0, sizeof(*pRe));
7734   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
7735   if( re_resize(pRe, 30) ){
7736     re_free(pRe);
7737     return "out of memory";
7738   }
7739   if( zIn[0]=='^' ){
7740     zIn++;
7741   }else{
7742     re_append(pRe, RE_OP_ANYSTAR, 0);
7743   }
7744   pRe->sIn.z = (unsigned char*)zIn;
7745   pRe->sIn.i = 0;
7746   pRe->sIn.mx = (int)strlen(zIn);
7747   zErr = re_subcompile_re(pRe);
7748   if( zErr ){
7749     re_free(pRe);
7750     return zErr;
7751   }
7752   if( pRe->sIn.i>=pRe->sIn.mx ){
7753     re_append(pRe, RE_OP_ACCEPT, 0);
7754     *ppRe = pRe;
7755   }else{
7756     re_free(pRe);
7757     return "unrecognized character";
7758   }
7759 
7760   /* The following is a performance optimization.  If the regex begins with
7761   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
7762   ** one or more matching characters, enter those matching characters into
7763   ** zInit[].  The re_match() routine can then search ahead in the input
7764   ** string looking for the initial match without having to run the whole
7765   ** regex engine over the string.  Do not worry about trying to match
7766   ** unicode characters beyond plane 0 - those are very rare and this is
7767   ** just an optimization. */
7768   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
7769     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
7770       unsigned x = pRe->aArg[i];
7771       if( x<=0x7f ){
7772         pRe->zInit[j++] = (unsigned char)x;
7773       }else if( x<=0x7ff ){
7774         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
7775         pRe->zInit[j++] = 0x80 | (x&0x3f);
7776       }else if( x<=0xffff ){
7777         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
7778         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
7779         pRe->zInit[j++] = 0x80 | (x&0x3f);
7780       }else{
7781         break;
7782       }
7783     }
7784     if( j>0 && pRe->zInit[j-1]==0 ) j--;
7785     pRe->nInit = j;
7786   }
7787   return pRe->zErr;
7788 }
7789 
7790 /*
7791 ** Implementation of the regexp() SQL function.  This function implements
7792 ** the build-in REGEXP operator.  The first argument to the function is the
7793 ** pattern and the second argument is the string.  So, the SQL statements:
7794 **
7795 **       A REGEXP B
7796 **
7797 ** is implemented as regexp(B,A).
7798 */
re_sql_func(sqlite3_context * context,int argc,sqlite3_value ** argv)7799 static void re_sql_func(
7800   sqlite3_context *context,
7801   int argc,
7802   sqlite3_value **argv
7803 ){
7804   ReCompiled *pRe;          /* Compiled regular expression */
7805   const char *zPattern;     /* The regular expression */
7806   const unsigned char *zStr;/* String being searched */
7807   const char *zErr;         /* Compile error message */
7808   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
7809 
7810   (void)argc;  /* Unused */
7811   pRe = sqlite3_get_auxdata(context, 0);
7812   if( pRe==0 ){
7813     zPattern = (const char*)sqlite3_value_text(argv[0]);
7814     if( zPattern==0 ) return;
7815     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7816     if( zErr ){
7817       re_free(pRe);
7818       sqlite3_result_error(context, zErr, -1);
7819       return;
7820     }
7821     if( pRe==0 ){
7822       sqlite3_result_error_nomem(context);
7823       return;
7824     }
7825     setAux = 1;
7826   }
7827   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
7828   if( zStr!=0 ){
7829     sqlite3_result_int(context, re_match(pRe, zStr, -1));
7830   }
7831   if( setAux ){
7832     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
7833   }
7834 }
7835 
7836 #if defined(SQLITE_DEBUG)
7837 /*
7838 ** This function is used for testing and debugging only.  It is only available
7839 ** if the SQLITE_DEBUG compile-time option is used.
7840 **
7841 ** Compile a regular expression and then convert the compiled expression into
7842 ** text and return that text.
7843 */
re_bytecode_func(sqlite3_context * context,int argc,sqlite3_value ** argv)7844 static void re_bytecode_func(
7845   sqlite3_context *context,
7846   int argc,
7847   sqlite3_value **argv
7848 ){
7849   const char *zPattern;
7850   const char *zErr;
7851   ReCompiled *pRe;
7852   sqlite3_str *pStr;
7853   int i;
7854   int n;
7855   char *z;
7856   (void)argc;
7857 
7858   zPattern = (const char*)sqlite3_value_text(argv[0]);
7859   if( zPattern==0 ) return;
7860   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7861   if( zErr ){
7862     re_free(pRe);
7863     sqlite3_result_error(context, zErr, -1);
7864     return;
7865   }
7866   if( pRe==0 ){
7867     sqlite3_result_error_nomem(context);
7868     return;
7869   }
7870   pStr = sqlite3_str_new(0);
7871   if( pStr==0 ) goto re_bytecode_func_err;
7872   if( pRe->nInit>0 ){
7873     sqlite3_str_appendf(pStr, "INIT     ");
7874     for(i=0; i<pRe->nInit; i++){
7875       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
7876     }
7877     sqlite3_str_appendf(pStr, "\n");
7878   }
7879   for(i=0; (unsigned)i<pRe->nState; i++){
7880     sqlite3_str_appendf(pStr, "%-8s %4d\n",
7881          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
7882   }
7883   n = sqlite3_str_length(pStr);
7884   z = sqlite3_str_finish(pStr);
7885   if( n==0 ){
7886     sqlite3_free(z);
7887   }else{
7888     sqlite3_result_text(context, z, n-1, sqlite3_free);
7889   }
7890 
7891 re_bytecode_func_err:
7892   re_free(pRe);
7893 }
7894 
7895 #endif /* SQLITE_DEBUG */
7896 
7897 
7898 /*
7899 ** Invoke this routine to register the regexp() function with the
7900 ** SQLite database connection.
7901 */
7902 #ifdef _WIN32
7903 
7904 #endif
sqlite3_regexp_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)7905 int sqlite3_regexp_init(
7906   sqlite3 *db,
7907   char **pzErrMsg,
7908   const sqlite3_api_routines *pApi
7909 ){
7910   int rc = SQLITE_OK;
7911   SQLITE_EXTENSION_INIT2(pApi);
7912   (void)pzErrMsg;  /* Unused */
7913   rc = sqlite3_create_function(db, "regexp", 2,
7914                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7915                             0, re_sql_func, 0, 0);
7916   if( rc==SQLITE_OK ){
7917     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
7918     ** of regexp(PATTERN,STRING). */
7919     rc = sqlite3_create_function(db, "regexpi", 2,
7920                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7921                             (void*)db, re_sql_func, 0, 0);
7922 #if defined(SQLITE_DEBUG)
7923     if( rc==SQLITE_OK ){
7924       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
7925                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7926                             0, re_bytecode_func, 0, 0);
7927     }
7928 #endif /* SQLITE_DEBUG */
7929   }
7930   return rc;
7931 }
7932 
7933 /************************* End ../ext/misc/regexp.c ********************/
7934 #ifndef SQLITE_SHELL_FIDDLE
7935 /************************* Begin ../ext/misc/fileio.c ******************/
7936 /*
7937 ** 2014-06-13
7938 **
7939 ** The author disclaims copyright to this source code.  In place of
7940 ** a legal notice, here is a blessing:
7941 **
7942 **    May you do good and not evil.
7943 **    May you find forgiveness for yourself and forgive others.
7944 **    May you share freely, never taking more than you give.
7945 **
7946 ******************************************************************************
7947 **
7948 ** This SQLite extension implements SQL functions readfile() and
7949 ** writefile(), and eponymous virtual type "fsdir".
7950 **
7951 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
7952 **
7953 **   If neither of the optional arguments is present, then this UDF
7954 **   function writes blob DATA to file FILE. If successful, the number
7955 **   of bytes written is returned. If an error occurs, NULL is returned.
7956 **
7957 **   If the first option argument - MODE - is present, then it must
7958 **   be passed an integer value that corresponds to a POSIX mode
7959 **   value (file type + permissions, as returned in the stat.st_mode
7960 **   field by the stat() system call). Three types of files may
7961 **   be written/created:
7962 **
7963 **     regular files:  (mode & 0170000)==0100000
7964 **     symbolic links: (mode & 0170000)==0120000
7965 **     directories:    (mode & 0170000)==0040000
7966 **
7967 **   For a directory, the DATA is ignored. For a symbolic link, it is
7968 **   interpreted as text and used as the target of the link. For a
7969 **   regular file, it is interpreted as a blob and written into the
7970 **   named file. Regardless of the type of file, its permissions are
7971 **   set to (mode & 0777) before returning.
7972 **
7973 **   If the optional MTIME argument is present, then it is interpreted
7974 **   as an integer - the number of seconds since the unix epoch. The
7975 **   modification-time of the target file is set to this value before
7976 **   returning.
7977 **
7978 **   If five or more arguments are passed to this function and an
7979 **   error is encountered, an exception is raised.
7980 **
7981 ** READFILE(FILE):
7982 **
7983 **   Read and return the contents of file FILE (type blob) from disk.
7984 **
7985 ** FSDIR:
7986 **
7987 **   Used as follows:
7988 **
7989 **     SELECT * FROM fsdir($path [, $dir]);
7990 **
7991 **   Parameter $path is an absolute or relative pathname. If the file that it
7992 **   refers to does not exist, it is an error. If the path refers to a regular
7993 **   file or symbolic link, it returns a single row. Or, if the path refers
7994 **   to a directory, it returns one row for the directory, and one row for each
7995 **   file within the hierarchy rooted at $path.
7996 **
7997 **   Each row has the following columns:
7998 **
7999 **     name:  Path to file or directory (text value).
8000 **     mode:  Value of stat.st_mode for directory entry (an integer).
8001 **     mtime: Value of stat.st_mtime for directory entry (an integer).
8002 **     data:  For a regular file, a blob containing the file data. For a
8003 **            symlink, a text value containing the text of the link. For a
8004 **            directory, NULL.
8005 **
8006 **   If a non-NULL value is specified for the optional $dir parameter and
8007 **   $path is a relative path, then $path is interpreted relative to $dir.
8008 **   And the paths returned in the "name" column of the table are also
8009 **   relative to directory $dir.
8010 **
8011 ** Notes on building this extension for Windows:
8012 **   Unless linked statically with the SQLite library, a preprocessor
8013 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
8014 **   DLL form of this extension for WIN32. See its use below for details.
8015 */
8016 /* #include "sqlite3ext.h" */
8017 SQLITE_EXTENSION_INIT1
8018 #include <stdio.h>
8019 #include <string.h>
8020 #include <assert.h>
8021 
8022 #include <sys/types.h>
8023 #include <sys/stat.h>
8024 #include <fcntl.h>
8025 #if !defined(_WIN32) && !defined(WIN32)
8026 #  include <unistd.h>
8027 #  include <dirent.h>
8028 #  include <utime.h>
8029 #  include <sys/time.h>
8030 #  define STRUCT_STAT struct stat
8031 #else
8032 #  include "windows.h"
8033 #  include <io.h>
8034 #  include <direct.h>
8035 /* #  include "test_windirent.h" */
8036 #  define dirent DIRENT
8037 #  define STRUCT_STAT struct _stat
8038 #  define chmod(path,mode) fileio_chmod(path,mode)
8039 #  define mkdir(path,mode) fileio_mkdir(path)
8040 #endif
8041 #include <time.h>
8042 #include <errno.h>
8043 
8044 /* When used as part of the CLI, the sqlite3_stdio.h module will have
8045 ** been included before this one. In that case use the sqlite3_stdio.h
8046 ** #defines.  If not, create our own for fopen().
8047 */
8048 #ifndef _SQLITE3_STDIO_H_
8049 # define sqlite3_fopen fopen
8050 #endif
8051 
8052 /*
8053 ** Structure of the fsdir() table-valued function
8054 */
8055                  /*    0    1    2     3    4           5             */
8056 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
8057 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
8058 #define FSDIR_COLUMN_MODE     1     /* Access mode */
8059 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
8060 #define FSDIR_COLUMN_DATA     3     /* File content */
8061 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
8062 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
8063 
8064 /*
8065 ** UTF8 chmod() function for Windows
8066 */
8067 #if defined(_WIN32) || defined(WIN32)
fileio_chmod(const char * zPath,int pmode)8068 static int fileio_chmod(const char *zPath, int pmode){
8069   sqlite3_int64 sz = strlen(zPath);
8070   wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(b1[0]) );
8071   int rc;
8072   if( b1==0 ) return -1;
8073   sz = MultiByteToWideChar(CP_UTF8, 0, zPath, sz, b1, sz);
8074   b1[sz] = 0;
8075   rc = _wchmod(b1, pmode);
8076   sqlite3_free(b1);
8077   return rc;
8078 }
8079 #endif
8080 
8081 /*
8082 ** UTF8 mkdir() function for Windows
8083 */
8084 #if defined(_WIN32) || defined(WIN32)
fileio_mkdir(const char * zPath)8085 static int fileio_mkdir(const char *zPath){
8086   sqlite3_int64 sz = strlen(zPath);
8087   wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(b1[0]) );
8088   int rc;
8089   if( b1==0 ) return -1;
8090   sz = MultiByteToWideChar(CP_UTF8, 0, zPath, sz, b1, sz);
8091   b1[sz] = 0;
8092   rc = _wmkdir(b1);
8093   sqlite3_free(b1);
8094   return rc;
8095 }
8096 #endif
8097 
8098 
8099 /*
8100 ** Set the result stored by context ctx to a blob containing the
8101 ** contents of file zName.  Or, leave the result unchanged (NULL)
8102 ** if the file does not exist or is unreadable.
8103 **
8104 ** If the file exceeds the SQLite blob size limit, through an
8105 ** SQLITE_TOOBIG error.
8106 **
8107 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
8108 ** off of disk.
8109 */
readFileContents(sqlite3_context * ctx,const char * zName)8110 static void readFileContents(sqlite3_context *ctx, const char *zName){
8111   FILE *in;
8112   sqlite3_int64 nIn;
8113   void *pBuf;
8114   sqlite3 *db;
8115   int mxBlob;
8116 
8117   in = sqlite3_fopen(zName, "rb");
8118   if( in==0 ){
8119     /* File does not exist or is unreadable. Leave the result set to NULL. */
8120     return;
8121   }
8122   fseek(in, 0, SEEK_END);
8123   nIn = ftell(in);
8124   rewind(in);
8125   db = sqlite3_context_db_handle(ctx);
8126   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
8127   if( nIn>mxBlob ){
8128     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
8129     fclose(in);
8130     return;
8131   }
8132   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
8133   if( pBuf==0 ){
8134     sqlite3_result_error_nomem(ctx);
8135     fclose(in);
8136     return;
8137   }
8138   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
8139     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
8140   }else{
8141     sqlite3_result_error_code(ctx, SQLITE_IOERR);
8142     sqlite3_free(pBuf);
8143   }
8144   fclose(in);
8145 }
8146 
8147 /*
8148 ** Implementation of the "readfile(X)" SQL function.  The entire content
8149 ** of the file named X is read and returned as a BLOB.  NULL is returned
8150 ** if the file does not exist or is unreadable.
8151 */
readfileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)8152 static void readfileFunc(
8153   sqlite3_context *context,
8154   int argc,
8155   sqlite3_value **argv
8156 ){
8157   const char *zName;
8158   (void)(argc);  /* Unused parameter */
8159   zName = (const char*)sqlite3_value_text(argv[0]);
8160   if( zName==0 ) return;
8161   readFileContents(context, zName);
8162 }
8163 
8164 /*
8165 ** Set the error message contained in context ctx to the results of
8166 ** vprintf(zFmt, ...).
8167 */
ctxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)8168 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
8169   char *zMsg = 0;
8170   va_list ap;
8171   va_start(ap, zFmt);
8172   zMsg = sqlite3_vmprintf(zFmt, ap);
8173   sqlite3_result_error(ctx, zMsg, -1);
8174   sqlite3_free(zMsg);
8175   va_end(ap);
8176 }
8177 
8178 #if defined(_WIN32)
8179 /*
8180 ** This function is designed to convert a Win32 FILETIME structure into the
8181 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
8182 */
fileTimeToUnixTime(LPFILETIME pFileTime)8183 static sqlite3_uint64 fileTimeToUnixTime(
8184   LPFILETIME pFileTime
8185 ){
8186   SYSTEMTIME epochSystemTime;
8187   ULARGE_INTEGER epochIntervals;
8188   FILETIME epochFileTime;
8189   ULARGE_INTEGER fileIntervals;
8190 
8191   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
8192   epochSystemTime.wYear = 1970;
8193   epochSystemTime.wMonth = 1;
8194   epochSystemTime.wDay = 1;
8195   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
8196   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
8197   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
8198 
8199   fileIntervals.LowPart = pFileTime->dwLowDateTime;
8200   fileIntervals.HighPart = pFileTime->dwHighDateTime;
8201 
8202   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
8203 }
8204 
8205 
8206 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
8207 #  /* To allow a standalone DLL, use this next replacement function: */
8208 #  undef sqlite3_win32_utf8_to_unicode
8209 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
8210 #
utf8_to_utf16(const char * z)8211 LPWSTR utf8_to_utf16(const char *z){
8212   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
8213   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
8214   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
8215     return rv;
8216   sqlite3_free(rv);
8217   return 0;
8218 }
8219 #endif
8220 
8221 /*
8222 ** This function attempts to normalize the time values found in the stat()
8223 ** buffer to UTC.  This is necessary on Win32, where the runtime library
8224 ** appears to return these values as local times.
8225 */
statTimesToUtc(const char * zPath,STRUCT_STAT * pStatBuf)8226 static void statTimesToUtc(
8227   const char *zPath,
8228   STRUCT_STAT *pStatBuf
8229 ){
8230   HANDLE hFindFile;
8231   WIN32_FIND_DATAW fd;
8232   LPWSTR zUnicodeName;
8233   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
8234   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
8235   if( zUnicodeName ){
8236     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
8237     hFindFile = FindFirstFileW(zUnicodeName, &fd);
8238     if( hFindFile!=NULL ){
8239       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
8240       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
8241       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
8242       FindClose(hFindFile);
8243     }
8244     sqlite3_free(zUnicodeName);
8245   }
8246 }
8247 #endif
8248 
8249 /*
8250 ** This function is used in place of stat().  On Windows, special handling
8251 ** is required in order for the included time to be returned as UTC.  On all
8252 ** other systems, this function simply calls stat().
8253 */
fileStat(const char * zPath,STRUCT_STAT * pStatBuf)8254 static int fileStat(
8255   const char *zPath,
8256   STRUCT_STAT *pStatBuf
8257 ){
8258 #if defined(_WIN32)
8259   sqlite3_int64 sz = strlen(zPath);
8260   wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(b1[0]) );
8261   int rc;
8262   if( b1==0 ) return 1;
8263   sz = MultiByteToWideChar(CP_UTF8, 0, zPath, sz, b1, sz);
8264   b1[sz] = 0;
8265   rc = _wstat(b1, pStatBuf);
8266   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
8267   return rc;
8268 #else
8269   return stat(zPath, pStatBuf);
8270 #endif
8271 }
8272 
8273 /*
8274 ** This function is used in place of lstat().  On Windows, special handling
8275 ** is required in order for the included time to be returned as UTC.  On all
8276 ** other systems, this function simply calls lstat().
8277 */
fileLinkStat(const char * zPath,STRUCT_STAT * pStatBuf)8278 static int fileLinkStat(
8279   const char *zPath,
8280   STRUCT_STAT *pStatBuf
8281 ){
8282 #if defined(_WIN32)
8283   return fileStat(zPath, pStatBuf);
8284 #else
8285   return lstat(zPath, pStatBuf);
8286 #endif
8287 }
8288 
8289 /*
8290 ** Argument zFile is the name of a file that will be created and/or written
8291 ** by SQL function writefile(). This function ensures that the directory
8292 ** zFile will be written to exists, creating it if required. The permissions
8293 ** for any path components created by this function are set in accordance
8294 ** with the current umask.
8295 **
8296 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
8297 ** SQLITE_OK is returned if the directory is successfully created, or
8298 ** SQLITE_ERROR otherwise.
8299 */
makeDirectory(const char * zFile)8300 static int makeDirectory(
8301   const char *zFile
8302 ){
8303   char *zCopy = sqlite3_mprintf("%s", zFile);
8304   int rc = SQLITE_OK;
8305 
8306   if( zCopy==0 ){
8307     rc = SQLITE_NOMEM;
8308   }else{
8309     int nCopy = (int)strlen(zCopy);
8310     int i = 1;
8311 
8312     while( rc==SQLITE_OK ){
8313       STRUCT_STAT sStat;
8314       int rc2;
8315 
8316       for(; zCopy[i]!='/' && i<nCopy; i++);
8317       if( i==nCopy ) break;
8318       zCopy[i] = '\0';
8319 
8320       rc2 = fileStat(zCopy, &sStat);
8321       if( rc2!=0 ){
8322         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
8323       }else{
8324         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
8325       }
8326       zCopy[i] = '/';
8327       i++;
8328     }
8329 
8330     sqlite3_free(zCopy);
8331   }
8332 
8333   return rc;
8334 }
8335 
8336 /*
8337 ** This function does the work for the writefile() UDF. Refer to
8338 ** header comments at the top of this file for details.
8339 */
writeFile(sqlite3_context * pCtx,const char * zFile,sqlite3_value * pData,mode_t mode,sqlite3_int64 mtime)8340 static int writeFile(
8341   sqlite3_context *pCtx,          /* Context to return bytes written in */
8342   const char *zFile,              /* File to write */
8343   sqlite3_value *pData,           /* Data to write */
8344   mode_t mode,                    /* MODE parameter passed to writefile() */
8345   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
8346 ){
8347   if( zFile==0 ) return 1;
8348 #if !defined(_WIN32) && !defined(WIN32)
8349   if( S_ISLNK(mode) ){
8350     const char *zTo = (const char*)sqlite3_value_text(pData);
8351     if( zTo==0 ) return 1;
8352     unlink(zFile);
8353     if( symlink(zTo, zFile)<0 ) return 1;
8354   }else
8355 #endif
8356   {
8357     if( S_ISDIR(mode) ){
8358       if( mkdir(zFile, mode) ){
8359         /* The mkdir() call to create the directory failed. This might not
8360         ** be an error though - if there is already a directory at the same
8361         ** path and either the permissions already match or can be changed
8362         ** to do so using chmod(), it is not an error.  */
8363         STRUCT_STAT sStat;
8364         if( errno!=EEXIST
8365          || 0!=fileStat(zFile, &sStat)
8366          || !S_ISDIR(sStat.st_mode)
8367          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
8368         ){
8369           return 1;
8370         }
8371       }
8372     }else{
8373       sqlite3_int64 nWrite = 0;
8374       const char *z;
8375       int rc = 0;
8376       FILE *out = sqlite3_fopen(zFile, "wb");
8377       if( out==0 ) return 1;
8378       z = (const char*)sqlite3_value_blob(pData);
8379       if( z ){
8380         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
8381         nWrite = sqlite3_value_bytes(pData);
8382         if( nWrite!=n ){
8383           rc = 1;
8384         }
8385       }
8386       fclose(out);
8387       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
8388         rc = 1;
8389       }
8390       if( rc ) return 2;
8391       sqlite3_result_int64(pCtx, nWrite);
8392     }
8393   }
8394 
8395   if( mtime>=0 ){
8396 #if defined(_WIN32)
8397 #if !SQLITE_OS_WINRT
8398     /* Windows */
8399     FILETIME lastAccess;
8400     FILETIME lastWrite;
8401     SYSTEMTIME currentTime;
8402     LONGLONG intervals;
8403     HANDLE hFile;
8404     LPWSTR zUnicodeName;
8405     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
8406 
8407     GetSystemTime(&currentTime);
8408     SystemTimeToFileTime(&currentTime, &lastAccess);
8409     intervals = (mtime*10000000) + 116444736000000000;
8410     lastWrite.dwLowDateTime = (DWORD)intervals;
8411     lastWrite.dwHighDateTime = intervals >> 32;
8412     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
8413     if( zUnicodeName==0 ){
8414       return 1;
8415     }
8416     hFile = CreateFileW(
8417       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
8418       FILE_FLAG_BACKUP_SEMANTICS, NULL
8419     );
8420     sqlite3_free(zUnicodeName);
8421     if( hFile!=INVALID_HANDLE_VALUE ){
8422       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
8423       CloseHandle(hFile);
8424       return !bResult;
8425     }else{
8426       return 1;
8427     }
8428 #endif
8429 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
8430     /* Recent unix */
8431     struct timespec times[2];
8432     times[0].tv_nsec = times[1].tv_nsec = 0;
8433     times[0].tv_sec = time(0);
8434     times[1].tv_sec = mtime;
8435     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
8436       return 1;
8437     }
8438 #else
8439     /* Legacy unix.
8440     **
8441     ** Do not use utimes() on a symbolic link - it sees through the link and
8442     ** modifies the timestamps on the target. Or fails if the target does
8443     ** not exist.  */
8444     if( 0==S_ISLNK(mode) ){
8445       struct timeval times[2];
8446       times[0].tv_usec = times[1].tv_usec = 0;
8447       times[0].tv_sec = time(0);
8448       times[1].tv_sec = mtime;
8449       if( utimes(zFile, times) ){
8450         return 1;
8451       }
8452     }
8453 #endif
8454   }
8455 
8456   return 0;
8457 }
8458 
8459 /*
8460 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
8461 ** Refer to header comments at the top of this file for details.
8462 */
writefileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)8463 static void writefileFunc(
8464   sqlite3_context *context,
8465   int argc,
8466   sqlite3_value **argv
8467 ){
8468   const char *zFile;
8469   mode_t mode = 0;
8470   int res;
8471   sqlite3_int64 mtime = -1;
8472 
8473   if( argc<2 || argc>4 ){
8474     sqlite3_result_error(context,
8475         "wrong number of arguments to function writefile()", -1
8476     );
8477     return;
8478   }
8479 
8480   zFile = (const char*)sqlite3_value_text(argv[0]);
8481   if( zFile==0 ) return;
8482   if( argc>=3 ){
8483     mode = (mode_t)sqlite3_value_int(argv[2]);
8484   }
8485   if( argc==4 ){
8486     mtime = sqlite3_value_int64(argv[3]);
8487   }
8488 
8489   res = writeFile(context, zFile, argv[1], mode, mtime);
8490   if( res==1 && errno==ENOENT ){
8491     if( makeDirectory(zFile)==SQLITE_OK ){
8492       res = writeFile(context, zFile, argv[1], mode, mtime);
8493     }
8494   }
8495 
8496   if( argc>2 && res!=0 ){
8497     if( S_ISLNK(mode) ){
8498       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
8499     }else if( S_ISDIR(mode) ){
8500       ctxErrorMsg(context, "failed to create directory: %s", zFile);
8501     }else{
8502       ctxErrorMsg(context, "failed to write file: %s", zFile);
8503     }
8504   }
8505 }
8506 
8507 /*
8508 ** SQL function:   lsmode(MODE)
8509 **
8510 ** Given a numberic st_mode from stat(), convert it into a human-readable
8511 ** text string in the style of "ls -l".
8512 */
lsModeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)8513 static void lsModeFunc(
8514   sqlite3_context *context,
8515   int argc,
8516   sqlite3_value **argv
8517 ){
8518   int i;
8519   int iMode = sqlite3_value_int(argv[0]);
8520   char z[16];
8521   (void)argc;
8522   if( S_ISLNK(iMode) ){
8523     z[0] = 'l';
8524   }else if( S_ISREG(iMode) ){
8525     z[0] = '-';
8526   }else if( S_ISDIR(iMode) ){
8527     z[0] = 'd';
8528   }else{
8529     z[0] = '?';
8530   }
8531   for(i=0; i<3; i++){
8532     int m = (iMode >> ((2-i)*3));
8533     char *a = &z[1 + i*3];
8534     a[0] = (m & 0x4) ? 'r' : '-';
8535     a[1] = (m & 0x2) ? 'w' : '-';
8536     a[2] = (m & 0x1) ? 'x' : '-';
8537   }
8538   z[10] = '\0';
8539   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
8540 }
8541 
8542 #ifndef SQLITE_OMIT_VIRTUALTABLE
8543 
8544 /*
8545 ** Cursor type for recursively iterating through a directory structure.
8546 */
8547 typedef struct fsdir_cursor fsdir_cursor;
8548 typedef struct FsdirLevel FsdirLevel;
8549 
8550 struct FsdirLevel {
8551   DIR *pDir;                 /* From opendir() */
8552   char *zDir;                /* Name of directory (nul-terminated) */
8553 };
8554 
8555 struct fsdir_cursor {
8556   sqlite3_vtab_cursor base;  /* Base class - must be first */
8557 
8558   int nLvl;                  /* Number of entries in aLvl[] array */
8559   int iLvl;                  /* Index of current entry */
8560   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
8561 
8562   const char *zBase;
8563   int nBase;
8564 
8565   STRUCT_STAT sStat;         /* Current lstat() results */
8566   char *zPath;               /* Path to current entry */
8567   sqlite3_int64 iRowid;      /* Current rowid */
8568 };
8569 
8570 typedef struct fsdir_tab fsdir_tab;
8571 struct fsdir_tab {
8572   sqlite3_vtab base;         /* Base class - must be first */
8573 };
8574 
8575 /*
8576 ** Construct a new fsdir virtual table object.
8577 */
fsdirConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)8578 static int fsdirConnect(
8579   sqlite3 *db,
8580   void *pAux,
8581   int argc, const char *const*argv,
8582   sqlite3_vtab **ppVtab,
8583   char **pzErr
8584 ){
8585   fsdir_tab *pNew = 0;
8586   int rc;
8587   (void)pAux;
8588   (void)argc;
8589   (void)argv;
8590   (void)pzErr;
8591   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
8592   if( rc==SQLITE_OK ){
8593     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
8594     if( pNew==0 ) return SQLITE_NOMEM;
8595     memset(pNew, 0, sizeof(*pNew));
8596     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
8597   }
8598   *ppVtab = (sqlite3_vtab*)pNew;
8599   return rc;
8600 }
8601 
8602 /*
8603 ** This method is the destructor for fsdir vtab objects.
8604 */
fsdirDisconnect(sqlite3_vtab * pVtab)8605 static int fsdirDisconnect(sqlite3_vtab *pVtab){
8606   sqlite3_free(pVtab);
8607   return SQLITE_OK;
8608 }
8609 
8610 /*
8611 ** Constructor for a new fsdir_cursor object.
8612 */
fsdirOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)8613 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
8614   fsdir_cursor *pCur;
8615   (void)p;
8616   pCur = sqlite3_malloc( sizeof(*pCur) );
8617   if( pCur==0 ) return SQLITE_NOMEM;
8618   memset(pCur, 0, sizeof(*pCur));
8619   pCur->iLvl = -1;
8620   *ppCursor = &pCur->base;
8621   return SQLITE_OK;
8622 }
8623 
8624 /*
8625 ** Reset a cursor back to the state it was in when first returned
8626 ** by fsdirOpen().
8627 */
fsdirResetCursor(fsdir_cursor * pCur)8628 static void fsdirResetCursor(fsdir_cursor *pCur){
8629   int i;
8630   for(i=0; i<=pCur->iLvl; i++){
8631     FsdirLevel *pLvl = &pCur->aLvl[i];
8632     if( pLvl->pDir ) closedir(pLvl->pDir);
8633     sqlite3_free(pLvl->zDir);
8634   }
8635   sqlite3_free(pCur->zPath);
8636   sqlite3_free(pCur->aLvl);
8637   pCur->aLvl = 0;
8638   pCur->zPath = 0;
8639   pCur->zBase = 0;
8640   pCur->nBase = 0;
8641   pCur->nLvl = 0;
8642   pCur->iLvl = -1;
8643   pCur->iRowid = 1;
8644 }
8645 
8646 /*
8647 ** Destructor for an fsdir_cursor.
8648 */
fsdirClose(sqlite3_vtab_cursor * cur)8649 static int fsdirClose(sqlite3_vtab_cursor *cur){
8650   fsdir_cursor *pCur = (fsdir_cursor*)cur;
8651 
8652   fsdirResetCursor(pCur);
8653   sqlite3_free(pCur);
8654   return SQLITE_OK;
8655 }
8656 
8657 /*
8658 ** Set the error message for the virtual table associated with cursor
8659 ** pCur to the results of vprintf(zFmt, ...).
8660 */
fsdirSetErrmsg(fsdir_cursor * pCur,const char * zFmt,...)8661 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
8662   va_list ap;
8663   va_start(ap, zFmt);
8664   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
8665   va_end(ap);
8666 }
8667 
8668 
8669 /*
8670 ** Advance an fsdir_cursor to its next row of output.
8671 */
fsdirNext(sqlite3_vtab_cursor * cur)8672 static int fsdirNext(sqlite3_vtab_cursor *cur){
8673   fsdir_cursor *pCur = (fsdir_cursor*)cur;
8674   mode_t m = pCur->sStat.st_mode;
8675 
8676   pCur->iRowid++;
8677   if( S_ISDIR(m) ){
8678     /* Descend into this directory */
8679     int iNew = pCur->iLvl + 1;
8680     FsdirLevel *pLvl;
8681     if( iNew>=pCur->nLvl ){
8682       int nNew = iNew+1;
8683       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
8684       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
8685       if( aNew==0 ) return SQLITE_NOMEM;
8686       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
8687       pCur->aLvl = aNew;
8688       pCur->nLvl = nNew;
8689     }
8690     pCur->iLvl = iNew;
8691     pLvl = &pCur->aLvl[iNew];
8692 
8693     pLvl->zDir = pCur->zPath;
8694     pCur->zPath = 0;
8695     pLvl->pDir = opendir(pLvl->zDir);
8696     if( pLvl->pDir==0 ){
8697       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
8698       return SQLITE_ERROR;
8699     }
8700   }
8701 
8702   while( pCur->iLvl>=0 ){
8703     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
8704     struct dirent *pEntry = readdir(pLvl->pDir);
8705     if( pEntry ){
8706       if( pEntry->d_name[0]=='.' ){
8707        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
8708        if( pEntry->d_name[1]=='\0' ) continue;
8709       }
8710       sqlite3_free(pCur->zPath);
8711       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
8712       if( pCur->zPath==0 ) return SQLITE_NOMEM;
8713       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
8714         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
8715         return SQLITE_ERROR;
8716       }
8717       return SQLITE_OK;
8718     }
8719     closedir(pLvl->pDir);
8720     sqlite3_free(pLvl->zDir);
8721     pLvl->pDir = 0;
8722     pLvl->zDir = 0;
8723     pCur->iLvl--;
8724   }
8725 
8726   /* EOF */
8727   sqlite3_free(pCur->zPath);
8728   pCur->zPath = 0;
8729   return SQLITE_OK;
8730 }
8731 
8732 /*
8733 ** Return values of columns for the row at which the series_cursor
8734 ** is currently pointing.
8735 */
fsdirColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)8736 static int fsdirColumn(
8737   sqlite3_vtab_cursor *cur,   /* The cursor */
8738   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8739   int i                       /* Which column to return */
8740 ){
8741   fsdir_cursor *pCur = (fsdir_cursor*)cur;
8742   switch( i ){
8743     case FSDIR_COLUMN_NAME: {
8744       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
8745       break;
8746     }
8747 
8748     case FSDIR_COLUMN_MODE:
8749       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
8750       break;
8751 
8752     case FSDIR_COLUMN_MTIME:
8753       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
8754       break;
8755 
8756     case FSDIR_COLUMN_DATA: {
8757       mode_t m = pCur->sStat.st_mode;
8758       if( S_ISDIR(m) ){
8759         sqlite3_result_null(ctx);
8760 #if !defined(_WIN32) && !defined(WIN32)
8761       }else if( S_ISLNK(m) ){
8762         char aStatic[64];
8763         char *aBuf = aStatic;
8764         sqlite3_int64 nBuf = 64;
8765         int n;
8766 
8767         while( 1 ){
8768           n = readlink(pCur->zPath, aBuf, nBuf);
8769           if( n<nBuf ) break;
8770           if( aBuf!=aStatic ) sqlite3_free(aBuf);
8771           nBuf = nBuf*2;
8772           aBuf = sqlite3_malloc64(nBuf);
8773           if( aBuf==0 ){
8774             sqlite3_result_error_nomem(ctx);
8775             return SQLITE_NOMEM;
8776           }
8777         }
8778 
8779         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
8780         if( aBuf!=aStatic ) sqlite3_free(aBuf);
8781 #endif
8782       }else{
8783         readFileContents(ctx, pCur->zPath);
8784       }
8785     }
8786     case FSDIR_COLUMN_PATH:
8787     default: {
8788       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
8789       ** always return their values as NULL */
8790       break;
8791     }
8792   }
8793   return SQLITE_OK;
8794 }
8795 
8796 /*
8797 ** Return the rowid for the current row. In this implementation, the
8798 ** first row returned is assigned rowid value 1, and each subsequent
8799 ** row a value 1 more than that of the previous.
8800 */
fsdirRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)8801 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8802   fsdir_cursor *pCur = (fsdir_cursor*)cur;
8803   *pRowid = pCur->iRowid;
8804   return SQLITE_OK;
8805 }
8806 
8807 /*
8808 ** Return TRUE if the cursor has been moved off of the last
8809 ** row of output.
8810 */
fsdirEof(sqlite3_vtab_cursor * cur)8811 static int fsdirEof(sqlite3_vtab_cursor *cur){
8812   fsdir_cursor *pCur = (fsdir_cursor*)cur;
8813   return (pCur->zPath==0);
8814 }
8815 
8816 /*
8817 ** xFilter callback.
8818 **
8819 ** idxNum==1   PATH parameter only
8820 ** idxNum==2   Both PATH and DIR supplied
8821 */
fsdirFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)8822 static int fsdirFilter(
8823   sqlite3_vtab_cursor *cur,
8824   int idxNum, const char *idxStr,
8825   int argc, sqlite3_value **argv
8826 ){
8827   const char *zDir = 0;
8828   fsdir_cursor *pCur = (fsdir_cursor*)cur;
8829   (void)idxStr;
8830   fsdirResetCursor(pCur);
8831 
8832   if( idxNum==0 ){
8833     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
8834     return SQLITE_ERROR;
8835   }
8836 
8837   assert( argc==idxNum && (argc==1 || argc==2) );
8838   zDir = (const char*)sqlite3_value_text(argv[0]);
8839   if( zDir==0 ){
8840     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
8841     return SQLITE_ERROR;
8842   }
8843   if( argc==2 ){
8844     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
8845   }
8846   if( pCur->zBase ){
8847     pCur->nBase = (int)strlen(pCur->zBase)+1;
8848     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
8849   }else{
8850     pCur->zPath = sqlite3_mprintf("%s", zDir);
8851   }
8852 
8853   if( pCur->zPath==0 ){
8854     return SQLITE_NOMEM;
8855   }
8856   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
8857     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
8858     return SQLITE_ERROR;
8859   }
8860 
8861   return SQLITE_OK;
8862 }
8863 
8864 /*
8865 ** SQLite will invoke this method one or more times while planning a query
8866 ** that uses the generate_series virtual table.  This routine needs to create
8867 ** a query plan for each invocation and compute an estimated cost for that
8868 ** plan.
8869 **
8870 ** In this implementation idxNum is used to represent the
8871 ** query plan.  idxStr is unused.
8872 **
8873 ** The query plan is represented by values of idxNum:
8874 **
8875 **  (1)  The path value is supplied by argv[0]
8876 **  (2)  Path is in argv[0] and dir is in argv[1]
8877 */
fsdirBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)8878 static int fsdirBestIndex(
8879   sqlite3_vtab *tab,
8880   sqlite3_index_info *pIdxInfo
8881 ){
8882   int i;                 /* Loop over constraints */
8883   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
8884   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
8885   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
8886   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
8887   const struct sqlite3_index_constraint *pConstraint;
8888 
8889   (void)tab;
8890   pConstraint = pIdxInfo->aConstraint;
8891   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8892     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8893     switch( pConstraint->iColumn ){
8894       case FSDIR_COLUMN_PATH: {
8895         if( pConstraint->usable ){
8896           idxPath = i;
8897           seenPath = 0;
8898         }else if( idxPath<0 ){
8899           seenPath = 1;
8900         }
8901         break;
8902       }
8903       case FSDIR_COLUMN_DIR: {
8904         if( pConstraint->usable ){
8905           idxDir = i;
8906           seenDir = 0;
8907         }else if( idxDir<0 ){
8908           seenDir = 1;
8909         }
8910         break;
8911       }
8912     }
8913   }
8914   if( seenPath || seenDir ){
8915     /* If input parameters are unusable, disallow this plan */
8916     return SQLITE_CONSTRAINT;
8917   }
8918 
8919   if( idxPath<0 ){
8920     pIdxInfo->idxNum = 0;
8921     /* The pIdxInfo->estimatedCost should have been initialized to a huge
8922     ** number.  Leave it unchanged. */
8923     pIdxInfo->estimatedRows = 0x7fffffff;
8924   }else{
8925     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
8926     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
8927     if( idxDir>=0 ){
8928       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
8929       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
8930       pIdxInfo->idxNum = 2;
8931       pIdxInfo->estimatedCost = 10.0;
8932     }else{
8933       pIdxInfo->idxNum = 1;
8934       pIdxInfo->estimatedCost = 100.0;
8935     }
8936   }
8937 
8938   return SQLITE_OK;
8939 }
8940 
8941 /*
8942 ** Register the "fsdir" virtual table.
8943 */
fsdirRegister(sqlite3 * db)8944 static int fsdirRegister(sqlite3 *db){
8945   static sqlite3_module fsdirModule = {
8946     0,                         /* iVersion */
8947     0,                         /* xCreate */
8948     fsdirConnect,              /* xConnect */
8949     fsdirBestIndex,            /* xBestIndex */
8950     fsdirDisconnect,           /* xDisconnect */
8951     0,                         /* xDestroy */
8952     fsdirOpen,                 /* xOpen - open a cursor */
8953     fsdirClose,                /* xClose - close a cursor */
8954     fsdirFilter,               /* xFilter - configure scan constraints */
8955     fsdirNext,                 /* xNext - advance a cursor */
8956     fsdirEof,                  /* xEof - check for end of scan */
8957     fsdirColumn,               /* xColumn - read data */
8958     fsdirRowid,                /* xRowid - read data */
8959     0,                         /* xUpdate */
8960     0,                         /* xBegin */
8961     0,                         /* xSync */
8962     0,                         /* xCommit */
8963     0,                         /* xRollback */
8964     0,                         /* xFindMethod */
8965     0,                         /* xRename */
8966     0,                         /* xSavepoint */
8967     0,                         /* xRelease */
8968     0,                         /* xRollbackTo */
8969     0,                         /* xShadowName */
8970     0                          /* xIntegrity */
8971   };
8972 
8973   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
8974   return rc;
8975 }
8976 #else         /* SQLITE_OMIT_VIRTUALTABLE */
8977 # define fsdirRegister(x) SQLITE_OK
8978 #endif
8979 
8980 #ifdef _WIN32
8981 
8982 #endif
sqlite3_fileio_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8983 int sqlite3_fileio_init(
8984   sqlite3 *db,
8985   char **pzErrMsg,
8986   const sqlite3_api_routines *pApi
8987 ){
8988   int rc = SQLITE_OK;
8989   SQLITE_EXTENSION_INIT2(pApi);
8990   (void)pzErrMsg;  /* Unused parameter */
8991   rc = sqlite3_create_function(db, "readfile", 1,
8992                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8993                                readfileFunc, 0, 0);
8994   if( rc==SQLITE_OK ){
8995     rc = sqlite3_create_function(db, "writefile", -1,
8996                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8997                                  writefileFunc, 0, 0);
8998   }
8999   if( rc==SQLITE_OK ){
9000     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
9001                                  lsModeFunc, 0, 0);
9002   }
9003   if( rc==SQLITE_OK ){
9004     rc = fsdirRegister(db);
9005   }
9006   return rc;
9007 }
9008 
9009 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
9010 /* To allow a standalone DLL, make test_windirent.c use the same
9011  * redefined SQLite API calls as the above extension code does.
9012  * Just pull in this .c to accomplish this. As a beneficial side
9013  * effect, this extension becomes a single translation unit. */
9014 #  include "test_windirent.c"
9015 #endif
9016 
9017 /************************* End ../ext/misc/fileio.c ********************/
9018 /************************* Begin ../ext/misc/completion.c ******************/
9019 /*
9020 ** 2017-07-10
9021 **
9022 ** The author disclaims copyright to this source code.  In place of
9023 ** a legal notice, here is a blessing:
9024 **
9025 **    May you do good and not evil.
9026 **    May you find forgiveness for yourself and forgive others.
9027 **    May you share freely, never taking more than you give.
9028 **
9029 *************************************************************************
9030 **
9031 ** This file implements an eponymous virtual table that returns suggested
9032 ** completions for a partial SQL input.
9033 **
9034 ** Suggested usage:
9035 **
9036 **     SELECT DISTINCT candidate COLLATE nocase
9037 **       FROM completion($prefix,$wholeline)
9038 **      ORDER BY 1;
9039 **
9040 ** The two query parameters are optional.  $prefix is the text of the
9041 ** current word being typed and that is to be completed.  $wholeline is
9042 ** the complete input line, used for context.
9043 **
9044 ** The raw completion() table might return the same candidate multiple
9045 ** times, for example if the same column name is used to two or more
9046 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
9047 ** the DISTINCT and ORDER BY are recommended.
9048 **
9049 ** This virtual table operates at the speed of human typing, and so there
9050 ** is no attempt to make it fast.  Even a slow implementation will be much
9051 ** faster than any human can type.
9052 **
9053 */
9054 /* #include "sqlite3ext.h" */
9055 SQLITE_EXTENSION_INIT1
9056 #include <assert.h>
9057 #include <string.h>
9058 #include <ctype.h>
9059 
9060 #ifndef SQLITE_OMIT_VIRTUALTABLE
9061 
9062 #ifndef IsAlnum
9063 #define IsAlnum(X)  isalnum((unsigned char)X)
9064 #endif
9065 
9066 
9067 /* completion_vtab is a subclass of sqlite3_vtab which will
9068 ** serve as the underlying representation of a completion virtual table
9069 */
9070 typedef struct completion_vtab completion_vtab;
9071 struct completion_vtab {
9072   sqlite3_vtab base;  /* Base class - must be first */
9073   sqlite3 *db;        /* Database connection for this completion vtab */
9074 };
9075 
9076 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
9077 ** serve as the underlying representation of a cursor that scans
9078 ** over rows of the result
9079 */
9080 typedef struct completion_cursor completion_cursor;
9081 struct completion_cursor {
9082   sqlite3_vtab_cursor base;  /* Base class - must be first */
9083   sqlite3 *db;               /* Database connection for this cursor */
9084   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
9085   char *zPrefix;             /* The prefix for the word we want to complete */
9086   char *zLine;               /* The whole that we want to complete */
9087   const char *zCurrentRow;   /* Current output row */
9088   int szRow;                 /* Length of the zCurrentRow string */
9089   sqlite3_stmt *pStmt;       /* Current statement */
9090   sqlite3_int64 iRowid;      /* The rowid */
9091   int ePhase;                /* Current phase */
9092   int j;                     /* inter-phase counter */
9093 };
9094 
9095 /* Values for ePhase:
9096 */
9097 #define COMPLETION_FIRST_PHASE   1
9098 #define COMPLETION_KEYWORDS      1
9099 #define COMPLETION_PRAGMAS       2
9100 #define COMPLETION_FUNCTIONS     3
9101 #define COMPLETION_COLLATIONS    4
9102 #define COMPLETION_INDEXES       5
9103 #define COMPLETION_TRIGGERS      6
9104 #define COMPLETION_DATABASES     7
9105 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
9106 #define COMPLETION_COLUMNS       9
9107 #define COMPLETION_MODULES       10
9108 #define COMPLETION_EOF           11
9109 
9110 /*
9111 ** The completionConnect() method is invoked to create a new
9112 ** completion_vtab that describes the completion virtual table.
9113 **
9114 ** Think of this routine as the constructor for completion_vtab objects.
9115 **
9116 ** All this routine needs to do is:
9117 **
9118 **    (1) Allocate the completion_vtab object and initialize all fields.
9119 **
9120 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
9121 **        result set of queries against completion will look like.
9122 */
completionConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)9123 static int completionConnect(
9124   sqlite3 *db,
9125   void *pAux,
9126   int argc, const char *const*argv,
9127   sqlite3_vtab **ppVtab,
9128   char **pzErr
9129 ){
9130   completion_vtab *pNew;
9131   int rc;
9132 
9133   (void)(pAux);    /* Unused parameter */
9134   (void)(argc);    /* Unused parameter */
9135   (void)(argv);    /* Unused parameter */
9136   (void)(pzErr);   /* Unused parameter */
9137 
9138 /* Column numbers */
9139 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
9140 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
9141 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
9142 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
9143 
9144   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
9145   rc = sqlite3_declare_vtab(db,
9146       "CREATE TABLE x("
9147       "  candidate TEXT,"
9148       "  prefix TEXT HIDDEN,"
9149       "  wholeline TEXT HIDDEN,"
9150       "  phase INT HIDDEN"        /* Used for debugging only */
9151       ")");
9152   if( rc==SQLITE_OK ){
9153     pNew = sqlite3_malloc( sizeof(*pNew) );
9154     *ppVtab = (sqlite3_vtab*)pNew;
9155     if( pNew==0 ) return SQLITE_NOMEM;
9156     memset(pNew, 0, sizeof(*pNew));
9157     pNew->db = db;
9158   }
9159   return rc;
9160 }
9161 
9162 /*
9163 ** This method is the destructor for completion_cursor objects.
9164 */
completionDisconnect(sqlite3_vtab * pVtab)9165 static int completionDisconnect(sqlite3_vtab *pVtab){
9166   sqlite3_free(pVtab);
9167   return SQLITE_OK;
9168 }
9169 
9170 /*
9171 ** Constructor for a new completion_cursor object.
9172 */
completionOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)9173 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
9174   completion_cursor *pCur;
9175   pCur = sqlite3_malloc( sizeof(*pCur) );
9176   if( pCur==0 ) return SQLITE_NOMEM;
9177   memset(pCur, 0, sizeof(*pCur));
9178   pCur->db = ((completion_vtab*)p)->db;
9179   *ppCursor = &pCur->base;
9180   return SQLITE_OK;
9181 }
9182 
9183 /*
9184 ** Reset the completion_cursor.
9185 */
completionCursorReset(completion_cursor * pCur)9186 static void completionCursorReset(completion_cursor *pCur){
9187   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
9188   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
9189   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
9190   pCur->j = 0;
9191 }
9192 
9193 /*
9194 ** Destructor for a completion_cursor.
9195 */
completionClose(sqlite3_vtab_cursor * cur)9196 static int completionClose(sqlite3_vtab_cursor *cur){
9197   completionCursorReset((completion_cursor*)cur);
9198   sqlite3_free(cur);
9199   return SQLITE_OK;
9200 }
9201 
9202 /*
9203 ** Advance a completion_cursor to its next row of output.
9204 **
9205 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
9206 ** record the current state of the scan.  This routine sets ->zCurrentRow
9207 ** to the current row of output and then returns.  If no more rows remain,
9208 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
9209 ** table that has reached the end of its scan.
9210 **
9211 ** The current implementation just lists potential identifiers and
9212 ** keywords and filters them by zPrefix.  Future enhancements should
9213 ** take zLine into account to try to restrict the set of identifiers and
9214 ** keywords based on what would be legal at the current point of input.
9215 */
completionNext(sqlite3_vtab_cursor * cur)9216 static int completionNext(sqlite3_vtab_cursor *cur){
9217   completion_cursor *pCur = (completion_cursor*)cur;
9218   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
9219   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
9220   pCur->iRowid++;
9221   while( pCur->ePhase!=COMPLETION_EOF ){
9222     switch( pCur->ePhase ){
9223       case COMPLETION_KEYWORDS: {
9224         if( pCur->j >= sqlite3_keyword_count() ){
9225           pCur->zCurrentRow = 0;
9226           pCur->ePhase = COMPLETION_DATABASES;
9227         }else{
9228           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
9229         }
9230         iCol = -1;
9231         break;
9232       }
9233       case COMPLETION_DATABASES: {
9234         if( pCur->pStmt==0 ){
9235           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
9236                              &pCur->pStmt, 0);
9237         }
9238         iCol = 1;
9239         eNextPhase = COMPLETION_TABLES;
9240         break;
9241       }
9242       case COMPLETION_TABLES: {
9243         if( pCur->pStmt==0 ){
9244           sqlite3_stmt *pS2;
9245           char *zSql = 0;
9246           const char *zSep = "";
9247           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
9248           while( sqlite3_step(pS2)==SQLITE_ROW ){
9249             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
9250             zSql = sqlite3_mprintf(
9251                "%z%s"
9252                "SELECT name FROM \"%w\".sqlite_schema",
9253                zSql, zSep, zDb
9254             );
9255             if( zSql==0 ) return SQLITE_NOMEM;
9256             zSep = " UNION ";
9257           }
9258           sqlite3_finalize(pS2);
9259           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
9260           sqlite3_free(zSql);
9261         }
9262         iCol = 0;
9263         eNextPhase = COMPLETION_COLUMNS;
9264         break;
9265       }
9266       case COMPLETION_COLUMNS: {
9267         if( pCur->pStmt==0 ){
9268           sqlite3_stmt *pS2;
9269           char *zSql = 0;
9270           const char *zSep = "";
9271           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
9272           while( sqlite3_step(pS2)==SQLITE_ROW ){
9273             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
9274             zSql = sqlite3_mprintf(
9275                "%z%s"
9276                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
9277                        " JOIN pragma_table_xinfo(sm.name,%Q) AS pti"
9278                " WHERE sm.type='table'",
9279                zSql, zSep, zDb, zDb
9280             );
9281             if( zSql==0 ) return SQLITE_NOMEM;
9282             zSep = " UNION ";
9283           }
9284           sqlite3_finalize(pS2);
9285           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
9286           sqlite3_free(zSql);
9287         }
9288         iCol = 0;
9289         eNextPhase = COMPLETION_EOF;
9290         break;
9291       }
9292     }
9293     if( iCol<0 ){
9294       /* This case is when the phase presets zCurrentRow */
9295       if( pCur->zCurrentRow==0 ) continue;
9296     }else{
9297       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
9298         /* Extract the next row of content */
9299         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
9300         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
9301       }else{
9302         /* When all rows are finished, advance to the next phase */
9303         sqlite3_finalize(pCur->pStmt);
9304         pCur->pStmt = 0;
9305         pCur->ePhase = eNextPhase;
9306         continue;
9307       }
9308     }
9309     if( pCur->nPrefix==0 ) break;
9310     if( pCur->nPrefix<=pCur->szRow
9311      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
9312     ){
9313       break;
9314     }
9315   }
9316 
9317   return SQLITE_OK;
9318 }
9319 
9320 /*
9321 ** Return values of columns for the row at which the completion_cursor
9322 ** is currently pointing.
9323 */
completionColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)9324 static int completionColumn(
9325   sqlite3_vtab_cursor *cur,   /* The cursor */
9326   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
9327   int i                       /* Which column to return */
9328 ){
9329   completion_cursor *pCur = (completion_cursor*)cur;
9330   switch( i ){
9331     case COMPLETION_COLUMN_CANDIDATE: {
9332       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
9333       break;
9334     }
9335     case COMPLETION_COLUMN_PREFIX: {
9336       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
9337       break;
9338     }
9339     case COMPLETION_COLUMN_WHOLELINE: {
9340       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
9341       break;
9342     }
9343     case COMPLETION_COLUMN_PHASE: {
9344       sqlite3_result_int(ctx, pCur->ePhase);
9345       break;
9346     }
9347   }
9348   return SQLITE_OK;
9349 }
9350 
9351 /*
9352 ** Return the rowid for the current row.  In this implementation, the
9353 ** rowid is the same as the output value.
9354 */
completionRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)9355 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
9356   completion_cursor *pCur = (completion_cursor*)cur;
9357   *pRowid = pCur->iRowid;
9358   return SQLITE_OK;
9359 }
9360 
9361 /*
9362 ** Return TRUE if the cursor has been moved off of the last
9363 ** row of output.
9364 */
completionEof(sqlite3_vtab_cursor * cur)9365 static int completionEof(sqlite3_vtab_cursor *cur){
9366   completion_cursor *pCur = (completion_cursor*)cur;
9367   return pCur->ePhase >= COMPLETION_EOF;
9368 }
9369 
9370 /*
9371 ** This method is called to "rewind" the completion_cursor object back
9372 ** to the first row of output.  This method is always called at least
9373 ** once prior to any call to completionColumn() or completionRowid() or
9374 ** completionEof().
9375 */
completionFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)9376 static int completionFilter(
9377   sqlite3_vtab_cursor *pVtabCursor,
9378   int idxNum, const char *idxStr,
9379   int argc, sqlite3_value **argv
9380 ){
9381   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
9382   int iArg = 0;
9383   (void)(idxStr);   /* Unused parameter */
9384   (void)(argc);     /* Unused parameter */
9385   completionCursorReset(pCur);
9386   if( idxNum & 1 ){
9387     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
9388     if( pCur->nPrefix>0 ){
9389       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
9390       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
9391     }
9392     iArg = 1;
9393   }
9394   if( idxNum & 2 ){
9395     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
9396     if( pCur->nLine>0 ){
9397       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
9398       if( pCur->zLine==0 ) return SQLITE_NOMEM;
9399     }
9400   }
9401   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
9402     int i = pCur->nLine;
9403     while( i>0 && (IsAlnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
9404       i--;
9405     }
9406     pCur->nPrefix = pCur->nLine - i;
9407     if( pCur->nPrefix>0 ){
9408       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
9409       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
9410     }
9411   }
9412   pCur->iRowid = 0;
9413   pCur->ePhase = COMPLETION_FIRST_PHASE;
9414   return completionNext(pVtabCursor);
9415 }
9416 
9417 /*
9418 ** SQLite will invoke this method one or more times while planning a query
9419 ** that uses the completion virtual table.  This routine needs to create
9420 ** a query plan for each invocation and compute an estimated cost for that
9421 ** plan.
9422 **
9423 ** There are two hidden parameters that act as arguments to the table-valued
9424 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
9425 ** is available and bit 1 is set if "wholeline" is available.
9426 */
completionBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)9427 static int completionBestIndex(
9428   sqlite3_vtab *tab,
9429   sqlite3_index_info *pIdxInfo
9430 ){
9431   int i;                 /* Loop over constraints */
9432   int idxNum = 0;        /* The query plan bitmask */
9433   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
9434   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
9435   int nArg = 0;          /* Number of arguments that completeFilter() expects */
9436   const struct sqlite3_index_constraint *pConstraint;
9437 
9438   (void)(tab);    /* Unused parameter */
9439   pConstraint = pIdxInfo->aConstraint;
9440   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
9441     if( pConstraint->usable==0 ) continue;
9442     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
9443     switch( pConstraint->iColumn ){
9444       case COMPLETION_COLUMN_PREFIX:
9445         prefixIdx = i;
9446         idxNum |= 1;
9447         break;
9448       case COMPLETION_COLUMN_WHOLELINE:
9449         wholelineIdx = i;
9450         idxNum |= 2;
9451         break;
9452     }
9453   }
9454   if( prefixIdx>=0 ){
9455     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
9456     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
9457   }
9458   if( wholelineIdx>=0 ){
9459     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
9460     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
9461   }
9462   pIdxInfo->idxNum = idxNum;
9463   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
9464   pIdxInfo->estimatedRows = 500 - 100*nArg;
9465   return SQLITE_OK;
9466 }
9467 
9468 /*
9469 ** This following structure defines all the methods for the
9470 ** completion virtual table.
9471 */
9472 static sqlite3_module completionModule = {
9473   0,                         /* iVersion */
9474   0,                         /* xCreate */
9475   completionConnect,         /* xConnect */
9476   completionBestIndex,       /* xBestIndex */
9477   completionDisconnect,      /* xDisconnect */
9478   0,                         /* xDestroy */
9479   completionOpen,            /* xOpen - open a cursor */
9480   completionClose,           /* xClose - close a cursor */
9481   completionFilter,          /* xFilter - configure scan constraints */
9482   completionNext,            /* xNext - advance a cursor */
9483   completionEof,             /* xEof - check for end of scan */
9484   completionColumn,          /* xColumn - read data */
9485   completionRowid,           /* xRowid - read data */
9486   0,                         /* xUpdate */
9487   0,                         /* xBegin */
9488   0,                         /* xSync */
9489   0,                         /* xCommit */
9490   0,                         /* xRollback */
9491   0,                         /* xFindMethod */
9492   0,                         /* xRename */
9493   0,                         /* xSavepoint */
9494   0,                         /* xRelease */
9495   0,                         /* xRollbackTo */
9496   0,                         /* xShadowName */
9497   0                          /* xIntegrity */
9498 };
9499 
9500 #endif /* SQLITE_OMIT_VIRTUALTABLE */
9501 
sqlite3CompletionVtabInit(sqlite3 * db)9502 int sqlite3CompletionVtabInit(sqlite3 *db){
9503   int rc = SQLITE_OK;
9504 #ifndef SQLITE_OMIT_VIRTUALTABLE
9505   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
9506 #endif
9507   return rc;
9508 }
9509 
9510 #ifdef _WIN32
9511 
9512 #endif
sqlite3_completion_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)9513 int sqlite3_completion_init(
9514   sqlite3 *db,
9515   char **pzErrMsg,
9516   const sqlite3_api_routines *pApi
9517 ){
9518   int rc = SQLITE_OK;
9519   SQLITE_EXTENSION_INIT2(pApi);
9520   (void)(pzErrMsg);  /* Unused parameter */
9521 #ifndef SQLITE_OMIT_VIRTUALTABLE
9522   rc = sqlite3CompletionVtabInit(db);
9523 #endif
9524   return rc;
9525 }
9526 
9527 /************************* End ../ext/misc/completion.c ********************/
9528 /************************* Begin ../ext/misc/appendvfs.c ******************/
9529 /*
9530 ** 2017-10-20
9531 **
9532 ** The author disclaims copyright to this source code.  In place of
9533 ** a legal notice, here is a blessing:
9534 **
9535 **    May you do good and not evil.
9536 **    May you find forgiveness for yourself and forgive others.
9537 **    May you share freely, never taking more than you give.
9538 **
9539 ******************************************************************************
9540 **
9541 ** This file implements a VFS shim that allows an SQLite database to be
9542 ** appended onto the end of some other file, such as an executable.
9543 **
9544 ** A special record must appear at the end of the file that identifies the
9545 ** file as an appended database and provides the offset to the first page
9546 ** of the exposed content. (Or, it is the length of the content prefix.)
9547 ** For best performance page 1 should be located at a disk page boundary,
9548 ** though that is not required.
9549 **
9550 ** When opening a database using this VFS, the connection might treat
9551 ** the file as an ordinary SQLite database, or it might treat it as a
9552 ** database appended onto some other file.  The decision is made by
9553 ** applying the following rules in order:
9554 **
9555 **  (1)  An empty file is an ordinary database.
9556 **
9557 **  (2)  If the file ends with the appendvfs trailer string
9558 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
9559 **
9560 **  (3)  If the file begins with the standard SQLite prefix string
9561 **       "SQLite format 3", that file is an ordinary database.
9562 **
9563 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
9564 **       set, then a new database is appended to the already existing file.
9565 **
9566 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
9567 **
9568 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
9569 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
9570 ** This VFS will not read or write past the 1GiB mark.  This restriction
9571 ** might be lifted in future versions.  For now, if you need a larger
9572 ** database, then keep it in a separate file.
9573 **
9574 ** If the file being opened is a plain database (not an appended one), then
9575 ** this shim is a pass-through into the default underlying VFS. (rule 3)
9576 **/
9577 /* #include "sqlite3ext.h" */
9578 SQLITE_EXTENSION_INIT1
9579 #include <string.h>
9580 #include <assert.h>
9581 
9582 /* The append mark at the end of the database is:
9583 **
9584 **     Start-Of-SQLite3-NNNNNNNN
9585 **     123456789 123456789 12345
9586 **
9587 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
9588 ** the offset to page 1, and also the length of the prefix content.
9589 */
9590 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
9591 #define APND_MARK_PREFIX_SZ  17
9592 #define APND_MARK_FOS_SZ      8
9593 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
9594 
9595 /*
9596 ** Maximum size of the combined prefix + database + append-mark.  This
9597 ** must be less than 0x40000000 to avoid locking issues on Windows.
9598 */
9599 #define APND_MAX_SIZE  (0x40000000)
9600 
9601 /*
9602 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
9603 */
9604 #ifndef APND_ROUNDUP
9605 #define APND_ROUNDUP 4096
9606 #endif
9607 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
9608 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
9609 
9610 /*
9611 ** Forward declaration of objects used by this utility
9612 */
9613 typedef struct sqlite3_vfs ApndVfs;
9614 typedef struct ApndFile ApndFile;
9615 
9616 /* Access to a lower-level VFS that (might) implement dynamic loading,
9617 ** access to randomness, etc.
9618 */
9619 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
9620 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
9621 
9622 /* An open appendvfs file
9623 **
9624 ** An instance of this structure describes the appended database file.
9625 ** A separate sqlite3_file object is always appended. The appended
9626 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
9627 ** the entire file, including the prefix, the database, and the
9628 ** append-mark.
9629 **
9630 ** The structure of an AppendVFS database is like this:
9631 **
9632 **   +-------------+---------+----------+-------------+
9633 **   | prefix-file | padding | database | append-mark |
9634 **   +-------------+---------+----------+-------------+
9635 **                           ^          ^
9636 **                           |          |
9637 **                         iPgOne      iMark
9638 **
9639 **
9640 ** "prefix file" -  file onto which the database has been appended.
9641 ** "padding"     -  zero or more bytes inserted so that "database"
9642 **                  starts on an APND_ROUNDUP boundary
9643 ** "database"    -  The SQLite database file
9644 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
9645 **                  the offset from the start of prefix-file to the start
9646 **                  of "database".
9647 **
9648 ** The size of the database is iMark - iPgOne.
9649 **
9650 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
9651 ** of iPgOne stored as a big-ending 64-bit integer.
9652 **
9653 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
9654 ** Or, iMark is -1 to indicate that it has not yet been written.
9655 */
9656 struct ApndFile {
9657   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
9658   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
9659   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
9660   /* Always followed by another sqlite3_file that describes the whole file */
9661 };
9662 
9663 /*
9664 ** Methods for ApndFile
9665 */
9666 static int apndClose(sqlite3_file*);
9667 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
9668 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
9669 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
9670 static int apndSync(sqlite3_file*, int flags);
9671 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
9672 static int apndLock(sqlite3_file*, int);
9673 static int apndUnlock(sqlite3_file*, int);
9674 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
9675 static int apndFileControl(sqlite3_file*, int op, void *pArg);
9676 static int apndSectorSize(sqlite3_file*);
9677 static int apndDeviceCharacteristics(sqlite3_file*);
9678 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
9679 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
9680 static void apndShmBarrier(sqlite3_file*);
9681 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
9682 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
9683 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
9684 
9685 /*
9686 ** Methods for ApndVfs
9687 */
9688 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
9689 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
9690 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
9691 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
9692 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
9693 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
9694 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
9695 static void apndDlClose(sqlite3_vfs*, void*);
9696 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
9697 static int apndSleep(sqlite3_vfs*, int microseconds);
9698 static int apndCurrentTime(sqlite3_vfs*, double*);
9699 static int apndGetLastError(sqlite3_vfs*, int, char *);
9700 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
9701 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
9702 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
9703 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
9704 
9705 static sqlite3_vfs apnd_vfs = {
9706   3,                            /* iVersion (set when registered) */
9707   0,                            /* szOsFile (set when registered) */
9708   1024,                         /* mxPathname */
9709   0,                            /* pNext */
9710   "apndvfs",                    /* zName */
9711   0,                            /* pAppData (set when registered) */
9712   apndOpen,                     /* xOpen */
9713   apndDelete,                   /* xDelete */
9714   apndAccess,                   /* xAccess */
9715   apndFullPathname,             /* xFullPathname */
9716   apndDlOpen,                   /* xDlOpen */
9717   apndDlError,                  /* xDlError */
9718   apndDlSym,                    /* xDlSym */
9719   apndDlClose,                  /* xDlClose */
9720   apndRandomness,               /* xRandomness */
9721   apndSleep,                    /* xSleep */
9722   apndCurrentTime,              /* xCurrentTime */
9723   apndGetLastError,             /* xGetLastError */
9724   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
9725   apndSetSystemCall,            /* xSetSystemCall */
9726   apndGetSystemCall,            /* xGetSystemCall */
9727   apndNextSystemCall            /* xNextSystemCall */
9728 };
9729 
9730 static const sqlite3_io_methods apnd_io_methods = {
9731   3,                              /* iVersion */
9732   apndClose,                      /* xClose */
9733   apndRead,                       /* xRead */
9734   apndWrite,                      /* xWrite */
9735   apndTruncate,                   /* xTruncate */
9736   apndSync,                       /* xSync */
9737   apndFileSize,                   /* xFileSize */
9738   apndLock,                       /* xLock */
9739   apndUnlock,                     /* xUnlock */
9740   apndCheckReservedLock,          /* xCheckReservedLock */
9741   apndFileControl,                /* xFileControl */
9742   apndSectorSize,                 /* xSectorSize */
9743   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
9744   apndShmMap,                     /* xShmMap */
9745   apndShmLock,                    /* xShmLock */
9746   apndShmBarrier,                 /* xShmBarrier */
9747   apndShmUnmap,                   /* xShmUnmap */
9748   apndFetch,                      /* xFetch */
9749   apndUnfetch                     /* xUnfetch */
9750 };
9751 
9752 /*
9753 ** Close an apnd-file.
9754 */
apndClose(sqlite3_file * pFile)9755 static int apndClose(sqlite3_file *pFile){
9756   pFile = ORIGFILE(pFile);
9757   return pFile->pMethods->xClose(pFile);
9758 }
9759 
9760 /*
9761 ** Read data from an apnd-file.
9762 */
apndRead(sqlite3_file * pFile,void * zBuf,int iAmt,sqlite_int64 iOfst)9763 static int apndRead(
9764   sqlite3_file *pFile,
9765   void *zBuf,
9766   int iAmt,
9767   sqlite_int64 iOfst
9768 ){
9769   ApndFile *paf = (ApndFile *)pFile;
9770   pFile = ORIGFILE(pFile);
9771   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
9772 }
9773 
9774 /*
9775 ** Add the append-mark onto what should become the end of the file.
9776 *  If and only if this succeeds, internal ApndFile.iMark is updated.
9777 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
9778 */
apndWriteMark(ApndFile * paf,sqlite3_file * pFile,sqlite_int64 iWriteEnd)9779 static int apndWriteMark(
9780   ApndFile *paf,
9781   sqlite3_file *pFile,
9782   sqlite_int64 iWriteEnd
9783 ){
9784   sqlite_int64 iPgOne = paf->iPgOne;
9785   unsigned char a[APND_MARK_SIZE];
9786   int i = APND_MARK_FOS_SZ;
9787   int rc;
9788   assert(pFile == ORIGFILE(paf));
9789   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
9790   while( --i >= 0 ){
9791     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
9792     iPgOne >>= 8;
9793   }
9794   iWriteEnd += paf->iPgOne;
9795   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
9796                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
9797     paf->iMark = iWriteEnd;
9798   }
9799   return rc;
9800 }
9801 
9802 /*
9803 ** Write data to an apnd-file.
9804 */
apndWrite(sqlite3_file * pFile,const void * zBuf,int iAmt,sqlite_int64 iOfst)9805 static int apndWrite(
9806   sqlite3_file *pFile,
9807   const void *zBuf,
9808   int iAmt,
9809   sqlite_int64 iOfst
9810 ){
9811   ApndFile *paf = (ApndFile *)pFile;
9812   sqlite_int64 iWriteEnd = iOfst + iAmt;
9813   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
9814   pFile = ORIGFILE(pFile);
9815   /* If append-mark is absent or will be overwritten, write it. */
9816   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
9817     int rc = apndWriteMark(paf, pFile, iWriteEnd);
9818     if( SQLITE_OK!=rc ) return rc;
9819   }
9820   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
9821 }
9822 
9823 /*
9824 ** Truncate an apnd-file.
9825 */
apndTruncate(sqlite3_file * pFile,sqlite_int64 size)9826 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
9827   ApndFile *paf = (ApndFile *)pFile;
9828   pFile = ORIGFILE(pFile);
9829   /* The append mark goes out first so truncate failure does not lose it. */
9830   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
9831   /* Truncate underlying file just past append mark */
9832   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
9833 }
9834 
9835 /*
9836 ** Sync an apnd-file.
9837 */
apndSync(sqlite3_file * pFile,int flags)9838 static int apndSync(sqlite3_file *pFile, int flags){
9839   pFile = ORIGFILE(pFile);
9840   return pFile->pMethods->xSync(pFile, flags);
9841 }
9842 
9843 /*
9844 ** Return the current file-size of an apnd-file.
9845 ** If the append mark is not yet there, the file-size is 0.
9846 */
apndFileSize(sqlite3_file * pFile,sqlite_int64 * pSize)9847 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
9848   ApndFile *paf = (ApndFile *)pFile;
9849   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
9850   return SQLITE_OK;
9851 }
9852 
9853 /*
9854 ** Lock an apnd-file.
9855 */
apndLock(sqlite3_file * pFile,int eLock)9856 static int apndLock(sqlite3_file *pFile, int eLock){
9857   pFile = ORIGFILE(pFile);
9858   return pFile->pMethods->xLock(pFile, eLock);
9859 }
9860 
9861 /*
9862 ** Unlock an apnd-file.
9863 */
apndUnlock(sqlite3_file * pFile,int eLock)9864 static int apndUnlock(sqlite3_file *pFile, int eLock){
9865   pFile = ORIGFILE(pFile);
9866   return pFile->pMethods->xUnlock(pFile, eLock);
9867 }
9868 
9869 /*
9870 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
9871 */
apndCheckReservedLock(sqlite3_file * pFile,int * pResOut)9872 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
9873   pFile = ORIGFILE(pFile);
9874   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
9875 }
9876 
9877 /*
9878 ** File control method. For custom operations on an apnd-file.
9879 */
apndFileControl(sqlite3_file * pFile,int op,void * pArg)9880 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
9881   ApndFile *paf = (ApndFile *)pFile;
9882   int rc;
9883   pFile = ORIGFILE(pFile);
9884   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
9885   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
9886   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
9887     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
9888   }
9889   return rc;
9890 }
9891 
9892 /*
9893 ** Return the sector-size in bytes for an apnd-file.
9894 */
apndSectorSize(sqlite3_file * pFile)9895 static int apndSectorSize(sqlite3_file *pFile){
9896   pFile = ORIGFILE(pFile);
9897   return pFile->pMethods->xSectorSize(pFile);
9898 }
9899 
9900 /*
9901 ** Return the device characteristic flags supported by an apnd-file.
9902 */
apndDeviceCharacteristics(sqlite3_file * pFile)9903 static int apndDeviceCharacteristics(sqlite3_file *pFile){
9904   pFile = ORIGFILE(pFile);
9905   return pFile->pMethods->xDeviceCharacteristics(pFile);
9906 }
9907 
9908 /* Create a shared memory file mapping */
apndShmMap(sqlite3_file * pFile,int iPg,int pgsz,int bExtend,void volatile ** pp)9909 static int apndShmMap(
9910   sqlite3_file *pFile,
9911   int iPg,
9912   int pgsz,
9913   int bExtend,
9914   void volatile **pp
9915 ){
9916   pFile = ORIGFILE(pFile);
9917   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
9918 }
9919 
9920 /* Perform locking on a shared-memory segment */
apndShmLock(sqlite3_file * pFile,int offset,int n,int flags)9921 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
9922   pFile = ORIGFILE(pFile);
9923   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
9924 }
9925 
9926 /* Memory barrier operation on shared memory */
apndShmBarrier(sqlite3_file * pFile)9927 static void apndShmBarrier(sqlite3_file *pFile){
9928   pFile = ORIGFILE(pFile);
9929   pFile->pMethods->xShmBarrier(pFile);
9930 }
9931 
9932 /* Unmap a shared memory segment */
apndShmUnmap(sqlite3_file * pFile,int deleteFlag)9933 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
9934   pFile = ORIGFILE(pFile);
9935   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
9936 }
9937 
9938 /* Fetch a page of a memory-mapped file */
apndFetch(sqlite3_file * pFile,sqlite3_int64 iOfst,int iAmt,void ** pp)9939 static int apndFetch(
9940   sqlite3_file *pFile,
9941   sqlite3_int64 iOfst,
9942   int iAmt,
9943   void **pp
9944 ){
9945   ApndFile *p = (ApndFile *)pFile;
9946   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
9947     return SQLITE_IOERR; /* Cannot read what is not yet there. */
9948   }
9949   pFile = ORIGFILE(pFile);
9950   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
9951 }
9952 
9953 /* Release a memory-mapped page */
apndUnfetch(sqlite3_file * pFile,sqlite3_int64 iOfst,void * pPage)9954 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
9955   ApndFile *p = (ApndFile *)pFile;
9956   pFile = ORIGFILE(pFile);
9957   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
9958 }
9959 
9960 /*
9961 ** Try to read the append-mark off the end of a file.  Return the
9962 ** start of the appended database if the append-mark is present.
9963 ** If there is no valid append-mark, return -1;
9964 **
9965 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
9966 ** indicates that the appended database contains at least one page.  The
9967 ** start-of-database value must be a multiple of 512.
9968 */
apndReadMark(sqlite3_int64 sz,sqlite3_file * pFile)9969 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
9970   int rc, i;
9971   sqlite3_int64 iMark;
9972   int msbs = 8 * (APND_MARK_FOS_SZ-1);
9973   unsigned char a[APND_MARK_SIZE];
9974 
9975   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
9976   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
9977   if( rc ) return -1;
9978   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
9979   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
9980   for(i=1; i<8; i++){
9981     msbs -= 8;
9982     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
9983   }
9984   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
9985   if( iMark & 0x1ff ) return -1;
9986   return iMark;
9987 }
9988 
9989 static const char apvfsSqliteHdr[] = "SQLite format 3";
9990 /*
9991 ** Check to see if the file is an appendvfs SQLite database file.
9992 ** Return true iff it is such. Parameter sz is the file's size.
9993 */
apndIsAppendvfsDatabase(sqlite3_int64 sz,sqlite3_file * pFile)9994 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
9995   int rc;
9996   char zHdr[16];
9997   sqlite3_int64 iMark = apndReadMark(sz, pFile);
9998   if( iMark>=0 ){
9999     /* If file has the correct end-marker, the expected odd size, and the
10000     ** SQLite DB type marker where the end-marker puts it, then it
10001     ** is an appendvfs database.
10002     */
10003     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
10004     if( SQLITE_OK==rc
10005      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
10006      && (sz & 0x1ff) == APND_MARK_SIZE
10007      && sz>=512+APND_MARK_SIZE
10008     ){
10009       return 1; /* It's an appendvfs database */
10010     }
10011   }
10012   return 0;
10013 }
10014 
10015 /*
10016 ** Check to see if the file is an ordinary SQLite database file.
10017 ** Return true iff so. Parameter sz is the file's size.
10018 */
apndIsOrdinaryDatabaseFile(sqlite3_int64 sz,sqlite3_file * pFile)10019 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
10020   char zHdr[16];
10021   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
10022    || (sz & 0x1ff) != 0
10023    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
10024    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
10025   ){
10026     return 0;
10027   }else{
10028     return 1;
10029   }
10030 }
10031 
10032 /*
10033 ** Open an apnd file handle.
10034 */
apndOpen(sqlite3_vfs * pApndVfs,const char * zName,sqlite3_file * pFile,int flags,int * pOutFlags)10035 static int apndOpen(
10036   sqlite3_vfs *pApndVfs,
10037   const char *zName,
10038   sqlite3_file *pFile,
10039   int flags,
10040   int *pOutFlags
10041 ){
10042   ApndFile *pApndFile = (ApndFile*)pFile;
10043   sqlite3_file *pBaseFile = ORIGFILE(pFile);
10044   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
10045   int rc;
10046   sqlite3_int64 sz = 0;
10047   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
10048     /* The appendvfs is not to be used for transient or temporary databases.
10049     ** Just use the base VFS open to initialize the given file object and
10050     ** open the underlying file. (Appendvfs is then unused for this file.)
10051     */
10052     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
10053   }
10054   memset(pApndFile, 0, sizeof(ApndFile));
10055   pFile->pMethods = &apnd_io_methods;
10056   pApndFile->iMark = -1;    /* Append mark not yet written */
10057 
10058   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
10059   if( rc==SQLITE_OK ){
10060     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
10061     if( rc ){
10062       pBaseFile->pMethods->xClose(pBaseFile);
10063     }
10064   }
10065   if( rc ){
10066     pFile->pMethods = 0;
10067     return rc;
10068   }
10069   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
10070     /* The file being opened appears to be just an ordinary DB. Copy
10071     ** the base dispatch-table so this instance mimics the base VFS.
10072     */
10073     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
10074     return SQLITE_OK;
10075   }
10076   pApndFile->iPgOne = apndReadMark(sz, pFile);
10077   if( pApndFile->iPgOne>=0 ){
10078     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
10079     return SQLITE_OK;
10080   }
10081   if( (flags & SQLITE_OPEN_CREATE)==0 ){
10082     pBaseFile->pMethods->xClose(pBaseFile);
10083     rc = SQLITE_CANTOPEN;
10084     pFile->pMethods = 0;
10085   }else{
10086     /* Round newly added appendvfs location to #define'd page boundary.
10087     ** Note that nothing has yet been written to the underlying file.
10088     ** The append mark will be written along with first content write.
10089     ** Until then, paf->iMark value indicates it is not yet written.
10090     */
10091     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
10092   }
10093   return rc;
10094 }
10095 
10096 /*
10097 ** Delete an apnd file.
10098 ** For an appendvfs, this could mean delete the appendvfs portion,
10099 ** leaving the appendee as it was before it gained an appendvfs.
10100 ** For now, this code deletes the underlying file too.
10101 */
apndDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)10102 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
10103   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
10104 }
10105 
10106 /*
10107 ** All other VFS methods are pass-thrus.
10108 */
apndAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)10109 static int apndAccess(
10110   sqlite3_vfs *pVfs,
10111   const char *zPath,
10112   int flags,
10113   int *pResOut
10114 ){
10115   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
10116 }
apndFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nOut,char * zOut)10117 static int apndFullPathname(
10118   sqlite3_vfs *pVfs,
10119   const char *zPath,
10120   int nOut,
10121   char *zOut
10122 ){
10123   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
10124 }
apndDlOpen(sqlite3_vfs * pVfs,const char * zPath)10125 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
10126   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
10127 }
apndDlError(sqlite3_vfs * pVfs,int nByte,char * zErrMsg)10128 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
10129   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
10130 }
apndDlSym(sqlite3_vfs * pVfs,void * p,const char * zSym)10131 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
10132   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
10133 }
apndDlClose(sqlite3_vfs * pVfs,void * pHandle)10134 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
10135   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
10136 }
apndRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)10137 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
10138   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
10139 }
apndSleep(sqlite3_vfs * pVfs,int nMicro)10140 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
10141   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
10142 }
apndCurrentTime(sqlite3_vfs * pVfs,double * pTimeOut)10143 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
10144   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
10145 }
apndGetLastError(sqlite3_vfs * pVfs,int a,char * b)10146 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
10147   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
10148 }
apndCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * p)10149 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
10150   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
10151 }
apndSetSystemCall(sqlite3_vfs * pVfs,const char * zName,sqlite3_syscall_ptr pCall)10152 static int apndSetSystemCall(
10153   sqlite3_vfs *pVfs,
10154   const char *zName,
10155   sqlite3_syscall_ptr pCall
10156 ){
10157   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
10158 }
apndGetSystemCall(sqlite3_vfs * pVfs,const char * zName)10159 static sqlite3_syscall_ptr apndGetSystemCall(
10160   sqlite3_vfs *pVfs,
10161   const char *zName
10162 ){
10163   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
10164 }
apndNextSystemCall(sqlite3_vfs * pVfs,const char * zName)10165 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
10166   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
10167 }
10168 
10169 
10170 #ifdef _WIN32
10171 
10172 #endif
10173 /*
10174 ** This routine is called when the extension is loaded.
10175 ** Register the new VFS.
10176 */
sqlite3_appendvfs_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)10177 int sqlite3_appendvfs_init(
10178   sqlite3 *db,
10179   char **pzErrMsg,
10180   const sqlite3_api_routines *pApi
10181 ){
10182   int rc = SQLITE_OK;
10183   sqlite3_vfs *pOrig;
10184   SQLITE_EXTENSION_INIT2(pApi);
10185   (void)pzErrMsg;
10186   (void)db;
10187   pOrig = sqlite3_vfs_find(0);
10188   if( pOrig==0 ) return SQLITE_ERROR;
10189   apnd_vfs.iVersion = pOrig->iVersion;
10190   apnd_vfs.pAppData = pOrig;
10191   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
10192   rc = sqlite3_vfs_register(&apnd_vfs, 0);
10193 #ifdef APPENDVFS_TEST
10194   if( rc==SQLITE_OK ){
10195     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
10196   }
10197 #endif
10198   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
10199   return rc;
10200 }
10201 
10202 /************************* End ../ext/misc/appendvfs.c ********************/
10203 #endif
10204 #ifdef SQLITE_HAVE_ZLIB
10205 /************************* Begin ../ext/misc/zipfile.c ******************/
10206 /*
10207 ** 2017-12-26
10208 **
10209 ** The author disclaims copyright to this source code.  In place of
10210 ** a legal notice, here is a blessing:
10211 **
10212 **    May you do good and not evil.
10213 **    May you find forgiveness for yourself and forgive others.
10214 **    May you share freely, never taking more than you give.
10215 **
10216 ******************************************************************************
10217 **
10218 ** This file implements a virtual table for reading and writing ZIP archive
10219 ** files.
10220 **
10221 ** Usage example:
10222 **
10223 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
10224 **
10225 ** Current limitations:
10226 **
10227 **    *  No support for encryption
10228 **    *  No support for ZIP archives spanning multiple files
10229 **    *  No support for zip64 extensions
10230 **    *  Only the "inflate/deflate" (zlib) compression method is supported
10231 */
10232 /* #include "sqlite3ext.h" */
10233 SQLITE_EXTENSION_INIT1
10234 #include <stdio.h>
10235 #include <string.h>
10236 #include <assert.h>
10237 #ifndef SQLITE_NO_STDINT
10238 #  include <stdint.h>
10239 #endif
10240 
10241 #include <zlib.h>
10242 
10243 /* When used as part of the CLI, the sqlite3_stdio.h module will have
10244 ** been included before this one. In that case use the sqlite3_stdio.h
10245 ** #defines.  If not, create our own for fopen().
10246 */
10247 #ifndef _SQLITE3_STDIO_H_
10248 # define sqlite3_fopen fopen
10249 #endif
10250 
10251 #ifndef SQLITE_OMIT_VIRTUALTABLE
10252 
10253 #ifndef SQLITE_AMALGAMATION
10254 
10255 #ifndef UINT32_TYPE
10256 # ifdef HAVE_UINT32_T
10257 #  define UINT32_TYPE uint32_t
10258 # else
10259 #  define UINT32_TYPE unsigned int
10260 # endif
10261 #endif
10262 #ifndef UINT16_TYPE
10263 # ifdef HAVE_UINT16_T
10264 #  define UINT16_TYPE uint16_t
10265 # else
10266 #  define UINT16_TYPE unsigned short int
10267 # endif
10268 #endif
10269 /* typedef sqlite3_int64 i64; */
10270 /* typedef unsigned char u8; */
10271 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
10272 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
10273 #define MIN(a,b) ((a)<(b) ? (a) : (b))
10274 
10275 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
10276 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
10277 #endif
10278 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
10279 # define ALWAYS(X)      (1)
10280 # define NEVER(X)       (0)
10281 #elif !defined(NDEBUG)
10282 # define ALWAYS(X)      ((X)?1:(assert(0),0))
10283 # define NEVER(X)       ((X)?(assert(0),1):0)
10284 #else
10285 # define ALWAYS(X)      (X)
10286 # define NEVER(X)       (X)
10287 #endif
10288 
10289 #endif   /* SQLITE_AMALGAMATION */
10290 
10291 /*
10292 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
10293 **
10294 ** In some ways it would be better to obtain these values from system
10295 ** header files. But, the dependency is undesirable and (a) these
10296 ** have been stable for decades, (b) the values are part of POSIX and
10297 ** are also made explicit in [man stat], and (c) are part of the
10298 ** file format for zip archives.
10299 */
10300 #ifndef S_IFDIR
10301 # define S_IFDIR 0040000
10302 #endif
10303 #ifndef S_IFREG
10304 # define S_IFREG 0100000
10305 #endif
10306 #ifndef S_IFLNK
10307 # define S_IFLNK 0120000
10308 #endif
10309 
10310 static const char ZIPFILE_SCHEMA[] =
10311   "CREATE TABLE y("
10312     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
10313     "mode,"              /* 1: POSIX mode for file */
10314     "mtime,"             /* 2: Last modification time (secs since 1970)*/
10315     "sz,"                /* 3: Size of object */
10316     "rawdata,"           /* 4: Raw data */
10317     "data,"              /* 5: Uncompressed data */
10318     "method,"            /* 6: Compression method (integer) */
10319     "z HIDDEN"           /* 7: Name of zip file */
10320   ") WITHOUT ROWID;";
10321 
10322 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
10323 #define ZIPFILE_BUFFER_SIZE (64*1024)
10324 
10325 
10326 /*
10327 ** Magic numbers used to read and write zip files.
10328 **
10329 ** ZIPFILE_NEWENTRY_MADEBY:
10330 **   Use this value for the "version-made-by" field in new zip file
10331 **   entries. The upper byte indicates "unix", and the lower byte
10332 **   indicates that the zip file matches pkzip specification 3.0.
10333 **   This is what info-zip seems to do.
10334 **
10335 ** ZIPFILE_NEWENTRY_REQUIRED:
10336 **   Value for "version-required-to-extract" field of new entries.
10337 **   Version 2.0 is required to support folders and deflate compression.
10338 **
10339 ** ZIPFILE_NEWENTRY_FLAGS:
10340 **   Value for "general-purpose-bit-flags" field of new entries. Bit
10341 **   11 means "utf-8 filename and comment".
10342 **
10343 ** ZIPFILE_SIGNATURE_CDS:
10344 **   First 4 bytes of a valid CDS record.
10345 **
10346 ** ZIPFILE_SIGNATURE_LFH:
10347 **   First 4 bytes of a valid LFH record.
10348 **
10349 ** ZIPFILE_SIGNATURE_EOCD
10350 **   First 4 bytes of a valid EOCD record.
10351 */
10352 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
10353 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
10354 #define ZIPFILE_NEWENTRY_REQUIRED 20
10355 #define ZIPFILE_NEWENTRY_FLAGS    0x800
10356 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
10357 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
10358 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
10359 
10360 /*
10361 ** The sizes of the fixed-size part of each of the three main data
10362 ** structures in a zip archive.
10363 */
10364 #define ZIPFILE_LFH_FIXED_SZ      30
10365 #define ZIPFILE_EOCD_FIXED_SZ     22
10366 #define ZIPFILE_CDS_FIXED_SZ      46
10367 
10368 /*
10369 *** 4.3.16  End of central directory record:
10370 ***
10371 ***   end of central dir signature    4 bytes  (0x06054b50)
10372 ***   number of this disk             2 bytes
10373 ***   number of the disk with the
10374 ***   start of the central directory  2 bytes
10375 ***   total number of entries in the
10376 ***   central directory on this disk  2 bytes
10377 ***   total number of entries in
10378 ***   the central directory           2 bytes
10379 ***   size of the central directory   4 bytes
10380 ***   offset of start of central
10381 ***   directory with respect to
10382 ***   the starting disk number        4 bytes
10383 ***   .ZIP file comment length        2 bytes
10384 ***   .ZIP file comment       (variable size)
10385 */
10386 typedef struct ZipfileEOCD ZipfileEOCD;
10387 struct ZipfileEOCD {
10388   u16 iDisk;
10389   u16 iFirstDisk;
10390   u16 nEntry;
10391   u16 nEntryTotal;
10392   u32 nSize;
10393   u32 iOffset;
10394 };
10395 
10396 /*
10397 *** 4.3.12  Central directory structure:
10398 ***
10399 *** ...
10400 ***
10401 ***   central file header signature   4 bytes  (0x02014b50)
10402 ***   version made by                 2 bytes
10403 ***   version needed to extract       2 bytes
10404 ***   general purpose bit flag        2 bytes
10405 ***   compression method              2 bytes
10406 ***   last mod file time              2 bytes
10407 ***   last mod file date              2 bytes
10408 ***   crc-32                          4 bytes
10409 ***   compressed size                 4 bytes
10410 ***   uncompressed size               4 bytes
10411 ***   file name length                2 bytes
10412 ***   extra field length              2 bytes
10413 ***   file comment length             2 bytes
10414 ***   disk number start               2 bytes
10415 ***   internal file attributes        2 bytes
10416 ***   external file attributes        4 bytes
10417 ***   relative offset of local header 4 bytes
10418 */
10419 typedef struct ZipfileCDS ZipfileCDS;
10420 struct ZipfileCDS {
10421   u16 iVersionMadeBy;
10422   u16 iVersionExtract;
10423   u16 flags;
10424   u16 iCompression;
10425   u16 mTime;
10426   u16 mDate;
10427   u32 crc32;
10428   u32 szCompressed;
10429   u32 szUncompressed;
10430   u16 nFile;
10431   u16 nExtra;
10432   u16 nComment;
10433   u16 iDiskStart;
10434   u16 iInternalAttr;
10435   u32 iExternalAttr;
10436   u32 iOffset;
10437   char *zFile;                    /* Filename (sqlite3_malloc()) */
10438 };
10439 
10440 /*
10441 *** 4.3.7  Local file header:
10442 ***
10443 ***   local file header signature     4 bytes  (0x04034b50)
10444 ***   version needed to extract       2 bytes
10445 ***   general purpose bit flag        2 bytes
10446 ***   compression method              2 bytes
10447 ***   last mod file time              2 bytes
10448 ***   last mod file date              2 bytes
10449 ***   crc-32                          4 bytes
10450 ***   compressed size                 4 bytes
10451 ***   uncompressed size               4 bytes
10452 ***   file name length                2 bytes
10453 ***   extra field length              2 bytes
10454 ***
10455 */
10456 typedef struct ZipfileLFH ZipfileLFH;
10457 struct ZipfileLFH {
10458   u16 iVersionExtract;
10459   u16 flags;
10460   u16 iCompression;
10461   u16 mTime;
10462   u16 mDate;
10463   u32 crc32;
10464   u32 szCompressed;
10465   u32 szUncompressed;
10466   u16 nFile;
10467   u16 nExtra;
10468 };
10469 
10470 typedef struct ZipfileEntry ZipfileEntry;
10471 struct ZipfileEntry {
10472   ZipfileCDS cds;            /* Parsed CDS record */
10473   u32 mUnixTime;             /* Modification time, in UNIX format */
10474   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
10475   i64 iDataOff;              /* Offset to data in file (if aData==0) */
10476   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
10477   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
10478 };
10479 
10480 /*
10481 ** Cursor type for zipfile tables.
10482 */
10483 typedef struct ZipfileCsr ZipfileCsr;
10484 struct ZipfileCsr {
10485   sqlite3_vtab_cursor base;  /* Base class - must be first */
10486   i64 iId;                   /* Cursor ID */
10487   u8 bEof;                   /* True when at EOF */
10488   u8 bNoop;                  /* If next xNext() call is no-op */
10489 
10490   /* Used outside of write transactions */
10491   FILE *pFile;               /* Zip file */
10492   i64 iNextOff;              /* Offset of next record in central directory */
10493   ZipfileEOCD eocd;          /* Parse of central directory record */
10494 
10495   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
10496   ZipfileEntry *pCurrent;    /* Current entry */
10497   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
10498 };
10499 
10500 typedef struct ZipfileTab ZipfileTab;
10501 struct ZipfileTab {
10502   sqlite3_vtab base;         /* Base class - must be first */
10503   char *zFile;               /* Zip file this table accesses (may be NULL) */
10504   sqlite3 *db;               /* Host database connection */
10505   u8 *aBuffer;               /* Temporary buffer used for various tasks */
10506 
10507   ZipfileCsr *pCsrList;      /* List of cursors */
10508   i64 iNextCsrid;
10509 
10510   /* The following are used by write transactions only */
10511   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
10512   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
10513   FILE *pWriteFd;            /* File handle open on zip archive */
10514   i64 szCurrent;             /* Current size of zip archive */
10515   i64 szOrig;                /* Size of archive at start of transaction */
10516 };
10517 
10518 /*
10519 ** Set the error message contained in context ctx to the results of
10520 ** vprintf(zFmt, ...).
10521 */
zipfileCtxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)10522 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
10523   char *zMsg = 0;
10524   va_list ap;
10525   va_start(ap, zFmt);
10526   zMsg = sqlite3_vmprintf(zFmt, ap);
10527   sqlite3_result_error(ctx, zMsg, -1);
10528   sqlite3_free(zMsg);
10529   va_end(ap);
10530 }
10531 
10532 /*
10533 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
10534 ** is not quoted, do nothing.
10535 */
zipfileDequote(char * zIn)10536 static void zipfileDequote(char *zIn){
10537   char q = zIn[0];
10538   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
10539     int iIn = 1;
10540     int iOut = 0;
10541     if( q=='[' ) q = ']';
10542     while( ALWAYS(zIn[iIn]) ){
10543       char c = zIn[iIn++];
10544       if( c==q && zIn[iIn++]!=q ) break;
10545       zIn[iOut++] = c;
10546     }
10547     zIn[iOut] = '\0';
10548   }
10549 }
10550 
10551 /*
10552 ** Construct a new ZipfileTab virtual table object.
10553 **
10554 **   argv[0]   -> module name  ("zipfile")
10555 **   argv[1]   -> database name
10556 **   argv[2]   -> table name
10557 **   argv[...] -> "column name" and other module argument fields.
10558 */
zipfileConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)10559 static int zipfileConnect(
10560   sqlite3 *db,
10561   void *pAux,
10562   int argc, const char *const*argv,
10563   sqlite3_vtab **ppVtab,
10564   char **pzErr
10565 ){
10566   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
10567   int nFile = 0;
10568   const char *zFile = 0;
10569   ZipfileTab *pNew = 0;
10570   int rc;
10571   (void)pAux;
10572 
10573   /* If the table name is not "zipfile", require that the argument be
10574   ** specified. This stops zipfile tables from being created as:
10575   **
10576   **   CREATE VIRTUAL TABLE zzz USING zipfile();
10577   **
10578   ** It does not prevent:
10579   **
10580   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
10581   */
10582   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
10583   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
10584     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
10585     return SQLITE_ERROR;
10586   }
10587 
10588   if( argc>3 ){
10589     zFile = argv[3];
10590     nFile = (int)strlen(zFile)+1;
10591   }
10592 
10593   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
10594   if( rc==SQLITE_OK ){
10595     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
10596     if( pNew==0 ) return SQLITE_NOMEM;
10597     memset(pNew, 0, nByte+nFile);
10598     pNew->db = db;
10599     pNew->aBuffer = (u8*)&pNew[1];
10600     if( zFile ){
10601       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
10602       memcpy(pNew->zFile, zFile, nFile);
10603       zipfileDequote(pNew->zFile);
10604     }
10605   }
10606   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
10607   *ppVtab = (sqlite3_vtab*)pNew;
10608   return rc;
10609 }
10610 
10611 /*
10612 ** Free the ZipfileEntry structure indicated by the only argument.
10613 */
zipfileEntryFree(ZipfileEntry * p)10614 static void zipfileEntryFree(ZipfileEntry *p){
10615   if( p ){
10616     sqlite3_free(p->cds.zFile);
10617     sqlite3_free(p);
10618   }
10619 }
10620 
10621 /*
10622 ** Release resources that should be freed at the end of a write
10623 ** transaction.
10624 */
zipfileCleanupTransaction(ZipfileTab * pTab)10625 static void zipfileCleanupTransaction(ZipfileTab *pTab){
10626   ZipfileEntry *pEntry;
10627   ZipfileEntry *pNext;
10628 
10629   if( pTab->pWriteFd ){
10630     fclose(pTab->pWriteFd);
10631     pTab->pWriteFd = 0;
10632   }
10633   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
10634     pNext = pEntry->pNext;
10635     zipfileEntryFree(pEntry);
10636   }
10637   pTab->pFirstEntry = 0;
10638   pTab->pLastEntry = 0;
10639   pTab->szCurrent = 0;
10640   pTab->szOrig = 0;
10641 }
10642 
10643 /*
10644 ** This method is the destructor for zipfile vtab objects.
10645 */
zipfileDisconnect(sqlite3_vtab * pVtab)10646 static int zipfileDisconnect(sqlite3_vtab *pVtab){
10647   zipfileCleanupTransaction((ZipfileTab*)pVtab);
10648   sqlite3_free(pVtab);
10649   return SQLITE_OK;
10650 }
10651 
10652 /*
10653 ** Constructor for a new ZipfileCsr object.
10654 */
zipfileOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCsr)10655 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
10656   ZipfileTab *pTab = (ZipfileTab*)p;
10657   ZipfileCsr *pCsr;
10658   pCsr = sqlite3_malloc(sizeof(*pCsr));
10659   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
10660   if( pCsr==0 ){
10661     return SQLITE_NOMEM;
10662   }
10663   memset(pCsr, 0, sizeof(*pCsr));
10664   pCsr->iId = ++pTab->iNextCsrid;
10665   pCsr->pCsrNext = pTab->pCsrList;
10666   pTab->pCsrList = pCsr;
10667   return SQLITE_OK;
10668 }
10669 
10670 /*
10671 ** Reset a cursor back to the state it was in when first returned
10672 ** by zipfileOpen().
10673 */
zipfileResetCursor(ZipfileCsr * pCsr)10674 static void zipfileResetCursor(ZipfileCsr *pCsr){
10675   ZipfileEntry *p;
10676   ZipfileEntry *pNext;
10677 
10678   pCsr->bEof = 0;
10679   if( pCsr->pFile ){
10680     fclose(pCsr->pFile);
10681     pCsr->pFile = 0;
10682     zipfileEntryFree(pCsr->pCurrent);
10683     pCsr->pCurrent = 0;
10684   }
10685 
10686   for(p=pCsr->pFreeEntry; p; p=pNext){
10687     pNext = p->pNext;
10688     zipfileEntryFree(p);
10689   }
10690 }
10691 
10692 /*
10693 ** Destructor for an ZipfileCsr.
10694 */
zipfileClose(sqlite3_vtab_cursor * cur)10695 static int zipfileClose(sqlite3_vtab_cursor *cur){
10696   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10697   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
10698   ZipfileCsr **pp;
10699   zipfileResetCursor(pCsr);
10700 
10701   /* Remove this cursor from the ZipfileTab.pCsrList list. */
10702   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
10703   *pp = pCsr->pCsrNext;
10704 
10705   sqlite3_free(pCsr);
10706   return SQLITE_OK;
10707 }
10708 
10709 /*
10710 ** Set the error message for the virtual table associated with cursor
10711 ** pCsr to the results of vprintf(zFmt, ...).
10712 */
zipfileTableErr(ZipfileTab * pTab,const char * zFmt,...)10713 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
10714   va_list ap;
10715   va_start(ap, zFmt);
10716   sqlite3_free(pTab->base.zErrMsg);
10717   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
10718   va_end(ap);
10719 }
zipfileCursorErr(ZipfileCsr * pCsr,const char * zFmt,...)10720 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
10721   va_list ap;
10722   va_start(ap, zFmt);
10723   sqlite3_free(pCsr->base.pVtab->zErrMsg);
10724   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
10725   va_end(ap);
10726 }
10727 
10728 /*
10729 ** Read nRead bytes of data from offset iOff of file pFile into buffer
10730 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
10731 ** otherwise.
10732 **
10733 ** If an error does occur, output variable (*pzErrmsg) may be set to point
10734 ** to an English language error message. It is the responsibility of the
10735 ** caller to eventually free this buffer using
10736 ** sqlite3_free().
10737 */
zipfileReadData(FILE * pFile,u8 * aRead,int nRead,i64 iOff,char ** pzErrmsg)10738 static int zipfileReadData(
10739   FILE *pFile,                    /* Read from this file */
10740   u8 *aRead,                      /* Read into this buffer */
10741   int nRead,                      /* Number of bytes to read */
10742   i64 iOff,                       /* Offset to read from */
10743   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
10744 ){
10745   size_t n;
10746   fseek(pFile, (long)iOff, SEEK_SET);
10747   n = fread(aRead, 1, nRead, pFile);
10748   if( (int)n!=nRead ){
10749     *pzErrmsg = sqlite3_mprintf("error in fread()");
10750     return SQLITE_ERROR;
10751   }
10752   return SQLITE_OK;
10753 }
10754 
zipfileAppendData(ZipfileTab * pTab,const u8 * aWrite,int nWrite)10755 static int zipfileAppendData(
10756   ZipfileTab *pTab,
10757   const u8 *aWrite,
10758   int nWrite
10759 ){
10760   if( nWrite>0 ){
10761     size_t n = nWrite;
10762     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
10763     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
10764     if( (int)n!=nWrite ){
10765       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
10766       return SQLITE_ERROR;
10767     }
10768     pTab->szCurrent += nWrite;
10769   }
10770   return SQLITE_OK;
10771 }
10772 
10773 /*
10774 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
10775 */
zipfileGetU16(const u8 * aBuf)10776 static u16 zipfileGetU16(const u8 *aBuf){
10777   return (aBuf[1] << 8) + aBuf[0];
10778 }
10779 
10780 /*
10781 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
10782 */
zipfileGetU32(const u8 * aBuf)10783 static u32 zipfileGetU32(const u8 *aBuf){
10784   if( aBuf==0 ) return 0;
10785   return ((u32)(aBuf[3]) << 24)
10786        + ((u32)(aBuf[2]) << 16)
10787        + ((u32)(aBuf[1]) <<  8)
10788        + ((u32)(aBuf[0]) <<  0);
10789 }
10790 
10791 /*
10792 ** Write a 16-bit little endiate integer into buffer aBuf.
10793 */
zipfilePutU16(u8 * aBuf,u16 val)10794 static void zipfilePutU16(u8 *aBuf, u16 val){
10795   aBuf[0] = val & 0xFF;
10796   aBuf[1] = (val>>8) & 0xFF;
10797 }
10798 
10799 /*
10800 ** Write a 32-bit little endiate integer into buffer aBuf.
10801 */
zipfilePutU32(u8 * aBuf,u32 val)10802 static void zipfilePutU32(u8 *aBuf, u32 val){
10803   aBuf[0] = val & 0xFF;
10804   aBuf[1] = (val>>8) & 0xFF;
10805   aBuf[2] = (val>>16) & 0xFF;
10806   aBuf[3] = (val>>24) & 0xFF;
10807 }
10808 
10809 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
10810 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
10811 
10812 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
10813 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
10814 
10815 /*
10816 ** Magic numbers used to read CDS records.
10817 */
10818 #define ZIPFILE_CDS_NFILE_OFF        28
10819 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
10820 
10821 /*
10822 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
10823 ** if the record is not well-formed, or SQLITE_OK otherwise.
10824 */
zipfileReadCDS(u8 * aBuf,ZipfileCDS * pCDS)10825 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
10826   u8 *aRead = aBuf;
10827   u32 sig = zipfileRead32(aRead);
10828   int rc = SQLITE_OK;
10829   if( sig!=ZIPFILE_SIGNATURE_CDS ){
10830     rc = SQLITE_ERROR;
10831   }else{
10832     pCDS->iVersionMadeBy = zipfileRead16(aRead);
10833     pCDS->iVersionExtract = zipfileRead16(aRead);
10834     pCDS->flags = zipfileRead16(aRead);
10835     pCDS->iCompression = zipfileRead16(aRead);
10836     pCDS->mTime = zipfileRead16(aRead);
10837     pCDS->mDate = zipfileRead16(aRead);
10838     pCDS->crc32 = zipfileRead32(aRead);
10839     pCDS->szCompressed = zipfileRead32(aRead);
10840     pCDS->szUncompressed = zipfileRead32(aRead);
10841     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
10842     pCDS->nFile = zipfileRead16(aRead);
10843     pCDS->nExtra = zipfileRead16(aRead);
10844     pCDS->nComment = zipfileRead16(aRead);
10845     pCDS->iDiskStart = zipfileRead16(aRead);
10846     pCDS->iInternalAttr = zipfileRead16(aRead);
10847     pCDS->iExternalAttr = zipfileRead32(aRead);
10848     pCDS->iOffset = zipfileRead32(aRead);
10849     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
10850   }
10851 
10852   return rc;
10853 }
10854 
10855 /*
10856 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
10857 ** if the record is not well-formed, or SQLITE_OK otherwise.
10858 */
zipfileReadLFH(u8 * aBuffer,ZipfileLFH * pLFH)10859 static int zipfileReadLFH(
10860   u8 *aBuffer,
10861   ZipfileLFH *pLFH
10862 ){
10863   u8 *aRead = aBuffer;
10864   int rc = SQLITE_OK;
10865 
10866   u32 sig = zipfileRead32(aRead);
10867   if( sig!=ZIPFILE_SIGNATURE_LFH ){
10868     rc = SQLITE_ERROR;
10869   }else{
10870     pLFH->iVersionExtract = zipfileRead16(aRead);
10871     pLFH->flags = zipfileRead16(aRead);
10872     pLFH->iCompression = zipfileRead16(aRead);
10873     pLFH->mTime = zipfileRead16(aRead);
10874     pLFH->mDate = zipfileRead16(aRead);
10875     pLFH->crc32 = zipfileRead32(aRead);
10876     pLFH->szCompressed = zipfileRead32(aRead);
10877     pLFH->szUncompressed = zipfileRead32(aRead);
10878     pLFH->nFile = zipfileRead16(aRead);
10879     pLFH->nExtra = zipfileRead16(aRead);
10880   }
10881   return rc;
10882 }
10883 
10884 
10885 /*
10886 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
10887 ** Scan through this buffer to find an "extra-timestamp" field. If one
10888 ** exists, extract the 32-bit modification-timestamp from it and store
10889 ** the value in output parameter *pmTime.
10890 **
10891 ** Zero is returned if no extra-timestamp record could be found (and so
10892 ** *pmTime is left unchanged), or non-zero otherwise.
10893 **
10894 ** The general format of an extra field is:
10895 **
10896 **   Header ID    2 bytes
10897 **   Data Size    2 bytes
10898 **   Data         N bytes
10899 */
zipfileScanExtra(u8 * aExtra,int nExtra,u32 * pmTime)10900 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
10901   int ret = 0;
10902   u8 *p = aExtra;
10903   u8 *pEnd = &aExtra[nExtra];
10904 
10905   while( p<pEnd ){
10906     u16 id = zipfileRead16(p);
10907     u16 nByte = zipfileRead16(p);
10908 
10909     switch( id ){
10910       case ZIPFILE_EXTRA_TIMESTAMP: {
10911         u8 b = p[0];
10912         if( b & 0x01 ){     /* 0x01 -> modtime is present */
10913           *pmTime = zipfileGetU32(&p[1]);
10914           ret = 1;
10915         }
10916         break;
10917       }
10918     }
10919 
10920     p += nByte;
10921   }
10922   return ret;
10923 }
10924 
10925 /*
10926 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10927 ** fields of the CDS structure passed as the only argument to a 32-bit
10928 ** UNIX seconds-since-the-epoch timestamp. Return the result.
10929 **
10930 ** "Standard" MS-DOS time format:
10931 **
10932 **   File modification time:
10933 **     Bits 00-04: seconds divided by 2
10934 **     Bits 05-10: minute
10935 **     Bits 11-15: hour
10936 **   File modification date:
10937 **     Bits 00-04: day
10938 **     Bits 05-08: month (1-12)
10939 **     Bits 09-15: years from 1980
10940 **
10941 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10942 */
zipfileMtime(ZipfileCDS * pCDS)10943 static u32 zipfileMtime(ZipfileCDS *pCDS){
10944   int Y,M,D,X1,X2,A,B,sec,min,hr;
10945   i64 JDsec;
10946   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
10947   M = ((pCDS->mDate >> 5) & 0x0F);
10948   D = (pCDS->mDate & 0x1F);
10949   sec = (pCDS->mTime & 0x1F)*2;
10950   min = (pCDS->mTime >> 5) & 0x3F;
10951   hr = (pCDS->mTime >> 11) & 0x1F;
10952   if( M<=2 ){
10953     Y--;
10954     M += 12;
10955   }
10956   X1 = 36525*(Y+4716)/100;
10957   X2 = 306001*(M+1)/10000;
10958   A = Y/100;
10959   B = 2 - A + (A/4);
10960   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
10961   return (u32)(JDsec - (i64)24405875*(i64)8640);
10962 }
10963 
10964 /*
10965 ** The opposite of zipfileMtime(). This function populates the mTime and
10966 ** mDate fields of the CDS structure passed as the first argument according
10967 ** to the UNIX timestamp value passed as the second.
10968 */
zipfileMtimeToDos(ZipfileCDS * pCds,u32 mUnixTime)10969 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
10970   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
10971   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
10972 
10973   int A, B, C, D, E;
10974   int yr, mon, day;
10975   int hr, min, sec;
10976 
10977   A = (int)((JD - 1867216.25)/36524.25);
10978   A = (int)(JD + 1 + A - (A/4));
10979   B = A + 1524;
10980   C = (int)((B - 122.1)/365.25);
10981   D = (36525*(C&32767))/100;
10982   E = (int)((B-D)/30.6001);
10983 
10984   day = B - D - (int)(30.6001*E);
10985   mon = (E<14 ? E-1 : E-13);
10986   yr = mon>2 ? C-4716 : C-4715;
10987 
10988   hr = (mUnixTime % (24*60*60)) / (60*60);
10989   min = (mUnixTime % (60*60)) / 60;
10990   sec = (mUnixTime % 60);
10991 
10992   if( yr>=1980 ){
10993     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
10994     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
10995   }else{
10996     pCds->mDate = pCds->mTime = 0;
10997   }
10998 
10999   assert( mUnixTime<315507600
11000        || mUnixTime==zipfileMtime(pCds)
11001        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
11002        /* || (mUnixTime % 2) */
11003   );
11004 }
11005 
11006 /*
11007 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
11008 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
11009 ** then pFile is a file-handle open on a zip file. In either case, this
11010 ** function creates a ZipfileEntry object based on the zip archive entry
11011 ** for which the CDS record is at offset iOff.
11012 **
11013 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
11014 ** the new object. Otherwise, an SQLite error code is returned and the
11015 ** final value of (*ppEntry) undefined.
11016 */
zipfileGetEntry(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,i64 iOff,ZipfileEntry ** ppEntry)11017 static int zipfileGetEntry(
11018   ZipfileTab *pTab,               /* Store any error message here */
11019   const u8 *aBlob,                /* Pointer to in-memory file image */
11020   int nBlob,                      /* Size of aBlob[] in bytes */
11021   FILE *pFile,                    /* If aBlob==0, read from this file */
11022   i64 iOff,                       /* Offset of CDS record */
11023   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
11024 ){
11025   u8 *aRead;
11026   char **pzErr = &pTab->base.zErrMsg;
11027   int rc = SQLITE_OK;
11028   (void)nBlob;
11029 
11030   if( aBlob==0 ){
11031     aRead = pTab->aBuffer;
11032     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
11033   }else{
11034     aRead = (u8*)&aBlob[iOff];
11035   }
11036 
11037   if( rc==SQLITE_OK ){
11038     sqlite3_int64 nAlloc;
11039     ZipfileEntry *pNew;
11040 
11041     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
11042     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
11043     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
11044 
11045     nAlloc = sizeof(ZipfileEntry) + nExtra;
11046     if( aBlob ){
11047       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
11048     }
11049 
11050     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
11051     if( pNew==0 ){
11052       rc = SQLITE_NOMEM;
11053     }else{
11054       memset(pNew, 0, sizeof(ZipfileEntry));
11055       rc = zipfileReadCDS(aRead, &pNew->cds);
11056       if( rc!=SQLITE_OK ){
11057         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
11058       }else if( aBlob==0 ){
11059         rc = zipfileReadData(
11060             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
11061         );
11062       }else{
11063         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
11064       }
11065     }
11066 
11067     if( rc==SQLITE_OK ){
11068       u32 *pt = &pNew->mUnixTime;
11069       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
11070       pNew->aExtra = (u8*)&pNew[1];
11071       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
11072       if( pNew->cds.zFile==0 ){
11073         rc = SQLITE_NOMEM;
11074       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
11075         pNew->mUnixTime = zipfileMtime(&pNew->cds);
11076       }
11077     }
11078 
11079     if( rc==SQLITE_OK ){
11080       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
11081       ZipfileLFH lfh;
11082       if( pFile ){
11083         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
11084       }else{
11085         aRead = (u8*)&aBlob[pNew->cds.iOffset];
11086       }
11087 
11088       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
11089       if( rc==SQLITE_OK ){
11090         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
11091         pNew->iDataOff += lfh.nFile + lfh.nExtra;
11092         if( aBlob && pNew->cds.szCompressed ){
11093           pNew->aData = &pNew->aExtra[nExtra];
11094           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
11095         }
11096       }else{
11097         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
11098             (int)pNew->cds.iOffset
11099         );
11100       }
11101     }
11102 
11103     if( rc!=SQLITE_OK ){
11104       zipfileEntryFree(pNew);
11105     }else{
11106       *ppEntry = pNew;
11107     }
11108   }
11109 
11110   return rc;
11111 }
11112 
11113 /*
11114 ** Advance an ZipfileCsr to its next row of output.
11115 */
zipfileNext(sqlite3_vtab_cursor * cur)11116 static int zipfileNext(sqlite3_vtab_cursor *cur){
11117   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
11118   int rc = SQLITE_OK;
11119 
11120   if( pCsr->pFile ){
11121     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
11122     zipfileEntryFree(pCsr->pCurrent);
11123     pCsr->pCurrent = 0;
11124     if( pCsr->iNextOff>=iEof ){
11125       pCsr->bEof = 1;
11126     }else{
11127       ZipfileEntry *p = 0;
11128       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
11129       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
11130       if( rc==SQLITE_OK ){
11131         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
11132         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
11133       }
11134       pCsr->pCurrent = p;
11135     }
11136   }else{
11137     if( !pCsr->bNoop ){
11138       pCsr->pCurrent = pCsr->pCurrent->pNext;
11139     }
11140     if( pCsr->pCurrent==0 ){
11141       pCsr->bEof = 1;
11142     }
11143   }
11144 
11145   pCsr->bNoop = 0;
11146   return rc;
11147 }
11148 
zipfileFree(void * p)11149 static void zipfileFree(void *p) {
11150   sqlite3_free(p);
11151 }
11152 
11153 /*
11154 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
11155 ** size is nOut bytes. This function uncompresses the data and sets the
11156 ** return value in context pCtx to the result (a blob).
11157 **
11158 ** If an error occurs, an error code is left in pCtx instead.
11159 */
zipfileInflate(sqlite3_context * pCtx,const u8 * aIn,int nIn,int nOut)11160 static void zipfileInflate(
11161   sqlite3_context *pCtx,          /* Store result here */
11162   const u8 *aIn,                  /* Compressed data */
11163   int nIn,                        /* Size of buffer aIn[] in bytes */
11164   int nOut                        /* Expected output size */
11165 ){
11166   u8 *aRes = sqlite3_malloc(nOut);
11167   if( aRes==0 ){
11168     sqlite3_result_error_nomem(pCtx);
11169   }else{
11170     int err;
11171     z_stream str;
11172     memset(&str, 0, sizeof(str));
11173 
11174     str.next_in = (Byte*)aIn;
11175     str.avail_in = nIn;
11176     str.next_out = (Byte*)aRes;
11177     str.avail_out = nOut;
11178 
11179     err = inflateInit2(&str, -15);
11180     if( err!=Z_OK ){
11181       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
11182     }else{
11183       err = inflate(&str, Z_NO_FLUSH);
11184       if( err!=Z_STREAM_END ){
11185         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
11186       }else{
11187         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
11188         aRes = 0;
11189       }
11190     }
11191     sqlite3_free(aRes);
11192     inflateEnd(&str);
11193   }
11194 }
11195 
11196 /*
11197 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
11198 ** compresses it and sets (*ppOut) to point to a buffer containing the
11199 ** compressed data. The caller is responsible for eventually calling
11200 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
11201 ** is set to the size of buffer (*ppOut) in bytes.
11202 **
11203 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
11204 ** code is returned and an error message left in virtual-table handle
11205 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
11206 ** case.
11207 */
zipfileDeflate(const u8 * aIn,int nIn,u8 ** ppOut,int * pnOut,char ** pzErr)11208 static int zipfileDeflate(
11209   const u8 *aIn, int nIn,         /* Input */
11210   u8 **ppOut, int *pnOut,         /* Output */
11211   char **pzErr                    /* OUT: Error message */
11212 ){
11213   int rc = SQLITE_OK;
11214   sqlite3_int64 nAlloc;
11215   z_stream str;
11216   u8 *aOut;
11217 
11218   memset(&str, 0, sizeof(str));
11219   str.next_in = (Bytef*)aIn;
11220   str.avail_in = nIn;
11221   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
11222 
11223   nAlloc = deflateBound(&str, nIn);
11224   aOut = (u8*)sqlite3_malloc64(nAlloc);
11225   if( aOut==0 ){
11226     rc = SQLITE_NOMEM;
11227   }else{
11228     int res;
11229     str.next_out = aOut;
11230     str.avail_out = nAlloc;
11231     res = deflate(&str, Z_FINISH);
11232     if( res==Z_STREAM_END ){
11233       *ppOut = aOut;
11234       *pnOut = (int)str.total_out;
11235     }else{
11236       sqlite3_free(aOut);
11237       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
11238       rc = SQLITE_ERROR;
11239     }
11240     deflateEnd(&str);
11241   }
11242 
11243   return rc;
11244 }
11245 
11246 
11247 /*
11248 ** Return values of columns for the row at which the series_cursor
11249 ** is currently pointing.
11250 */
zipfileColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)11251 static int zipfileColumn(
11252   sqlite3_vtab_cursor *cur,   /* The cursor */
11253   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
11254   int i                       /* Which column to return */
11255 ){
11256   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
11257   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
11258   int rc = SQLITE_OK;
11259   switch( i ){
11260     case 0:   /* name */
11261       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
11262       break;
11263     case 1:   /* mode */
11264       /* TODO: Whether or not the following is correct surely depends on
11265       ** the platform on which the archive was created.  */
11266       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
11267       break;
11268     case 2: { /* mtime */
11269       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
11270       break;
11271     }
11272     case 3: { /* sz */
11273       if( sqlite3_vtab_nochange(ctx)==0 ){
11274         sqlite3_result_int64(ctx, pCDS->szUncompressed);
11275       }
11276       break;
11277     }
11278     case 4:   /* rawdata */
11279       if( sqlite3_vtab_nochange(ctx) ) break;
11280     case 5: { /* data */
11281       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
11282         int sz = pCDS->szCompressed;
11283         int szFinal = pCDS->szUncompressed;
11284         if( szFinal>0 ){
11285           u8 *aBuf;
11286           u8 *aFree = 0;
11287           if( pCsr->pCurrent->aData ){
11288             aBuf = pCsr->pCurrent->aData;
11289           }else{
11290             aBuf = aFree = sqlite3_malloc64(sz);
11291             if( aBuf==0 ){
11292               rc = SQLITE_NOMEM;
11293             }else{
11294               FILE *pFile = pCsr->pFile;
11295               if( pFile==0 ){
11296                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
11297               }
11298               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
11299                   &pCsr->base.pVtab->zErrMsg
11300               );
11301             }
11302           }
11303           if( rc==SQLITE_OK ){
11304             if( i==5 && pCDS->iCompression ){
11305               zipfileInflate(ctx, aBuf, sz, szFinal);
11306             }else{
11307               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
11308             }
11309           }
11310           sqlite3_free(aFree);
11311         }else{
11312           /* Figure out if this is a directory or a zero-sized file. Consider
11313           ** it to be a directory either if the mode suggests so, or if
11314           ** the final character in the name is '/'.  */
11315           u32 mode = pCDS->iExternalAttr >> 16;
11316           if( !(mode & S_IFDIR)
11317            && pCDS->nFile>=1
11318            && pCDS->zFile[pCDS->nFile-1]!='/'
11319           ){
11320             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
11321           }
11322         }
11323       }
11324       break;
11325     }
11326     case 6:   /* method */
11327       sqlite3_result_int(ctx, pCDS->iCompression);
11328       break;
11329     default:  /* z */
11330       assert( i==7 );
11331       sqlite3_result_int64(ctx, pCsr->iId);
11332       break;
11333   }
11334 
11335   return rc;
11336 }
11337 
11338 /*
11339 ** Return TRUE if the cursor is at EOF.
11340 */
zipfileEof(sqlite3_vtab_cursor * cur)11341 static int zipfileEof(sqlite3_vtab_cursor *cur){
11342   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
11343   return pCsr->bEof;
11344 }
11345 
11346 /*
11347 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
11348 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
11349 ** is guaranteed to be a file-handle open on a zip file.
11350 **
11351 ** This function attempts to locate the EOCD record within the zip archive
11352 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
11353 ** returned if successful. Otherwise, an SQLite error code is returned and
11354 ** an English language error message may be left in virtual-table pTab.
11355 */
zipfileReadEOCD(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,ZipfileEOCD * pEOCD)11356 static int zipfileReadEOCD(
11357   ZipfileTab *pTab,               /* Return errors here */
11358   const u8 *aBlob,                /* Pointer to in-memory file image */
11359   int nBlob,                      /* Size of aBlob[] in bytes */
11360   FILE *pFile,                    /* Read from this file if aBlob==0 */
11361   ZipfileEOCD *pEOCD              /* Object to populate */
11362 ){
11363   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
11364   int nRead;                      /* Bytes to read from file */
11365   int rc = SQLITE_OK;
11366 
11367   memset(pEOCD, 0, sizeof(ZipfileEOCD));
11368   if( aBlob==0 ){
11369     i64 iOff;                     /* Offset to read from */
11370     i64 szFile;                   /* Total size of file in bytes */
11371     fseek(pFile, 0, SEEK_END);
11372     szFile = (i64)ftell(pFile);
11373     if( szFile==0 ){
11374       return SQLITE_OK;
11375     }
11376     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
11377     iOff = szFile - nRead;
11378     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
11379   }else{
11380     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
11381     aRead = (u8*)&aBlob[nBlob-nRead];
11382   }
11383 
11384   if( rc==SQLITE_OK ){
11385     int i;
11386 
11387     /* Scan backwards looking for the signature bytes */
11388     for(i=nRead-20; i>=0; i--){
11389       if( aRead[i]==0x50 && aRead[i+1]==0x4b
11390        && aRead[i+2]==0x05 && aRead[i+3]==0x06
11391       ){
11392         break;
11393       }
11394     }
11395     if( i<0 ){
11396       pTab->base.zErrMsg = sqlite3_mprintf(
11397           "cannot find end of central directory record"
11398       );
11399       return SQLITE_ERROR;
11400     }
11401 
11402     aRead += i+4;
11403     pEOCD->iDisk = zipfileRead16(aRead);
11404     pEOCD->iFirstDisk = zipfileRead16(aRead);
11405     pEOCD->nEntry = zipfileRead16(aRead);
11406     pEOCD->nEntryTotal = zipfileRead16(aRead);
11407     pEOCD->nSize = zipfileRead32(aRead);
11408     pEOCD->iOffset = zipfileRead32(aRead);
11409   }
11410 
11411   return rc;
11412 }
11413 
11414 /*
11415 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
11416 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
11417 ** to the end of the list. Otherwise, it is added to the list immediately
11418 ** before pBefore (which is guaranteed to be a part of said list).
11419 */
zipfileAddEntry(ZipfileTab * pTab,ZipfileEntry * pBefore,ZipfileEntry * pNew)11420 static void zipfileAddEntry(
11421   ZipfileTab *pTab,
11422   ZipfileEntry *pBefore,
11423   ZipfileEntry *pNew
11424 ){
11425   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
11426   assert( pNew->pNext==0 );
11427   if( pBefore==0 ){
11428     if( pTab->pFirstEntry==0 ){
11429       pTab->pFirstEntry = pTab->pLastEntry = pNew;
11430     }else{
11431       assert( pTab->pLastEntry->pNext==0 );
11432       pTab->pLastEntry->pNext = pNew;
11433       pTab->pLastEntry = pNew;
11434     }
11435   }else{
11436     ZipfileEntry **pp;
11437     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
11438     pNew->pNext = pBefore;
11439     *pp = pNew;
11440   }
11441 }
11442 
zipfileLoadDirectory(ZipfileTab * pTab,const u8 * aBlob,int nBlob)11443 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
11444   ZipfileEOCD eocd;
11445   int rc;
11446   int i;
11447   i64 iOff;
11448 
11449   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
11450   iOff = eocd.iOffset;
11451   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
11452     ZipfileEntry *pNew = 0;
11453     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
11454 
11455     if( rc==SQLITE_OK ){
11456       zipfileAddEntry(pTab, 0, pNew);
11457       iOff += ZIPFILE_CDS_FIXED_SZ;
11458       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
11459     }
11460   }
11461   return rc;
11462 }
11463 
11464 /*
11465 ** xFilter callback.
11466 */
zipfileFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)11467 static int zipfileFilter(
11468   sqlite3_vtab_cursor *cur,
11469   int idxNum, const char *idxStr,
11470   int argc, sqlite3_value **argv
11471 ){
11472   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
11473   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
11474   const char *zFile = 0;          /* Zip file to scan */
11475   int rc = SQLITE_OK;             /* Return Code */
11476   int bInMemory = 0;              /* True for an in-memory zipfile */
11477 
11478   (void)idxStr;
11479   (void)argc;
11480 
11481   zipfileResetCursor(pCsr);
11482 
11483   if( pTab->zFile ){
11484     zFile = pTab->zFile;
11485   }else if( idxNum==0 ){
11486     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
11487     return SQLITE_ERROR;
11488   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
11489     static const u8 aEmptyBlob = 0;
11490     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
11491     int nBlob = sqlite3_value_bytes(argv[0]);
11492     assert( pTab->pFirstEntry==0 );
11493     if( aBlob==0 ){
11494       aBlob = &aEmptyBlob;
11495       nBlob = 0;
11496     }
11497     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
11498     pCsr->pFreeEntry = pTab->pFirstEntry;
11499     pTab->pFirstEntry = pTab->pLastEntry = 0;
11500     if( rc!=SQLITE_OK ) return rc;
11501     bInMemory = 1;
11502   }else{
11503     zFile = (const char*)sqlite3_value_text(argv[0]);
11504   }
11505 
11506   if( 0==pTab->pWriteFd && 0==bInMemory ){
11507     pCsr->pFile = zFile ? sqlite3_fopen(zFile, "rb") : 0;
11508     if( pCsr->pFile==0 ){
11509       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
11510       rc = SQLITE_ERROR;
11511     }else{
11512       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
11513       if( rc==SQLITE_OK ){
11514         if( pCsr->eocd.nEntry==0 ){
11515           pCsr->bEof = 1;
11516         }else{
11517           pCsr->iNextOff = pCsr->eocd.iOffset;
11518           rc = zipfileNext(cur);
11519         }
11520       }
11521     }
11522   }else{
11523     pCsr->bNoop = 1;
11524     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
11525     rc = zipfileNext(cur);
11526   }
11527 
11528   return rc;
11529 }
11530 
11531 /*
11532 ** xBestIndex callback.
11533 */
zipfileBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)11534 static int zipfileBestIndex(
11535   sqlite3_vtab *tab,
11536   sqlite3_index_info *pIdxInfo
11537 ){
11538   int i;
11539   int idx = -1;
11540   int unusable = 0;
11541   (void)tab;
11542 
11543   for(i=0; i<pIdxInfo->nConstraint; i++){
11544     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
11545     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
11546     if( pCons->usable==0 ){
11547       unusable = 1;
11548     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
11549       idx = i;
11550     }
11551   }
11552   pIdxInfo->estimatedCost = 1000.0;
11553   if( idx>=0 ){
11554     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
11555     pIdxInfo->aConstraintUsage[idx].omit = 1;
11556     pIdxInfo->idxNum = 1;
11557   }else if( unusable ){
11558     return SQLITE_CONSTRAINT;
11559   }
11560   return SQLITE_OK;
11561 }
11562 
zipfileNewEntry(const char * zPath)11563 static ZipfileEntry *zipfileNewEntry(const char *zPath){
11564   ZipfileEntry *pNew;
11565   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
11566   if( pNew ){
11567     memset(pNew, 0, sizeof(ZipfileEntry));
11568     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
11569     if( pNew->cds.zFile==0 ){
11570       sqlite3_free(pNew);
11571       pNew = 0;
11572     }
11573   }
11574   return pNew;
11575 }
11576 
zipfileSerializeLFH(ZipfileEntry * pEntry,u8 * aBuf)11577 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
11578   ZipfileCDS *pCds = &pEntry->cds;
11579   u8 *a = aBuf;
11580 
11581   pCds->nExtra = 9;
11582 
11583   /* Write the LFH itself */
11584   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
11585   zipfileWrite16(a, pCds->iVersionExtract);
11586   zipfileWrite16(a, pCds->flags);
11587   zipfileWrite16(a, pCds->iCompression);
11588   zipfileWrite16(a, pCds->mTime);
11589   zipfileWrite16(a, pCds->mDate);
11590   zipfileWrite32(a, pCds->crc32);
11591   zipfileWrite32(a, pCds->szCompressed);
11592   zipfileWrite32(a, pCds->szUncompressed);
11593   zipfileWrite16(a, (u16)pCds->nFile);
11594   zipfileWrite16(a, pCds->nExtra);
11595   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
11596 
11597   /* Add the file name */
11598   memcpy(a, pCds->zFile, (int)pCds->nFile);
11599   a += (int)pCds->nFile;
11600 
11601   /* The "extra" data */
11602   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
11603   zipfileWrite16(a, 5);
11604   *a++ = 0x01;
11605   zipfileWrite32(a, pEntry->mUnixTime);
11606 
11607   return a-aBuf;
11608 }
11609 
zipfileAppendEntry(ZipfileTab * pTab,ZipfileEntry * pEntry,const u8 * pData,int nData)11610 static int zipfileAppendEntry(
11611   ZipfileTab *pTab,
11612   ZipfileEntry *pEntry,
11613   const u8 *pData,
11614   int nData
11615 ){
11616   u8 *aBuf = pTab->aBuffer;
11617   int nBuf;
11618   int rc;
11619 
11620   nBuf = zipfileSerializeLFH(pEntry, aBuf);
11621   rc = zipfileAppendData(pTab, aBuf, nBuf);
11622   if( rc==SQLITE_OK ){
11623     pEntry->iDataOff = pTab->szCurrent;
11624     rc = zipfileAppendData(pTab, pData, nData);
11625   }
11626 
11627   return rc;
11628 }
11629 
zipfileGetMode(sqlite3_value * pVal,int bIsDir,u32 * pMode,char ** pzErr)11630 static int zipfileGetMode(
11631   sqlite3_value *pVal,
11632   int bIsDir,                     /* If true, default to directory */
11633   u32 *pMode,                     /* OUT: Mode value */
11634   char **pzErr                    /* OUT: Error message */
11635 ){
11636   const char *z = (const char*)sqlite3_value_text(pVal);
11637   u32 mode = 0;
11638   if( z==0 ){
11639     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
11640   }else if( z[0]>='0' && z[0]<='9' ){
11641     mode = (unsigned int)sqlite3_value_int(pVal);
11642   }else{
11643     const char zTemplate[11] = "-rwxrwxrwx";
11644     int i;
11645     if( strlen(z)!=10 ) goto parse_error;
11646     switch( z[0] ){
11647       case '-': mode |= S_IFREG; break;
11648       case 'd': mode |= S_IFDIR; break;
11649       case 'l': mode |= S_IFLNK; break;
11650       default: goto parse_error;
11651     }
11652     for(i=1; i<10; i++){
11653       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
11654       else if( z[i]!='-' ) goto parse_error;
11655     }
11656   }
11657   if( ((mode & S_IFDIR)==0)==bIsDir ){
11658     /* The "mode" attribute is a directory, but data has been specified.
11659     ** Or vice-versa - no data but "mode" is a file or symlink.  */
11660     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
11661     return SQLITE_CONSTRAINT;
11662   }
11663   *pMode = mode;
11664   return SQLITE_OK;
11665 
11666  parse_error:
11667   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
11668   return SQLITE_ERROR;
11669 }
11670 
11671 /*
11672 ** Both (const char*) arguments point to nul-terminated strings. Argument
11673 ** nB is the value of strlen(zB). This function returns 0 if the strings are
11674 ** identical, ignoring any trailing '/' character in either path.  */
zipfileComparePath(const char * zA,const char * zB,int nB)11675 static int zipfileComparePath(const char *zA, const char *zB, int nB){
11676   int nA = (int)strlen(zA);
11677   if( nA>0 && zA[nA-1]=='/' ) nA--;
11678   if( nB>0 && zB[nB-1]=='/' ) nB--;
11679   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
11680   return 1;
11681 }
11682 
zipfileBegin(sqlite3_vtab * pVtab)11683 static int zipfileBegin(sqlite3_vtab *pVtab){
11684   ZipfileTab *pTab = (ZipfileTab*)pVtab;
11685   int rc = SQLITE_OK;
11686 
11687   assert( pTab->pWriteFd==0 );
11688   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
11689     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
11690     return SQLITE_ERROR;
11691   }
11692 
11693   /* Open a write fd on the file. Also load the entire central directory
11694   ** structure into memory. During the transaction any new file data is
11695   ** appended to the archive file, but the central directory is accumulated
11696   ** in main-memory until the transaction is committed.  */
11697   pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+");
11698   if( pTab->pWriteFd==0 ){
11699     pTab->base.zErrMsg = sqlite3_mprintf(
11700         "zipfile: failed to open file %s for writing", pTab->zFile
11701         );
11702     rc = SQLITE_ERROR;
11703   }else{
11704     fseek(pTab->pWriteFd, 0, SEEK_END);
11705     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
11706     rc = zipfileLoadDirectory(pTab, 0, 0);
11707   }
11708 
11709   if( rc!=SQLITE_OK ){
11710     zipfileCleanupTransaction(pTab);
11711   }
11712 
11713   return rc;
11714 }
11715 
11716 /*
11717 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
11718 ** time(2)).
11719 */
zipfileTime(void)11720 static u32 zipfileTime(void){
11721   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
11722   u32 ret;
11723   if( pVfs==0 ) return 0;
11724   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
11725     i64 ms;
11726     pVfs->xCurrentTimeInt64(pVfs, &ms);
11727     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
11728   }else{
11729     double day;
11730     pVfs->xCurrentTime(pVfs, &day);
11731     ret = (u32)((day - 2440587.5) * 86400);
11732   }
11733   return ret;
11734 }
11735 
11736 /*
11737 ** Return a 32-bit timestamp in UNIX epoch format.
11738 **
11739 ** If the value passed as the only argument is either NULL or an SQL NULL,
11740 ** return the current time. Otherwise, return the value stored in (*pVal)
11741 ** cast to a 32-bit unsigned integer.
11742 */
zipfileGetTime(sqlite3_value * pVal)11743 static u32 zipfileGetTime(sqlite3_value *pVal){
11744   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
11745     return zipfileTime();
11746   }
11747   return (u32)sqlite3_value_int64(pVal);
11748 }
11749 
11750 /*
11751 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
11752 ** linked list.  Remove it from the list and free the object.
11753 */
zipfileRemoveEntryFromList(ZipfileTab * pTab,ZipfileEntry * pOld)11754 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
11755   if( pOld ){
11756     if( pTab->pFirstEntry==pOld ){
11757       pTab->pFirstEntry = pOld->pNext;
11758       if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
11759     }else{
11760       ZipfileEntry *p;
11761       for(p=pTab->pFirstEntry; p; p=p->pNext){
11762         if( p->pNext==pOld ){
11763           p->pNext = pOld->pNext;
11764           if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
11765           break;
11766         }
11767       }
11768     }
11769     zipfileEntryFree(pOld);
11770   }
11771 }
11772 
11773 /*
11774 ** xUpdate method.
11775 */
zipfileUpdate(sqlite3_vtab * pVtab,int nVal,sqlite3_value ** apVal,sqlite_int64 * pRowid)11776 static int zipfileUpdate(
11777   sqlite3_vtab *pVtab,
11778   int nVal,
11779   sqlite3_value **apVal,
11780   sqlite_int64 *pRowid
11781 ){
11782   ZipfileTab *pTab = (ZipfileTab*)pVtab;
11783   int rc = SQLITE_OK;             /* Return Code */
11784   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
11785 
11786   u32 mode = 0;                   /* Mode for new entry */
11787   u32 mTime = 0;                  /* Modification time for new entry */
11788   i64 sz = 0;                     /* Uncompressed size */
11789   const char *zPath = 0;          /* Path for new entry */
11790   int nPath = 0;                  /* strlen(zPath) */
11791   const u8 *pData = 0;            /* Pointer to buffer containing content */
11792   int nData = 0;                  /* Size of pData buffer in bytes */
11793   int iMethod = 0;                /* Compression method for new entry */
11794   u8 *pFree = 0;                  /* Free this */
11795   char *zFree = 0;                /* Also free this */
11796   ZipfileEntry *pOld = 0;
11797   ZipfileEntry *pOld2 = 0;
11798   int bUpdate = 0;                /* True for an update that modifies "name" */
11799   int bIsDir = 0;
11800   u32 iCrc32 = 0;
11801 
11802   (void)pRowid;
11803 
11804   if( pTab->pWriteFd==0 ){
11805     rc = zipfileBegin(pVtab);
11806     if( rc!=SQLITE_OK ) return rc;
11807   }
11808 
11809   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
11810   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
11811     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
11812     int nDelete = (int)strlen(zDelete);
11813     if( nVal>1 ){
11814       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
11815       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
11816         bUpdate = 1;
11817       }
11818     }
11819     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
11820       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
11821         break;
11822       }
11823       assert( pOld->pNext );
11824     }
11825   }
11826 
11827   if( nVal>1 ){
11828     /* Check that "sz" and "rawdata" are both NULL: */
11829     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
11830       zipfileTableErr(pTab, "sz must be NULL");
11831       rc = SQLITE_CONSTRAINT;
11832     }
11833     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
11834       zipfileTableErr(pTab, "rawdata must be NULL");
11835       rc = SQLITE_CONSTRAINT;
11836     }
11837 
11838     if( rc==SQLITE_OK ){
11839       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
11840         /* data=NULL. A directory */
11841         bIsDir = 1;
11842       }else{
11843         /* Value specified for "data", and possibly "method". This must be
11844         ** a regular file or a symlink. */
11845         const u8 *aIn = sqlite3_value_blob(apVal[7]);
11846         int nIn = sqlite3_value_bytes(apVal[7]);
11847         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
11848 
11849         iMethod = sqlite3_value_int(apVal[8]);
11850         sz = nIn;
11851         pData = aIn;
11852         nData = nIn;
11853         if( iMethod!=0 && iMethod!=8 ){
11854           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
11855           rc = SQLITE_CONSTRAINT;
11856         }else{
11857           if( bAuto || iMethod ){
11858             int nCmp;
11859             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
11860             if( rc==SQLITE_OK ){
11861               if( iMethod || nCmp<nIn ){
11862                 iMethod = 8;
11863                 pData = pFree;
11864                 nData = nCmp;
11865               }
11866             }
11867           }
11868           iCrc32 = crc32(0, aIn, nIn);
11869         }
11870       }
11871     }
11872 
11873     if( rc==SQLITE_OK ){
11874       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
11875     }
11876 
11877     if( rc==SQLITE_OK ){
11878       zPath = (const char*)sqlite3_value_text(apVal[2]);
11879       if( zPath==0 ) zPath = "";
11880       nPath = (int)strlen(zPath);
11881       mTime = zipfileGetTime(apVal[4]);
11882     }
11883 
11884     if( rc==SQLITE_OK && bIsDir ){
11885       /* For a directory, check that the last character in the path is a
11886       ** '/'. This appears to be required for compatibility with info-zip
11887       ** (the unzip command on unix). It does not create directories
11888       ** otherwise.  */
11889       if( nPath<=0 || zPath[nPath-1]!='/' ){
11890         zFree = sqlite3_mprintf("%s/", zPath);
11891         zPath = (const char*)zFree;
11892         if( zFree==0 ){
11893           rc = SQLITE_NOMEM;
11894           nPath = 0;
11895         }else{
11896           nPath = (int)strlen(zPath);
11897         }
11898       }
11899     }
11900 
11901     /* Check that we're not inserting a duplicate entry -OR- updating an
11902     ** entry with a path, thereby making it into a duplicate. */
11903     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
11904       ZipfileEntry *p;
11905       for(p=pTab->pFirstEntry; p; p=p->pNext){
11906         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
11907           switch( sqlite3_vtab_on_conflict(pTab->db) ){
11908             case SQLITE_IGNORE: {
11909               goto zipfile_update_done;
11910             }
11911             case SQLITE_REPLACE: {
11912               pOld2 = p;
11913               break;
11914             }
11915             default: {
11916               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
11917               rc = SQLITE_CONSTRAINT;
11918               break;
11919             }
11920           }
11921           break;
11922         }
11923       }
11924     }
11925 
11926     if( rc==SQLITE_OK ){
11927       /* Create the new CDS record. */
11928       pNew = zipfileNewEntry(zPath);
11929       if( pNew==0 ){
11930         rc = SQLITE_NOMEM;
11931       }else{
11932         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11933         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11934         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11935         pNew->cds.iCompression = (u16)iMethod;
11936         zipfileMtimeToDos(&pNew->cds, mTime);
11937         pNew->cds.crc32 = iCrc32;
11938         pNew->cds.szCompressed = nData;
11939         pNew->cds.szUncompressed = (u32)sz;
11940         pNew->cds.iExternalAttr = (mode<<16);
11941         pNew->cds.iOffset = (u32)pTab->szCurrent;
11942         pNew->cds.nFile = (u16)nPath;
11943         pNew->mUnixTime = (u32)mTime;
11944         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
11945         zipfileAddEntry(pTab, pOld, pNew);
11946       }
11947     }
11948   }
11949 
11950   if( rc==SQLITE_OK && (pOld || pOld2) ){
11951     ZipfileCsr *pCsr;
11952     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11953       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
11954         pCsr->pCurrent = pCsr->pCurrent->pNext;
11955         pCsr->bNoop = 1;
11956       }
11957     }
11958 
11959     zipfileRemoveEntryFromList(pTab, pOld);
11960     zipfileRemoveEntryFromList(pTab, pOld2);
11961   }
11962 
11963 zipfile_update_done:
11964   sqlite3_free(pFree);
11965   sqlite3_free(zFree);
11966   return rc;
11967 }
11968 
zipfileSerializeEOCD(ZipfileEOCD * p,u8 * aBuf)11969 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
11970   u8 *a = aBuf;
11971   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
11972   zipfileWrite16(a, p->iDisk);
11973   zipfileWrite16(a, p->iFirstDisk);
11974   zipfileWrite16(a, p->nEntry);
11975   zipfileWrite16(a, p->nEntryTotal);
11976   zipfileWrite32(a, p->nSize);
11977   zipfileWrite32(a, p->iOffset);
11978   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
11979 
11980   return a-aBuf;
11981 }
11982 
zipfileAppendEOCD(ZipfileTab * pTab,ZipfileEOCD * p)11983 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
11984   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
11985   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
11986   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
11987 }
11988 
11989 /*
11990 ** Serialize the CDS structure into buffer aBuf[]. Return the number
11991 ** of bytes written.
11992 */
zipfileSerializeCDS(ZipfileEntry * pEntry,u8 * aBuf)11993 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
11994   u8 *a = aBuf;
11995   ZipfileCDS *pCDS = &pEntry->cds;
11996 
11997   if( pEntry->aExtra==0 ){
11998     pCDS->nExtra = 9;
11999   }
12000 
12001   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
12002   zipfileWrite16(a, pCDS->iVersionMadeBy);
12003   zipfileWrite16(a, pCDS->iVersionExtract);
12004   zipfileWrite16(a, pCDS->flags);
12005   zipfileWrite16(a, pCDS->iCompression);
12006   zipfileWrite16(a, pCDS->mTime);
12007   zipfileWrite16(a, pCDS->mDate);
12008   zipfileWrite32(a, pCDS->crc32);
12009   zipfileWrite32(a, pCDS->szCompressed);
12010   zipfileWrite32(a, pCDS->szUncompressed);
12011   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
12012   zipfileWrite16(a, pCDS->nFile);
12013   zipfileWrite16(a, pCDS->nExtra);
12014   zipfileWrite16(a, pCDS->nComment);
12015   zipfileWrite16(a, pCDS->iDiskStart);
12016   zipfileWrite16(a, pCDS->iInternalAttr);
12017   zipfileWrite32(a, pCDS->iExternalAttr);
12018   zipfileWrite32(a, pCDS->iOffset);
12019 
12020   memcpy(a, pCDS->zFile, pCDS->nFile);
12021   a += pCDS->nFile;
12022 
12023   if( pEntry->aExtra ){
12024     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
12025     memcpy(a, pEntry->aExtra, n);
12026     a += n;
12027   }else{
12028     assert( pCDS->nExtra==9 );
12029     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
12030     zipfileWrite16(a, 5);
12031     *a++ = 0x01;
12032     zipfileWrite32(a, pEntry->mUnixTime);
12033   }
12034 
12035   return a-aBuf;
12036 }
12037 
zipfileCommit(sqlite3_vtab * pVtab)12038 static int zipfileCommit(sqlite3_vtab *pVtab){
12039   ZipfileTab *pTab = (ZipfileTab*)pVtab;
12040   int rc = SQLITE_OK;
12041   if( pTab->pWriteFd ){
12042     i64 iOffset = pTab->szCurrent;
12043     ZipfileEntry *p;
12044     ZipfileEOCD eocd;
12045     int nEntry = 0;
12046 
12047     /* Write out all entries */
12048     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
12049       int n = zipfileSerializeCDS(p, pTab->aBuffer);
12050       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
12051       nEntry++;
12052     }
12053 
12054     /* Write out the EOCD record */
12055     eocd.iDisk = 0;
12056     eocd.iFirstDisk = 0;
12057     eocd.nEntry = (u16)nEntry;
12058     eocd.nEntryTotal = (u16)nEntry;
12059     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
12060     eocd.iOffset = (u32)iOffset;
12061     rc = zipfileAppendEOCD(pTab, &eocd);
12062 
12063     zipfileCleanupTransaction(pTab);
12064   }
12065   return rc;
12066 }
12067 
zipfileRollback(sqlite3_vtab * pVtab)12068 static int zipfileRollback(sqlite3_vtab *pVtab){
12069   return zipfileCommit(pVtab);
12070 }
12071 
zipfileFindCursor(ZipfileTab * pTab,i64 iId)12072 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
12073   ZipfileCsr *pCsr;
12074   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
12075     if( iId==pCsr->iId ) break;
12076   }
12077   return pCsr;
12078 }
12079 
zipfileFunctionCds(sqlite3_context * context,int argc,sqlite3_value ** argv)12080 static void zipfileFunctionCds(
12081   sqlite3_context *context,
12082   int argc,
12083   sqlite3_value **argv
12084 ){
12085   ZipfileCsr *pCsr;
12086   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
12087   assert( argc>0 );
12088 
12089   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
12090   if( pCsr ){
12091     ZipfileCDS *p = &pCsr->pCurrent->cds;
12092     char *zRes = sqlite3_mprintf("{"
12093         "\"version-made-by\" : %u, "
12094         "\"version-to-extract\" : %u, "
12095         "\"flags\" : %u, "
12096         "\"compression\" : %u, "
12097         "\"time\" : %u, "
12098         "\"date\" : %u, "
12099         "\"crc32\" : %u, "
12100         "\"compressed-size\" : %u, "
12101         "\"uncompressed-size\" : %u, "
12102         "\"file-name-length\" : %u, "
12103         "\"extra-field-length\" : %u, "
12104         "\"file-comment-length\" : %u, "
12105         "\"disk-number-start\" : %u, "
12106         "\"internal-attr\" : %u, "
12107         "\"external-attr\" : %u, "
12108         "\"offset\" : %u }",
12109         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
12110         (u32)p->flags, (u32)p->iCompression,
12111         (u32)p->mTime, (u32)p->mDate,
12112         (u32)p->crc32, (u32)p->szCompressed,
12113         (u32)p->szUncompressed, (u32)p->nFile,
12114         (u32)p->nExtra, (u32)p->nComment,
12115         (u32)p->iDiskStart, (u32)p->iInternalAttr,
12116         (u32)p->iExternalAttr, (u32)p->iOffset
12117     );
12118 
12119     if( zRes==0 ){
12120       sqlite3_result_error_nomem(context);
12121     }else{
12122       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
12123       sqlite3_free(zRes);
12124     }
12125   }
12126 }
12127 
12128 /*
12129 ** xFindFunction method.
12130 */
zipfileFindFunction(sqlite3_vtab * pVtab,int nArg,const char * zName,void (** pxFunc)(sqlite3_context *,int,sqlite3_value **),void ** ppArg)12131 static int zipfileFindFunction(
12132   sqlite3_vtab *pVtab,            /* Virtual table handle */
12133   int nArg,                       /* Number of SQL function arguments */
12134   const char *zName,              /* Name of SQL function */
12135   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
12136   void **ppArg                    /* OUT: User data for *pxFunc */
12137 ){
12138   (void)nArg;
12139   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
12140     *pxFunc = zipfileFunctionCds;
12141     *ppArg = (void*)pVtab;
12142     return 1;
12143   }
12144   return 0;
12145 }
12146 
12147 typedef struct ZipfileBuffer ZipfileBuffer;
12148 struct ZipfileBuffer {
12149   u8 *a;                          /* Pointer to buffer */
12150   int n;                          /* Size of buffer in bytes */
12151   int nAlloc;                     /* Byte allocated at a[] */
12152 };
12153 
12154 typedef struct ZipfileCtx ZipfileCtx;
12155 struct ZipfileCtx {
12156   int nEntry;
12157   ZipfileBuffer body;
12158   ZipfileBuffer cds;
12159 };
12160 
zipfileBufferGrow(ZipfileBuffer * pBuf,int nByte)12161 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
12162   if( pBuf->n+nByte>pBuf->nAlloc ){
12163     u8 *aNew;
12164     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
12165     int nReq = pBuf->n + nByte;
12166 
12167     while( nNew<nReq ) nNew = nNew*2;
12168     aNew = sqlite3_realloc64(pBuf->a, nNew);
12169     if( aNew==0 ) return SQLITE_NOMEM;
12170     pBuf->a = aNew;
12171     pBuf->nAlloc = (int)nNew;
12172   }
12173   return SQLITE_OK;
12174 }
12175 
12176 /*
12177 ** xStep() callback for the zipfile() aggregate. This can be called in
12178 ** any of the following ways:
12179 **
12180 **   SELECT zipfile(name,data) ...
12181 **   SELECT zipfile(name,mode,mtime,data) ...
12182 **   SELECT zipfile(name,mode,mtime,data,method) ...
12183 */
zipfileStep(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)12184 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
12185   ZipfileCtx *p;                  /* Aggregate function context */
12186   ZipfileEntry e;                 /* New entry to add to zip archive */
12187 
12188   sqlite3_value *pName = 0;
12189   sqlite3_value *pMode = 0;
12190   sqlite3_value *pMtime = 0;
12191   sqlite3_value *pData = 0;
12192   sqlite3_value *pMethod = 0;
12193 
12194   int bIsDir = 0;
12195   u32 mode;
12196   int rc = SQLITE_OK;
12197   char *zErr = 0;
12198 
12199   int iMethod = -1;               /* Compression method to use (0 or 8) */
12200 
12201   const u8 *aData = 0;            /* Possibly compressed data for new entry */
12202   int nData = 0;                  /* Size of aData[] in bytes */
12203   int szUncompressed = 0;         /* Size of data before compression */
12204   u8 *aFree = 0;                  /* Free this before returning */
12205   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
12206 
12207   char *zName = 0;                /* Path (name) of new entry */
12208   int nName = 0;                  /* Size of zName in bytes */
12209   char *zFree = 0;                /* Free this before returning */
12210   int nByte;
12211 
12212   memset(&e, 0, sizeof(e));
12213   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
12214   if( p==0 ) return;
12215 
12216   /* Martial the arguments into stack variables */
12217   if( nVal!=2 && nVal!=4 && nVal!=5 ){
12218     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
12219     rc = SQLITE_ERROR;
12220     goto zipfile_step_out;
12221   }
12222   pName = apVal[0];
12223   if( nVal==2 ){
12224     pData = apVal[1];
12225   }else{
12226     pMode = apVal[1];
12227     pMtime = apVal[2];
12228     pData = apVal[3];
12229     if( nVal==5 ){
12230       pMethod = apVal[4];
12231     }
12232   }
12233 
12234   /* Check that the 'name' parameter looks ok. */
12235   zName = (char*)sqlite3_value_text(pName);
12236   nName = sqlite3_value_bytes(pName);
12237   if( zName==0 ){
12238     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
12239     rc = SQLITE_ERROR;
12240     goto zipfile_step_out;
12241   }
12242 
12243   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
12244   ** deflate compression) or NULL (choose automatically).  */
12245   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
12246     iMethod = (int)sqlite3_value_int64(pMethod);
12247     if( iMethod!=0 && iMethod!=8 ){
12248       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
12249       rc = SQLITE_ERROR;
12250       goto zipfile_step_out;
12251     }
12252   }
12253 
12254   /* Now inspect the data. If this is NULL, then the new entry must be a
12255   ** directory.  Otherwise, figure out whether or not the data should
12256   ** be deflated or simply stored in the zip archive. */
12257   if( sqlite3_value_type(pData)==SQLITE_NULL ){
12258     bIsDir = 1;
12259     iMethod = 0;
12260   }else{
12261     aData = sqlite3_value_blob(pData);
12262     szUncompressed = nData = sqlite3_value_bytes(pData);
12263     iCrc32 = crc32(0, aData, nData);
12264     if( iMethod<0 || iMethod==8 ){
12265       int nOut = 0;
12266       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
12267       if( rc!=SQLITE_OK ){
12268         goto zipfile_step_out;
12269       }
12270       if( iMethod==8 || nOut<nData ){
12271         aData = aFree;
12272         nData = nOut;
12273         iMethod = 8;
12274       }else{
12275         iMethod = 0;
12276       }
12277     }
12278   }
12279 
12280   /* Decode the "mode" argument. */
12281   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
12282   if( rc ) goto zipfile_step_out;
12283 
12284   /* Decode the "mtime" argument. */
12285   e.mUnixTime = zipfileGetTime(pMtime);
12286 
12287   /* If this is a directory entry, ensure that there is exactly one '/'
12288   ** at the end of the path. Or, if this is not a directory and the path
12289   ** ends in '/' it is an error. */
12290   if( bIsDir==0 ){
12291     if( nName>0 && zName[nName-1]=='/' ){
12292       zErr = sqlite3_mprintf("non-directory name must not end with /");
12293       rc = SQLITE_ERROR;
12294       goto zipfile_step_out;
12295     }
12296   }else{
12297     if( nName==0 || zName[nName-1]!='/' ){
12298       zName = zFree = sqlite3_mprintf("%s/", zName);
12299       if( zName==0 ){
12300         rc = SQLITE_NOMEM;
12301         goto zipfile_step_out;
12302       }
12303       nName = (int)strlen(zName);
12304     }else{
12305       while( nName>1 && zName[nName-2]=='/' ) nName--;
12306     }
12307   }
12308 
12309   /* Assemble the ZipfileEntry object for the new zip archive entry */
12310   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
12311   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
12312   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
12313   e.cds.iCompression = (u16)iMethod;
12314   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
12315   e.cds.crc32 = iCrc32;
12316   e.cds.szCompressed = nData;
12317   e.cds.szUncompressed = szUncompressed;
12318   e.cds.iExternalAttr = (mode<<16);
12319   e.cds.iOffset = p->body.n;
12320   e.cds.nFile = (u16)nName;
12321   e.cds.zFile = zName;
12322 
12323   /* Append the LFH to the body of the new archive */
12324   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
12325   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
12326   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
12327 
12328   /* Append the data to the body of the new archive */
12329   if( nData>0 ){
12330     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
12331     memcpy(&p->body.a[p->body.n], aData, nData);
12332     p->body.n += nData;
12333   }
12334 
12335   /* Append the CDS record to the directory of the new archive */
12336   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
12337   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
12338   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
12339 
12340   /* Increment the count of entries in the archive */
12341   p->nEntry++;
12342 
12343  zipfile_step_out:
12344   sqlite3_free(aFree);
12345   sqlite3_free(zFree);
12346   if( rc ){
12347     if( zErr ){
12348       sqlite3_result_error(pCtx, zErr, -1);
12349     }else{
12350       sqlite3_result_error_code(pCtx, rc);
12351     }
12352   }
12353   sqlite3_free(zErr);
12354 }
12355 
12356 /*
12357 ** xFinalize() callback for zipfile aggregate function.
12358 */
zipfileFinal(sqlite3_context * pCtx)12359 static void zipfileFinal(sqlite3_context *pCtx){
12360   ZipfileCtx *p;
12361   ZipfileEOCD eocd;
12362   sqlite3_int64 nZip;
12363   u8 *aZip;
12364 
12365   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
12366   if( p==0 ) return;
12367   if( p->nEntry>0 ){
12368     memset(&eocd, 0, sizeof(eocd));
12369     eocd.nEntry = (u16)p->nEntry;
12370     eocd.nEntryTotal = (u16)p->nEntry;
12371     eocd.nSize = p->cds.n;
12372     eocd.iOffset = p->body.n;
12373 
12374     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
12375     aZip = (u8*)sqlite3_malloc64(nZip);
12376     if( aZip==0 ){
12377       sqlite3_result_error_nomem(pCtx);
12378     }else{
12379       memcpy(aZip, p->body.a, p->body.n);
12380       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
12381       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
12382       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
12383     }
12384   }
12385 
12386   sqlite3_free(p->body.a);
12387   sqlite3_free(p->cds.a);
12388 }
12389 
12390 
12391 /*
12392 ** Register the "zipfile" virtual table.
12393 */
zipfileRegister(sqlite3 * db)12394 static int zipfileRegister(sqlite3 *db){
12395   static sqlite3_module zipfileModule = {
12396     1,                         /* iVersion */
12397     zipfileConnect,            /* xCreate */
12398     zipfileConnect,            /* xConnect */
12399     zipfileBestIndex,          /* xBestIndex */
12400     zipfileDisconnect,         /* xDisconnect */
12401     zipfileDisconnect,         /* xDestroy */
12402     zipfileOpen,               /* xOpen - open a cursor */
12403     zipfileClose,              /* xClose - close a cursor */
12404     zipfileFilter,             /* xFilter - configure scan constraints */
12405     zipfileNext,               /* xNext - advance a cursor */
12406     zipfileEof,                /* xEof - check for end of scan */
12407     zipfileColumn,             /* xColumn - read data */
12408     0,                         /* xRowid - read data */
12409     zipfileUpdate,             /* xUpdate */
12410     zipfileBegin,              /* xBegin */
12411     0,                         /* xSync */
12412     zipfileCommit,             /* xCommit */
12413     zipfileRollback,           /* xRollback */
12414     zipfileFindFunction,       /* xFindMethod */
12415     0,                         /* xRename */
12416     0,                         /* xSavepoint */
12417     0,                         /* xRelease */
12418     0,                         /* xRollback */
12419     0,                         /* xShadowName */
12420     0                          /* xIntegrity */
12421   };
12422 
12423   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
12424   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
12425   if( rc==SQLITE_OK ){
12426     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
12427         zipfileStep, zipfileFinal
12428     );
12429   }
12430   assert( sizeof(i64)==8 );
12431   assert( sizeof(u32)==4 );
12432   assert( sizeof(u16)==2 );
12433   assert( sizeof(u8)==1 );
12434   return rc;
12435 }
12436 #else         /* SQLITE_OMIT_VIRTUALTABLE */
12437 # define zipfileRegister(x) SQLITE_OK
12438 #endif
12439 
12440 #ifdef _WIN32
12441 
12442 #endif
sqlite3_zipfile_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)12443 int sqlite3_zipfile_init(
12444   sqlite3 *db,
12445   char **pzErrMsg,
12446   const sqlite3_api_routines *pApi
12447 ){
12448   SQLITE_EXTENSION_INIT2(pApi);
12449   (void)pzErrMsg;  /* Unused parameter */
12450   return zipfileRegister(db);
12451 }
12452 
12453 /************************* End ../ext/misc/zipfile.c ********************/
12454 /************************* Begin ../ext/misc/sqlar.c ******************/
12455 /*
12456 ** 2017-12-17
12457 **
12458 ** The author disclaims copyright to this source code.  In place of
12459 ** a legal notice, here is a blessing:
12460 **
12461 **    May you do good and not evil.
12462 **    May you find forgiveness for yourself and forgive others.
12463 **    May you share freely, never taking more than you give.
12464 **
12465 ******************************************************************************
12466 **
12467 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
12468 ** for working with sqlar archives and used by the shell tool's built-in
12469 ** sqlar support.
12470 */
12471 /* #include "sqlite3ext.h" */
12472 SQLITE_EXTENSION_INIT1
12473 #include <zlib.h>
12474 #include <assert.h>
12475 
12476 /*
12477 ** Implementation of the "sqlar_compress(X)" SQL function.
12478 **
12479 ** If the type of X is SQLITE_BLOB, and compressing that blob using
12480 ** zlib utility function compress() yields a smaller blob, return the
12481 ** compressed blob. Otherwise, return a copy of X.
12482 **
12483 ** SQLar uses the "zlib format" for compressed content.  The zlib format
12484 ** contains a two-byte identification header and a four-byte checksum at
12485 ** the end.  This is different from ZIP which uses the raw deflate format.
12486 **
12487 ** Future enhancements to SQLar might add support for new compression formats.
12488 ** If so, those new formats will be identified by alternative headers in the
12489 ** compressed data.
12490 */
sqlarCompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)12491 static void sqlarCompressFunc(
12492   sqlite3_context *context,
12493   int argc,
12494   sqlite3_value **argv
12495 ){
12496   assert( argc==1 );
12497   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
12498     const Bytef *pData = sqlite3_value_blob(argv[0]);
12499     uLong nData = sqlite3_value_bytes(argv[0]);
12500     uLongf nOut = compressBound(nData);
12501     Bytef *pOut;
12502 
12503     pOut = (Bytef*)sqlite3_malloc(nOut);
12504     if( pOut==0 ){
12505       sqlite3_result_error_nomem(context);
12506       return;
12507     }else{
12508       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
12509         sqlite3_result_error(context, "error in compress()", -1);
12510       }else if( nOut<nData ){
12511         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
12512       }else{
12513         sqlite3_result_value(context, argv[0]);
12514       }
12515       sqlite3_free(pOut);
12516     }
12517   }else{
12518     sqlite3_result_value(context, argv[0]);
12519   }
12520 }
12521 
12522 /*
12523 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
12524 **
12525 ** Parameter SZ is interpreted as an integer. If it is less than or
12526 ** equal to zero, then this function returns a copy of X. Or, if
12527 ** SZ is equal to the size of X when interpreted as a blob, also
12528 ** return a copy of X. Otherwise, decompress blob X using zlib
12529 ** utility function uncompress() and return the results (another
12530 ** blob).
12531 */
sqlarUncompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)12532 static void sqlarUncompressFunc(
12533   sqlite3_context *context,
12534   int argc,
12535   sqlite3_value **argv
12536 ){
12537   uLong nData;
12538   sqlite3_int64 sz;
12539 
12540   assert( argc==2 );
12541   sz = sqlite3_value_int(argv[1]);
12542 
12543   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
12544     sqlite3_result_value(context, argv[0]);
12545   }else{
12546     uLongf szf = sz;
12547     const Bytef *pData= sqlite3_value_blob(argv[0]);
12548     Bytef *pOut = sqlite3_malloc(sz);
12549     if( pOut==0 ){
12550       sqlite3_result_error_nomem(context);
12551     }else if( Z_OK!=uncompress(pOut, &szf, pData, nData) ){
12552       sqlite3_result_error(context, "error in uncompress()", -1);
12553     }else{
12554       sqlite3_result_blob(context, pOut, szf, SQLITE_TRANSIENT);
12555     }
12556     sqlite3_free(pOut);
12557   }
12558 }
12559 
12560 #ifdef _WIN32
12561 
12562 #endif
sqlite3_sqlar_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)12563 int sqlite3_sqlar_init(
12564   sqlite3 *db,
12565   char **pzErrMsg,
12566   const sqlite3_api_routines *pApi
12567 ){
12568   int rc = SQLITE_OK;
12569   SQLITE_EXTENSION_INIT2(pApi);
12570   (void)pzErrMsg;  /* Unused parameter */
12571   rc = sqlite3_create_function(db, "sqlar_compress", 1,
12572                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
12573                                sqlarCompressFunc, 0, 0);
12574   if( rc==SQLITE_OK ){
12575     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
12576                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
12577                                  sqlarUncompressFunc, 0, 0);
12578   }
12579   return rc;
12580 }
12581 
12582 /************************* End ../ext/misc/sqlar.c ********************/
12583 #endif
12584 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
12585 /*
12586 ** 2017 April 07
12587 **
12588 ** The author disclaims copyright to this source code.  In place of
12589 ** a legal notice, here is a blessing:
12590 **
12591 **    May you do good and not evil.
12592 **    May you find forgiveness for yourself and forgive others.
12593 **    May you share freely, never taking more than you give.
12594 **
12595 *************************************************************************
12596 */
12597 #if !defined(SQLITEEXPERT_H)
12598 #define SQLITEEXPERT_H 1
12599 /* #include "sqlite3.h" */
12600 
12601 typedef struct sqlite3expert sqlite3expert;
12602 
12603 /*
12604 ** Create a new sqlite3expert object.
12605 **
12606 ** If successful, a pointer to the new object is returned and (*pzErr) set
12607 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
12608 ** an English-language error message. In this case it is the responsibility
12609 ** of the caller to eventually free the error message buffer using
12610 ** sqlite3_free().
12611 */
12612 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
12613 
12614 /*
12615 ** Configure an sqlite3expert object.
12616 **
12617 ** EXPERT_CONFIG_SAMPLE:
12618 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
12619 **   each candidate index. This involves scanning and sorting the entire
12620 **   contents of each user database table once for each candidate index
12621 **   associated with the table. For large databases, this can be
12622 **   prohibitively slow. This option allows the sqlite3expert object to
12623 **   be configured so that sqlite_stat1 data is instead generated based on a
12624 **   subset of each table, or so that no sqlite_stat1 data is used at all.
12625 **
12626 **   A single integer argument is passed to this option. If the value is less
12627 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
12628 **   the analysis - indexes are recommended based on the database schema only.
12629 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
12630 **   generated for each candidate index (this is the default). Finally, if the
12631 **   value falls between 0 and 100, then it represents the percentage of user
12632 **   table rows that should be considered when generating sqlite_stat1 data.
12633 **
12634 **   Examples:
12635 **
12636 **     // Do not generate any sqlite_stat1 data
12637 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
12638 **
12639 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
12640 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
12641 */
12642 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
12643 
12644 #define EXPERT_CONFIG_SAMPLE 1    /* int */
12645 
12646 /*
12647 ** Specify zero or more SQL statements to be included in the analysis.
12648 **
12649 ** Buffer zSql must contain zero or more complete SQL statements. This
12650 ** function parses all statements contained in the buffer and adds them
12651 ** to the internal list of statements to analyze. If successful, SQLITE_OK
12652 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
12653 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
12654 ** may be set to point to an English language error message. In this case
12655 ** the caller is responsible for eventually freeing the error message buffer
12656 ** using sqlite3_free().
12657 **
12658 ** If an error does occur while processing one of the statements in the
12659 ** buffer passed as the second argument, none of the statements in the
12660 ** buffer are added to the analysis.
12661 **
12662 ** This function must be called before sqlite3_expert_analyze(). If a call
12663 ** to this function is made on an sqlite3expert object that has already
12664 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
12665 ** immediately and no statements are added to the analysis.
12666 */
12667 int sqlite3_expert_sql(
12668   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
12669   const char *zSql,               /* SQL statement(s) to add */
12670   char **pzErr                    /* OUT: Error message (if any) */
12671 );
12672 
12673 
12674 /*
12675 ** This function is called after the sqlite3expert object has been configured
12676 ** with all SQL statements using sqlite3_expert_sql() to actually perform
12677 ** the analysis. Once this function has been called, it is not possible to
12678 ** add further SQL statements to the analysis.
12679 **
12680 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
12681 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
12682 ** point to a buffer containing an English language error message. In this
12683 ** case it is the responsibility of the caller to eventually free the buffer
12684 ** using sqlite3_free().
12685 **
12686 ** If an error does occur within this function, the sqlite3expert object
12687 ** is no longer useful for any purpose. At that point it is no longer
12688 ** possible to add further SQL statements to the object or to re-attempt
12689 ** the analysis. The sqlite3expert object must still be freed using a call
12690 ** sqlite3_expert_destroy().
12691 */
12692 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
12693 
12694 /*
12695 ** Return the total number of statements loaded using sqlite3_expert_sql().
12696 ** The total number of SQL statements may be different from the total number
12697 ** to calls to sqlite3_expert_sql().
12698 */
12699 int sqlite3_expert_count(sqlite3expert*);
12700 
12701 /*
12702 ** Return a component of the report.
12703 **
12704 ** This function is called after sqlite3_expert_analyze() to extract the
12705 ** results of the analysis. Each call to this function returns either a
12706 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
12707 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
12708 ** #define constants defined below.
12709 **
12710 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
12711 ** information relating to a specific SQL statement. In these cases that
12712 ** SQL statement is identified by the value passed as the second argument.
12713 ** SQL statements are numbered from 0 in the order in which they are parsed.
12714 ** If an out-of-range value (less than zero or equal to or greater than the
12715 ** value returned by sqlite3_expert_count()) is passed as the second argument
12716 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
12717 **
12718 ** EXPERT_REPORT_SQL:
12719 **   Return the text of SQL statement iStmt.
12720 **
12721 ** EXPERT_REPORT_INDEXES:
12722 **   Return a buffer containing the CREATE INDEX statements for all recommended
12723 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
12724 **   is returned.
12725 **
12726 ** EXPERT_REPORT_PLAN:
12727 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
12728 **   iStmt after the proposed indexes have been added to the database schema.
12729 **
12730 ** EXPERT_REPORT_CANDIDATES:
12731 **   Return a pointer to a buffer containing the CREATE INDEX statements
12732 **   for all indexes that were tested (for all SQL statements). The iStmt
12733 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
12734 */
12735 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
12736 
12737 /*
12738 ** Values for the third argument passed to sqlite3_expert_report().
12739 */
12740 #define EXPERT_REPORT_SQL        1
12741 #define EXPERT_REPORT_INDEXES    2
12742 #define EXPERT_REPORT_PLAN       3
12743 #define EXPERT_REPORT_CANDIDATES 4
12744 
12745 /*
12746 ** Free an (sqlite3expert*) handle and all associated resources. There
12747 ** should be one call to this function for each successful call to
12748 ** sqlite3-expert_new().
12749 */
12750 void sqlite3_expert_destroy(sqlite3expert*);
12751 
12752 #endif  /* !defined(SQLITEEXPERT_H) */
12753 
12754 /************************* End ../ext/expert/sqlite3expert.h ********************/
12755 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
12756 /*
12757 ** 2017 April 09
12758 **
12759 ** The author disclaims copyright to this source code.  In place of
12760 ** a legal notice, here is a blessing:
12761 **
12762 **    May you do good and not evil.
12763 **    May you find forgiveness for yourself and forgive others.
12764 **    May you share freely, never taking more than you give.
12765 **
12766 *************************************************************************
12767 */
12768 /* #include "sqlite3expert.h" */
12769 #include <assert.h>
12770 #include <string.h>
12771 #include <stdio.h>
12772 
12773 #if !defined(SQLITE_AMALGAMATION)
12774 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
12775 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
12776 #endif
12777 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
12778 # define ALWAYS(X)      (1)
12779 # define NEVER(X)       (0)
12780 #elif !defined(NDEBUG)
12781 # define ALWAYS(X)      ((X)?1:(assert(0),0))
12782 # define NEVER(X)       ((X)?(assert(0),1):0)
12783 #else
12784 # define ALWAYS(X)      (X)
12785 # define NEVER(X)       (X)
12786 #endif
12787 #endif /* !defined(SQLITE_AMALGAMATION) */
12788 
12789 
12790 #ifndef SQLITE_OMIT_VIRTUALTABLE
12791 
12792 /* typedef sqlite3_int64 i64; */
12793 /* typedef sqlite3_uint64 u64; */
12794 
12795 typedef struct IdxColumn IdxColumn;
12796 typedef struct IdxConstraint IdxConstraint;
12797 typedef struct IdxScan IdxScan;
12798 typedef struct IdxStatement IdxStatement;
12799 typedef struct IdxTable IdxTable;
12800 typedef struct IdxWrite IdxWrite;
12801 
12802 #define STRLEN  (int)strlen
12803 
12804 /*
12805 ** A temp table name that we assume no user database will actually use.
12806 ** If this assumption proves incorrect triggers on the table with the
12807 ** conflicting name will be ignored.
12808 */
12809 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
12810 
12811 /*
12812 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
12813 ** any other type of single-ended range constraint on a column).
12814 **
12815 ** pLink:
12816 **   Used to temporarily link IdxConstraint objects into lists while
12817 **   creating candidate indexes.
12818 */
12819 struct IdxConstraint {
12820   char *zColl;                    /* Collation sequence */
12821   int bRange;                     /* True for range, false for eq */
12822   int iCol;                       /* Constrained table column */
12823   int bFlag;                      /* Used by idxFindCompatible() */
12824   int bDesc;                      /* True if ORDER BY <expr> DESC */
12825   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
12826   IdxConstraint *pLink;           /* See above */
12827 };
12828 
12829 /*
12830 ** A single scan of a single table.
12831 */
12832 struct IdxScan {
12833   IdxTable *pTab;                 /* Associated table object */
12834   int iDb;                        /* Database containing table zTable */
12835   i64 covering;                   /* Mask of columns required for cov. index */
12836   IdxConstraint *pOrder;          /* ORDER BY columns */
12837   IdxConstraint *pEq;             /* List of == constraints */
12838   IdxConstraint *pRange;          /* List of < constraints */
12839   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
12840 };
12841 
12842 /*
12843 ** Information regarding a single database table. Extracted from
12844 ** "PRAGMA table_info" by function idxGetTableInfo().
12845 */
12846 struct IdxColumn {
12847   char *zName;
12848   char *zColl;
12849   int iPk;
12850 };
12851 struct IdxTable {
12852   int nCol;
12853   char *zName;                    /* Table name */
12854   IdxColumn *aCol;
12855   IdxTable *pNext;                /* Next table in linked list of all tables */
12856 };
12857 
12858 /*
12859 ** An object of the following type is created for each unique table/write-op
12860 ** seen. The objects are stored in a singly-linked list beginning at
12861 ** sqlite3expert.pWrite.
12862 */
12863 struct IdxWrite {
12864   IdxTable *pTab;
12865   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
12866   IdxWrite *pNext;
12867 };
12868 
12869 /*
12870 ** Each statement being analyzed is represented by an instance of this
12871 ** structure.
12872 */
12873 struct IdxStatement {
12874   int iId;                        /* Statement number */
12875   char *zSql;                     /* SQL statement */
12876   char *zIdx;                     /* Indexes */
12877   char *zEQP;                     /* Plan */
12878   IdxStatement *pNext;
12879 };
12880 
12881 
12882 /*
12883 ** A hash table for storing strings. With space for a payload string
12884 ** with each entry. Methods are:
12885 **
12886 **   idxHashInit()
12887 **   idxHashClear()
12888 **   idxHashAdd()
12889 **   idxHashSearch()
12890 */
12891 #define IDX_HASH_SIZE 1023
12892 typedef struct IdxHashEntry IdxHashEntry;
12893 typedef struct IdxHash IdxHash;
12894 struct IdxHashEntry {
12895   char *zKey;                     /* nul-terminated key */
12896   char *zVal;                     /* nul-terminated value string */
12897   char *zVal2;                    /* nul-terminated value string 2 */
12898   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
12899   IdxHashEntry *pNext;            /* Next entry in hash */
12900 };
12901 struct IdxHash {
12902   IdxHashEntry *pFirst;
12903   IdxHashEntry *aHash[IDX_HASH_SIZE];
12904 };
12905 
12906 /*
12907 ** sqlite3expert object.
12908 */
12909 struct sqlite3expert {
12910   int iSample;                    /* Percentage of tables to sample for stat1 */
12911   sqlite3 *db;                    /* User database */
12912   sqlite3 *dbm;                   /* In-memory db for this analysis */
12913   sqlite3 *dbv;                   /* Vtab schema for this analysis */
12914   IdxTable *pTable;               /* List of all IdxTable objects */
12915   IdxScan *pScan;                 /* List of scan objects */
12916   IdxWrite *pWrite;               /* List of write objects */
12917   IdxStatement *pStatement;       /* List of IdxStatement objects */
12918   int bRun;                       /* True once analysis has run */
12919   char **pzErrmsg;
12920   int rc;                         /* Error code from whereinfo hook */
12921   IdxHash hIdx;                   /* Hash containing all candidate indexes */
12922   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
12923 };
12924 
12925 
12926 /*
12927 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
12928 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
12929 */
idxMalloc(int * pRc,int nByte)12930 static void *idxMalloc(int *pRc, int nByte){
12931   void *pRet;
12932   assert( *pRc==SQLITE_OK );
12933   assert( nByte>0 );
12934   pRet = sqlite3_malloc(nByte);
12935   if( pRet ){
12936     memset(pRet, 0, nByte);
12937   }else{
12938     *pRc = SQLITE_NOMEM;
12939   }
12940   return pRet;
12941 }
12942 
12943 /*
12944 ** Initialize an IdxHash hash table.
12945 */
idxHashInit(IdxHash * pHash)12946 static void idxHashInit(IdxHash *pHash){
12947   memset(pHash, 0, sizeof(IdxHash));
12948 }
12949 
12950 /*
12951 ** Reset an IdxHash hash table.
12952 */
idxHashClear(IdxHash * pHash)12953 static void idxHashClear(IdxHash *pHash){
12954   int i;
12955   for(i=0; i<IDX_HASH_SIZE; i++){
12956     IdxHashEntry *pEntry;
12957     IdxHashEntry *pNext;
12958     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
12959       pNext = pEntry->pHashNext;
12960       sqlite3_free(pEntry->zVal2);
12961       sqlite3_free(pEntry);
12962     }
12963   }
12964   memset(pHash, 0, sizeof(IdxHash));
12965 }
12966 
12967 /*
12968 ** Return the index of the hash bucket that the string specified by the
12969 ** arguments to this function belongs.
12970 */
idxHashString(const char * z,int n)12971 static int idxHashString(const char *z, int n){
12972   unsigned int ret = 0;
12973   int i;
12974   for(i=0; i<n; i++){
12975     ret += (ret<<3) + (unsigned char)(z[i]);
12976   }
12977   return (int)(ret % IDX_HASH_SIZE);
12978 }
12979 
12980 /*
12981 ** If zKey is already present in the hash table, return non-zero and do
12982 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
12983 ** the hash table passed as the second argument.
12984 */
idxHashAdd(int * pRc,IdxHash * pHash,const char * zKey,const char * zVal)12985 static int idxHashAdd(
12986   int *pRc,
12987   IdxHash *pHash,
12988   const char *zKey,
12989   const char *zVal
12990 ){
12991   int nKey = STRLEN(zKey);
12992   int iHash = idxHashString(zKey, nKey);
12993   int nVal = (zVal ? STRLEN(zVal) : 0);
12994   IdxHashEntry *pEntry;
12995   assert( iHash>=0 );
12996   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12997     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12998       return 1;
12999     }
13000   }
13001   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
13002   if( pEntry ){
13003     pEntry->zKey = (char*)&pEntry[1];
13004     memcpy(pEntry->zKey, zKey, nKey);
13005     if( zVal ){
13006       pEntry->zVal = &pEntry->zKey[nKey+1];
13007       memcpy(pEntry->zVal, zVal, nVal);
13008     }
13009     pEntry->pHashNext = pHash->aHash[iHash];
13010     pHash->aHash[iHash] = pEntry;
13011 
13012     pEntry->pNext = pHash->pFirst;
13013     pHash->pFirst = pEntry;
13014   }
13015   return 0;
13016 }
13017 
13018 /*
13019 ** If zKey/nKey is present in the hash table, return a pointer to the
13020 ** hash-entry object.
13021 */
idxHashFind(IdxHash * pHash,const char * zKey,int nKey)13022 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
13023   int iHash;
13024   IdxHashEntry *pEntry;
13025   if( nKey<0 ) nKey = STRLEN(zKey);
13026   iHash = idxHashString(zKey, nKey);
13027   assert( iHash>=0 );
13028   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
13029     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
13030       return pEntry;
13031     }
13032   }
13033   return 0;
13034 }
13035 
13036 /*
13037 ** If the hash table contains an entry with a key equal to the string
13038 ** passed as the final two arguments to this function, return a pointer
13039 ** to the payload string. Otherwise, if zKey/nKey is not present in the
13040 ** hash table, return NULL.
13041 */
idxHashSearch(IdxHash * pHash,const char * zKey,int nKey)13042 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
13043   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
13044   if( pEntry ) return pEntry->zVal;
13045   return 0;
13046 }
13047 
13048 /*
13049 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
13050 ** variable to point to a copy of nul-terminated string zColl.
13051 */
idxNewConstraint(int * pRc,const char * zColl)13052 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
13053   IdxConstraint *pNew;
13054   int nColl = STRLEN(zColl);
13055 
13056   assert( *pRc==SQLITE_OK );
13057   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
13058   if( pNew ){
13059     pNew->zColl = (char*)&pNew[1];
13060     memcpy(pNew->zColl, zColl, nColl+1);
13061   }
13062   return pNew;
13063 }
13064 
13065 /*
13066 ** An error associated with database handle db has just occurred. Pass
13067 ** the error message to callback function xOut.
13068 */
idxDatabaseError(sqlite3 * db,char ** pzErrmsg)13069 static void idxDatabaseError(
13070   sqlite3 *db,                    /* Database handle */
13071   char **pzErrmsg                 /* Write error here */
13072 ){
13073   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
13074 }
13075 
13076 /*
13077 ** Prepare an SQL statement.
13078 */
idxPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zSql)13079 static int idxPrepareStmt(
13080   sqlite3 *db,                    /* Database handle to compile against */
13081   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
13082   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
13083   const char *zSql                /* SQL statement to compile */
13084 ){
13085   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
13086   if( rc!=SQLITE_OK ){
13087     *ppStmt = 0;
13088     idxDatabaseError(db, pzErrmsg);
13089   }
13090   return rc;
13091 }
13092 
13093 /*
13094 ** Prepare an SQL statement using the results of a printf() formatting.
13095 */
idxPrintfPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zFmt,...)13096 static int idxPrintfPrepareStmt(
13097   sqlite3 *db,                    /* Database handle to compile against */
13098   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
13099   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
13100   const char *zFmt,               /* printf() format of SQL statement */
13101   ...                             /* Trailing printf() arguments */
13102 ){
13103   va_list ap;
13104   int rc;
13105   char *zSql;
13106   va_start(ap, zFmt);
13107   zSql = sqlite3_vmprintf(zFmt, ap);
13108   if( zSql==0 ){
13109     rc = SQLITE_NOMEM;
13110   }else{
13111     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
13112     sqlite3_free(zSql);
13113   }
13114   va_end(ap);
13115   return rc;
13116 }
13117 
13118 
13119 /*************************************************************************
13120 ** Beginning of virtual table implementation.
13121 */
13122 typedef struct ExpertVtab ExpertVtab;
13123 struct ExpertVtab {
13124   sqlite3_vtab base;
13125   IdxTable *pTab;
13126   sqlite3expert *pExpert;
13127 };
13128 
13129 typedef struct ExpertCsr ExpertCsr;
13130 struct ExpertCsr {
13131   sqlite3_vtab_cursor base;
13132   sqlite3_stmt *pData;
13133 };
13134 
expertDequote(const char * zIn)13135 static char *expertDequote(const char *zIn){
13136   int n = STRLEN(zIn);
13137   char *zRet = sqlite3_malloc(n);
13138 
13139   assert( zIn[0]=='\'' );
13140   assert( zIn[n-1]=='\'' );
13141 
13142   if( zRet ){
13143     int iOut = 0;
13144     int iIn = 0;
13145     for(iIn=1; iIn<(n-1); iIn++){
13146       if( zIn[iIn]=='\'' ){
13147         assert( zIn[iIn+1]=='\'' );
13148         iIn++;
13149       }
13150       zRet[iOut++] = zIn[iIn];
13151     }
13152     zRet[iOut] = '\0';
13153   }
13154 
13155   return zRet;
13156 }
13157 
13158 /*
13159 ** This function is the implementation of both the xConnect and xCreate
13160 ** methods of the r-tree virtual table.
13161 **
13162 **   argv[0]   -> module name
13163 **   argv[1]   -> database name
13164 **   argv[2]   -> table name
13165 **   argv[...] -> column names...
13166 */
expertConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)13167 static int expertConnect(
13168   sqlite3 *db,
13169   void *pAux,
13170   int argc, const char *const*argv,
13171   sqlite3_vtab **ppVtab,
13172   char **pzErr
13173 ){
13174   sqlite3expert *pExpert = (sqlite3expert*)pAux;
13175   ExpertVtab *p = 0;
13176   int rc;
13177 
13178   if( argc!=4 ){
13179     *pzErr = sqlite3_mprintf("internal error!");
13180     rc = SQLITE_ERROR;
13181   }else{
13182     char *zCreateTable = expertDequote(argv[3]);
13183     if( zCreateTable ){
13184       rc = sqlite3_declare_vtab(db, zCreateTable);
13185       if( rc==SQLITE_OK ){
13186         p = idxMalloc(&rc, sizeof(ExpertVtab));
13187       }
13188       if( rc==SQLITE_OK ){
13189         p->pExpert = pExpert;
13190         p->pTab = pExpert->pTable;
13191         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
13192       }
13193       sqlite3_free(zCreateTable);
13194     }else{
13195       rc = SQLITE_NOMEM;
13196     }
13197   }
13198 
13199   *ppVtab = (sqlite3_vtab*)p;
13200   return rc;
13201 }
13202 
expertDisconnect(sqlite3_vtab * pVtab)13203 static int expertDisconnect(sqlite3_vtab *pVtab){
13204   ExpertVtab *p = (ExpertVtab*)pVtab;
13205   sqlite3_free(p);
13206   return SQLITE_OK;
13207 }
13208 
expertBestIndex(sqlite3_vtab * pVtab,sqlite3_index_info * pIdxInfo)13209 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
13210   ExpertVtab *p = (ExpertVtab*)pVtab;
13211   int rc = SQLITE_OK;
13212   int n = 0;
13213   IdxScan *pScan;
13214   const int opmask =
13215     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
13216     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
13217     SQLITE_INDEX_CONSTRAINT_LE;
13218 
13219   pScan = idxMalloc(&rc, sizeof(IdxScan));
13220   if( pScan ){
13221     int i;
13222 
13223     /* Link the new scan object into the list */
13224     pScan->pTab = p->pTab;
13225     pScan->pNextScan = p->pExpert->pScan;
13226     p->pExpert->pScan = pScan;
13227 
13228     /* Add the constraints to the IdxScan object */
13229     for(i=0; i<pIdxInfo->nConstraint; i++){
13230       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
13231       if( pCons->usable
13232        && pCons->iColumn>=0
13233        && p->pTab->aCol[pCons->iColumn].iPk==0
13234        && (pCons->op & opmask)
13235       ){
13236         IdxConstraint *pNew;
13237         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
13238         pNew = idxNewConstraint(&rc, zColl);
13239         if( pNew ){
13240           pNew->iCol = pCons->iColumn;
13241           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
13242             pNew->pNext = pScan->pEq;
13243             pScan->pEq = pNew;
13244           }else{
13245             pNew->bRange = 1;
13246             pNew->pNext = pScan->pRange;
13247             pScan->pRange = pNew;
13248           }
13249         }
13250         n++;
13251         pIdxInfo->aConstraintUsage[i].argvIndex = n;
13252       }
13253     }
13254 
13255     /* Add the ORDER BY to the IdxScan object */
13256     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
13257       int iCol = pIdxInfo->aOrderBy[i].iColumn;
13258       if( iCol>=0 ){
13259         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
13260         if( pNew ){
13261           pNew->iCol = iCol;
13262           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
13263           pNew->pNext = pScan->pOrder;
13264           pNew->pLink = pScan->pOrder;
13265           pScan->pOrder = pNew;
13266           n++;
13267         }
13268       }
13269     }
13270   }
13271 
13272   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
13273   return rc;
13274 }
13275 
expertUpdate(sqlite3_vtab * pVtab,int nData,sqlite3_value ** azData,sqlite_int64 * pRowid)13276 static int expertUpdate(
13277   sqlite3_vtab *pVtab,
13278   int nData,
13279   sqlite3_value **azData,
13280   sqlite_int64 *pRowid
13281 ){
13282   (void)pVtab;
13283   (void)nData;
13284   (void)azData;
13285   (void)pRowid;
13286   return SQLITE_OK;
13287 }
13288 
13289 /*
13290 ** Virtual table module xOpen method.
13291 */
expertOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)13292 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
13293   int rc = SQLITE_OK;
13294   ExpertCsr *pCsr;
13295   (void)pVTab;
13296   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
13297   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
13298   return rc;
13299 }
13300 
13301 /*
13302 ** Virtual table module xClose method.
13303 */
expertClose(sqlite3_vtab_cursor * cur)13304 static int expertClose(sqlite3_vtab_cursor *cur){
13305   ExpertCsr *pCsr = (ExpertCsr*)cur;
13306   sqlite3_finalize(pCsr->pData);
13307   sqlite3_free(pCsr);
13308   return SQLITE_OK;
13309 }
13310 
13311 /*
13312 ** Virtual table module xEof method.
13313 **
13314 ** Return non-zero if the cursor does not currently point to a valid
13315 ** record (i.e if the scan has finished), or zero otherwise.
13316 */
expertEof(sqlite3_vtab_cursor * cur)13317 static int expertEof(sqlite3_vtab_cursor *cur){
13318   ExpertCsr *pCsr = (ExpertCsr*)cur;
13319   return pCsr->pData==0;
13320 }
13321 
13322 /*
13323 ** Virtual table module xNext method.
13324 */
expertNext(sqlite3_vtab_cursor * cur)13325 static int expertNext(sqlite3_vtab_cursor *cur){
13326   ExpertCsr *pCsr = (ExpertCsr*)cur;
13327   int rc = SQLITE_OK;
13328 
13329   assert( pCsr->pData );
13330   rc = sqlite3_step(pCsr->pData);
13331   if( rc!=SQLITE_ROW ){
13332     rc = sqlite3_finalize(pCsr->pData);
13333     pCsr->pData = 0;
13334   }else{
13335     rc = SQLITE_OK;
13336   }
13337 
13338   return rc;
13339 }
13340 
13341 /*
13342 ** Virtual table module xRowid method.
13343 */
expertRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)13344 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
13345   (void)cur;
13346   *pRowid = 0;
13347   return SQLITE_OK;
13348 }
13349 
13350 /*
13351 ** Virtual table module xColumn method.
13352 */
expertColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)13353 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
13354   ExpertCsr *pCsr = (ExpertCsr*)cur;
13355   sqlite3_value *pVal;
13356   pVal = sqlite3_column_value(pCsr->pData, i);
13357   if( pVal ){
13358     sqlite3_result_value(ctx, pVal);
13359   }
13360   return SQLITE_OK;
13361 }
13362 
13363 /*
13364 ** Virtual table module xFilter method.
13365 */
expertFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)13366 static int expertFilter(
13367   sqlite3_vtab_cursor *cur,
13368   int idxNum, const char *idxStr,
13369   int argc, sqlite3_value **argv
13370 ){
13371   ExpertCsr *pCsr = (ExpertCsr*)cur;
13372   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
13373   sqlite3expert *pExpert = pVtab->pExpert;
13374   int rc;
13375 
13376   (void)idxNum;
13377   (void)idxStr;
13378   (void)argc;
13379   (void)argv;
13380   rc = sqlite3_finalize(pCsr->pData);
13381   pCsr->pData = 0;
13382   if( rc==SQLITE_OK ){
13383     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
13384         "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName
13385     );
13386   }
13387 
13388   if( rc==SQLITE_OK ){
13389     rc = expertNext(cur);
13390   }
13391   return rc;
13392 }
13393 
idxRegisterVtab(sqlite3expert * p)13394 static int idxRegisterVtab(sqlite3expert *p){
13395   static sqlite3_module expertModule = {
13396     2,                            /* iVersion */
13397     expertConnect,                /* xCreate - create a table */
13398     expertConnect,                /* xConnect - connect to an existing table */
13399     expertBestIndex,              /* xBestIndex - Determine search strategy */
13400     expertDisconnect,             /* xDisconnect - Disconnect from a table */
13401     expertDisconnect,             /* xDestroy - Drop a table */
13402     expertOpen,                   /* xOpen - open a cursor */
13403     expertClose,                  /* xClose - close a cursor */
13404     expertFilter,                 /* xFilter - configure scan constraints */
13405     expertNext,                   /* xNext - advance a cursor */
13406     expertEof,                    /* xEof */
13407     expertColumn,                 /* xColumn - read data */
13408     expertRowid,                  /* xRowid - read data */
13409     expertUpdate,                 /* xUpdate - write data */
13410     0,                            /* xBegin - begin transaction */
13411     0,                            /* xSync - sync transaction */
13412     0,                            /* xCommit - commit transaction */
13413     0,                            /* xRollback - rollback transaction */
13414     0,                            /* xFindFunction - function overloading */
13415     0,                            /* xRename - rename the table */
13416     0,                            /* xSavepoint */
13417     0,                            /* xRelease */
13418     0,                            /* xRollbackTo */
13419     0,                            /* xShadowName */
13420     0,                            /* xIntegrity */
13421   };
13422 
13423   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
13424 }
13425 /*
13426 ** End of virtual table implementation.
13427 *************************************************************************/
13428 /*
13429 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
13430 ** is called, set it to the return value of sqlite3_finalize() before
13431 ** returning. Otherwise, discard the sqlite3_finalize() return value.
13432 */
idxFinalize(int * pRc,sqlite3_stmt * pStmt)13433 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
13434   int rc = sqlite3_finalize(pStmt);
13435   if( *pRc==SQLITE_OK ) *pRc = rc;
13436 }
13437 
13438 /*
13439 ** Attempt to allocate an IdxTable structure corresponding to table zTab
13440 ** in the main database of connection db. If successful, set (*ppOut) to
13441 ** point to the new object and return SQLITE_OK. Otherwise, return an
13442 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
13443 ** set to point to an error string.
13444 **
13445 ** It is the responsibility of the caller to eventually free either the
13446 ** IdxTable object or error message using sqlite3_free().
13447 */
idxGetTableInfo(sqlite3 * db,const char * zTab,IdxTable ** ppOut,char ** pzErrmsg)13448 static int idxGetTableInfo(
13449   sqlite3 *db,                    /* Database connection to read details from */
13450   const char *zTab,               /* Table name */
13451   IdxTable **ppOut,               /* OUT: New object (if successful) */
13452   char **pzErrmsg                 /* OUT: Error message (if not) */
13453 ){
13454   sqlite3_stmt *p1 = 0;
13455   int nCol = 0;
13456   int nTab;
13457   int nByte;
13458   IdxTable *pNew = 0;
13459   int rc, rc2;
13460   char *pCsr = 0;
13461   int nPk = 0;
13462 
13463   *ppOut = 0;
13464   if( zTab==0 ) return SQLITE_ERROR;
13465   nTab = STRLEN(zTab);
13466   nByte = sizeof(IdxTable) + nTab + 1;
13467   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
13468   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
13469     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
13470     const char *zColSeq = 0;
13471     if( zCol==0 ){
13472       rc = SQLITE_ERROR;
13473       break;
13474     }
13475     nByte += 1 + STRLEN(zCol);
13476     rc = sqlite3_table_column_metadata(
13477         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
13478     );
13479     if( zColSeq==0 ) zColSeq = "binary";
13480     nByte += 1 + STRLEN(zColSeq);
13481     nCol++;
13482     nPk += (sqlite3_column_int(p1, 5)>0);
13483   }
13484   rc2 = sqlite3_reset(p1);
13485   if( rc==SQLITE_OK ) rc = rc2;
13486 
13487   nByte += sizeof(IdxColumn) * nCol;
13488   if( rc==SQLITE_OK ){
13489     pNew = idxMalloc(&rc, nByte);
13490   }
13491   if( rc==SQLITE_OK ){
13492     pNew->aCol = (IdxColumn*)&pNew[1];
13493     pNew->nCol = nCol;
13494     pCsr = (char*)&pNew->aCol[nCol];
13495   }
13496 
13497   nCol = 0;
13498   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
13499     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
13500     const char *zColSeq = 0;
13501     int nCopy;
13502     if( zCol==0 ) continue;
13503     nCopy = STRLEN(zCol) + 1;
13504     pNew->aCol[nCol].zName = pCsr;
13505     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
13506     memcpy(pCsr, zCol, nCopy);
13507     pCsr += nCopy;
13508 
13509     rc = sqlite3_table_column_metadata(
13510         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
13511     );
13512     if( rc==SQLITE_OK ){
13513       if( zColSeq==0 ) zColSeq = "binary";
13514       nCopy = STRLEN(zColSeq) + 1;
13515       pNew->aCol[nCol].zColl = pCsr;
13516       memcpy(pCsr, zColSeq, nCopy);
13517       pCsr += nCopy;
13518     }
13519 
13520     nCol++;
13521   }
13522   idxFinalize(&rc, p1);
13523 
13524   if( rc!=SQLITE_OK ){
13525     sqlite3_free(pNew);
13526     pNew = 0;
13527   }else if( ALWAYS(pNew!=0) ){
13528     pNew->zName = pCsr;
13529     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
13530   }
13531 
13532   *ppOut = pNew;
13533   return rc;
13534 }
13535 
13536 /*
13537 ** This function is a no-op if *pRc is set to anything other than
13538 ** SQLITE_OK when it is called.
13539 **
13540 ** If *pRc is initially set to SQLITE_OK, then the text specified by
13541 ** the printf() style arguments is appended to zIn and the result returned
13542 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
13543 ** zIn before returning.
13544 */
idxAppendText(int * pRc,char * zIn,const char * zFmt,...)13545 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
13546   va_list ap;
13547   char *zAppend = 0;
13548   char *zRet = 0;
13549   int nIn = zIn ? STRLEN(zIn) : 0;
13550   int nAppend = 0;
13551   va_start(ap, zFmt);
13552   if( *pRc==SQLITE_OK ){
13553     zAppend = sqlite3_vmprintf(zFmt, ap);
13554     if( zAppend ){
13555       nAppend = STRLEN(zAppend);
13556       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
13557     }
13558     if( zAppend && zRet ){
13559       if( nIn ) memcpy(zRet, zIn, nIn);
13560       memcpy(&zRet[nIn], zAppend, nAppend+1);
13561     }else{
13562       sqlite3_free(zRet);
13563       zRet = 0;
13564       *pRc = SQLITE_NOMEM;
13565     }
13566     sqlite3_free(zAppend);
13567     sqlite3_free(zIn);
13568   }
13569   va_end(ap);
13570   return zRet;
13571 }
13572 
13573 /*
13574 ** Return true if zId must be quoted in order to use it as an SQL
13575 ** identifier, or false otherwise.
13576 */
idxIdentifierRequiresQuotes(const char * zId)13577 static int idxIdentifierRequiresQuotes(const char *zId){
13578   int i;
13579   int nId = STRLEN(zId);
13580 
13581   if( sqlite3_keyword_check(zId, nId) ) return 1;
13582 
13583   for(i=0; zId[i]; i++){
13584     if( !(zId[i]=='_')
13585      && !(zId[i]>='0' && zId[i]<='9')
13586      && !(zId[i]>='a' && zId[i]<='z')
13587      && !(zId[i]>='A' && zId[i]<='Z')
13588     ){
13589       return 1;
13590     }
13591   }
13592   return 0;
13593 }
13594 
13595 /*
13596 ** This function appends an index column definition suitable for constraint
13597 ** pCons to the string passed as zIn and returns the result.
13598 */
idxAppendColDefn(int * pRc,char * zIn,IdxTable * pTab,IdxConstraint * pCons)13599 static char *idxAppendColDefn(
13600   int *pRc,                       /* IN/OUT: Error code */
13601   char *zIn,                      /* Column defn accumulated so far */
13602   IdxTable *pTab,                 /* Table index will be created on */
13603   IdxConstraint *pCons
13604 ){
13605   char *zRet = zIn;
13606   IdxColumn *p = &pTab->aCol[pCons->iCol];
13607   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
13608 
13609   if( idxIdentifierRequiresQuotes(p->zName) ){
13610     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
13611   }else{
13612     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
13613   }
13614 
13615   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
13616     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
13617       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
13618     }else{
13619       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
13620     }
13621   }
13622 
13623   if( pCons->bDesc ){
13624     zRet = idxAppendText(pRc, zRet, " DESC");
13625   }
13626   return zRet;
13627 }
13628 
13629 /*
13630 ** Search database dbm for an index compatible with the one idxCreateFromCons()
13631 ** would create from arguments pScan, pEq and pTail. If no error occurs and
13632 ** such an index is found, return non-zero. Or, if no such index is found,
13633 ** return zero.
13634 **
13635 ** If an error occurs, set *pRc to an SQLite error code and return zero.
13636 */
idxFindCompatible(int * pRc,sqlite3 * dbm,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)13637 static int idxFindCompatible(
13638   int *pRc,                       /* OUT: Error code */
13639   sqlite3* dbm,                   /* Database to search */
13640   IdxScan *pScan,                 /* Scan for table to search for index on */
13641   IdxConstraint *pEq,             /* List of == constraints */
13642   IdxConstraint *pTail            /* List of range constraints */
13643 ){
13644   const char *zTbl = pScan->pTab->zName;
13645   sqlite3_stmt *pIdxList = 0;
13646   IdxConstraint *pIter;
13647   int nEq = 0;                    /* Number of elements in pEq */
13648   int rc;
13649 
13650   /* Count the elements in list pEq */
13651   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
13652 
13653   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
13654   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
13655     int bMatch = 1;
13656     IdxConstraint *pT = pTail;
13657     sqlite3_stmt *pInfo = 0;
13658     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
13659     if( zIdx==0 ) continue;
13660 
13661     /* Zero the IdxConstraint.bFlag values in the pEq list */
13662     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
13663 
13664     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
13665     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
13666       int iIdx = sqlite3_column_int(pInfo, 0);
13667       int iCol = sqlite3_column_int(pInfo, 1);
13668       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
13669 
13670       if( iIdx<nEq ){
13671         for(pIter=pEq; pIter; pIter=pIter->pLink){
13672           if( pIter->bFlag ) continue;
13673           if( pIter->iCol!=iCol ) continue;
13674           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
13675           pIter->bFlag = 1;
13676           break;
13677         }
13678         if( pIter==0 ){
13679           bMatch = 0;
13680           break;
13681         }
13682       }else{
13683         if( pT ){
13684           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
13685             bMatch = 0;
13686             break;
13687           }
13688           pT = pT->pLink;
13689         }
13690       }
13691     }
13692     idxFinalize(&rc, pInfo);
13693 
13694     if( rc==SQLITE_OK && bMatch ){
13695       sqlite3_finalize(pIdxList);
13696       return 1;
13697     }
13698   }
13699   idxFinalize(&rc, pIdxList);
13700 
13701   *pRc = rc;
13702   return 0;
13703 }
13704 
13705 /* Callback for sqlite3_exec() with query with leading count(*) column.
13706  * The first argument is expected to be an int*, referent to be incremented
13707  * if that leading column is not exactly '0'.
13708  */
countNonzeros(void * pCount,int nc,char * azResults[],char * azColumns[])13709 static int countNonzeros(void* pCount, int nc,
13710                          char* azResults[], char* azColumns[]){
13711   (void)azColumns;  /* Suppress unused parameter warning */
13712   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
13713     *((int *)pCount) += 1;
13714   }
13715   return 0;
13716 }
13717 
idxCreateFromCons(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)13718 static int idxCreateFromCons(
13719   sqlite3expert *p,
13720   IdxScan *pScan,
13721   IdxConstraint *pEq,
13722   IdxConstraint *pTail
13723 ){
13724   sqlite3 *dbm = p->dbm;
13725   int rc = SQLITE_OK;
13726   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
13727     IdxTable *pTab = pScan->pTab;
13728     char *zCols = 0;
13729     char *zIdx = 0;
13730     IdxConstraint *pCons;
13731     unsigned int h = 0;
13732     const char *zFmt;
13733 
13734     for(pCons=pEq; pCons; pCons=pCons->pLink){
13735       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
13736     }
13737     for(pCons=pTail; pCons; pCons=pCons->pLink){
13738       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
13739     }
13740 
13741     if( rc==SQLITE_OK ){
13742       /* Hash the list of columns to come up with a name for the index */
13743       const char *zTable = pScan->pTab->zName;
13744       int quoteTable = idxIdentifierRequiresQuotes(zTable);
13745       char *zName = 0;          /* Index name */
13746       int collisions = 0;
13747       do{
13748         int i;
13749         char *zFind;
13750         for(i=0; zCols[i]; i++){
13751           h += ((h<<3) + zCols[i]);
13752         }
13753         sqlite3_free(zName);
13754         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
13755         if( zName==0 ) break;
13756         /* Is is unique among table, view and index names? */
13757         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
13758           " AND type in ('index','table','view')";
13759         zFind = sqlite3_mprintf(zFmt, zName);
13760         i = 0;
13761         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
13762         assert(rc==SQLITE_OK);
13763         sqlite3_free(zFind);
13764         if( i==0 ){
13765           collisions = 0;
13766           break;
13767         }
13768         ++collisions;
13769       }while( collisions<50 && zName!=0 );
13770       if( collisions ){
13771         /* This return means "Gave up trying to find a unique index name." */
13772         rc = SQLITE_BUSY_TIMEOUT;
13773       }else if( zName==0 ){
13774         rc = SQLITE_NOMEM;
13775       }else{
13776         if( quoteTable ){
13777           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
13778         }else{
13779           zFmt = "CREATE INDEX %s ON %s(%s)";
13780         }
13781         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
13782         if( !zIdx ){
13783           rc = SQLITE_NOMEM;
13784         }else{
13785           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
13786           if( rc!=SQLITE_OK ){
13787             rc = SQLITE_BUSY_TIMEOUT;
13788           }else{
13789             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
13790           }
13791         }
13792         sqlite3_free(zName);
13793         sqlite3_free(zIdx);
13794       }
13795     }
13796 
13797     sqlite3_free(zCols);
13798   }
13799   return rc;
13800 }
13801 
13802 /*
13803 ** Return true if list pList (linked by IdxConstraint.pLink) contains
13804 ** a constraint compatible with *p. Otherwise return false.
13805 */
idxFindConstraint(IdxConstraint * pList,IdxConstraint * p)13806 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
13807   IdxConstraint *pCmp;
13808   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
13809     if( p->iCol==pCmp->iCol ) return 1;
13810   }
13811   return 0;
13812 }
13813 
idxCreateFromWhere(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pTail)13814 static int idxCreateFromWhere(
13815   sqlite3expert *p,
13816   IdxScan *pScan,                 /* Create indexes for this scan */
13817   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
13818 ){
13819   IdxConstraint *p1 = 0;
13820   IdxConstraint *pCon;
13821   int rc;
13822 
13823   /* Gather up all the == constraints. */
13824   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
13825     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
13826       pCon->pLink = p1;
13827       p1 = pCon;
13828     }
13829   }
13830 
13831   /* Create an index using the == constraints collected above. And the
13832   ** range constraint/ORDER BY terms passed in by the caller, if any. */
13833   rc = idxCreateFromCons(p, pScan, p1, pTail);
13834 
13835   /* If no range/ORDER BY passed by the caller, create a version of the
13836   ** index for each range constraint.  */
13837   if( pTail==0 ){
13838     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
13839       assert( pCon->pLink==0 );
13840       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
13841         rc = idxCreateFromCons(p, pScan, p1, pCon);
13842       }
13843     }
13844   }
13845 
13846   return rc;
13847 }
13848 
13849 /*
13850 ** Create candidate indexes in database [dbm] based on the data in
13851 ** linked-list pScan.
13852 */
idxCreateCandidates(sqlite3expert * p)13853 static int idxCreateCandidates(sqlite3expert *p){
13854   int rc = SQLITE_OK;
13855   IdxScan *pIter;
13856 
13857   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
13858     rc = idxCreateFromWhere(p, pIter, 0);
13859     if( rc==SQLITE_OK && pIter->pOrder ){
13860       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
13861     }
13862   }
13863 
13864   return rc;
13865 }
13866 
13867 /*
13868 ** Free all elements of the linked list starting at pConstraint.
13869 */
idxConstraintFree(IdxConstraint * pConstraint)13870 static void idxConstraintFree(IdxConstraint *pConstraint){
13871   IdxConstraint *pNext;
13872   IdxConstraint *p;
13873 
13874   for(p=pConstraint; p; p=pNext){
13875     pNext = p->pNext;
13876     sqlite3_free(p);
13877   }
13878 }
13879 
13880 /*
13881 ** Free all elements of the linked list starting from pScan up until pLast
13882 ** (pLast is not freed).
13883 */
idxScanFree(IdxScan * pScan,IdxScan * pLast)13884 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
13885   IdxScan *p;
13886   IdxScan *pNext;
13887   for(p=pScan; p!=pLast; p=pNext){
13888     pNext = p->pNextScan;
13889     idxConstraintFree(p->pOrder);
13890     idxConstraintFree(p->pEq);
13891     idxConstraintFree(p->pRange);
13892     sqlite3_free(p);
13893   }
13894 }
13895 
13896 /*
13897 ** Free all elements of the linked list starting from pStatement up
13898 ** until pLast (pLast is not freed).
13899 */
idxStatementFree(IdxStatement * pStatement,IdxStatement * pLast)13900 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
13901   IdxStatement *p;
13902   IdxStatement *pNext;
13903   for(p=pStatement; p!=pLast; p=pNext){
13904     pNext = p->pNext;
13905     sqlite3_free(p->zEQP);
13906     sqlite3_free(p->zIdx);
13907     sqlite3_free(p);
13908   }
13909 }
13910 
13911 /*
13912 ** Free the linked list of IdxTable objects starting at pTab.
13913 */
idxTableFree(IdxTable * pTab)13914 static void idxTableFree(IdxTable *pTab){
13915   IdxTable *pIter;
13916   IdxTable *pNext;
13917   for(pIter=pTab; pIter; pIter=pNext){
13918     pNext = pIter->pNext;
13919     sqlite3_free(pIter);
13920   }
13921 }
13922 
13923 /*
13924 ** Free the linked list of IdxWrite objects starting at pTab.
13925 */
idxWriteFree(IdxWrite * pTab)13926 static void idxWriteFree(IdxWrite *pTab){
13927   IdxWrite *pIter;
13928   IdxWrite *pNext;
13929   for(pIter=pTab; pIter; pIter=pNext){
13930     pNext = pIter->pNext;
13931     sqlite3_free(pIter);
13932   }
13933 }
13934 
13935 
13936 
13937 /*
13938 ** This function is called after candidate indexes have been created. It
13939 ** runs all the queries to see which indexes they prefer, and populates
13940 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
13941 */
idxFindIndexes(sqlite3expert * p,char ** pzErr)13942 static int idxFindIndexes(
13943   sqlite3expert *p,
13944   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
13945 ){
13946   IdxStatement *pStmt;
13947   sqlite3 *dbm = p->dbm;
13948   int rc = SQLITE_OK;
13949 
13950   IdxHash hIdx;
13951   idxHashInit(&hIdx);
13952 
13953   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
13954     IdxHashEntry *pEntry;
13955     sqlite3_stmt *pExplain = 0;
13956     idxHashClear(&hIdx);
13957     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
13958         "EXPLAIN QUERY PLAN %s", pStmt->zSql
13959     );
13960     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
13961       /* int iId = sqlite3_column_int(pExplain, 0); */
13962       /* int iParent = sqlite3_column_int(pExplain, 1); */
13963       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
13964       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
13965       int nDetail;
13966       int i;
13967 
13968       if( !zDetail ) continue;
13969       nDetail = STRLEN(zDetail);
13970 
13971       for(i=0; i<nDetail; i++){
13972         const char *zIdx = 0;
13973         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
13974           zIdx = &zDetail[i+13];
13975         }else if( i+22<nDetail
13976             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
13977         ){
13978           zIdx = &zDetail[i+22];
13979         }
13980         if( zIdx ){
13981           const char *zSql;
13982           int nIdx = 0;
13983           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
13984             nIdx++;
13985           }
13986           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
13987           if( zSql ){
13988             idxHashAdd(&rc, &hIdx, zSql, 0);
13989             if( rc ) goto find_indexes_out;
13990           }
13991           break;
13992         }
13993       }
13994 
13995       if( zDetail[0]!='-' ){
13996         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
13997       }
13998     }
13999 
14000     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
14001       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
14002     }
14003 
14004     idxFinalize(&rc, pExplain);
14005   }
14006 
14007  find_indexes_out:
14008   idxHashClear(&hIdx);
14009   return rc;
14010 }
14011 
idxAuthCallback(void * pCtx,int eOp,const char * z3,const char * z4,const char * zDb,const char * zTrigger)14012 static int idxAuthCallback(
14013   void *pCtx,
14014   int eOp,
14015   const char *z3,
14016   const char *z4,
14017   const char *zDb,
14018   const char *zTrigger
14019 ){
14020   int rc = SQLITE_OK;
14021   (void)z4;
14022   (void)zTrigger;
14023   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
14024     if( sqlite3_stricmp(zDb, "main")==0 ){
14025       sqlite3expert *p = (sqlite3expert*)pCtx;
14026       IdxTable *pTab;
14027       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
14028         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
14029       }
14030       if( pTab ){
14031         IdxWrite *pWrite;
14032         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
14033           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
14034         }
14035         if( pWrite==0 ){
14036           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
14037           if( rc==SQLITE_OK ){
14038             pWrite->pTab = pTab;
14039             pWrite->eOp = eOp;
14040             pWrite->pNext = p->pWrite;
14041             p->pWrite = pWrite;
14042           }
14043         }
14044       }
14045     }
14046   }
14047   return rc;
14048 }
14049 
idxProcessOneTrigger(sqlite3expert * p,IdxWrite * pWrite,char ** pzErr)14050 static int idxProcessOneTrigger(
14051   sqlite3expert *p,
14052   IdxWrite *pWrite,
14053   char **pzErr
14054 ){
14055   static const char *zInt = UNIQUE_TABLE_NAME;
14056   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
14057   IdxTable *pTab = pWrite->pTab;
14058   const char *zTab = pTab->zName;
14059   const char *zSql =
14060     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
14061     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
14062     "ORDER BY type;";
14063   sqlite3_stmt *pSelect = 0;
14064   int rc = SQLITE_OK;
14065   char *zWrite = 0;
14066 
14067   /* Create the table and its triggers in the temp schema */
14068   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
14069   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
14070     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
14071     if( zCreate==0 ) continue;
14072     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
14073   }
14074   idxFinalize(&rc, pSelect);
14075 
14076   /* Rename the table in the temp schema to zInt */
14077   if( rc==SQLITE_OK ){
14078     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
14079     if( z==0 ){
14080       rc = SQLITE_NOMEM;
14081     }else{
14082       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
14083       sqlite3_free(z);
14084     }
14085   }
14086 
14087   switch( pWrite->eOp ){
14088     case SQLITE_INSERT: {
14089       int i;
14090       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
14091       for(i=0; i<pTab->nCol; i++){
14092         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
14093       }
14094       zWrite = idxAppendText(&rc, zWrite, ")");
14095       break;
14096     }
14097     case SQLITE_UPDATE: {
14098       int i;
14099       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
14100       for(i=0; i<pTab->nCol; i++){
14101         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
14102             pTab->aCol[i].zName
14103         );
14104       }
14105       break;
14106     }
14107     default: {
14108       assert( pWrite->eOp==SQLITE_DELETE );
14109       if( rc==SQLITE_OK ){
14110         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
14111         if( zWrite==0 ) rc = SQLITE_NOMEM;
14112       }
14113     }
14114   }
14115 
14116   if( rc==SQLITE_OK ){
14117     sqlite3_stmt *pX = 0;
14118     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
14119     idxFinalize(&rc, pX);
14120     if( rc!=SQLITE_OK ){
14121       idxDatabaseError(p->dbv, pzErr);
14122     }
14123   }
14124   sqlite3_free(zWrite);
14125 
14126   if( rc==SQLITE_OK ){
14127     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
14128   }
14129 
14130   return rc;
14131 }
14132 
idxProcessTriggers(sqlite3expert * p,char ** pzErr)14133 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
14134   int rc = SQLITE_OK;
14135   IdxWrite *pEnd = 0;
14136   IdxWrite *pFirst = p->pWrite;
14137 
14138   while( rc==SQLITE_OK && pFirst!=pEnd ){
14139     IdxWrite *pIter;
14140     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
14141       rc = idxProcessOneTrigger(p, pIter, pzErr);
14142     }
14143     pEnd = pFirst;
14144     pFirst = p->pWrite;
14145   }
14146 
14147   return rc;
14148 }
14149 
14150 /*
14151 ** This function tests if the schema of the main database of database handle
14152 ** db contains an object named zTab. Assuming no error occurs, output parameter
14153 ** (*pbContains) is set to true if zTab exists, or false if it does not.
14154 **
14155 ** Or, if an error occurs, an SQLite error code is returned. The final value
14156 ** of (*pbContains) is undefined in this case.
14157 */
expertDbContainsObject(sqlite3 * db,const char * zTab,int * pbContains)14158 static int expertDbContainsObject(
14159   sqlite3 *db,
14160   const char *zTab,
14161   int *pbContains                 /* OUT: True if object exists */
14162 ){
14163   const char *zSql = "SELECT 1 FROM sqlite_schema WHERE name = ?";
14164   sqlite3_stmt *pSql = 0;
14165   int rc = SQLITE_OK;
14166   int ret = 0;
14167 
14168   rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
14169   if( rc==SQLITE_OK ){
14170     sqlite3_bind_text(pSql, 1, zTab, -1, SQLITE_STATIC);
14171     if( SQLITE_ROW==sqlite3_step(pSql) ){
14172       ret = 1;
14173     }
14174     rc = sqlite3_finalize(pSql);
14175   }
14176 
14177   *pbContains = ret;
14178   return rc;
14179 }
14180 
14181 /*
14182 ** Execute SQL command zSql using database handle db. If no error occurs,
14183 ** set (*pzErr) to NULL and return SQLITE_OK.
14184 **
14185 ** If an error does occur, return an SQLite error code and set (*pzErr) to
14186 ** point to a buffer containing an English language error message. Except,
14187 ** if the error message begins with "no such module:", then ignore the
14188 ** error and return as if the SQL statement had succeeded.
14189 **
14190 ** This is used to copy as much of the database schema as possible while
14191 ** ignoring any errors related to missing virtual table modules.
14192 */
expertSchemaSql(sqlite3 * db,const char * zSql,char ** pzErr)14193 static int expertSchemaSql(sqlite3 *db, const char *zSql, char **pzErr){
14194   int rc = SQLITE_OK;
14195   char *zErr = 0;
14196 
14197   rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
14198   if( rc!=SQLITE_OK && zErr ){
14199     int nErr = STRLEN(zErr);
14200     if( nErr>=15 && memcmp(zErr, "no such module:", 15)==0 ){
14201       sqlite3_free(zErr);
14202       rc = SQLITE_OK;
14203       zErr = 0;
14204     }
14205   }
14206 
14207   *pzErr = zErr;
14208   return rc;
14209 }
14210 
idxCreateVtabSchema(sqlite3expert * p,char ** pzErrmsg)14211 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
14212   int rc = idxRegisterVtab(p);
14213   sqlite3_stmt *pSchema = 0;
14214 
14215   /* For each table in the main db schema:
14216   **
14217   **   1) Add an entry to the p->pTable list, and
14218   **   2) Create the equivalent virtual table in dbv.
14219   */
14220   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
14221       "SELECT type, name, sql, 1, "
14222       "       substr(sql,1,14)=='create virtual' COLLATE nocase "
14223       "FROM sqlite_schema "
14224       "WHERE type IN ('table','view') AND "
14225       "      substr(name,1,7)!='sqlite_' COLLATE nocase "
14226       " UNION ALL "
14227       "SELECT type, name, sql, 2, 0 FROM sqlite_schema "
14228       "WHERE type = 'trigger'"
14229       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
14230       "ORDER BY 4, 5 DESC, 1"
14231   );
14232   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
14233     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
14234     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
14235     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
14236     int bVirtual = sqlite3_column_int(pSchema, 4);
14237     int bExists = 0;
14238 
14239     if( zType==0 || zName==0 ) continue;
14240     rc = expertDbContainsObject(p->dbv, zName, &bExists);
14241     if( rc || bExists ) continue;
14242 
14243     if( zType[0]=='v' || zType[1]=='r' || bVirtual ){
14244       /* A view. Or a trigger on a view. */
14245       if( zSql ) rc = expertSchemaSql(p->dbv, zSql, pzErrmsg);
14246     }else{
14247       IdxTable *pTab;
14248       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
14249       if( rc==SQLITE_OK && ALWAYS(pTab!=0) ){
14250         int i;
14251         char *zInner = 0;
14252         char *zOuter = 0;
14253         pTab->pNext = p->pTable;
14254         p->pTable = pTab;
14255 
14256         /* The statement the vtab will pass to sqlite3_declare_vtab() */
14257         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
14258         for(i=0; i<pTab->nCol; i++){
14259           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
14260               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
14261           );
14262         }
14263         zInner = idxAppendText(&rc, zInner, ")");
14264 
14265         /* The CVT statement to create the vtab */
14266         zOuter = idxAppendText(&rc, 0,
14267             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
14268         );
14269         if( rc==SQLITE_OK ){
14270           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
14271         }
14272         sqlite3_free(zInner);
14273         sqlite3_free(zOuter);
14274       }
14275     }
14276   }
14277   idxFinalize(&rc, pSchema);
14278   return rc;
14279 }
14280 
14281 struct IdxSampleCtx {
14282   int iTarget;
14283   double target;                  /* Target nRet/nRow value */
14284   double nRow;                    /* Number of rows seen */
14285   double nRet;                    /* Number of rows returned */
14286 };
14287 
idxSampleFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)14288 static void idxSampleFunc(
14289   sqlite3_context *pCtx,
14290   int argc,
14291   sqlite3_value **argv
14292 ){
14293   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
14294   int bRet;
14295 
14296   (void)argv;
14297   assert( argc==0 );
14298   if( p->nRow==0.0 ){
14299     bRet = 1;
14300   }else{
14301     bRet = (p->nRet / p->nRow) <= p->target;
14302     if( bRet==0 ){
14303       unsigned short rnd;
14304       sqlite3_randomness(2, (void*)&rnd);
14305       bRet = ((int)rnd % 100) <= p->iTarget;
14306     }
14307   }
14308 
14309   sqlite3_result_int(pCtx, bRet);
14310   p->nRow += 1.0;
14311   p->nRet += (double)bRet;
14312 }
14313 
14314 struct IdxRemCtx {
14315   int nSlot;
14316   struct IdxRemSlot {
14317     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
14318     i64 iVal;                     /* SQLITE_INTEGER value */
14319     double rVal;                  /* SQLITE_FLOAT value */
14320     int nByte;                    /* Bytes of space allocated at z */
14321     int n;                        /* Size of buffer z */
14322     char *z;                      /* SQLITE_TEXT/BLOB value */
14323   } aSlot[1];
14324 };
14325 
14326 /*
14327 ** Implementation of scalar function sqlite_expert_rem().
14328 */
idxRemFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)14329 static void idxRemFunc(
14330   sqlite3_context *pCtx,
14331   int argc,
14332   sqlite3_value **argv
14333 ){
14334   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
14335   struct IdxRemSlot *pSlot;
14336   int iSlot;
14337   assert( argc==2 );
14338 
14339   iSlot = sqlite3_value_int(argv[0]);
14340   assert( iSlot<p->nSlot );
14341   pSlot = &p->aSlot[iSlot];
14342 
14343   switch( pSlot->eType ){
14344     case SQLITE_NULL:
14345       /* no-op */
14346       break;
14347 
14348     case SQLITE_INTEGER:
14349       sqlite3_result_int64(pCtx, pSlot->iVal);
14350       break;
14351 
14352     case SQLITE_FLOAT:
14353       sqlite3_result_double(pCtx, pSlot->rVal);
14354       break;
14355 
14356     case SQLITE_BLOB:
14357       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
14358       break;
14359 
14360     case SQLITE_TEXT:
14361       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
14362       break;
14363   }
14364 
14365   pSlot->eType = sqlite3_value_type(argv[1]);
14366   switch( pSlot->eType ){
14367     case SQLITE_NULL:
14368       /* no-op */
14369       break;
14370 
14371     case SQLITE_INTEGER:
14372       pSlot->iVal = sqlite3_value_int64(argv[1]);
14373       break;
14374 
14375     case SQLITE_FLOAT:
14376       pSlot->rVal = sqlite3_value_double(argv[1]);
14377       break;
14378 
14379     case SQLITE_BLOB:
14380     case SQLITE_TEXT: {
14381       int nByte = sqlite3_value_bytes(argv[1]);
14382       const void *pData = 0;
14383       if( nByte>pSlot->nByte ){
14384         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
14385         if( zNew==0 ){
14386           sqlite3_result_error_nomem(pCtx);
14387           return;
14388         }
14389         pSlot->nByte = nByte*2;
14390         pSlot->z = zNew;
14391       }
14392       pSlot->n = nByte;
14393       if( pSlot->eType==SQLITE_BLOB ){
14394         pData = sqlite3_value_blob(argv[1]);
14395         if( pData ) memcpy(pSlot->z, pData, nByte);
14396       }else{
14397         pData = sqlite3_value_text(argv[1]);
14398         memcpy(pSlot->z, pData, nByte);
14399       }
14400       break;
14401     }
14402   }
14403 }
14404 
idxLargestIndex(sqlite3 * db,int * pnMax,char ** pzErr)14405 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
14406   int rc = SQLITE_OK;
14407   const char *zMax =
14408     "SELECT max(i.seqno) FROM "
14409     "  sqlite_schema AS s, "
14410     "  pragma_index_list(s.name) AS l, "
14411     "  pragma_index_info(l.name) AS i "
14412     "WHERE s.type = 'table'";
14413   sqlite3_stmt *pMax = 0;
14414 
14415   *pnMax = 0;
14416   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
14417   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
14418     *pnMax = sqlite3_column_int(pMax, 0) + 1;
14419   }
14420   idxFinalize(&rc, pMax);
14421 
14422   return rc;
14423 }
14424 
idxPopulateOneStat1(sqlite3expert * p,sqlite3_stmt * pIndexXInfo,sqlite3_stmt * pWriteStat,const char * zTab,const char * zIdx,char ** pzErr)14425 static int idxPopulateOneStat1(
14426   sqlite3expert *p,
14427   sqlite3_stmt *pIndexXInfo,
14428   sqlite3_stmt *pWriteStat,
14429   const char *zTab,
14430   const char *zIdx,
14431   char **pzErr
14432 ){
14433   char *zCols = 0;
14434   char *zOrder = 0;
14435   char *zQuery = 0;
14436   int nCol = 0;
14437   int i;
14438   sqlite3_stmt *pQuery = 0;
14439   int *aStat = 0;
14440   int rc = SQLITE_OK;
14441 
14442   assert( p->iSample>0 );
14443 
14444   /* Formulate the query text */
14445   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
14446   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
14447     const char *zComma = zCols==0 ? "" : ", ";
14448     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
14449     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
14450     if( zName==0 ){
14451       /* This index contains an expression. Ignore it. */
14452       sqlite3_free(zCols);
14453       sqlite3_free(zOrder);
14454       return sqlite3_reset(pIndexXInfo);
14455     }
14456     zCols = idxAppendText(&rc, zCols,
14457         "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s",
14458         zComma, zName, nCol, zName, zColl
14459     );
14460     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
14461   }
14462   sqlite3_reset(pIndexXInfo);
14463   if( rc==SQLITE_OK ){
14464     if( p->iSample==100 ){
14465       zQuery = sqlite3_mprintf(
14466           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
14467       );
14468     }else{
14469       zQuery = sqlite3_mprintf(
14470           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
14471       );
14472     }
14473   }
14474   sqlite3_free(zCols);
14475   sqlite3_free(zOrder);
14476 
14477   /* Formulate the query text */
14478   if( rc==SQLITE_OK ){
14479     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
14480     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
14481   }
14482   sqlite3_free(zQuery);
14483 
14484   if( rc==SQLITE_OK ){
14485     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
14486   }
14487   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
14488     IdxHashEntry *pEntry;
14489     char *zStat = 0;
14490     for(i=0; i<=nCol; i++) aStat[i] = 1;
14491     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
14492       aStat[0]++;
14493       for(i=0; i<nCol; i++){
14494         if( sqlite3_column_int(pQuery, i)==0 ) break;
14495       }
14496       for(/*no-op*/; i<nCol; i++){
14497         aStat[i+1]++;
14498       }
14499     }
14500 
14501     if( rc==SQLITE_OK ){
14502       int s0 = aStat[0];
14503       zStat = sqlite3_mprintf("%d", s0);
14504       if( zStat==0 ) rc = SQLITE_NOMEM;
14505       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
14506         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
14507       }
14508     }
14509 
14510     if( rc==SQLITE_OK ){
14511       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
14512       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
14513       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
14514       sqlite3_step(pWriteStat);
14515       rc = sqlite3_reset(pWriteStat);
14516     }
14517 
14518     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
14519     if( pEntry ){
14520       assert( pEntry->zVal2==0 );
14521       pEntry->zVal2 = zStat;
14522     }else{
14523       sqlite3_free(zStat);
14524     }
14525   }
14526   sqlite3_free(aStat);
14527   idxFinalize(&rc, pQuery);
14528 
14529   return rc;
14530 }
14531 
idxBuildSampleTable(sqlite3expert * p,const char * zTab)14532 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
14533   int rc;
14534   char *zSql;
14535 
14536   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
14537   if( rc!=SQLITE_OK ) return rc;
14538 
14539   zSql = sqlite3_mprintf(
14540       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
14541   );
14542   if( zSql==0 ) return SQLITE_NOMEM;
14543   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
14544   sqlite3_free(zSql);
14545 
14546   return rc;
14547 }
14548 
14549 /*
14550 ** This function is called as part of sqlite3_expert_analyze(). Candidate
14551 ** indexes have already been created in database sqlite3expert.dbm, this
14552 ** function populates sqlite_stat1 table in the same database.
14553 **
14554 ** The stat1 data is generated by querying the
14555 */
idxPopulateStat1(sqlite3expert * p,char ** pzErr)14556 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
14557   int rc = SQLITE_OK;
14558   int nMax =0;
14559   struct IdxRemCtx *pCtx = 0;
14560   struct IdxSampleCtx samplectx;
14561   int i;
14562   i64 iPrev = -100000;
14563   sqlite3_stmt *pAllIndex = 0;
14564   sqlite3_stmt *pIndexXInfo = 0;
14565   sqlite3_stmt *pWrite = 0;
14566 
14567   const char *zAllIndex =
14568     "SELECT s.rowid, s.name, l.name FROM "
14569     "  sqlite_schema AS s, "
14570     "  pragma_index_list(s.name) AS l "
14571     "WHERE s.type = 'table'";
14572   const char *zIndexXInfo =
14573     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
14574   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
14575 
14576   /* If iSample==0, no sqlite_stat1 data is required. */
14577   if( p->iSample==0 ) return SQLITE_OK;
14578 
14579   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
14580   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
14581 
14582   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
14583 
14584   if( rc==SQLITE_OK ){
14585     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
14586     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
14587   }
14588 
14589   if( rc==SQLITE_OK ){
14590     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
14591     rc = sqlite3_create_function(dbrem, "sqlite_expert_rem",
14592         2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
14593     );
14594   }
14595   if( rc==SQLITE_OK ){
14596     rc = sqlite3_create_function(p->db, "sqlite_expert_sample",
14597         0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
14598     );
14599   }
14600 
14601   if( rc==SQLITE_OK ){
14602     pCtx->nSlot = nMax+1;
14603     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
14604   }
14605   if( rc==SQLITE_OK ){
14606     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
14607   }
14608   if( rc==SQLITE_OK ){
14609     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
14610   }
14611 
14612   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
14613     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
14614     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
14615     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
14616     if( zTab==0 || zIdx==0 ) continue;
14617     if( p->iSample<100 && iPrev!=iRowid ){
14618       samplectx.target = (double)p->iSample / 100.0;
14619       samplectx.iTarget = p->iSample;
14620       samplectx.nRow = 0.0;
14621       samplectx.nRet = 0.0;
14622       rc = idxBuildSampleTable(p, zTab);
14623       if( rc!=SQLITE_OK ) break;
14624     }
14625     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
14626     iPrev = iRowid;
14627   }
14628   if( rc==SQLITE_OK && p->iSample<100 ){
14629     rc = sqlite3_exec(p->dbv,
14630         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
14631     );
14632   }
14633 
14634   idxFinalize(&rc, pAllIndex);
14635   idxFinalize(&rc, pIndexXInfo);
14636   idxFinalize(&rc, pWrite);
14637 
14638   if( pCtx ){
14639     for(i=0; i<pCtx->nSlot; i++){
14640       sqlite3_free(pCtx->aSlot[i].z);
14641     }
14642     sqlite3_free(pCtx);
14643   }
14644 
14645   if( rc==SQLITE_OK ){
14646     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
14647   }
14648 
14649   sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0);
14650   sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0);
14651 
14652   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
14653   return rc;
14654 }
14655 
14656 /*
14657 ** Define and possibly pretend to use a useless collation sequence.
14658 ** This pretense allows expert to accept SQL using custom collations.
14659 */
dummyCompare(void * up1,int up2,const void * up3,int up4,const void * up5)14660 int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
14661   (void)up1;
14662   (void)up2;
14663   (void)up3;
14664   (void)up4;
14665   (void)up5;
14666   assert(0); /* VDBE should never be run. */
14667   return 0;
14668 }
14669 /* And a callback to register above upon actual need */
useDummyCS(void * up1,sqlite3 * db,int etr,const char * zName)14670 void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
14671   (void)up1;
14672   sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
14673 }
14674 
14675 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
14676   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
14677 /*
14678 ** dummy functions for no-op implementation of UDFs during expert's work
14679 */
dummyUDF(sqlite3_context * up1,int up2,sqlite3_value ** up3)14680 void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
14681   (void)up1;
14682   (void)up2;
14683   (void)up3;
14684   assert(0); /* VDBE should never be run. */
14685 }
dummyUDFvalue(sqlite3_context * up1)14686 void dummyUDFvalue(sqlite3_context *up1){
14687   (void)up1;
14688   assert(0); /* VDBE should never be run. */
14689 }
14690 
14691 /*
14692 ** Register UDFs from user database with another.
14693 */
registerUDFs(sqlite3 * dbSrc,sqlite3 * dbDst)14694 int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
14695   sqlite3_stmt *pStmt;
14696   int rc = sqlite3_prepare_v2(dbSrc,
14697             "SELECT name,type,enc,narg,flags "
14698             "FROM pragma_function_list() "
14699             "WHERE builtin==0", -1, &pStmt, 0);
14700   if( rc==SQLITE_OK ){
14701     while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
14702       int nargs = sqlite3_column_int(pStmt,3);
14703       int flags = sqlite3_column_int(pStmt,4);
14704       const char *name = (char*)sqlite3_column_text(pStmt,0);
14705       const char *type = (char*)sqlite3_column_text(pStmt,1);
14706       const char *enc = (char*)sqlite3_column_text(pStmt,2);
14707       if( name==0 || type==0 || enc==0 ){
14708         /* no-op.  Only happens on OOM */
14709       }else{
14710         int ienc = SQLITE_UTF8;
14711         int rcf = SQLITE_ERROR;
14712         if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
14713         else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
14714         ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
14715         if( strcmp(type,"w")==0 ){
14716           rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
14717                                                dummyUDF,dummyUDFvalue,0,0,0);
14718         }else if( strcmp(type,"a")==0 ){
14719           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
14720                                         0,dummyUDF,dummyUDFvalue);
14721         }else if( strcmp(type,"s")==0 ){
14722           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
14723                                         dummyUDF,0,0);
14724         }
14725         if( rcf!=SQLITE_OK ){
14726           rc = rcf;
14727           break;
14728         }
14729       }
14730     }
14731     sqlite3_finalize(pStmt);
14732     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
14733   }
14734   return rc;
14735 }
14736 #endif
14737 
14738 /*
14739 ** Allocate a new sqlite3expert object.
14740 */
sqlite3_expert_new(sqlite3 * db,char ** pzErrmsg)14741 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
14742   int rc = SQLITE_OK;
14743   sqlite3expert *pNew;
14744 
14745   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
14746 
14747   /* Open two in-memory databases to work with. The "vtab database" (dbv)
14748   ** will contain a virtual table corresponding to each real table in
14749   ** the user database schema, and a copy of each view. It is used to
14750   ** collect information regarding the WHERE, ORDER BY and other clauses
14751   ** of the user's query.
14752   */
14753   if( rc==SQLITE_OK ){
14754     pNew->db = db;
14755     pNew->iSample = 100;
14756     rc = sqlite3_open(":memory:", &pNew->dbv);
14757   }
14758   if( rc==SQLITE_OK ){
14759     rc = sqlite3_open(":memory:", &pNew->dbm);
14760     if( rc==SQLITE_OK ){
14761       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
14762     }
14763   }
14764 
14765   /* Allow custom collations to be dealt with through prepare. */
14766   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
14767   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
14768 
14769 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
14770   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
14771   /* Register UDFs from database [db] with [dbm] and [dbv]. */
14772   if( rc==SQLITE_OK ){
14773     rc = registerUDFs(pNew->db, pNew->dbm);
14774   }
14775   if( rc==SQLITE_OK ){
14776     rc = registerUDFs(pNew->db, pNew->dbv);
14777   }
14778 #endif
14779 
14780   /* Copy the entire schema of database [db] into [dbm]. */
14781   if( rc==SQLITE_OK ){
14782     sqlite3_stmt *pSql = 0;
14783     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
14784         "SELECT sql, name, substr(sql,1,14)=='create virtual' COLLATE nocase"
14785         " FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' COLLATE nocase"
14786         " ORDER BY 3 DESC, rowid"
14787     );
14788     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
14789       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
14790       const char *zName = (const char*)sqlite3_column_text(pSql, 1);
14791       int bExists = 0;
14792       rc = expertDbContainsObject(pNew->dbm, zName, &bExists);
14793       if( rc==SQLITE_OK && zSql && bExists==0 ){
14794         rc = expertSchemaSql(pNew->dbm, zSql, pzErrmsg);
14795       }
14796     }
14797     idxFinalize(&rc, pSql);
14798   }
14799 
14800   /* Create the vtab schema */
14801   if( rc==SQLITE_OK ){
14802     rc = idxCreateVtabSchema(pNew, pzErrmsg);
14803   }
14804 
14805   /* Register the auth callback with dbv */
14806   if( rc==SQLITE_OK ){
14807     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
14808   }
14809 
14810   /* If an error has occurred, free the new object and return NULL. Otherwise,
14811   ** return the new sqlite3expert handle.  */
14812   if( rc!=SQLITE_OK ){
14813     sqlite3_expert_destroy(pNew);
14814     pNew = 0;
14815   }
14816   return pNew;
14817 }
14818 
14819 /*
14820 ** Configure an sqlite3expert object.
14821 */
sqlite3_expert_config(sqlite3expert * p,int op,...)14822 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
14823   int rc = SQLITE_OK;
14824   va_list ap;
14825   va_start(ap, op);
14826   switch( op ){
14827     case EXPERT_CONFIG_SAMPLE: {
14828       int iVal = va_arg(ap, int);
14829       if( iVal<0 ) iVal = 0;
14830       if( iVal>100 ) iVal = 100;
14831       p->iSample = iVal;
14832       break;
14833     }
14834     default:
14835       rc = SQLITE_NOTFOUND;
14836       break;
14837   }
14838 
14839   va_end(ap);
14840   return rc;
14841 }
14842 
14843 /*
14844 ** Add an SQL statement to the analysis.
14845 */
sqlite3_expert_sql(sqlite3expert * p,const char * zSql,char ** pzErr)14846 int sqlite3_expert_sql(
14847   sqlite3expert *p,               /* From sqlite3_expert_new() */
14848   const char *zSql,               /* SQL statement to add */
14849   char **pzErr                    /* OUT: Error message (if any) */
14850 ){
14851   IdxScan *pScanOrig = p->pScan;
14852   IdxStatement *pStmtOrig = p->pStatement;
14853   int rc = SQLITE_OK;
14854   const char *zStmt = zSql;
14855 
14856   if( p->bRun ) return SQLITE_MISUSE;
14857 
14858   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
14859     sqlite3_stmt *pStmt = 0;
14860     /* Ensure that the provided statement compiles against user's DB. */
14861     rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
14862     if( rc!=SQLITE_OK ) break;
14863     sqlite3_finalize(pStmt);
14864     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
14865     if( rc==SQLITE_OK ){
14866       if( pStmt ){
14867         IdxStatement *pNew;
14868         const char *z = sqlite3_sql(pStmt);
14869         int n = STRLEN(z);
14870         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
14871         if( rc==SQLITE_OK ){
14872           pNew->zSql = (char*)&pNew[1];
14873           memcpy(pNew->zSql, z, n+1);
14874           pNew->pNext = p->pStatement;
14875           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
14876           p->pStatement = pNew;
14877         }
14878         sqlite3_finalize(pStmt);
14879       }
14880     }else{
14881       idxDatabaseError(p->dbv, pzErr);
14882     }
14883   }
14884 
14885   if( rc!=SQLITE_OK ){
14886     idxScanFree(p->pScan, pScanOrig);
14887     idxStatementFree(p->pStatement, pStmtOrig);
14888     p->pScan = pScanOrig;
14889     p->pStatement = pStmtOrig;
14890   }
14891 
14892   return rc;
14893 }
14894 
sqlite3_expert_analyze(sqlite3expert * p,char ** pzErr)14895 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
14896   int rc;
14897   IdxHashEntry *pEntry;
14898 
14899   /* Do trigger processing to collect any extra IdxScan structures */
14900   rc = idxProcessTriggers(p, pzErr);
14901 
14902   /* Create candidate indexes within the in-memory database file */
14903   if( rc==SQLITE_OK ){
14904     rc = idxCreateCandidates(p);
14905   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
14906     if( pzErr )
14907       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
14908     return rc;
14909   }
14910 
14911   /* Generate the stat1 data */
14912   if( rc==SQLITE_OK ){
14913     rc = idxPopulateStat1(p, pzErr);
14914   }
14915 
14916   /* Formulate the EXPERT_REPORT_CANDIDATES text */
14917   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
14918     p->zCandidates = idxAppendText(&rc, p->zCandidates,
14919         "%s;%s%s\n", pEntry->zVal,
14920         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
14921     );
14922   }
14923 
14924   /* Figure out which of the candidate indexes are preferred by the query
14925   ** planner and report the results to the user.  */
14926   if( rc==SQLITE_OK ){
14927     rc = idxFindIndexes(p, pzErr);
14928   }
14929 
14930   if( rc==SQLITE_OK ){
14931     p->bRun = 1;
14932   }
14933   return rc;
14934 }
14935 
14936 /*
14937 ** Return the total number of statements that have been added to this
14938 ** sqlite3expert using sqlite3_expert_sql().
14939 */
sqlite3_expert_count(sqlite3expert * p)14940 int sqlite3_expert_count(sqlite3expert *p){
14941   int nRet = 0;
14942   if( p->pStatement ) nRet = p->pStatement->iId+1;
14943   return nRet;
14944 }
14945 
14946 /*
14947 ** Return a component of the report.
14948 */
sqlite3_expert_report(sqlite3expert * p,int iStmt,int eReport)14949 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
14950   const char *zRet = 0;
14951   IdxStatement *pStmt;
14952 
14953   if( p->bRun==0 ) return 0;
14954   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
14955   switch( eReport ){
14956     case EXPERT_REPORT_SQL:
14957       if( pStmt ) zRet = pStmt->zSql;
14958       break;
14959     case EXPERT_REPORT_INDEXES:
14960       if( pStmt ) zRet = pStmt->zIdx;
14961       break;
14962     case EXPERT_REPORT_PLAN:
14963       if( pStmt ) zRet = pStmt->zEQP;
14964       break;
14965     case EXPERT_REPORT_CANDIDATES:
14966       zRet = p->zCandidates;
14967       break;
14968   }
14969   return zRet;
14970 }
14971 
14972 /*
14973 ** Free an sqlite3expert object.
14974 */
sqlite3_expert_destroy(sqlite3expert * p)14975 void sqlite3_expert_destroy(sqlite3expert *p){
14976   if( p ){
14977     sqlite3_close(p->dbm);
14978     sqlite3_close(p->dbv);
14979     idxScanFree(p->pScan, 0);
14980     idxStatementFree(p->pStatement, 0);
14981     idxTableFree(p->pTable);
14982     idxWriteFree(p->pWrite);
14983     idxHashClear(&p->hIdx);
14984     sqlite3_free(p->zCandidates);
14985     sqlite3_free(p);
14986   }
14987 }
14988 
14989 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
14990 
14991 /************************* End ../ext/expert/sqlite3expert.c ********************/
14992 /************************* Begin ../ext/intck/sqlite3intck.h ******************/
14993 /*
14994 ** 2024-02-08
14995 **
14996 ** The author disclaims copyright to this source code.  In place of
14997 ** a legal notice, here is a blessing:
14998 **
14999 **    May you do good and not evil.
15000 **    May you find forgiveness for yourself and forgive others.
15001 **    May you share freely, never taking more than you give.
15002 **
15003 *************************************************************************
15004 */
15005 
15006 /*
15007 ** Incremental Integrity-Check Extension
15008 ** -------------------------------------
15009 **
15010 ** This module contains code to check whether or not an SQLite database
15011 ** is well-formed or corrupt. This is the same task as performed by SQLite's
15012 ** built-in "PRAGMA integrity_check" command. This module differs from
15013 ** "PRAGMA integrity_check" in that:
15014 **
15015 **   +  It is less thorough - this module does not detect certain types
15016 **      of corruption that are detected by the PRAGMA command. However,
15017 **      it does detect all kinds of corruption that are likely to cause
15018 **      errors in SQLite applications.
15019 **
15020 **   +  It is slower. Sometimes up to three times slower.
15021 **
15022 **   +  It allows integrity-check operations to be split into multiple
15023 **      transactions, so that the database does not need to be read-locked
15024 **      for the duration of the integrity-check.
15025 **
15026 ** One way to use the API to run integrity-check on the "main" database
15027 ** of handle db is:
15028 **
15029 **   int rc = SQLITE_OK;
15030 **   sqlite3_intck *p = 0;
15031 **
15032 **   sqlite3_intck_open(db, "main", &p);
15033 **   while( SQLITE_OK==sqlite3_intck_step(p) ){
15034 **     const char *zMsg = sqlite3_intck_message(p);
15035 **     if( zMsg ) printf("corruption: %s\n", zMsg);
15036 **   }
15037 **   rc = sqlite3_intck_error(p, &zErr);
15038 **   if( rc!=SQLITE_OK ){
15039 **     printf("error occured (rc=%d), (errmsg=%s)\n", rc, zErr);
15040 **   }
15041 **   sqlite3_intck_close(p);
15042 **
15043 ** Usually, the sqlite3_intck object opens a read transaction within the
15044 ** first call to sqlite3_intck_step() and holds it open until the
15045 ** integrity-check is complete. However, if sqlite3_intck_unlock() is
15046 ** called, the read transaction is ended and a new read transaction opened
15047 ** by the subsequent call to sqlite3_intck_step().
15048 */
15049 
15050 #ifndef _SQLITE_INTCK_H
15051 #define _SQLITE_INTCK_H
15052 
15053 /* #include "sqlite3.h" */
15054 
15055 #ifdef __cplusplus
15056 extern "C" {
15057 #endif
15058 
15059 /*
15060 ** An ongoing incremental integrity-check operation is represented by an
15061 ** opaque pointer of the following type.
15062 */
15063 typedef struct sqlite3_intck sqlite3_intck;
15064 
15065 /*
15066 ** Open a new incremental integrity-check object. If successful, populate
15067 ** output variable (*ppOut) with the new object handle and return SQLITE_OK.
15068 ** Or, if an error occurs, set (*ppOut) to NULL and return an SQLite error
15069 ** code (e.g. SQLITE_NOMEM).
15070 **
15071 ** The integrity-check will be conducted on database zDb (which must be "main",
15072 ** "temp", or the name of an attached database) of database handle db. Once
15073 ** this function has been called successfully, the caller should not use
15074 ** database handle db until the integrity-check object has been destroyed
15075 ** using sqlite3_intck_close().
15076 */
15077 int sqlite3_intck_open(
15078   sqlite3 *db,                    /* Database handle */
15079   const char *zDb,                /* Database name ("main", "temp" etc.) */
15080   sqlite3_intck **ppOut           /* OUT: New sqlite3_intck handle */
15081 );
15082 
15083 /*
15084 ** Close and release all resources associated with a handle opened by an
15085 ** earlier call to sqlite3_intck_open(). The results of using an
15086 ** integrity-check handle after it has been passed to this function are
15087 ** undefined.
15088 */
15089 void sqlite3_intck_close(sqlite3_intck *pCk);
15090 
15091 /*
15092 ** Do the next step of the integrity-check operation specified by the handle
15093 ** passed as the only argument. This function returns SQLITE_DONE if the
15094 ** integrity-check operation is finished, or an SQLite error code if
15095 ** an error occurs, or SQLITE_OK if no error occurs but the integrity-check
15096 ** is not finished. It is not considered an error if database corruption
15097 ** is encountered.
15098 **
15099 ** Following a successful call to sqlite3_intck_step() (one that returns
15100 ** SQLITE_OK), sqlite3_intck_message() returns a non-NULL value if
15101 ** corruption was detected in the db.
15102 **
15103 ** If an error occurs and a value other than SQLITE_OK or SQLITE_DONE is
15104 ** returned, then the integrity-check handle is placed in an error state.
15105 ** In this state all subsequent calls to sqlite3_intck_step() or
15106 ** sqlite3_intck_unlock() will immediately return the same error. The
15107 ** sqlite3_intck_error() method may be used to obtain an English language
15108 ** error message in this case.
15109 */
15110 int sqlite3_intck_step(sqlite3_intck *pCk);
15111 
15112 /*
15113 ** If the previous call to sqlite3_intck_step() encountered corruption
15114 ** within the database, then this function returns a pointer to a buffer
15115 ** containing a nul-terminated string describing the corruption in
15116 ** English. If the previous call to sqlite3_intck_step() did not encounter
15117 ** corruption, or if there was no previous call, this function returns
15118 ** NULL.
15119 */
15120 const char *sqlite3_intck_message(sqlite3_intck *pCk);
15121 
15122 /*
15123 ** Close any read-transaction opened by an earlier call to
15124 ** sqlite3_intck_step(). Any subsequent call to sqlite3_intck_step() will
15125 ** open a new transaction. Return SQLITE_OK if successful, or an SQLite error
15126 ** code otherwise.
15127 **
15128 ** If an error occurs, then the integrity-check handle is placed in an error
15129 ** state. In this state all subsequent calls to sqlite3_intck_step() or
15130 ** sqlite3_intck_unlock() will immediately return the same error. The
15131 ** sqlite3_intck_error() method may be used to obtain an English language
15132 ** error message in this case.
15133 */
15134 int sqlite3_intck_unlock(sqlite3_intck *pCk);
15135 
15136 /*
15137 ** If an error has occurred in an earlier call to sqlite3_intck_step()
15138 ** or sqlite3_intck_unlock(), then this method returns the associated
15139 ** SQLite error code. Additionally, if pzErr is not NULL, then (*pzErr)
15140 ** may be set to point to a nul-terminated string containing an English
15141 ** language error message. Or, if no error message is available, to
15142 ** NULL.
15143 **
15144 ** If no error has occurred within sqlite3_intck_step() or
15145 ** sqlite_intck_unlock() calls on the handle passed as the first argument,
15146 ** then SQLITE_OK is returned and (*pzErr) set to NULL.
15147 */
15148 int sqlite3_intck_error(sqlite3_intck *pCk, const char **pzErr);
15149 
15150 /*
15151 ** This API is used for testing only. It returns the full-text of an SQL
15152 ** statement used to test object zObj, which may be a table or index.
15153 ** The returned buffer is valid until the next call to either this function
15154 ** or sqlite3_intck_close() on the same sqlite3_intck handle.
15155 */
15156 const char *sqlite3_intck_test_sql(sqlite3_intck *pCk, const char *zObj);
15157 
15158 
15159 #ifdef __cplusplus
15160 }  /* end of the 'extern "C"' block */
15161 #endif
15162 
15163 #endif /* ifndef _SQLITE_INTCK_H */
15164 
15165 /************************* End ../ext/intck/sqlite3intck.h ********************/
15166 /************************* Begin ../ext/intck/sqlite3intck.c ******************/
15167 /*
15168 ** 2024-02-08
15169 **
15170 ** The author disclaims copyright to this source code.  In place of
15171 ** a legal notice, here is a blessing:
15172 **
15173 **    May you do good and not evil.
15174 **    May you find forgiveness for yourself and forgive others.
15175 **    May you share freely, never taking more than you give.
15176 **
15177 *************************************************************************
15178 */
15179 
15180 /* #include "sqlite3intck.h" */
15181 #include <string.h>
15182 #include <assert.h>
15183 
15184 #include <stdio.h>
15185 #include <stdlib.h>
15186 
15187 /*
15188 ** nKeyVal:
15189 **   The number of values that make up the 'key' for the current pCheck
15190 **   statement.
15191 **
15192 ** rc:
15193 **   Error code returned by most recent sqlite3_intck_step() or
15194 **   sqlite3_intck_unlock() call. This is set to SQLITE_DONE when
15195 **   the integrity-check operation is finished.
15196 **
15197 ** zErr:
15198 **   If the object has entered the error state, this is the error message.
15199 **   Is freed using sqlite3_free() when the object is deleted.
15200 **
15201 ** zTestSql:
15202 **   The value returned by the most recent call to sqlite3_intck_testsql().
15203 **   Each call to testsql() frees the previous zTestSql value (using
15204 **   sqlite3_free()) and replaces it with the new value it will return.
15205 */
15206 struct sqlite3_intck {
15207   sqlite3 *db;
15208   const char *zDb;                /* Copy of zDb parameter to _open() */
15209   char *zObj;                     /* Current object. Or NULL. */
15210 
15211   sqlite3_stmt *pCheck;           /* Current check statement */
15212   char *zKey;
15213   int nKeyVal;
15214 
15215   char *zMessage;
15216   int bCorruptSchema;
15217 
15218   int rc;                         /* Error code */
15219   char *zErr;                     /* Error message */
15220   char *zTestSql;                 /* Returned by sqlite3_intck_test_sql() */
15221 };
15222 
15223 
15224 /*
15225 ** Some error has occurred while using database p->db. Save the error message
15226 ** and error code currently held by the database handle in p->rc and p->zErr.
15227 */
intckSaveErrmsg(sqlite3_intck * p)15228 static void intckSaveErrmsg(sqlite3_intck *p){
15229   p->rc = sqlite3_errcode(p->db);
15230   sqlite3_free(p->zErr);
15231   p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
15232 }
15233 
15234 /*
15235 ** If the handle passed as the first argument is already in the error state,
15236 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
15237 ** error occurs within this function, it leaves an error in said handle.
15238 **
15239 ** Otherwise, this function attempts to prepare SQL statement zSql and
15240 ** return the resulting statement handle to the user.
15241 */
intckPrepare(sqlite3_intck * p,const char * zSql)15242 static sqlite3_stmt *intckPrepare(sqlite3_intck *p, const char *zSql){
15243   sqlite3_stmt *pRet = 0;
15244   if( p->rc==SQLITE_OK ){
15245     p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0);
15246     if( p->rc!=SQLITE_OK ){
15247       intckSaveErrmsg(p);
15248       assert( pRet==0 );
15249     }
15250   }
15251   return pRet;
15252 }
15253 
15254 /*
15255 ** If the handle passed as the first argument is already in the error state,
15256 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
15257 ** error occurs within this function, it leaves an error in said handle.
15258 **
15259 ** Otherwise, this function treats argument zFmt as a printf() style format
15260 ** string. It formats it according to the trailing arguments and then
15261 ** attempts to prepare the results and return the resulting prepared
15262 ** statement.
15263 */
intckPrepareFmt(sqlite3_intck * p,const char * zFmt,...)15264 static sqlite3_stmt *intckPrepareFmt(sqlite3_intck *p, const char *zFmt, ...){
15265   sqlite3_stmt *pRet = 0;
15266   va_list ap;
15267   char *zSql = 0;
15268   va_start(ap, zFmt);
15269   zSql = sqlite3_vmprintf(zFmt, ap);
15270   if( p->rc==SQLITE_OK && zSql==0 ){
15271     p->rc = SQLITE_NOMEM;
15272   }
15273   pRet = intckPrepare(p, zSql);
15274   sqlite3_free(zSql);
15275   va_end(ap);
15276   return pRet;
15277 }
15278 
15279 /*
15280 ** Finalize SQL statement pStmt. If an error occurs and the handle passed
15281 ** as the first argument does not already contain an error, store the
15282 ** error in the handle.
15283 */
intckFinalize(sqlite3_intck * p,sqlite3_stmt * pStmt)15284 static void intckFinalize(sqlite3_intck *p, sqlite3_stmt *pStmt){
15285   int rc = sqlite3_finalize(pStmt);
15286   if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
15287     intckSaveErrmsg(p);
15288   }
15289 }
15290 
15291 /*
15292 ** If there is already an error in handle p, return it. Otherwise, call
15293 ** sqlite3_step() on the statement handle and return that value.
15294 */
intckStep(sqlite3_intck * p,sqlite3_stmt * pStmt)15295 static int intckStep(sqlite3_intck *p, sqlite3_stmt *pStmt){
15296   if( p->rc ) return p->rc;
15297   return sqlite3_step(pStmt);
15298 }
15299 
15300 /*
15301 ** Execute SQL statement zSql. There is no way to obtain any results
15302 ** returned by the statement. This function uses the sqlite3_intck error
15303 ** code convention.
15304 */
intckExec(sqlite3_intck * p,const char * zSql)15305 static void intckExec(sqlite3_intck *p, const char *zSql){
15306   sqlite3_stmt *pStmt = 0;
15307   pStmt = intckPrepare(p, zSql);
15308   intckStep(p, pStmt);
15309   intckFinalize(p, pStmt);
15310 }
15311 
15312 /*
15313 ** A wrapper around sqlite3_mprintf() that uses the sqlite3_intck error
15314 ** code convention.
15315 */
intckMprintf(sqlite3_intck * p,const char * zFmt,...)15316 static char *intckMprintf(sqlite3_intck *p, const char *zFmt, ...){
15317   va_list ap;
15318   char *zRet = 0;
15319   va_start(ap, zFmt);
15320   zRet = sqlite3_vmprintf(zFmt, ap);
15321   if( p->rc==SQLITE_OK ){
15322     if( zRet==0 ){
15323       p->rc = SQLITE_NOMEM;
15324     }
15325   }else{
15326     sqlite3_free(zRet);
15327     zRet = 0;
15328   }
15329   return zRet;
15330 }
15331 
15332 /*
15333 ** This is used by sqlite3_intck_unlock() to save the vector key value
15334 ** required to restart the current pCheck query as a nul-terminated string
15335 ** in p->zKey.
15336 */
intckSaveKey(sqlite3_intck * p)15337 static void intckSaveKey(sqlite3_intck *p){
15338   int ii;
15339   char *zSql = 0;
15340   sqlite3_stmt *pStmt = 0;
15341   sqlite3_stmt *pXinfo = 0;
15342   const char *zDir = 0;
15343 
15344   assert( p->pCheck );
15345   assert( p->zKey==0 );
15346 
15347   pXinfo = intckPrepareFmt(p,
15348       "SELECT group_concat(desc, '') FROM %Q.sqlite_schema s, "
15349       "pragma_index_xinfo(%Q, %Q) "
15350       "WHERE s.type='index' AND s.name=%Q",
15351       p->zDb, p->zObj, p->zDb, p->zObj
15352   );
15353   if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){
15354     zDir = (const char*)sqlite3_column_text(pXinfo, 0);
15355   }
15356 
15357   if( zDir==0 ){
15358     /* Object is a table, not an index. This is the easy case,as there are
15359     ** no DESC columns or NULL values in a primary key.  */
15360     const char *zSep = "SELECT '(' || ";
15361     for(ii=0; ii<p->nKeyVal; ii++){
15362       zSql = intckMprintf(p, "%z%squote(?)", zSql, zSep);
15363       zSep = " || ', ' || ";
15364     }
15365     zSql = intckMprintf(p, "%z || ')'", zSql);
15366   }else{
15367 
15368     /* Object is an index. */
15369     assert( p->nKeyVal>1 );
15370     for(ii=p->nKeyVal; ii>0; ii--){
15371       int bLastIsDesc = zDir[ii-1]=='1';
15372       int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL;
15373       const char *zLast = sqlite3_column_name(p->pCheck, ii);
15374       char *zLhs = 0;
15375       char *zRhs = 0;
15376       char *zWhere = 0;
15377 
15378       if( bLastIsNull ){
15379         if( bLastIsDesc ) continue;
15380         zWhere = intckMprintf(p, "'%s IS NOT NULL'", zLast);
15381       }else{
15382         const char *zOp = bLastIsDesc ? "<" : ">";
15383         zWhere = intckMprintf(p, "'%s %s ' || quote(?%d)", zLast, zOp, ii);
15384       }
15385 
15386       if( ii>1 ){
15387         const char *zLhsSep = "";
15388         const char *zRhsSep = "";
15389         int jj;
15390         for(jj=0; jj<ii-1; jj++){
15391           const char *zAlias = (const char*)sqlite3_column_name(p->pCheck,jj+1);
15392           zLhs = intckMprintf(p, "%z%s%s", zLhs, zLhsSep, zAlias);
15393           zRhs = intckMprintf(p, "%z%squote(?%d)", zRhs, zRhsSep, jj+1);
15394           zLhsSep = ",";
15395           zRhsSep = " || ',' || ";
15396         }
15397 
15398         zWhere = intckMprintf(p,
15399             "'(%z) IS (' || %z || ') AND ' || %z",
15400             zLhs, zRhs, zWhere);
15401       }
15402       zWhere = intckMprintf(p, "'WHERE ' || %z", zWhere);
15403 
15404       zSql = intckMprintf(p, "%z%s(quote( %z ) )",
15405           zSql,
15406           (zSql==0 ? "VALUES" : ",\n      "),
15407           zWhere
15408       );
15409     }
15410     zSql = intckMprintf(p,
15411         "WITH wc(q) AS (\n%z\n)"
15412         "SELECT 'VALUES' || group_concat('(' || q || ')', ',\n      ') FROM wc"
15413         , zSql
15414     );
15415   }
15416 
15417   pStmt = intckPrepare(p, zSql);
15418   if( p->rc==SQLITE_OK ){
15419     for(ii=0; ii<p->nKeyVal; ii++){
15420       sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1));
15421     }
15422     if( SQLITE_ROW==sqlite3_step(pStmt) ){
15423       p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
15424     }
15425     intckFinalize(p, pStmt);
15426   }
15427 
15428   sqlite3_free(zSql);
15429   intckFinalize(p, pXinfo);
15430 }
15431 
15432 /*
15433 ** Find the next database object (table or index) to check. If successful,
15434 ** set sqlite3_intck.zObj to point to a nul-terminated buffer containing
15435 ** the object's name before returning.
15436 */
intckFindObject(sqlite3_intck * p)15437 static void intckFindObject(sqlite3_intck *p){
15438   sqlite3_stmt *pStmt = 0;
15439   char *zPrev = p->zObj;
15440   p->zObj = 0;
15441 
15442   assert( p->rc==SQLITE_OK );
15443   assert( p->pCheck==0 );
15444 
15445   pStmt = intckPrepareFmt(p,
15446     "WITH tables(table_name) AS ("
15447     "  SELECT name"
15448     "  FROM %Q.sqlite_schema WHERE (type='table' OR type='index') AND rootpage"
15449     "  UNION ALL "
15450     "  SELECT 'sqlite_schema'"
15451     ")"
15452     "SELECT table_name FROM tables "
15453     "WHERE ?1 IS NULL OR table_name%s?1 "
15454     "ORDER BY 1"
15455     , p->zDb, (p->zKey ? ">=" : ">")
15456   );
15457 
15458   if( p->rc==SQLITE_OK ){
15459     sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT);
15460     if( sqlite3_step(pStmt)==SQLITE_ROW ){
15461       p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
15462     }
15463   }
15464   intckFinalize(p, pStmt);
15465 
15466   /* If this is a new object, ensure the previous key value is cleared. */
15467   if( sqlite3_stricmp(p->zObj, zPrev) ){
15468     sqlite3_free(p->zKey);
15469     p->zKey = 0;
15470   }
15471 
15472   sqlite3_free(zPrev);
15473 }
15474 
15475 /*
15476 ** Return the size in bytes of the first token in nul-terminated buffer z.
15477 ** For the purposes of this call, a token is either:
15478 **
15479 **   *  a quoted SQL string,
15480 *    *  a contiguous series of ascii alphabet characters, or
15481 *    *  any other single byte.
15482 */
intckGetToken(const char * z)15483 static int intckGetToken(const char *z){
15484   char c = z[0];
15485   int iRet = 1;
15486   if( c=='\'' || c=='"' || c=='`' ){
15487     while( 1 ){
15488       if( z[iRet]==c ){
15489         iRet++;
15490         if( z[iRet]!=c ) break;
15491       }
15492       iRet++;
15493     }
15494   }
15495   else if( c=='[' ){
15496     while( z[iRet++]!=']' && z[iRet] );
15497   }
15498   else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
15499     while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){
15500       iRet++;
15501     }
15502   }
15503 
15504   return iRet;
15505 }
15506 
15507 /*
15508 ** Return true if argument c is an ascii whitespace character.
15509 */
intckIsSpace(char c)15510 static int intckIsSpace(char c){
15511   return (c==' ' || c=='\t' || c=='\n' || c=='\r');
15512 }
15513 
15514 /*
15515 ** Argument z points to the text of a CREATE INDEX statement. This function
15516 ** identifies the part of the text that contains either the index WHERE
15517 ** clause (if iCol<0) or the iCol'th column of the index.
15518 **
15519 ** If (iCol<0), the identified fragment does not include the "WHERE" keyword,
15520 ** only the expression that follows it. If (iCol>=0) then the identified
15521 ** fragment does not include any trailing sort-order keywords - "ASC" or
15522 ** "DESC".
15523 **
15524 ** If the CREATE INDEX statement does not contain the requested field or
15525 ** clause, NULL is returned and (*pnByte) is set to 0. Otherwise, a pointer to
15526 ** the identified fragment is returned and output parameter (*pnByte) set
15527 ** to its size in bytes.
15528 */
intckParseCreateIndex(const char * z,int iCol,int * pnByte)15529 static const char *intckParseCreateIndex(const char *z, int iCol, int *pnByte){
15530   int iOff = 0;
15531   int iThisCol = 0;
15532   int iStart = 0;
15533   int nOpen = 0;
15534 
15535   const char *zRet = 0;
15536   int nRet = 0;
15537 
15538   int iEndOfCol = 0;
15539 
15540   /* Skip forward until the first "(" token */
15541   while( z[iOff]!='(' ){
15542     iOff += intckGetToken(&z[iOff]);
15543     if( z[iOff]=='\0' ) return 0;
15544   }
15545   assert( z[iOff]=='(' );
15546 
15547   nOpen = 1;
15548   iOff++;
15549   iStart = iOff;
15550   while( z[iOff] ){
15551     const char *zToken = &z[iOff];
15552     int nToken = 0;
15553 
15554     /* Check if this is the end of the current column - either a "," or ")"
15555     ** when nOpen==1.  */
15556     if( nOpen==1 ){
15557       if( z[iOff]==',' || z[iOff]==')' ){
15558         if( iCol==iThisCol ){
15559           int iEnd = iEndOfCol ? iEndOfCol : iOff;
15560           nRet = (iEnd - iStart);
15561           zRet = &z[iStart];
15562           break;
15563         }
15564         iStart = iOff+1;
15565         while( intckIsSpace(z[iStart]) ) iStart++;
15566         iThisCol++;
15567       }
15568       if( z[iOff]==')' ) break;
15569     }
15570     if( z[iOff]=='(' ) nOpen++;
15571     if( z[iOff]==')' ) nOpen--;
15572     nToken = intckGetToken(zToken);
15573 
15574     if( (nToken==3 && 0==sqlite3_strnicmp(zToken, "ASC", nToken))
15575      || (nToken==4 && 0==sqlite3_strnicmp(zToken, "DESC", nToken))
15576     ){
15577       iEndOfCol = iOff;
15578     }else if( 0==intckIsSpace(zToken[0]) ){
15579       iEndOfCol = 0;
15580     }
15581 
15582     iOff += nToken;
15583   }
15584 
15585   /* iStart is now the byte offset of 1 byte passed the final ')' in the
15586   ** CREATE INDEX statement. Try to find a WHERE clause to return.  */
15587   while( zRet==0 && z[iOff] ){
15588     int n = intckGetToken(&z[iOff]);
15589     if( n==5 && 0==sqlite3_strnicmp(&z[iOff], "where", 5) ){
15590       zRet = &z[iOff+5];
15591       nRet = (int)strlen(zRet);
15592     }
15593     iOff += n;
15594   }
15595 
15596   /* Trim any whitespace from the start and end of the returned string. */
15597   if( zRet ){
15598     while( intckIsSpace(zRet[0]) ){
15599       nRet--;
15600       zRet++;
15601     }
15602     while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--;
15603   }
15604 
15605   *pnByte = nRet;
15606   return zRet;
15607 }
15608 
15609 /*
15610 ** User-defined SQL function wrapper for intckParseCreateIndex():
15611 **
15612 **     SELECT parse_create_index(<sql>, <icol>);
15613 */
intckParseCreateIndexFunc(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)15614 static void intckParseCreateIndexFunc(
15615   sqlite3_context *pCtx,
15616   int nVal,
15617   sqlite3_value **apVal
15618 ){
15619   const char *zSql = (const char*)sqlite3_value_text(apVal[0]);
15620   int idx = sqlite3_value_int(apVal[1]);
15621   const char *zRes = 0;
15622   int nRes = 0;
15623 
15624   assert( nVal==2 );
15625   if( zSql ){
15626     zRes = intckParseCreateIndex(zSql, idx, &nRes);
15627   }
15628   sqlite3_result_text(pCtx, zRes, nRes, SQLITE_TRANSIENT);
15629 }
15630 
15631 /*
15632 ** Return true if sqlite3_intck.db has automatic indexes enabled, false
15633 ** otherwise.
15634 */
intckGetAutoIndex(sqlite3_intck * p)15635 static int intckGetAutoIndex(sqlite3_intck *p){
15636   int bRet = 0;
15637   sqlite3_stmt *pStmt = 0;
15638   pStmt = intckPrepare(p, "PRAGMA automatic_index");
15639   if( SQLITE_ROW==intckStep(p, pStmt) ){
15640     bRet = sqlite3_column_int(pStmt, 0);
15641   }
15642   intckFinalize(p, pStmt);
15643   return bRet;
15644 }
15645 
15646 /*
15647 ** Return true if zObj is an index, or false otherwise.
15648 */
intckIsIndex(sqlite3_intck * p,const char * zObj)15649 static int intckIsIndex(sqlite3_intck *p, const char *zObj){
15650   int bRet = 0;
15651   sqlite3_stmt *pStmt = 0;
15652   pStmt = intckPrepareFmt(p,
15653       "SELECT 1 FROM %Q.sqlite_schema WHERE name=%Q AND type='index'",
15654       p->zDb, zObj
15655   );
15656   if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15657     bRet = 1;
15658   }
15659   intckFinalize(p, pStmt);
15660   return bRet;
15661 }
15662 
15663 /*
15664 ** Return a pointer to a nul-terminated buffer containing the SQL statement
15665 ** used to check database object zObj (a table or index) for corruption.
15666 ** If parameter zPrev is not NULL, then it must be a string containing the
15667 ** vector key required to restart the check where it left off last time.
15668 ** If pnKeyVal is not NULL, then (*pnKeyVal) is set to the number of
15669 ** columns in the vector key value for the specified object.
15670 **
15671 ** This function uses the sqlite3_intck error code convention.
15672 */
intckCheckObjectSql(sqlite3_intck * p,const char * zObj,const char * zPrev,int * pnKeyVal)15673 static char *intckCheckObjectSql(
15674   sqlite3_intck *p,               /* Integrity check object */
15675   const char *zObj,               /* Object (table or index) to scan */
15676   const char *zPrev,              /* Restart key vector, if any */
15677   int *pnKeyVal                   /* OUT: Number of key-values for this scan */
15678 ){
15679   char *zRet = 0;
15680   sqlite3_stmt *pStmt = 0;
15681   int bAutoIndex = 0;
15682   int bIsIndex = 0;
15683 
15684   const char *zCommon =
15685       /* Relation without_rowid also contains just one row. Column "b" is
15686       ** set to true if the table being examined is a WITHOUT ROWID table,
15687       ** or false otherwise.  */
15688       ", without_rowid(b) AS ("
15689       "  SELECT EXISTS ("
15690       "    SELECT 1 FROM tabname, pragma_index_list(tab, db) AS l"
15691       "      WHERE origin='pk' "
15692       "      AND NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name=l.name)"
15693       "  )"
15694       ")"
15695       ""
15696       /* Table idx_cols contains 1 row for each column in each index on the
15697       ** table being checked. Columns are:
15698       **
15699       **   idx_name: Name of the index.
15700       **   idx_ispk: True if this index is the PK of a WITHOUT ROWID table.
15701       **   col_name: Name of indexed column, or NULL for index on expression.
15702       **   col_expr: Indexed expression, including COLLATE clause.
15703       **   col_alias: Alias used for column in 'intck_wrapper' table.
15704       */
15705       ", idx_cols(idx_name, idx_ispk, col_name, col_expr, col_alias) AS ("
15706       "  SELECT l.name, (l.origin=='pk' AND w.b), i.name, COALESCE(("
15707       "    SELECT parse_create_index(sql, i.seqno) FROM "
15708       "    sqlite_schema WHERE name = l.name"
15709       "  ), format('\"%w\"', i.name) || ' COLLATE ' || quote(i.coll)),"
15710       "  'c' || row_number() OVER ()"
15711       "  FROM "
15712       "      tabname t,"
15713       "      without_rowid w,"
15714       "      pragma_index_list(t.tab, t.db) l,"
15715       "      pragma_index_xinfo(l.name) i"
15716       "      WHERE i.key"
15717       "  UNION ALL"
15718       "  SELECT '', 1, '_rowid_', '_rowid_', 'r1' FROM without_rowid WHERE b=0"
15719       ")"
15720       ""
15721       ""
15722       /*
15723       ** For a PK declared as "PRIMARY KEY(a, b) ... WITHOUT ROWID", where
15724       ** the intck_wrapper aliases of "a" and "b" are "c1" and "c2":
15725       **
15726       **   o_pk:   "o.c1, o.c2"
15727       **   i_pk:   "i.'a', i.'b'"
15728       **   ...
15729       **   n_pk:   2
15730       */
15731       ", tabpk(db, tab, idx, o_pk, i_pk, q_pk, eq_pk, ps_pk, pk_pk, n_pk) AS ("
15732       "    WITH pkfields(f, a) AS ("
15733       "      SELECT i.col_name, i.col_alias FROM idx_cols i WHERE i.idx_ispk"
15734       "    )"
15735       "    SELECT t.db, t.tab, t.idx, "
15736       "           group_concat(a, ', '), "
15737       "           group_concat('i.'||quote(f), ', '), "
15738       "           group_concat('quote(o.'||a||')', ' || '','' || '),  "
15739       "           format('(%s)==(%s)',"
15740       "               group_concat('o.'||a, ', '), "
15741       "               group_concat(format('\"%w\"', f), ', ')"
15742       "           ),"
15743       "           group_concat('%s', ','),"
15744       "           group_concat('quote('||a||')', ', '),  "
15745       "           count(*)"
15746       "    FROM tabname t, pkfields"
15747       ")"
15748       ""
15749       ", idx(name, match_expr, partial, partial_alias, idx_ps, idx_idx) AS ("
15750       "  SELECT idx_name,"
15751       "    format('(%s,%s) IS (%s,%s)', "
15752       "           group_concat(i.col_expr, ', '), i_pk,"
15753       "           group_concat('o.'||i.col_alias, ', '), o_pk"
15754       "    ), "
15755       "    parse_create_index("
15756       "        (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1"
15757       "    ),"
15758       "    'cond' || row_number() OVER ()"
15759       "    , group_concat('%s', ',')"
15760       "    , group_concat('quote('||i.col_alias||')', ', ')"
15761       "  FROM tabpk t, "
15762       "       without_rowid w,"
15763       "       idx_cols i"
15764       "  WHERE i.idx_ispk==0 "
15765       "  GROUP BY idx_name"
15766       ")"
15767       ""
15768       ", wrapper_with(s) AS ("
15769       "  SELECT 'intck_wrapper AS (\n  SELECT\n    ' || ("
15770       "      WITH f(a, b) AS ("
15771       "        SELECT col_expr, col_alias FROM idx_cols"
15772       "          UNION ALL "
15773       "        SELECT partial, partial_alias FROM idx WHERE partial IS NOT NULL"
15774       "      )"
15775       "      SELECT group_concat(format('%s AS %s', a, b), ',\n    ') FROM f"
15776       "    )"
15777       "    || format('\n  FROM %Q.%Q ', t.db, t.tab)"
15778            /* If the object being checked is a table, append "NOT INDEXED".
15779            ** Otherwise, append "INDEXED BY <index>", and then, if the index
15780            ** is a partial index " WHERE <condition>".  */
15781       "    || CASE WHEN t.idx IS NULL THEN "
15782       "        'NOT INDEXED'"
15783       "       ELSE"
15784       "        format('INDEXED BY %Q%s', t.idx, ' WHERE '||i.partial)"
15785       "       END"
15786       "    || '\n)'"
15787       "    FROM tabname t LEFT JOIN idx i ON (i.name=t.idx)"
15788       ")"
15789       ""
15790   ;
15791 
15792   bAutoIndex = intckGetAutoIndex(p);
15793   if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 0");
15794 
15795   bIsIndex = intckIsIndex(p, zObj);
15796   if( bIsIndex ){
15797     pStmt = intckPrepareFmt(p,
15798       /* Table idxname contains a single row. The first column, "db", contains
15799       ** the name of the db containing the table (e.g. "main") and the second,
15800       ** "tab", the name of the table itself.  */
15801       "WITH tabname(db, tab, idx) AS ("
15802       "  SELECT %Q, (SELECT tbl_name FROM %Q.sqlite_schema WHERE name=%Q), %Q "
15803       ")"
15804       ""
15805       ", whereclause(w_c) AS (%s)"
15806       ""
15807       "%s" /* zCommon */
15808       ""
15809       ", case_statement(c) AS ("
15810       "  SELECT "
15811       "    'CASE WHEN (' || group_concat(col_alias, ', ') || ', 1) IS (\n' "
15812       "    || '      SELECT ' || group_concat(col_expr, ', ') || ', 1 FROM '"
15813       "    || format('%%Q.%%Q NOT INDEXED WHERE %%s\n', t.db, t.tab, p.eq_pk)"
15814       "    || '    )\n  THEN NULL\n    '"
15815       "    || 'ELSE format(''surplus entry ('"
15816       "    ||   group_concat('%%s', ',') || ',' || p.ps_pk"
15817       "    || ') in index ' || t.idx || ''', ' "
15818       "    ||   group_concat('quote('||i.col_alias||')', ', ') || ', ' || p.pk_pk"
15819       "    || ')'"
15820       "    || '\n  END AS error_message'"
15821       "  FROM tabname t, tabpk p, idx_cols i WHERE i.idx_name=t.idx"
15822       ")"
15823       ""
15824       ", thiskey(k, n) AS ("
15825       "    SELECT group_concat(i.col_alias, ', ') || ', ' || p.o_pk, "
15826       "           count(*) + p.n_pk "
15827       "    FROM tabpk p, idx_cols i WHERE i.idx_name=p.idx"
15828       ")"
15829       ""
15830       ", main_select(m, n) AS ("
15831       "  SELECT format("
15832       "      'WITH %%s\n' ||"
15833       "      ', idx_checker AS (\n' ||"
15834       "      '  SELECT %%s,\n' ||"
15835       "      '  %%s\n' || "
15836       "      '  FROM intck_wrapper AS o\n' ||"
15837       "      ')\n',"
15838       "      ww.s, c, t.k"
15839       "  ), t.n"
15840       "  FROM case_statement, wrapper_with ww, thiskey t"
15841       ")"
15842 
15843       "SELECT m || "
15844       "    group_concat('SELECT * FROM idx_checker ' || w_c, ' UNION ALL '), n"
15845       " FROM "
15846       "main_select, whereclause "
15847       , p->zDb, p->zDb, zObj, zObj
15848       , zPrev ? zPrev : "VALUES('')", zCommon
15849       );
15850   }else{
15851     pStmt = intckPrepareFmt(p,
15852       /* Table tabname contains a single row. The first column, "db", contains
15853       ** the name of the db containing the table (e.g. "main") and the second,
15854       ** "tab", the name of the table itself.  */
15855       "WITH tabname(db, tab, idx, prev) AS (SELECT %Q, %Q, NULL, %Q)"
15856       ""
15857       "%s" /* zCommon */
15858 
15859       /* expr(e) contains one row for each index on table zObj. Value e
15860       ** is set to an expression that evaluates to NULL if the required
15861       ** entry is present in the index, or an error message otherwise.  */
15862       ", expr(e, p) AS ("
15863       "  SELECT format('CASE WHEN EXISTS \n"
15864       "    (SELECT 1 FROM %%Q.%%Q AS i INDEXED BY %%Q WHERE %%s%%s)\n"
15865       "    THEN NULL\n"
15866       "    ELSE format(''entry (%%s,%%s) missing from index %%s'', %%s, %%s)\n"
15867       "  END\n'"
15868       "    , t.db, t.tab, i.name, i.match_expr, ' AND (' || partial || ')',"
15869       "      i.idx_ps, t.ps_pk, i.name, i.idx_idx, t.pk_pk),"
15870       "    CASE WHEN partial IS NULL THEN NULL ELSE i.partial_alias END"
15871       "  FROM tabpk t, idx i"
15872       ")"
15873 
15874       ", numbered(ii, cond, e) AS ("
15875       "  SELECT 0, 'n.ii=0', 'NULL'"
15876       "    UNION ALL "
15877       "  SELECT row_number() OVER (),"
15878       "      '(n.ii='||row_number() OVER ()||COALESCE(' AND '||p||')', ')'), e"
15879       "  FROM expr"
15880       ")"
15881 
15882       ", counter_with(w) AS ("
15883       "    SELECT 'WITH intck_counter(ii) AS (\n  ' || "
15884       "       group_concat('SELECT '||ii, ' UNION ALL\n  ') "
15885       "    || '\n)' FROM numbered"
15886       ")"
15887       ""
15888       ", case_statement(c) AS ("
15889       "    SELECT 'CASE ' || "
15890       "    group_concat(format('\n  WHEN %%s THEN (%%s)', cond, e), '') ||"
15891       "    '\nEND AS error_message'"
15892       "    FROM numbered"
15893       ")"
15894       ""
15895 
15896       /* This table contains a single row consisting of a single value -
15897       ** the text of an SQL expression that may be used by the main SQL
15898       ** statement to output an SQL literal that can be used to resume
15899       ** the scan if it is suspended. e.g. for a rowid table, an expression
15900       ** like:
15901       **
15902       **     format('(%d,%d)', _rowid_, n.ii)
15903       */
15904       ", thiskey(k, n) AS ("
15905       "    SELECT o_pk || ', ii', n_pk+1 FROM tabpk"
15906       ")"
15907       ""
15908       ", whereclause(w_c) AS ("
15909       "    SELECT CASE WHEN prev!='' THEN "
15910       "    '\nWHERE (' || o_pk ||', n.ii) > ' || prev"
15911       "    ELSE ''"
15912       "    END"
15913       "    FROM tabpk, tabname"
15914       ")"
15915       ""
15916       ", main_select(m, n) AS ("
15917       "  SELECT format("
15918       "      '%%s, %%s\nSELECT %%s,\n%%s\nFROM intck_wrapper AS o"
15919                ", intck_counter AS n%%s\nORDER BY %%s', "
15920       "      w, ww.s, c, thiskey.k, whereclause.w_c, t.o_pk"
15921       "  ), thiskey.n"
15922       "  FROM case_statement, tabpk t, counter_with, "
15923       "       wrapper_with ww, thiskey, whereclause"
15924       ")"
15925 
15926       "SELECT m, n FROM main_select",
15927       p->zDb, zObj, zPrev, zCommon
15928     );
15929   }
15930 
15931   while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15932     zRet = intckMprintf(p, "%s", (const char*)sqlite3_column_text(pStmt, 0));
15933     if( pnKeyVal ){
15934       *pnKeyVal = sqlite3_column_int(pStmt, 1);
15935     }
15936   }
15937   intckFinalize(p, pStmt);
15938 
15939   if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1");
15940   return zRet;
15941 }
15942 
15943 /*
15944 ** Open a new integrity-check object.
15945 */
sqlite3_intck_open(sqlite3 * db,const char * zDbArg,sqlite3_intck ** ppOut)15946 int sqlite3_intck_open(
15947   sqlite3 *db,                    /* Database handle to operate on */
15948   const char *zDbArg,             /* "main", "temp" etc. */
15949   sqlite3_intck **ppOut           /* OUT: New integrity-check handle */
15950 ){
15951   sqlite3_intck *pNew = 0;
15952   int rc = SQLITE_OK;
15953   const char *zDb = zDbArg ? zDbArg : "main";
15954   int nDb = (int)strlen(zDb);
15955 
15956   pNew = (sqlite3_intck*)sqlite3_malloc(sizeof(*pNew) + nDb + 1);
15957   if( pNew==0 ){
15958     rc = SQLITE_NOMEM;
15959   }else{
15960     memset(pNew, 0, sizeof(*pNew));
15961     pNew->db = db;
15962     pNew->zDb = (const char*)&pNew[1];
15963     memcpy(&pNew[1], zDb, nDb+1);
15964     rc = sqlite3_create_function(db, "parse_create_index",
15965         2, SQLITE_UTF8, 0, intckParseCreateIndexFunc, 0, 0
15966     );
15967     if( rc!=SQLITE_OK ){
15968       sqlite3_intck_close(pNew);
15969       pNew = 0;
15970     }
15971   }
15972 
15973   *ppOut = pNew;
15974   return rc;
15975 }
15976 
15977 /*
15978 ** Free the integrity-check object.
15979 */
sqlite3_intck_close(sqlite3_intck * p)15980 void sqlite3_intck_close(sqlite3_intck *p){
15981   if( p ){
15982     sqlite3_finalize(p->pCheck);
15983     sqlite3_create_function(
15984         p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0
15985     );
15986     sqlite3_free(p->zObj);
15987     sqlite3_free(p->zKey);
15988     sqlite3_free(p->zTestSql);
15989     sqlite3_free(p->zErr);
15990     sqlite3_free(p->zMessage);
15991     sqlite3_free(p);
15992   }
15993 }
15994 
15995 /*
15996 ** Step the integrity-check object.
15997 */
sqlite3_intck_step(sqlite3_intck * p)15998 int sqlite3_intck_step(sqlite3_intck *p){
15999   if( p->rc==SQLITE_OK ){
16000 
16001     if( p->zMessage ){
16002       sqlite3_free(p->zMessage);
16003       p->zMessage = 0;
16004     }
16005 
16006     if( p->bCorruptSchema ){
16007       p->rc = SQLITE_DONE;
16008     }else
16009     if( p->pCheck==0 ){
16010       intckFindObject(p);
16011       if( p->rc==SQLITE_OK ){
16012         if( p->zObj ){
16013           char *zSql = 0;
16014           zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal);
16015           p->pCheck = intckPrepare(p, zSql);
16016           sqlite3_free(zSql);
16017           sqlite3_free(p->zKey);
16018           p->zKey = 0;
16019         }else{
16020           p->rc = SQLITE_DONE;
16021         }
16022       }else if( p->rc==SQLITE_CORRUPT ){
16023         p->rc = SQLITE_OK;
16024         p->zMessage = intckMprintf(p, "%s",
16025             "corruption found while reading database schema"
16026         );
16027         p->bCorruptSchema = 1;
16028       }
16029     }
16030 
16031     if( p->pCheck ){
16032       assert( p->rc==SQLITE_OK );
16033       if( sqlite3_step(p->pCheck)==SQLITE_ROW ){
16034         /* Normal case, do nothing. */
16035       }else{
16036         intckFinalize(p, p->pCheck);
16037         p->pCheck = 0;
16038         p->nKeyVal = 0;
16039         if( p->rc==SQLITE_CORRUPT ){
16040           p->rc = SQLITE_OK;
16041           p->zMessage = intckMprintf(p,
16042               "corruption found while scanning database object %s", p->zObj
16043           );
16044         }
16045       }
16046     }
16047   }
16048 
16049   return p->rc;
16050 }
16051 
16052 /*
16053 ** Return a message describing the corruption encountered by the most recent
16054 ** call to sqlite3_intck_step(), or NULL if no corruption was encountered.
16055 */
sqlite3_intck_message(sqlite3_intck * p)16056 const char *sqlite3_intck_message(sqlite3_intck *p){
16057   assert( p->pCheck==0 || p->zMessage==0 );
16058   if( p->zMessage ){
16059     return p->zMessage;
16060   }
16061   if( p->pCheck ){
16062     return (const char*)sqlite3_column_text(p->pCheck, 0);
16063   }
16064   return 0;
16065 }
16066 
16067 /*
16068 ** Return the error code and message.
16069 */
sqlite3_intck_error(sqlite3_intck * p,const char ** pzErr)16070 int sqlite3_intck_error(sqlite3_intck *p, const char **pzErr){
16071   if( pzErr ) *pzErr = p->zErr;
16072   return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc);
16073 }
16074 
16075 /*
16076 ** Close any read transaction the integrity-check object is holding open
16077 ** on the database.
16078 */
sqlite3_intck_unlock(sqlite3_intck * p)16079 int sqlite3_intck_unlock(sqlite3_intck *p){
16080   if( p->rc==SQLITE_OK && p->pCheck ){
16081     assert( p->zKey==0 && p->nKeyVal>0 );
16082     intckSaveKey(p);
16083     intckFinalize(p, p->pCheck);
16084     p->pCheck = 0;
16085   }
16086   return p->rc;
16087 }
16088 
16089 /*
16090 ** Return the SQL statement used to check object zObj. Or, if zObj is
16091 ** NULL, the current SQL statement.
16092 */
sqlite3_intck_test_sql(sqlite3_intck * p,const char * zObj)16093 const char *sqlite3_intck_test_sql(sqlite3_intck *p, const char *zObj){
16094   sqlite3_free(p->zTestSql);
16095   if( zObj ){
16096     p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0);
16097   }else{
16098     if( p->zObj ){
16099       p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0);
16100     }else{
16101       sqlite3_free(p->zTestSql);
16102       p->zTestSql = 0;
16103     }
16104   }
16105   return p->zTestSql;
16106 }
16107 
16108 /************************* End ../ext/intck/sqlite3intck.c ********************/
16109 /************************* Begin ../ext/misc/stmtrand.c ******************/
16110 /*
16111 ** 2024-05-24
16112 **
16113 ** The author disclaims copyright to this source code.  In place of
16114 ** a legal notice, here is a blessing:
16115 **
16116 **    May you do good and not evil.
16117 **    May you find forgiveness for yourself and forgive others.
16118 **    May you share freely, never taking more than you give.
16119 **
16120 ******************************************************************************
16121 **
16122 ** An SQL function that return pseudo-random non-negative integers.
16123 **
16124 **      SELECT stmtrand(123);
16125 **
16126 ** A special feature of this function is that the same sequence of random
16127 ** integers is returned for each invocation of the statement.  This makes
16128 ** the results repeatable, and hence useful for testing.  The argument is
16129 ** an integer which is the seed for the random number sequence.  The seed
16130 ** is used by the first invocation of this function only and is ignored
16131 ** for all subsequent calls within the same statement.
16132 **
16133 ** Resetting a statement (sqlite3_reset()) also resets the random number
16134 ** sequence.
16135 */
16136 /* #include "sqlite3ext.h" */
16137 SQLITE_EXTENSION_INIT1
16138 #include <assert.h>
16139 #include <string.h>
16140 
16141 /* State of the pseudo-random number generator */
16142 typedef struct Stmtrand {
16143   unsigned int x, y;
16144 } Stmtrand;
16145 
16146 /* auxdata key */
16147 #define STMTRAND_KEY  (-4418371)
16148 
16149 /*
16150 ** Function:     stmtrand(SEED)
16151 **
16152 ** Return a pseudo-random number.
16153 */
stmtrandFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)16154 static void stmtrandFunc(
16155   sqlite3_context *context,
16156   int argc,
16157   sqlite3_value **argv
16158 ){
16159   Stmtrand *p;
16160 
16161   p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY);
16162   if( p==0 ){
16163     unsigned int seed;
16164     p = sqlite3_malloc( sizeof(*p) );
16165     if( p==0 ){
16166       sqlite3_result_error_nomem(context);
16167       return;
16168     }
16169     if( argc>=1 ){
16170       seed = (unsigned int)sqlite3_value_int(argv[0]);
16171     }else{
16172       seed = 0;
16173     }
16174     p->x = seed | 1;
16175     p->y = seed;
16176     sqlite3_set_auxdata(context, STMTRAND_KEY, p, sqlite3_free);
16177     p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY);
16178     if( p==0 ){
16179       sqlite3_result_error_nomem(context);
16180       return;
16181     }
16182   }
16183   p->x = (p->x>>1) ^ ((1+~(p->x&1)) & 0xd0000001);
16184   p->y = p->y*1103515245 + 12345;
16185   sqlite3_result_int(context, (int)((p->x ^ p->y)&0x7fffffff));
16186 }
16187 
16188 #ifdef _WIN32
16189 
16190 #endif
sqlite3_stmtrand_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)16191 int sqlite3_stmtrand_init(
16192   sqlite3 *db,
16193   char **pzErrMsg,
16194   const sqlite3_api_routines *pApi
16195 ){
16196   int rc = SQLITE_OK;
16197   SQLITE_EXTENSION_INIT2(pApi);
16198   (void)pzErrMsg;  /* Unused parameter */
16199   rc = sqlite3_create_function(db, "stmtrand", 1, SQLITE_UTF8, 0,
16200                                stmtrandFunc, 0, 0);
16201   if( rc==SQLITE_OK ){
16202     rc = sqlite3_create_function(db, "stmtrand", 0, SQLITE_UTF8, 0,
16203                                  stmtrandFunc, 0, 0);
16204   }
16205   return rc;
16206 }
16207 
16208 /************************* End ../ext/misc/stmtrand.c ********************/
16209 /************************* Begin ../ext/misc/vfstrace.c ******************/
16210 /*
16211 ** 2011 March 16
16212 **
16213 ** The author disclaims copyright to this source code.  In place of
16214 ** a legal notice, here is a blessing:
16215 **
16216 **    May you do good and not evil.
16217 **    May you find forgiveness for yourself and forgive others.
16218 **    May you share freely, never taking more than you give.
16219 **
16220 ******************************************************************************
16221 **
16222 ** This file contains code implements a VFS shim that writes diagnostic
16223 ** output for each VFS call, similar to "strace".
16224 **
16225 ** USAGE:
16226 **
16227 ** This source file exports a single symbol which is the name of a
16228 ** function:
16229 **
16230 **   int vfstrace_register(
16231 **     const char *zTraceName,         // Name of the newly constructed VFS
16232 **     const char *zOldVfsName,        // Name of the underlying VFS
16233 **     int (*xOut)(const char*,void*), // Output routine.  ex: fputs
16234 **     void *pOutArg,                  // 2nd argument to xOut.  ex: stderr
16235 **     int makeDefault                 // Make the new VFS the default
16236 **   );
16237 **
16238 ** Applications that want to trace their VFS usage must provide a callback
16239 ** function with this prototype:
16240 **
16241 **   int traceOutput(const char *zMessage, void *pAppData);
16242 **
16243 ** This function will "output" the trace messages, where "output" can
16244 ** mean different things to different applications.  The traceOutput function
16245 ** for the command-line shell (see shell.c) is "fputs" from the standard
16246 ** library, which means that all trace output is written on the stream
16247 ** specified by the second argument.  In the case of the command-line shell
16248 ** the second argument is stderr.  Other applications might choose to output
16249 ** trace information to a file, over a socket, or write it into a buffer.
16250 **
16251 ** The vfstrace_register() function creates a new "shim" VFS named by
16252 ** the zTraceName parameter.  A "shim" VFS is an SQLite backend that does
16253 ** not really perform the duties of a true backend, but simply filters or
16254 ** interprets VFS calls before passing them off to another VFS which does
16255 ** the actual work.  In this case the other VFS - the one that does the
16256 ** real work - is identified by the second parameter, zOldVfsName.  If
16257 ** the 2nd parameter is NULL then the default VFS is used.  The common
16258 ** case is for the 2nd parameter to be NULL.
16259 **
16260 ** The third and fourth parameters are the pointer to the output function
16261 ** and the second argument to the output function.  For the SQLite
16262 ** command-line shell, when the -vfstrace option is used, these parameters
16263 ** are fputs and stderr, respectively.
16264 **
16265 ** The fifth argument is true (non-zero) to cause the newly created VFS
16266 ** to become the default VFS.  The common case is for the fifth parameter
16267 ** to be true.
16268 **
16269 ** The call to vfstrace_register() simply creates the shim VFS that does
16270 ** tracing.  The application must also arrange to use the new VFS for
16271 ** all database connections that are created and for which tracing is
16272 ** desired.  This can be done by specifying the trace VFS using URI filename
16273 ** notation, or by specifying the trace VFS as the 4th parameter to
16274 ** sqlite3_open_v2() or by making the trace VFS be the default (by setting
16275 ** the 5th parameter of vfstrace_register() to 1).
16276 **
16277 **
16278 ** ENABLING VFSTRACE IN A COMMAND-LINE SHELL
16279 **
16280 ** The SQLite command line shell implemented by the shell.c source file
16281 ** can be used with this module.  To compile in -vfstrace support, first
16282 ** gather this file (test_vfstrace.c), the shell source file (shell.c),
16283 ** and the SQLite amalgamation source files (sqlite3.c, sqlite3.h) into
16284 ** the working directory.  Then compile using a command like the following:
16285 **
16286 **    gcc -o sqlite3 -Os -I. -DSQLITE_ENABLE_VFSTRACE \
16287 **        -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE \
16288 **        -DHAVE_READLINE -DHAVE_USLEEP=1 \
16289 **        shell.c test_vfstrace.c sqlite3.c -ldl -lreadline -lncurses
16290 **
16291 ** The gcc command above works on Linux and provides (in addition to the
16292 ** -vfstrace option) support for FTS3 and FTS4, RTREE, and command-line
16293 ** editing using the readline library.  The command-line shell does not
16294 ** use threads so we added -DSQLITE_THREADSAFE=0 just to make the code
16295 ** run a little faster.   For compiling on a Mac, you'll probably need
16296 ** to omit the -DHAVE_READLINE, the -lreadline, and the -lncurses options.
16297 ** The compilation could be simplified to just this:
16298 **
16299 **    gcc -DSQLITE_ENABLE_VFSTRACE \
16300 **         shell.c test_vfstrace.c sqlite3.c -ldl -lpthread
16301 **
16302 ** In this second example, all unnecessary options have been removed
16303 ** Note that since the code is now threadsafe, we had to add the -lpthread
16304 ** option to pull in the pthreads library.
16305 **
16306 ** To cross-compile for windows using MinGW, a command like this might
16307 ** work:
16308 **
16309 **    /opt/mingw/bin/i386-mingw32msvc-gcc -o sqlite3.exe -Os -I \
16310 **         -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_VFSTRACE \
16311 **         shell.c test_vfstrace.c sqlite3.c
16312 **
16313 ** Similar compiler commands will work on different systems.  The key
16314 ** invariants are (1) you must have -DSQLITE_ENABLE_VFSTRACE so that
16315 ** the shell.c source file will know to include the -vfstrace command-line
16316 ** option and (2) you must compile and link the three source files
16317 ** shell,c, test_vfstrace.c, and sqlite3.c.
16318 **
16319 ** RUNTIME CONTROL OF VFSTRACE OUTPUT
16320 **
16321 ** The application can use the "vfstrace" pragma to control which VFS
16322 ** APIs are traced.  To disable all output:
16323 **
16324 **    PRAGMA vfstrace('-all');
16325 **
16326 ** To enable all output (which is the default setting):
16327 **
16328 **    PRAGMA vfstrace('+all');
16329 **
16330 ** Individual APIs can be enabled or disabled by name, with or without
16331 ** the initial "x" character.  For example, to set up for tracing lock
16332 ** primitives only:
16333 **
16334 **    PRAGMA vfstrace('-all, +Lock,Unlock,ShmLock');
16335 **
16336 ** The argument to the vfstrace pragma ignores capitalization and any
16337 ** characters other than alphabetics, '+', and '-'.
16338 */
16339 #include <stdlib.h>
16340 #include <string.h>
16341 /* #include "sqlite3.h" */
16342 
16343 /*
16344 ** An instance of this structure is attached to the each trace VFS to
16345 ** provide auxiliary information.
16346 */
16347 typedef struct vfstrace_info vfstrace_info;
16348 struct vfstrace_info {
16349   sqlite3_vfs *pRootVfs;              /* The underlying real VFS */
16350   int (*xOut)(const char*, void*);    /* Send output here */
16351   unsigned int mTrace;                /* Mask of interfaces to trace */
16352   u8 bOn;                             /* Tracing on/off */
16353   void *pOutArg;                      /* First argument to xOut */
16354   const char *zVfsName;               /* Name of this trace-VFS */
16355   sqlite3_vfs *pTraceVfs;             /* Pointer back to the trace VFS */
16356 };
16357 
16358 /*
16359 ** The sqlite3_file object for the trace VFS
16360 */
16361 typedef struct vfstrace_file vfstrace_file;
16362 struct vfstrace_file {
16363   sqlite3_file base;        /* Base class.  Must be first */
16364   vfstrace_info *pInfo;     /* The trace-VFS to which this file belongs */
16365   const char *zFName;       /* Base name of the file */
16366   sqlite3_file *pReal;      /* The real underlying file */
16367 };
16368 
16369 /*
16370 ** Bit values for vfstrace_info.mTrace.
16371 */
16372 #define VTR_CLOSE           0x00000001
16373 #define VTR_READ            0x00000002
16374 #define VTR_WRITE           0x00000004
16375 #define VTR_TRUNC           0x00000008
16376 #define VTR_SYNC            0x00000010
16377 #define VTR_FSIZE           0x00000020
16378 #define VTR_LOCK            0x00000040
16379 #define VTR_UNLOCK          0x00000080
16380 #define VTR_CRL             0x00000100
16381 #define VTR_FCTRL           0x00000200
16382 #define VTR_SECSZ           0x00000400
16383 #define VTR_DEVCHAR         0x00000800
16384 #define VTR_SHMLOCK         0x00001000
16385 #define VTR_SHMMAP          0x00002000
16386 #define VTR_SHMBAR          0x00004000
16387 #define VTR_SHMUNMAP        0x00008000
16388 #define VTR_OPEN            0x00010000
16389 #define VTR_DELETE          0x00020000
16390 #define VTR_ACCESS          0x00040000
16391 #define VTR_FULLPATH        0x00080000
16392 #define VTR_DLOPEN          0x00100000
16393 #define VTR_DLERR           0x00200000
16394 #define VTR_DLSYM           0x00400000
16395 #define VTR_DLCLOSE         0x00800000
16396 #define VTR_RAND            0x01000000
16397 #define VTR_SLEEP           0x02000000
16398 #define VTR_CURTIME         0x04000000
16399 #define VTR_LASTERR         0x08000000
16400 #define VTR_FETCH           0x10000000   /* Also coverse xUnfetch */
16401 
16402 /*
16403 ** Method declarations for vfstrace_file.
16404 */
16405 static int vfstraceClose(sqlite3_file*);
16406 static int vfstraceRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
16407 static int vfstraceWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64);
16408 static int vfstraceTruncate(sqlite3_file*, sqlite3_int64 size);
16409 static int vfstraceSync(sqlite3_file*, int flags);
16410 static int vfstraceFileSize(sqlite3_file*, sqlite3_int64 *pSize);
16411 static int vfstraceLock(sqlite3_file*, int);
16412 static int vfstraceUnlock(sqlite3_file*, int);
16413 static int vfstraceCheckReservedLock(sqlite3_file*, int *);
16414 static int vfstraceFileControl(sqlite3_file*, int op, void *pArg);
16415 static int vfstraceSectorSize(sqlite3_file*);
16416 static int vfstraceDeviceCharacteristics(sqlite3_file*);
16417 static int vfstraceShmLock(sqlite3_file*,int,int,int);
16418 static int vfstraceShmMap(sqlite3_file*,int,int,int, void volatile **);
16419 static void vfstraceShmBarrier(sqlite3_file*);
16420 static int vfstraceShmUnmap(sqlite3_file*,int);
16421 
16422 /*
16423 ** Method declarations for vfstrace_vfs.
16424 */
16425 static int vfstraceOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
16426 static int vfstraceDelete(sqlite3_vfs*, const char *zName, int syncDir);
16427 static int vfstraceAccess(sqlite3_vfs*, const char *zName, int flags, int *);
16428 static int vfstraceFullPathname(sqlite3_vfs*, const char *zName, int, char *);
16429 static void *vfstraceDlOpen(sqlite3_vfs*, const char *zFilename);
16430 static void vfstraceDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
16431 static void (*vfstraceDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void);
16432 static void vfstraceDlClose(sqlite3_vfs*, void*);
16433 static int vfstraceRandomness(sqlite3_vfs*, int nByte, char *zOut);
16434 static int vfstraceSleep(sqlite3_vfs*, int microseconds);
16435 static int vfstraceCurrentTime(sqlite3_vfs*, double*);
16436 static int vfstraceGetLastError(sqlite3_vfs*, int, char*);
16437 static int vfstraceCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
16438 static int vfstraceSetSystemCall(sqlite3_vfs*,const char*, sqlite3_syscall_ptr);
16439 static sqlite3_syscall_ptr vfstraceGetSystemCall(sqlite3_vfs*, const char *);
16440 static const char *vfstraceNextSystemCall(sqlite3_vfs*, const char *zName);
16441 
16442 /*
16443 ** Return a pointer to the tail of the pathname.  Examples:
16444 **
16445 **     /home/drh/xyzzy.txt -> xyzzy.txt
16446 **     xyzzy.txt           -> xyzzy.txt
16447 */
fileTail(const char * z)16448 static const char *fileTail(const char *z){
16449   size_t i;
16450   if( z==0 ) return 0;
16451   i = strlen(z)-1;
16452   while( i>0 && z[i-1]!='/' ){ i--; }
16453   return &z[i];
16454 }
16455 
16456 /*
16457 ** Send trace output defined by zFormat and subsequent arguments.
16458 */
vfstrace_printf(vfstrace_info * pInfo,const char * zFormat,...)16459 static void vfstrace_printf(
16460   vfstrace_info *pInfo,
16461   const char *zFormat,
16462   ...
16463 ){
16464   va_list ap;
16465   char *zMsg;
16466   if( pInfo->bOn ){
16467     va_start(ap, zFormat);
16468     zMsg = sqlite3_vmprintf(zFormat, ap);
16469     va_end(ap);
16470     pInfo->xOut(zMsg, pInfo->pOutArg);
16471     sqlite3_free(zMsg);
16472   }
16473 }
16474 
16475 /*
16476 ** Try to convert an error code into a symbolic name for that error code.
16477 */
vfstrace_errcode_name(int rc)16478 static const char *vfstrace_errcode_name(int rc ){
16479   const char *zVal = 0;
16480   switch( rc ){
16481     case SQLITE_OK:                 zVal = "SQLITE_OK";                 break;
16482     case SQLITE_INTERNAL:           zVal = "SQLITE_INTERNAL";           break;
16483     case SQLITE_ERROR:              zVal = "SQLITE_ERROR";              break;
16484     case SQLITE_PERM:               zVal = "SQLITE_PERM";               break;
16485     case SQLITE_ABORT:              zVal = "SQLITE_ABORT";              break;
16486     case SQLITE_BUSY:               zVal = "SQLITE_BUSY";               break;
16487     case SQLITE_LOCKED:             zVal = "SQLITE_LOCKED";             break;
16488     case SQLITE_NOMEM:              zVal = "SQLITE_NOMEM";              break;
16489     case SQLITE_READONLY:           zVal = "SQLITE_READONLY";           break;
16490     case SQLITE_INTERRUPT:          zVal = "SQLITE_INTERRUPT";          break;
16491     case SQLITE_IOERR:              zVal = "SQLITE_IOERR";              break;
16492     case SQLITE_CORRUPT:            zVal = "SQLITE_CORRUPT";            break;
16493     case SQLITE_NOTFOUND:           zVal = "SQLITE_NOTFOUND";           break;
16494     case SQLITE_FULL:               zVal = "SQLITE_FULL";               break;
16495     case SQLITE_CANTOPEN:           zVal = "SQLITE_CANTOPEN";           break;
16496     case SQLITE_PROTOCOL:           zVal = "SQLITE_PROTOCOL";           break;
16497     case SQLITE_EMPTY:              zVal = "SQLITE_EMPTY";              break;
16498     case SQLITE_SCHEMA:             zVal = "SQLITE_SCHEMA";             break;
16499     case SQLITE_TOOBIG:             zVal = "SQLITE_TOOBIG";             break;
16500     case SQLITE_CONSTRAINT:         zVal = "SQLITE_CONSTRAINT";         break;
16501     case SQLITE_MISMATCH:           zVal = "SQLITE_MISMATCH";           break;
16502     case SQLITE_MISUSE:             zVal = "SQLITE_MISUSE";             break;
16503     case SQLITE_NOLFS:              zVal = "SQLITE_NOLFS";              break;
16504     case SQLITE_IOERR_READ:         zVal = "SQLITE_IOERR_READ";         break;
16505     case SQLITE_IOERR_SHORT_READ:   zVal = "SQLITE_IOERR_SHORT_READ";   break;
16506     case SQLITE_IOERR_WRITE:        zVal = "SQLITE_IOERR_WRITE";        break;
16507     case SQLITE_IOERR_FSYNC:        zVal = "SQLITE_IOERR_FSYNC";        break;
16508     case SQLITE_IOERR_DIR_FSYNC:    zVal = "SQLITE_IOERR_DIR_FSYNC";    break;
16509     case SQLITE_IOERR_TRUNCATE:     zVal = "SQLITE_IOERR_TRUNCATE";     break;
16510     case SQLITE_IOERR_FSTAT:        zVal = "SQLITE_IOERR_FSTAT";        break;
16511     case SQLITE_IOERR_UNLOCK:       zVal = "SQLITE_IOERR_UNLOCK";       break;
16512     case SQLITE_IOERR_RDLOCK:       zVal = "SQLITE_IOERR_RDLOCK";       break;
16513     case SQLITE_IOERR_DELETE:       zVal = "SQLITE_IOERR_DELETE";       break;
16514     case SQLITE_IOERR_BLOCKED:      zVal = "SQLITE_IOERR_BLOCKED";      break;
16515     case SQLITE_IOERR_NOMEM:        zVal = "SQLITE_IOERR_NOMEM";        break;
16516     case SQLITE_IOERR_ACCESS:       zVal = "SQLITE_IOERR_ACCESS";       break;
16517     case SQLITE_IOERR_CHECKRESERVEDLOCK:
16518                                zVal = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
16519     case SQLITE_IOERR_LOCK:         zVal = "SQLITE_IOERR_LOCK";         break;
16520     case SQLITE_IOERR_CLOSE:        zVal = "SQLITE_IOERR_CLOSE";        break;
16521     case SQLITE_IOERR_DIR_CLOSE:    zVal = "SQLITE_IOERR_DIR_CLOSE";    break;
16522     case SQLITE_IOERR_SHMOPEN:      zVal = "SQLITE_IOERR_SHMOPEN";      break;
16523     case SQLITE_IOERR_SHMSIZE:      zVal = "SQLITE_IOERR_SHMSIZE";      break;
16524     case SQLITE_IOERR_SHMLOCK:      zVal = "SQLITE_IOERR_SHMLOCK";      break;
16525     case SQLITE_IOERR_SHMMAP:       zVal = "SQLITE_IOERR_SHMMAP";       break;
16526     case SQLITE_IOERR_SEEK:         zVal = "SQLITE_IOERR_SEEK";         break;
16527     case SQLITE_IOERR_GETTEMPPATH:  zVal = "SQLITE_IOERR_GETTEMPPATH";  break;
16528     case SQLITE_IOERR_CONVPATH:     zVal = "SQLITE_IOERR_CONVPATH";     break;
16529     case SQLITE_READONLY_DBMOVED:   zVal = "SQLITE_READONLY_DBMOVED";   break;
16530     case SQLITE_LOCKED_SHAREDCACHE: zVal = "SQLITE_LOCKED_SHAREDCACHE"; break;
16531     case SQLITE_BUSY_RECOVERY:      zVal = "SQLITE_BUSY_RECOVERY";      break;
16532     case SQLITE_CANTOPEN_NOTEMPDIR: zVal = "SQLITE_CANTOPEN_NOTEMPDIR"; break;
16533   }
16534   return zVal;
16535 }
16536 
16537 /*
16538 ** Convert value rc into a string and print it using zFormat.  zFormat
16539 ** should have exactly one %s
16540 */
vfstrace_print_errcode(vfstrace_info * pInfo,const char * zFormat,int rc)16541 static void vfstrace_print_errcode(
16542   vfstrace_info *pInfo,
16543   const char *zFormat,
16544   int rc
16545 ){
16546   const char *zVal;
16547   char zBuf[50];
16548   zVal = vfstrace_errcode_name(rc);
16549   if( zVal==0 ){
16550     zVal = vfstrace_errcode_name(rc&0xff);
16551     if( zVal ){
16552       sqlite3_snprintf(sizeof(zBuf), zBuf, "%s | 0x%x", zVal, rc&0xffff00);
16553     }else{
16554       sqlite3_snprintf(sizeof(zBuf), zBuf, "%d (0x%x)", rc, rc);
16555     }
16556     zVal = zBuf;
16557   }
16558   vfstrace_printf(pInfo, zFormat, zVal);
16559 }
16560 
16561 /*
16562 ** Append to a buffer.
16563 */
strappend(char * z,int * pI,const char * zAppend)16564 static void strappend(char *z, int *pI, const char *zAppend){
16565   int i = *pI;
16566   while( zAppend[0] ){ z[i++] = *(zAppend++); }
16567   z[i] = 0;
16568   *pI = i;
16569 }
16570 
16571 /*
16572 ** Turn tracing output on or off according to mMask.
16573 */
vfstraceOnOff(vfstrace_info * pInfo,unsigned int mMask)16574 static void vfstraceOnOff(vfstrace_info *pInfo, unsigned int mMask){
16575   pInfo->bOn = (pInfo->mTrace & mMask)!=0;
16576 }
16577 
16578 /*
16579 ** Close an vfstrace-file.
16580 */
vfstraceClose(sqlite3_file * pFile)16581 static int vfstraceClose(sqlite3_file *pFile){
16582   vfstrace_file *p = (vfstrace_file *)pFile;
16583   vfstrace_info *pInfo = p->pInfo;
16584   int rc;
16585   vfstraceOnOff(pInfo, VTR_CLOSE);
16586   vfstrace_printf(pInfo, "%s.xClose(%s)", pInfo->zVfsName, p->zFName);
16587   rc = p->pReal->pMethods->xClose(p->pReal);
16588   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
16589   if( rc==SQLITE_OK ){
16590     sqlite3_free((void*)p->base.pMethods);
16591     p->base.pMethods = 0;
16592   }
16593   return rc;
16594 }
16595 
16596 /*
16597 ** Read data from an vfstrace-file.
16598 */
vfstraceRead(sqlite3_file * pFile,void * zBuf,int iAmt,sqlite_int64 iOfst)16599 static int vfstraceRead(
16600   sqlite3_file *pFile,
16601   void *zBuf,
16602   int iAmt,
16603   sqlite_int64 iOfst
16604 ){
16605   vfstrace_file *p = (vfstrace_file *)pFile;
16606   vfstrace_info *pInfo = p->pInfo;
16607   int rc;
16608   vfstraceOnOff(pInfo, VTR_READ);
16609   vfstrace_printf(pInfo, "%s.xRead(%s,n=%d,ofst=%lld)",
16610                   pInfo->zVfsName, p->zFName, iAmt, iOfst);
16611   rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
16612   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
16613   return rc;
16614 }
16615 
16616 /*
16617 ** Write data to an vfstrace-file.
16618 */
vfstraceWrite(sqlite3_file * pFile,const void * zBuf,int iAmt,sqlite_int64 iOfst)16619 static int vfstraceWrite(
16620   sqlite3_file *pFile,
16621   const void *zBuf,
16622   int iAmt,
16623   sqlite_int64 iOfst
16624 ){
16625   vfstrace_file *p = (vfstrace_file *)pFile;
16626   vfstrace_info *pInfo = p->pInfo;
16627   int rc;
16628   vfstraceOnOff(pInfo, VTR_WRITE);
16629   vfstrace_printf(pInfo, "%s.xWrite(%s,n=%d,ofst=%lld)",
16630                   pInfo->zVfsName, p->zFName, iAmt, iOfst);
16631   rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
16632   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
16633   return rc;
16634 }
16635 
16636 /*
16637 ** Truncate an vfstrace-file.
16638 */
vfstraceTruncate(sqlite3_file * pFile,sqlite_int64 size)16639 static int vfstraceTruncate(sqlite3_file *pFile, sqlite_int64 size){
16640   vfstrace_file *p = (vfstrace_file *)pFile;
16641   vfstrace_info *pInfo = p->pInfo;
16642   int rc;
16643   vfstraceOnOff(pInfo, VTR_TRUNC);
16644   vfstrace_printf(pInfo, "%s.xTruncate(%s,%lld)", pInfo->zVfsName, p->zFName,
16645                   size);
16646   rc = p->pReal->pMethods->xTruncate(p->pReal, size);
16647   vfstrace_printf(pInfo, " -> %d\n", rc);
16648   return rc;
16649 }
16650 
16651 /*
16652 ** Sync an vfstrace-file.
16653 */
vfstraceSync(sqlite3_file * pFile,int flags)16654 static int vfstraceSync(sqlite3_file *pFile, int flags){
16655   vfstrace_file *p = (vfstrace_file *)pFile;
16656   vfstrace_info *pInfo = p->pInfo;
16657   int rc;
16658   int i;
16659   char zBuf[100];
16660   memcpy(zBuf, "|0", 3);
16661   i = 0;
16662   if( flags & SQLITE_SYNC_FULL )        strappend(zBuf, &i, "|FULL");
16663   else if( flags & SQLITE_SYNC_NORMAL ) strappend(zBuf, &i, "|NORMAL");
16664   if( flags & SQLITE_SYNC_DATAONLY )    strappend(zBuf, &i, "|DATAONLY");
16665   if( flags & ~(SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY) ){
16666     sqlite3_snprintf(sizeof(zBuf)-i, &zBuf[i], "|0x%x", flags);
16667   }
16668   vfstraceOnOff(pInfo, VTR_SYNC);
16669   vfstrace_printf(pInfo, "%s.xSync(%s,%s)", pInfo->zVfsName, p->zFName,
16670                   &zBuf[1]);
16671   rc = p->pReal->pMethods->xSync(p->pReal, flags);
16672   vfstrace_printf(pInfo, " -> %d\n", rc);
16673   return rc;
16674 }
16675 
16676 /*
16677 ** Return the current file-size of an vfstrace-file.
16678 */
vfstraceFileSize(sqlite3_file * pFile,sqlite_int64 * pSize)16679 static int vfstraceFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
16680   vfstrace_file *p = (vfstrace_file *)pFile;
16681   vfstrace_info *pInfo = p->pInfo;
16682   int rc;
16683   vfstraceOnOff(pInfo, VTR_FSIZE);
16684   vfstrace_printf(pInfo, "%s.xFileSize(%s)", pInfo->zVfsName, p->zFName);
16685   rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
16686   vfstrace_print_errcode(pInfo, " -> %s,", rc);
16687   vfstrace_printf(pInfo, " size=%lld\n", *pSize);
16688   return rc;
16689 }
16690 
16691 /*
16692 ** Return the name of a lock.
16693 */
lockName(int eLock)16694 static const char *lockName(int eLock){
16695   const char *azLockNames[] = {
16696      "NONE", "SHARED", "RESERVED", "PENDING", "EXCLUSIVE"
16697   };
16698   if( eLock<0 || eLock>=(int)(sizeof(azLockNames)/sizeof(azLockNames[0])) ){
16699     return "???";
16700   }else{
16701     return azLockNames[eLock];
16702   }
16703 }
16704 
16705 /*
16706 ** Lock an vfstrace-file.
16707 */
vfstraceLock(sqlite3_file * pFile,int eLock)16708 static int vfstraceLock(sqlite3_file *pFile, int eLock){
16709   vfstrace_file *p = (vfstrace_file *)pFile;
16710   vfstrace_info *pInfo = p->pInfo;
16711   int rc;
16712   vfstraceOnOff(pInfo, VTR_LOCK);
16713   vfstrace_printf(pInfo, "%s.xLock(%s,%s)", pInfo->zVfsName, p->zFName,
16714                   lockName(eLock));
16715   rc = p->pReal->pMethods->xLock(p->pReal, eLock);
16716   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
16717   return rc;
16718 }
16719 
16720 /*
16721 ** Unlock an vfstrace-file.
16722 */
vfstraceUnlock(sqlite3_file * pFile,int eLock)16723 static int vfstraceUnlock(sqlite3_file *pFile, int eLock){
16724   vfstrace_file *p = (vfstrace_file *)pFile;
16725   vfstrace_info *pInfo = p->pInfo;
16726   int rc;
16727   vfstraceOnOff(pInfo, VTR_UNLOCK);
16728   vfstrace_printf(pInfo, "%s.xUnlock(%s,%s)", pInfo->zVfsName, p->zFName,
16729                   lockName(eLock));
16730   rc = p->pReal->pMethods->xUnlock(p->pReal, eLock);
16731   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
16732   return rc;
16733 }
16734 
16735 /*
16736 ** Check if another file-handle holds a RESERVED lock on an vfstrace-file.
16737 */
vfstraceCheckReservedLock(sqlite3_file * pFile,int * pResOut)16738 static int vfstraceCheckReservedLock(sqlite3_file *pFile, int *pResOut){
16739   vfstrace_file *p = (vfstrace_file *)pFile;
16740   vfstrace_info *pInfo = p->pInfo;
16741   int rc;
16742   vfstraceOnOff(pInfo, VTR_CRL);
16743   vfstrace_printf(pInfo, "%s.xCheckReservedLock(%s,%d)",
16744                   pInfo->zVfsName, p->zFName);
16745   rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
16746   vfstrace_print_errcode(pInfo, " -> %s", rc);
16747   vfstrace_printf(pInfo, ", out=%d\n", *pResOut);
16748   return rc;
16749 }
16750 
16751 /*
16752 ** File control method. For custom operations on an vfstrace-file.
16753 */
vfstraceFileControl(sqlite3_file * pFile,int op,void * pArg)16754 static int vfstraceFileControl(sqlite3_file *pFile, int op, void *pArg){
16755   vfstrace_file *p = (vfstrace_file *)pFile;
16756   vfstrace_info *pInfo = p->pInfo;
16757   int rc;
16758   char zBuf[100];
16759   char zBuf2[100];
16760   char *zOp;
16761   char *zRVal = 0;
16762   vfstraceOnOff(pInfo, VTR_FCTRL);
16763   switch( op ){
16764     case SQLITE_FCNTL_LOCKSTATE:           zOp = "LOCKSTATE";           break;
16765     case SQLITE_GET_LOCKPROXYFILE:         zOp = "GET_LOCKPROXYFILE";   break;
16766     case SQLITE_SET_LOCKPROXYFILE:         zOp = "SET_LOCKPROXYFILE";   break;
16767     case SQLITE_LAST_ERRNO:                zOp = "LAST_ERRNO";          break;
16768     case SQLITE_FCNTL_SIZE_HINT: {
16769       sqlite3_snprintf(sizeof(zBuf), zBuf, "SIZE_HINT,%lld",
16770                        *(sqlite3_int64*)pArg);
16771       zOp = zBuf;
16772       break;
16773     }
16774     case SQLITE_FCNTL_CHUNK_SIZE: {
16775       sqlite3_snprintf(sizeof(zBuf), zBuf, "CHUNK_SIZE,%d", *(int*)pArg);
16776       zOp = zBuf;
16777       break;
16778     }
16779     case SQLITE_FCNTL_FILE_POINTER:        zOp = "FILE_POINTER";        break;
16780     case SQLITE_FCNTL_WIN32_AV_RETRY:      zOp = "WIN32_AV_RETRY";      break;
16781     case SQLITE_FCNTL_PERSIST_WAL: {
16782        sqlite3_snprintf(sizeof(zBuf), zBuf, "PERSIST_WAL,%d", *(int*)pArg);
16783        zOp = zBuf;
16784        break;
16785     }
16786     case SQLITE_FCNTL_OVERWRITE:           zOp = "OVERWRITE";           break;
16787     case SQLITE_FCNTL_VFSNAME:             zOp = "VFSNAME";             break;
16788     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: zOp = "POWERSAFE_OVERWRITE"; break;
16789     case SQLITE_FCNTL_PRAGMA: {
16790       const char *const* a = (const char*const*)pArg;
16791       if( a[1] && strcmp(a[1],"vfstrace")==0 && a[2] ){
16792         const u8 *zArg = (const u8*)a[2];
16793         if( zArg[0]>='0' && zArg[0]<='9' ){
16794           pInfo->mTrace = (sqlite3_uint64)strtoll(a[2], 0, 0);
16795         }else{
16796           static const struct {
16797             const char *z;
16798             unsigned int m;
16799           } aKw[] = {
16800             { "all",                   0xffffffff   },
16801             { "close",                 VTR_CLOSE    },
16802             { "read",                  VTR_READ     },
16803             { "write",                 VTR_WRITE    },
16804             { "truncate",              VTR_TRUNC    },
16805             { "sync",                  VTR_SYNC     },
16806             { "filesize",              VTR_FSIZE    },
16807             { "lock",                  VTR_LOCK     },
16808             { "unlock",                VTR_UNLOCK   },
16809             { "checkreservedlock",     VTR_CRL      },
16810             { "filecontrol",           VTR_FCTRL    },
16811             { "sectorsize",            VTR_SECSZ    },
16812             { "devicecharacteristics", VTR_DEVCHAR  },
16813             { "shmlock",               VTR_SHMLOCK  },
16814             { "shmmap",                VTR_SHMMAP   },
16815             { "shmummap",              VTR_SHMUNMAP },
16816             { "shmbarrier",            VTR_SHMBAR   },
16817             { "open",                  VTR_OPEN     },
16818             { "delete",                VTR_DELETE   },
16819             { "access",                VTR_ACCESS   },
16820             { "fullpathname",          VTR_FULLPATH },
16821             { "dlopen",                VTR_DLOPEN   },
16822             { "dlerror",               VTR_DLERR    },
16823             { "dlsym",                 VTR_DLSYM    },
16824             { "dlclose",               VTR_DLCLOSE  },
16825             { "randomness",            VTR_RAND     },
16826             { "sleep",                 VTR_SLEEP    },
16827             { "currenttime",           VTR_CURTIME  },
16828             { "currenttimeint64",      VTR_CURTIME  },
16829             { "getlasterror",          VTR_LASTERR  },
16830             { "fetch",                 VTR_FETCH    },
16831           };
16832           int onOff = 1;
16833           while( zArg[0] ){
16834             int jj, n;
16835             while( zArg[0]!=0 && zArg[0]!='-' && zArg[0]!='+'
16836                    && !isalpha(zArg[0]) ) zArg++;
16837             if( zArg[0]==0 ) break;
16838             if( zArg[0]=='-' ){
16839               onOff = 0;
16840               zArg++;
16841             }else if( zArg[0]=='+' ){
16842               onOff = 1;
16843               zArg++;
16844             }
16845             while( !isalpha(zArg[0]) ){
16846               if( zArg[0]==0 ) break;
16847               zArg++;
16848             }
16849             if( zArg[0]=='x' && isalpha(zArg[1]) ) zArg++;
16850             for(n=0; isalpha(zArg[n]); n++){}
16851             for(jj=0; jj<(int)(sizeof(aKw)/sizeof(aKw[0])); jj++){
16852               if( sqlite3_strnicmp(aKw[jj].z,(const char*)zArg,n)==0 ){
16853                 if( onOff ){
16854                   pInfo->mTrace |= aKw[jj].m;
16855                 }else{
16856                   pInfo->mTrace &= ~aKw[jj].m;
16857                 }
16858                 break;
16859               }
16860             }
16861             zArg += n;
16862           }
16863         }
16864       }
16865       sqlite3_snprintf(sizeof(zBuf), zBuf, "PRAGMA,[%s,%s]",a[1],a[2]);
16866       zOp = zBuf;
16867       break;
16868     }
16869     case SQLITE_FCNTL_BUSYHANDLER:         zOp = "BUSYHANDLER";         break;
16870     case SQLITE_FCNTL_TEMPFILENAME:        zOp = "TEMPFILENAME";        break;
16871     case SQLITE_FCNTL_MMAP_SIZE: {
16872       sqlite3_int64 iMMap = *(sqlite3_int64*)pArg;
16873       sqlite3_snprintf(sizeof(zBuf), zBuf, "MMAP_SIZE,%lld",iMMap);
16874       zOp = zBuf;
16875       break;
16876     }
16877     case SQLITE_FCNTL_TRACE:               zOp = "TRACE";               break;
16878     case SQLITE_FCNTL_HAS_MOVED:           zOp = "HAS_MOVED";           break;
16879     case SQLITE_FCNTL_SYNC:                zOp = "SYNC";                break;
16880     case SQLITE_FCNTL_COMMIT_PHASETWO:     zOp = "COMMIT_PHASETWO";     break;
16881     case SQLITE_FCNTL_WIN32_SET_HANDLE:    zOp = "WIN32_SET_HANDLE";    break;
16882     case SQLITE_FCNTL_WAL_BLOCK:           zOp = "WAL_BLOCK";           break;
16883     case SQLITE_FCNTL_ZIPVFS:              zOp = "ZIPVFS";              break;
16884     case SQLITE_FCNTL_RBU:                 zOp = "RBU";                 break;
16885     case SQLITE_FCNTL_VFS_POINTER:         zOp = "VFS_POINTER";         break;
16886     case SQLITE_FCNTL_JOURNAL_POINTER:     zOp = "JOURNAL_POINTER";     break;
16887     case SQLITE_FCNTL_WIN32_GET_HANDLE:    zOp = "WIN32_GET_HANDLE";    break;
16888     case SQLITE_FCNTL_PDB:                 zOp = "PDB";                 break;
16889     case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE:  zOp = "BEGIN_ATOMIC_WRITE";  break;
16890     case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: zOp = "COMMIT_ATOMIC_WRITE"; break;
16891     case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
16892        zOp = "ROLLBACK_ATOMIC_WRITE";
16893        break;
16894     }
16895     case SQLITE_FCNTL_LOCK_TIMEOUT: {
16896        sqlite3_snprintf(sizeof(zBuf), zBuf, "LOCK_TIMEOUT,%d", *(int*)pArg);
16897        zOp = zBuf;
16898        break;
16899     }
16900     case SQLITE_FCNTL_DATA_VERSION:        zOp = "DATA_VERSION";        break;
16901     case SQLITE_FCNTL_SIZE_LIMIT:          zOp = "SIZE_LIMIT";          break;
16902     case SQLITE_FCNTL_CKPT_DONE:           zOp = "CKPT_DONE";           break;
16903     case SQLITE_FCNTL_RESERVE_BYTES:       zOp = "RESERVED_BYTES";      break;
16904     case SQLITE_FCNTL_CKPT_START:          zOp = "CKPT_START";          break;
16905     case SQLITE_FCNTL_EXTERNAL_READER:     zOp = "EXTERNAL_READER";     break;
16906     case SQLITE_FCNTL_CKSM_FILE:           zOp = "CKSM_FILE";           break;
16907     case SQLITE_FCNTL_RESET_CACHE:         zOp = "RESET_CACHE";         break;
16908     case 0xca093fa0:                       zOp = "DB_UNCHANGED";        break;
16909     default: {
16910       sqlite3_snprintf(sizeof zBuf, zBuf, "%d", op);
16911       zOp = zBuf;
16912       break;
16913     }
16914   }
16915   vfstrace_printf(pInfo, "%s.xFileControl(%s,%s)",
16916                   pInfo->zVfsName, p->zFName, zOp);
16917   rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg);
16918   if( rc==SQLITE_OK ){
16919     switch( op ){
16920       case SQLITE_FCNTL_VFSNAME: {
16921         *(char**)pArg = sqlite3_mprintf("vfstrace.%s/%z",
16922                                     pInfo->zVfsName, *(char**)pArg);
16923         zRVal = *(char**)pArg;
16924         break;
16925       }
16926       case SQLITE_FCNTL_MMAP_SIZE: {
16927         sqlite3_snprintf(sizeof(zBuf2), zBuf2, "%lld", *(sqlite3_int64*)pArg);
16928         zRVal = zBuf2;
16929         break;
16930       }
16931       case SQLITE_FCNTL_HAS_MOVED:
16932       case SQLITE_FCNTL_PERSIST_WAL: {
16933         sqlite3_snprintf(sizeof(zBuf2), zBuf2, "%d", *(int*)pArg);
16934         zRVal = zBuf2;
16935         break;
16936       }
16937       case SQLITE_FCNTL_PRAGMA:
16938       case SQLITE_FCNTL_TEMPFILENAME: {
16939         zRVal = *(char**)pArg;
16940         break;
16941       }
16942     }
16943   }
16944   if( zRVal ){
16945     vfstrace_print_errcode(pInfo, " -> %s", rc);
16946     vfstrace_printf(pInfo, ", %s\n", zRVal);
16947   }else{
16948     vfstrace_print_errcode(pInfo, " -> %s\n", rc);
16949   }
16950   return rc;
16951 }
16952 
16953 /*
16954 ** Return the sector-size in bytes for an vfstrace-file.
16955 */
vfstraceSectorSize(sqlite3_file * pFile)16956 static int vfstraceSectorSize(sqlite3_file *pFile){
16957   vfstrace_file *p = (vfstrace_file *)pFile;
16958   vfstrace_info *pInfo = p->pInfo;
16959   int rc;
16960   vfstraceOnOff(pInfo, VTR_SECSZ);
16961   vfstrace_printf(pInfo, "%s.xSectorSize(%s)", pInfo->zVfsName, p->zFName);
16962   rc = p->pReal->pMethods->xSectorSize(p->pReal);
16963   vfstrace_printf(pInfo, " -> %d\n", rc);
16964   return rc;
16965 }
16966 
16967 /*
16968 ** Return the device characteristic flags supported by an vfstrace-file.
16969 */
vfstraceDeviceCharacteristics(sqlite3_file * pFile)16970 static int vfstraceDeviceCharacteristics(sqlite3_file *pFile){
16971   vfstrace_file *p = (vfstrace_file *)pFile;
16972   vfstrace_info *pInfo = p->pInfo;
16973   int rc;
16974   vfstraceOnOff(pInfo, VTR_DEVCHAR);
16975   vfstrace_printf(pInfo, "%s.xDeviceCharacteristics(%s)",
16976                   pInfo->zVfsName, p->zFName);
16977   rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
16978   vfstrace_printf(pInfo, " -> 0x%08x\n", rc);
16979   return rc;
16980 }
16981 
16982 /*
16983 ** Shared-memory operations.
16984 */
vfstraceShmLock(sqlite3_file * pFile,int ofst,int n,int flags)16985 static int vfstraceShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
16986   static const char *azLockName[] = {
16987      "WRITE",
16988      "CKPT",
16989      "RECOVER",
16990      "READ0",
16991      "READ1",
16992      "READ2",
16993      "READ3",
16994      "READ4",
16995   };
16996   vfstrace_file *p = (vfstrace_file *)pFile;
16997   vfstrace_info *pInfo = p->pInfo;
16998   int rc;
16999   char zLck[100];
17000   int i = 0;
17001   vfstraceOnOff(pInfo, VTR_SHMLOCK);
17002   memcpy(zLck, "|0", 3);
17003   if( flags & SQLITE_SHM_UNLOCK )    strappend(zLck, &i, "|UNLOCK");
17004   if( flags & SQLITE_SHM_LOCK )      strappend(zLck, &i, "|LOCK");
17005   if( flags & SQLITE_SHM_SHARED )    strappend(zLck, &i, "|SHARED");
17006   if( flags & SQLITE_SHM_EXCLUSIVE ) strappend(zLck, &i, "|EXCLUSIVE");
17007   if( flags & ~(0xf) ){
17008      sqlite3_snprintf(sizeof(zLck)-i, &zLck[i], "|0x%x", flags);
17009   }
17010   if( ofst>=0 && ofst<(int)(sizeof(azLockName)/sizeof(azLockName[0])) ){
17011     vfstrace_printf(pInfo, "%s.xShmLock(%s,ofst=%d(%s),n=%d,%s)",
17012                   pInfo->zVfsName, p->zFName, ofst, azLockName[ofst],
17013                   n, &zLck[1]);
17014   }else{
17015     vfstrace_printf(pInfo, "%s.xShmLock(%s,ofst=5d,n=%d,%s)",
17016                   pInfo->zVfsName, p->zFName, ofst,
17017                   n, &zLck[1]);
17018   }
17019   rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
17020   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
17021   return rc;
17022 }
vfstraceShmMap(sqlite3_file * pFile,int iRegion,int szRegion,int isWrite,void volatile ** pp)17023 static int vfstraceShmMap(
17024   sqlite3_file *pFile,
17025   int iRegion,
17026   int szRegion,
17027   int isWrite,
17028   void volatile **pp
17029 ){
17030   vfstrace_file *p = (vfstrace_file *)pFile;
17031   vfstrace_info *pInfo = p->pInfo;
17032   int rc;
17033   vfstraceOnOff(pInfo, VTR_SHMMAP);
17034   vfstrace_printf(pInfo, "%s.xShmMap(%s,iRegion=%d,szRegion=%d,isWrite=%d,*)",
17035                   pInfo->zVfsName, p->zFName, iRegion, szRegion, isWrite);
17036   rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
17037   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
17038   return rc;
17039 }
vfstraceShmBarrier(sqlite3_file * pFile)17040 static void vfstraceShmBarrier(sqlite3_file *pFile){
17041   vfstrace_file *p = (vfstrace_file *)pFile;
17042   vfstrace_info *pInfo = p->pInfo;
17043   vfstraceOnOff(pInfo, VTR_SHMBAR);
17044   vfstrace_printf(pInfo, "%s.xShmBarrier(%s)\n", pInfo->zVfsName, p->zFName);
17045   p->pReal->pMethods->xShmBarrier(p->pReal);
17046 }
vfstraceShmUnmap(sqlite3_file * pFile,int delFlag)17047 static int vfstraceShmUnmap(sqlite3_file *pFile, int delFlag){
17048   vfstrace_file *p = (vfstrace_file *)pFile;
17049   vfstrace_info *pInfo = p->pInfo;
17050   int rc;
17051   vfstraceOnOff(pInfo, VTR_SHMUNMAP);
17052   vfstrace_printf(pInfo, "%s.xShmUnmap(%s,delFlag=%d)",
17053                   pInfo->zVfsName, p->zFName, delFlag);
17054   rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
17055   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
17056   return rc;
17057 }
vfstraceFetch(sqlite3_file * pFile,i64 iOff,int nAmt,void ** pptr)17058 static int vfstraceFetch(sqlite3_file *pFile, i64 iOff, int nAmt, void **pptr){
17059   vfstrace_file *p = (vfstrace_file *)pFile;
17060   vfstrace_info *pInfo = p->pInfo;
17061   int rc;
17062   vfstraceOnOff(pInfo, VTR_FETCH);
17063   vfstrace_printf(pInfo, "%s.xFetch(%s,iOff=%lld,nAmt=%d,p=%p)",
17064                   pInfo->zVfsName, p->zFName, iOff, nAmt, *pptr);
17065   rc = p->pReal->pMethods->xFetch(p->pReal, iOff, nAmt, pptr);
17066   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
17067   return rc;
17068 }
vfstraceUnfetch(sqlite3_file * pFile,i64 iOff,void * ptr)17069 static int vfstraceUnfetch(sqlite3_file *pFile, i64 iOff, void *ptr){
17070   vfstrace_file *p = (vfstrace_file *)pFile;
17071   vfstrace_info *pInfo = p->pInfo;
17072   int rc;
17073   vfstraceOnOff(pInfo, VTR_FETCH);
17074   vfstrace_printf(pInfo, "%s.xUnfetch(%s,iOff=%lld,p=%p)",
17075                   pInfo->zVfsName, p->zFName, iOff, ptr);
17076   rc = p->pReal->pMethods->xUnfetch(p->pReal, iOff, ptr);
17077   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
17078   return rc;
17079 }
17080 
17081 
17082 /*
17083 ** Open an vfstrace file handle.
17084 */
vfstraceOpen(sqlite3_vfs * pVfs,const char * zName,sqlite3_file * pFile,int flags,int * pOutFlags)17085 static int vfstraceOpen(
17086   sqlite3_vfs *pVfs,
17087   const char *zName,
17088   sqlite3_file *pFile,
17089   int flags,
17090   int *pOutFlags
17091 ){
17092   int rc;
17093   vfstrace_file *p = (vfstrace_file *)pFile;
17094   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17095   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17096   p->pInfo = pInfo;
17097   p->zFName = zName ? fileTail(zName) : "<temp>";
17098   p->pReal = (sqlite3_file *)&p[1];
17099   rc = pRoot->xOpen(pRoot, zName, p->pReal, flags, pOutFlags);
17100   vfstraceOnOff(pInfo, VTR_OPEN);
17101   vfstrace_printf(pInfo, "%s.xOpen(%s,flags=0x%x)",
17102                   pInfo->zVfsName, p->zFName, flags);
17103   if( p->pReal->pMethods ){
17104     sqlite3_io_methods *pNew = sqlite3_malloc( sizeof(*pNew) );
17105     const sqlite3_io_methods *pSub = p->pReal->pMethods;
17106     memset(pNew, 0, sizeof(*pNew));
17107     pNew->iVersion = pSub->iVersion;
17108     pNew->xClose = vfstraceClose;
17109     pNew->xRead = vfstraceRead;
17110     pNew->xWrite = vfstraceWrite;
17111     pNew->xTruncate = vfstraceTruncate;
17112     pNew->xSync = vfstraceSync;
17113     pNew->xFileSize = vfstraceFileSize;
17114     pNew->xLock = vfstraceLock;
17115     pNew->xUnlock = vfstraceUnlock;
17116     pNew->xCheckReservedLock = vfstraceCheckReservedLock;
17117     pNew->xFileControl = vfstraceFileControl;
17118     pNew->xSectorSize = vfstraceSectorSize;
17119     pNew->xDeviceCharacteristics = vfstraceDeviceCharacteristics;
17120     if( pNew->iVersion>=2 ){
17121       pNew->xShmMap = pSub->xShmMap ? vfstraceShmMap : 0;
17122       pNew->xShmLock = pSub->xShmLock ? vfstraceShmLock : 0;
17123       pNew->xShmBarrier = pSub->xShmBarrier ? vfstraceShmBarrier : 0;
17124       pNew->xShmUnmap = pSub->xShmUnmap ? vfstraceShmUnmap : 0;
17125     }
17126     if( pNew->iVersion>=3 ){
17127       pNew->xFetch = pSub->xFetch ? vfstraceFetch : 0;
17128       pNew->xUnfetch = pSub->xUnfetch ? vfstraceUnfetch : 0;
17129     }
17130     pFile->pMethods = pNew;
17131   }
17132   vfstrace_print_errcode(pInfo, " -> %s", rc);
17133   if( pOutFlags ){
17134     vfstrace_printf(pInfo, ", outFlags=0x%x\n", *pOutFlags);
17135   }else{
17136     vfstrace_printf(pInfo, "\n");
17137   }
17138   return rc;
17139 }
17140 
17141 /*
17142 ** Delete the file located at zPath. If the dirSync argument is true,
17143 ** ensure the file-system modifications are synced to disk before
17144 ** returning.
17145 */
vfstraceDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)17146 static int vfstraceDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
17147   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17148   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17149   int rc;
17150   vfstraceOnOff(pInfo, VTR_DELETE);
17151   vfstrace_printf(pInfo, "%s.xDelete(\"%s\",%d)",
17152                   pInfo->zVfsName, zPath, dirSync);
17153   rc = pRoot->xDelete(pRoot, zPath, dirSync);
17154   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
17155   return rc;
17156 }
17157 
17158 /*
17159 ** Test for access permissions. Return true if the requested permission
17160 ** is available, or false otherwise.
17161 */
vfstraceAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)17162 static int vfstraceAccess(
17163   sqlite3_vfs *pVfs,
17164   const char *zPath,
17165   int flags,
17166   int *pResOut
17167 ){
17168   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17169   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17170   int rc;
17171   vfstraceOnOff(pInfo, VTR_ACCESS);
17172   vfstrace_printf(pInfo, "%s.xAccess(\"%s\",%d)",
17173                   pInfo->zVfsName, zPath, flags);
17174   rc = pRoot->xAccess(pRoot, zPath, flags, pResOut);
17175   vfstrace_print_errcode(pInfo, " -> %s", rc);
17176   vfstrace_printf(pInfo, ", out=%d\n", *pResOut);
17177   return rc;
17178 }
17179 
17180 /*
17181 ** Populate buffer zOut with the full canonical pathname corresponding
17182 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
17183 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
17184 */
vfstraceFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nOut,char * zOut)17185 static int vfstraceFullPathname(
17186   sqlite3_vfs *pVfs,
17187   const char *zPath,
17188   int nOut,
17189   char *zOut
17190 ){
17191   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17192   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17193   int rc;
17194   vfstraceOnOff(pInfo, VTR_FULLPATH);
17195   vfstrace_printf(pInfo, "%s.xFullPathname(\"%s\")",
17196                   pInfo->zVfsName, zPath);
17197   rc = pRoot->xFullPathname(pRoot, zPath, nOut, zOut);
17198   vfstrace_print_errcode(pInfo, " -> %s", rc);
17199   vfstrace_printf(pInfo, ", out=\"%.*s\"\n", nOut, zOut);
17200   return rc;
17201 }
17202 
17203 /*
17204 ** Open the dynamic library located at zPath and return a handle.
17205 */
vfstraceDlOpen(sqlite3_vfs * pVfs,const char * zPath)17206 static void *vfstraceDlOpen(sqlite3_vfs *pVfs, const char *zPath){
17207   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17208   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17209   vfstraceOnOff(pInfo, VTR_DLOPEN);
17210   vfstrace_printf(pInfo, "%s.xDlOpen(\"%s\")\n", pInfo->zVfsName, zPath);
17211   return pRoot->xDlOpen(pRoot, zPath);
17212 }
17213 
17214 /*
17215 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
17216 ** utf-8 string describing the most recent error encountered associated
17217 ** with dynamic libraries.
17218 */
vfstraceDlError(sqlite3_vfs * pVfs,int nByte,char * zErrMsg)17219 static void vfstraceDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
17220   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17221   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17222   vfstraceOnOff(pInfo, VTR_DLERR);
17223   vfstrace_printf(pInfo, "%s.xDlError(%d)", pInfo->zVfsName, nByte);
17224   pRoot->xDlError(pRoot, nByte, zErrMsg);
17225   vfstrace_printf(pInfo, " -> \"%s\"", zErrMsg);
17226 }
17227 
17228 /*
17229 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
17230 */
vfstraceDlSym(sqlite3_vfs * pVfs,void * p,const char * zSym)17231 static void (*vfstraceDlSym(sqlite3_vfs *pVfs,void *p,const char *zSym))(void){
17232   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17233   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17234   vfstrace_printf(pInfo, "%s.xDlSym(\"%s\")\n", pInfo->zVfsName, zSym);
17235   return pRoot->xDlSym(pRoot, p, zSym);
17236 }
17237 
17238 /*
17239 ** Close the dynamic library handle pHandle.
17240 */
vfstraceDlClose(sqlite3_vfs * pVfs,void * pHandle)17241 static void vfstraceDlClose(sqlite3_vfs *pVfs, void *pHandle){
17242   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17243   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17244   vfstraceOnOff(pInfo, VTR_DLCLOSE);
17245   vfstrace_printf(pInfo, "%s.xDlClose()\n", pInfo->zVfsName);
17246   pRoot->xDlClose(pRoot, pHandle);
17247 }
17248 
17249 /*
17250 ** Populate the buffer pointed to by zBufOut with nByte bytes of
17251 ** random data.
17252 */
vfstraceRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)17253 static int vfstraceRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
17254   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17255   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17256   vfstraceOnOff(pInfo, VTR_RAND);
17257   vfstrace_printf(pInfo, "%s.xRandomness(%d)\n", pInfo->zVfsName, nByte);
17258   return pRoot->xRandomness(pRoot, nByte, zBufOut);
17259 }
17260 
17261 /*
17262 ** Sleep for nMicro microseconds. Return the number of microseconds
17263 ** actually slept.
17264 */
vfstraceSleep(sqlite3_vfs * pVfs,int nMicro)17265 static int vfstraceSleep(sqlite3_vfs *pVfs, int nMicro){
17266   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17267   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17268   vfstraceOnOff(pInfo, VTR_SLEEP);
17269   vfstrace_printf(pInfo, "%s.xSleep(%d)\n", pInfo->zVfsName, nMicro);
17270   return pRoot->xSleep(pRoot, nMicro);
17271 }
17272 
17273 /*
17274 ** Return the current time as a Julian Day number in *pTimeOut.
17275 */
vfstraceCurrentTime(sqlite3_vfs * pVfs,double * pTimeOut)17276 static int vfstraceCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
17277   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17278   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17279   int rc;
17280   vfstraceOnOff(pInfo, VTR_CURTIME);
17281   vfstrace_printf(pInfo, "%s.xCurrentTime()", pInfo->zVfsName);
17282   rc = pRoot->xCurrentTime(pRoot, pTimeOut);
17283   vfstrace_printf(pInfo, " -> %.17g\n", *pTimeOut);
17284   return rc;
17285 }
vfstraceCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * pTimeOut)17286 static int vfstraceCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
17287   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17288   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17289   int rc;
17290   vfstraceOnOff(pInfo, VTR_CURTIME);
17291   vfstrace_printf(pInfo, "%s.xCurrentTimeInt64()", pInfo->zVfsName);
17292   rc = pRoot->xCurrentTimeInt64(pRoot, pTimeOut);
17293   vfstrace_printf(pInfo, " -> %lld\n", *pTimeOut);
17294   return rc;
17295 }
17296 
17297 /*
17298 ** Return the most recent error code and message
17299 */
vfstraceGetLastError(sqlite3_vfs * pVfs,int nErr,char * zErr)17300 static int vfstraceGetLastError(sqlite3_vfs *pVfs, int nErr, char *zErr){
17301   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17302   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17303   int rc;
17304   vfstraceOnOff(pInfo, VTR_LASTERR);
17305   vfstrace_printf(pInfo, "%s.xGetLastError(%d,zBuf)", pInfo->zVfsName, nErr);
17306   if( nErr ) zErr[0] = 0;
17307   rc = pRoot->xGetLastError(pRoot, nErr, zErr);
17308   vfstrace_printf(pInfo, " -> zBuf[] = \"%s\", rc = %d\n", nErr?zErr:"", rc);
17309   return rc;
17310 }
17311 
17312 /*
17313 ** Override system calls.
17314 */
vfstraceSetSystemCall(sqlite3_vfs * pVfs,const char * zName,sqlite3_syscall_ptr pFunc)17315 static int vfstraceSetSystemCall(
17316   sqlite3_vfs *pVfs,
17317   const char *zName,
17318   sqlite3_syscall_ptr pFunc
17319 ){
17320   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17321   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17322   return pRoot->xSetSystemCall(pRoot, zName, pFunc);
17323 }
vfstraceGetSystemCall(sqlite3_vfs * pVfs,const char * zName)17324 static sqlite3_syscall_ptr vfstraceGetSystemCall(
17325   sqlite3_vfs *pVfs,
17326   const char *zName
17327 ){
17328   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17329   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17330   return pRoot->xGetSystemCall(pRoot, zName);
17331 }
vfstraceNextSystemCall(sqlite3_vfs * pVfs,const char * zName)17332 static const char *vfstraceNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
17333   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
17334   sqlite3_vfs *pRoot = pInfo->pRootVfs;
17335   return pRoot->xNextSystemCall(pRoot, zName);
17336 }
17337 
17338 
17339 /*
17340 ** Clients invoke this routine to construct a new trace-vfs shim.
17341 **
17342 ** Return SQLITE_OK on success.
17343 **
17344 ** SQLITE_NOMEM is returned in the case of a memory allocation error.
17345 ** SQLITE_NOTFOUND is returned if zOldVfsName does not exist.
17346 */
vfstrace_register(const char * zTraceName,const char * zOldVfsName,int (* xOut)(const char *,void *),void * pOutArg,int makeDefault)17347 int vfstrace_register(
17348    const char *zTraceName,           /* Name of the newly constructed VFS */
17349    const char *zOldVfsName,          /* Name of the underlying VFS */
17350    int (*xOut)(const char*,void*),   /* Output routine.  ex: fputs */
17351    void *pOutArg,                    /* 2nd argument to xOut.  ex: stderr */
17352    int makeDefault                   /* True to make the new VFS the default */
17353 ){
17354   sqlite3_vfs *pNew;
17355   sqlite3_vfs *pRoot;
17356   vfstrace_info *pInfo;
17357   size_t nName;
17358   size_t nByte;
17359 
17360   pRoot = sqlite3_vfs_find(zOldVfsName);
17361   if( pRoot==0 ) return SQLITE_NOTFOUND;
17362   nName = strlen(zTraceName);
17363   nByte = sizeof(*pNew) + sizeof(*pInfo) + nName + 1;
17364   pNew = sqlite3_malloc64( nByte );
17365   if( pNew==0 ) return SQLITE_NOMEM;
17366   memset(pNew, 0, nByte);
17367   pInfo = (vfstrace_info*)&pNew[1];
17368   pNew->iVersion = pRoot->iVersion;
17369   pNew->szOsFile = pRoot->szOsFile + sizeof(vfstrace_file);
17370   pNew->mxPathname = pRoot->mxPathname;
17371   pNew->zName = (char*)&pInfo[1];
17372   memcpy((char*)&pInfo[1], zTraceName, nName+1);
17373   pNew->pAppData = pInfo;
17374   pNew->xOpen = vfstraceOpen;
17375   pNew->xDelete = vfstraceDelete;
17376   pNew->xAccess = vfstraceAccess;
17377   pNew->xFullPathname = vfstraceFullPathname;
17378   pNew->xDlOpen = pRoot->xDlOpen==0 ? 0 : vfstraceDlOpen;
17379   pNew->xDlError = pRoot->xDlError==0 ? 0 : vfstraceDlError;
17380   pNew->xDlSym = pRoot->xDlSym==0 ? 0 : vfstraceDlSym;
17381   pNew->xDlClose = pRoot->xDlClose==0 ? 0 : vfstraceDlClose;
17382   pNew->xRandomness = vfstraceRandomness;
17383   pNew->xSleep = vfstraceSleep;
17384   pNew->xCurrentTime = vfstraceCurrentTime;
17385   pNew->xGetLastError = pRoot->xGetLastError==0 ? 0 : vfstraceGetLastError;
17386   if( pNew->iVersion>=2 ){
17387     pNew->xCurrentTimeInt64 = pRoot->xCurrentTimeInt64==0 ? 0 :
17388                                    vfstraceCurrentTimeInt64;
17389     if( pNew->iVersion>=3 ){
17390       pNew->xSetSystemCall = pRoot->xSetSystemCall==0 ? 0 :
17391                                    vfstraceSetSystemCall;
17392       pNew->xGetSystemCall = pRoot->xGetSystemCall==0 ? 0 :
17393                                    vfstraceGetSystemCall;
17394       pNew->xNextSystemCall = pRoot->xNextSystemCall==0 ? 0 :
17395                                    vfstraceNextSystemCall;
17396     }
17397   }
17398   pInfo->pRootVfs = pRoot;
17399   pInfo->xOut = xOut;
17400   pInfo->pOutArg = pOutArg;
17401   pInfo->zVfsName = pNew->zName;
17402   pInfo->pTraceVfs = pNew;
17403   pInfo->mTrace = 0xffffffff;
17404   pInfo->bOn = 1;
17405   vfstrace_printf(pInfo, "%s.enabled_for(\"%s\")\n",
17406        pInfo->zVfsName, pRoot->zName);
17407   return sqlite3_vfs_register(pNew, makeDefault);
17408 }
17409 
17410 /*
17411 ** Look for the named VFS.  If it is a TRACEVFS, then unregister it
17412 ** and delete it.
17413 */
vfstrace_unregister(const char * zTraceName)17414 void vfstrace_unregister(const char *zTraceName){
17415   sqlite3_vfs *pVfs = sqlite3_vfs_find(zTraceName);
17416   if( pVfs==0 ) return;
17417   if( pVfs->xOpen!=vfstraceOpen ) return;
17418   sqlite3_vfs_unregister(pVfs);
17419   sqlite3_free(pVfs);
17420 }
17421 
17422 /************************* End ../ext/misc/vfstrace.c ********************/
17423 
17424 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
17425 #define SQLITE_SHELL_HAVE_RECOVER 1
17426 #else
17427 #define SQLITE_SHELL_HAVE_RECOVER 0
17428 #endif
17429 #if SQLITE_SHELL_HAVE_RECOVER
17430 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
17431 /*
17432 ** 2022-08-27
17433 **
17434 ** The author disclaims copyright to this source code.  In place of
17435 ** a legal notice, here is a blessing:
17436 **
17437 **    May you do good and not evil.
17438 **    May you find forgiveness for yourself and forgive others.
17439 **    May you share freely, never taking more than you give.
17440 **
17441 *************************************************************************
17442 **
17443 ** This file contains the public interface to the "recover" extension -
17444 ** an SQLite extension designed to recover data from corrupted database
17445 ** files.
17446 */
17447 
17448 /*
17449 ** OVERVIEW:
17450 **
17451 ** To use the API to recover data from a corrupted database, an
17452 ** application:
17453 **
17454 **   1) Creates an sqlite3_recover handle by calling either
17455 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
17456 **
17457 **   2) Configures the new handle using one or more calls to
17458 **      sqlite3_recover_config().
17459 **
17460 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
17461 **      the handle until it returns something other than SQLITE_OK. If it
17462 **      returns SQLITE_DONE, then the recovery operation completed without
17463 **      error. If it returns some other non-SQLITE_OK value, then an error
17464 **      has occurred.
17465 **
17466 **   4) Retrieves any error code and English language error message using the
17467 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
17468 **      respectively.
17469 **
17470 **   5) Destroys the sqlite3_recover handle and frees all resources
17471 **      using sqlite3_recover_finish().
17472 **
17473 ** The application may abandon the recovery operation at any point
17474 ** before it is finished by passing the sqlite3_recover handle to
17475 ** sqlite3_recover_finish(). This is not an error, but the final state
17476 ** of the output database, or the results of running the partial script
17477 ** delivered to the SQL callback, are undefined.
17478 */
17479 
17480 #ifndef _SQLITE_RECOVER_H
17481 #define _SQLITE_RECOVER_H
17482 
17483 /* #include "sqlite3.h" */
17484 
17485 #ifdef __cplusplus
17486 extern "C" {
17487 #endif
17488 
17489 /*
17490 ** An instance of the sqlite3_recover object represents a recovery
17491 ** operation in progress.
17492 **
17493 ** Constructors:
17494 **
17495 **    sqlite3_recover_init()
17496 **    sqlite3_recover_init_sql()
17497 **
17498 ** Destructor:
17499 **
17500 **    sqlite3_recover_finish()
17501 **
17502 ** Methods:
17503 **
17504 **    sqlite3_recover_config()
17505 **    sqlite3_recover_errcode()
17506 **    sqlite3_recover_errmsg()
17507 **    sqlite3_recover_run()
17508 **    sqlite3_recover_step()
17509 */
17510 typedef struct sqlite3_recover sqlite3_recover;
17511 
17512 /*
17513 ** These two APIs attempt to create and return a new sqlite3_recover object.
17514 ** In both cases the first two arguments identify the (possibly
17515 ** corrupt) database to recover data from. The first argument is an open
17516 ** database handle and the second the name of a database attached to that
17517 ** handle (i.e. "main", "temp" or the name of an attached database).
17518 **
17519 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
17520 ** handle, then data is recovered into a new database, identified by
17521 ** string parameter zUri. zUri may be an absolute or relative file path,
17522 ** or may be an SQLite URI. If the identified database file already exists,
17523 ** it is overwritten.
17524 **
17525 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
17526 ** be returned to the user as a series of SQL statements. Executing these
17527 ** SQL statements results in the same database as would have been created
17528 ** had sqlite3_recover_init() been used. For each SQL statement in the
17529 ** output, the callback function passed as the third argument (xSql) is
17530 ** invoked once. The first parameter is a passed a copy of the fourth argument
17531 ** to this function (pCtx) as its first parameter, and a pointer to a
17532 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
17533 ** the second. If the xSql callback returns any value other than SQLITE_OK,
17534 ** then processing is immediately abandoned and the value returned used as
17535 ** the recover handle error code (see below).
17536 **
17537 ** If an out-of-memory error occurs, NULL may be returned instead of
17538 ** a valid handle. In all other cases, it is the responsibility of the
17539 ** application to avoid resource leaks by ensuring that
17540 ** sqlite3_recover_finish() is called on all allocated handles.
17541 */
17542 sqlite3_recover *sqlite3_recover_init(
17543   sqlite3* db,
17544   const char *zDb,
17545   const char *zUri
17546 );
17547 sqlite3_recover *sqlite3_recover_init_sql(
17548   sqlite3* db,
17549   const char *zDb,
17550   int (*xSql)(void*, const char*),
17551   void *pCtx
17552 );
17553 
17554 /*
17555 ** Configure an sqlite3_recover object that has just been created using
17556 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
17557 ** may only be called before the first call to sqlite3_recover_step()
17558 ** or sqlite3_recover_run() on the object.
17559 **
17560 ** The second argument passed to this function must be one of the
17561 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
17562 ** depend on the specific SQLITE_RECOVER_* symbol in use.
17563 **
17564 ** SQLITE_OK is returned if the configuration operation was successful,
17565 ** or an SQLite error code otherwise.
17566 */
17567 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
17568 
17569 /*
17570 ** SQLITE_RECOVER_LOST_AND_FOUND:
17571 **   The pArg argument points to a string buffer containing the name
17572 **   of a "lost-and-found" table in the output database, or NULL. If
17573 **   the argument is non-NULL and the database contains seemingly
17574 **   valid pages that cannot be associated with any table in the
17575 **   recovered part of the schema, data is extracted from these
17576 **   pages to add to the lost-and-found table.
17577 **
17578 ** SQLITE_RECOVER_FREELIST_CORRUPT:
17579 **   The pArg value must actually be a pointer to a value of type
17580 **   int containing value 0 or 1 cast as a (void*). If this option is set
17581 **   (argument is 1) and a lost-and-found table has been configured using
17582 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
17583 **   corrupt and an attempt is made to recover records from pages that
17584 **   appear to be linked into the freelist. Otherwise, pages on the freelist
17585 **   are ignored. Setting this option can recover more data from the
17586 **   database, but often ends up "recovering" deleted records. The default
17587 **   value is 0 (clear).
17588 **
17589 ** SQLITE_RECOVER_ROWIDS:
17590 **   The pArg value must actually be a pointer to a value of type
17591 **   int containing value 0 or 1 cast as a (void*). If this option is set
17592 **   (argument is 1), then an attempt is made to recover rowid values
17593 **   that are not also INTEGER PRIMARY KEY values. If this option is
17594 **   clear, then new rowids are assigned to all recovered rows. The
17595 **   default value is 1 (set).
17596 **
17597 ** SQLITE_RECOVER_SLOWINDEXES:
17598 **   The pArg value must actually be a pointer to a value of type
17599 **   int containing value 0 or 1 cast as a (void*). If this option is clear
17600 **   (argument is 0), then when creating an output database, the recover
17601 **   module creates and populates non-UNIQUE indexes right at the end of the
17602 **   recovery operation - after all recoverable data has been inserted
17603 **   into the new database. This is faster overall, but means that the
17604 **   final call to sqlite3_recover_step() for a recovery operation may
17605 **   be need to create a large number of indexes, which may be very slow.
17606 **
17607 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
17608 **   are created in the output database before it is populated with
17609 **   recovered data. This is slower overall, but avoids the slow call
17610 **   to sqlite3_recover_step() at the end of the recovery operation.
17611 **
17612 **   The default option value is 0.
17613 */
17614 #define SQLITE_RECOVER_LOST_AND_FOUND   1
17615 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
17616 #define SQLITE_RECOVER_ROWIDS           3
17617 #define SQLITE_RECOVER_SLOWINDEXES      4
17618 
17619 /*
17620 ** Perform a unit of work towards the recovery operation. This function
17621 ** must normally be called multiple times to complete database recovery.
17622 **
17623 ** If no error occurs but the recovery operation is not completed, this
17624 ** function returns SQLITE_OK. If recovery has been completed successfully
17625 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
17626 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
17627 ** considered an error if some or all of the data cannot be recovered
17628 ** due to database corruption.
17629 **
17630 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
17631 ** all further such calls on the same recover handle are no-ops that return
17632 ** the same non-SQLITE_OK value.
17633 */
17634 int sqlite3_recover_step(sqlite3_recover*);
17635 
17636 /*
17637 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
17638 ** or an SQLite error code otherwise. Calling this function is the same
17639 ** as executing:
17640 **
17641 **     while( SQLITE_OK==sqlite3_recover_step(p) );
17642 **     return sqlite3_recover_errcode(p);
17643 */
17644 int sqlite3_recover_run(sqlite3_recover*);
17645 
17646 /*
17647 ** If an error has been encountered during a prior call to
17648 ** sqlite3_recover_step(), then this function attempts to return a
17649 ** pointer to a buffer containing an English language explanation of
17650 ** the error. If no error message is available, or if an out-of memory
17651 ** error occurs while attempting to allocate a buffer in which to format
17652 ** the error message, NULL is returned.
17653 **
17654 ** The returned buffer remains valid until the sqlite3_recover handle is
17655 ** destroyed using sqlite3_recover_finish().
17656 */
17657 const char *sqlite3_recover_errmsg(sqlite3_recover*);
17658 
17659 /*
17660 ** If this function is called on an sqlite3_recover handle after
17661 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
17662 */
17663 int sqlite3_recover_errcode(sqlite3_recover*);
17664 
17665 /*
17666 ** Clean up a recovery object created by a call to sqlite3_recover_init().
17667 ** The results of using a recovery object with any API after it has been
17668 ** passed to this function are undefined.
17669 **
17670 ** This function returns the same value as sqlite3_recover_errcode().
17671 */
17672 int sqlite3_recover_finish(sqlite3_recover*);
17673 
17674 
17675 #ifdef __cplusplus
17676 }  /* end of the 'extern "C"' block */
17677 #endif
17678 
17679 #endif /* ifndef _SQLITE_RECOVER_H */
17680 
17681 /************************* End ../ext/recover/sqlite3recover.h ********************/
17682 # ifndef SQLITE_HAVE_SQLITE3R
17683 /************************* Begin ../ext/recover/dbdata.c ******************/
17684 /*
17685 ** 2019-04-17
17686 **
17687 ** The author disclaims copyright to this source code.  In place of
17688 ** a legal notice, here is a blessing:
17689 **
17690 **    May you do good and not evil.
17691 **    May you find forgiveness for yourself and forgive others.
17692 **    May you share freely, never taking more than you give.
17693 **
17694 ******************************************************************************
17695 **
17696 ** This file contains an implementation of two eponymous virtual tables,
17697 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
17698 ** "sqlite_dbpage" eponymous virtual table be available.
17699 **
17700 ** SQLITE_DBDATA:
17701 **   sqlite_dbdata is used to extract data directly from a database b-tree
17702 **   page and its associated overflow pages, bypassing the b-tree layer.
17703 **   The table schema is equivalent to:
17704 **
17705 **     CREATE TABLE sqlite_dbdata(
17706 **       pgno INTEGER,
17707 **       cell INTEGER,
17708 **       field INTEGER,
17709 **       value ANY,
17710 **       schema TEXT HIDDEN
17711 **     );
17712 **
17713 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
17714 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
17715 **   "schema".
17716 **
17717 **   Each page of the database is inspected. If it cannot be interpreted as
17718 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
17719 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
17720 **   table contains one row for each field in the record associated with
17721 **   each cell on the page. For intkey b-trees, the key value is stored in
17722 **   field -1.
17723 **
17724 **   For example, for the database:
17725 **
17726 **     CREATE TABLE t1(a, b);     -- root page is page 2
17727 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
17728 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
17729 **
17730 **   the sqlite_dbdata table contains, as well as from entries related to
17731 **   page 1, content equivalent to:
17732 **
17733 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
17734 **         (2, 0, -1, 5     ),
17735 **         (2, 0,  0, 'v'   ),
17736 **         (2, 0,  1, 'five'),
17737 **         (2, 1, -1, 10    ),
17738 **         (2, 1,  0, 'x'   ),
17739 **         (2, 1,  1, 'ten' );
17740 **
17741 **   If database corruption is encountered, this module does not report an
17742 **   error. Instead, it attempts to extract as much data as possible and
17743 **   ignores the corruption.
17744 **
17745 ** SQLITE_DBPTR:
17746 **   The sqlite_dbptr table has the following schema:
17747 **
17748 **     CREATE TABLE sqlite_dbptr(
17749 **       pgno INTEGER,
17750 **       child INTEGER,
17751 **       schema TEXT HIDDEN
17752 **     );
17753 **
17754 **   It contains one entry for each b-tree pointer between a parent and
17755 **   child page in the database.
17756 */
17757 
17758 #if !defined(SQLITEINT_H)
17759 /* #include "sqlite3.h" */
17760 
17761 /* typedef unsigned char u8; */
17762 /* typedef unsigned int u32; */
17763 
17764 #endif
17765 #include <string.h>
17766 #include <assert.h>
17767 
17768 #ifndef SQLITE_OMIT_VIRTUALTABLE
17769 
17770 #define DBDATA_PADDING_BYTES 100
17771 
17772 typedef struct DbdataTable DbdataTable;
17773 typedef struct DbdataCursor DbdataCursor;
17774 typedef struct DbdataBuffer DbdataBuffer;
17775 
17776 /*
17777 ** Buffer type.
17778 */
17779 struct DbdataBuffer {
17780   u8 *aBuf;
17781   sqlite3_int64 nBuf;
17782 };
17783 
17784 /* Cursor object */
17785 struct DbdataCursor {
17786   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
17787   sqlite3_stmt *pStmt;            /* For fetching database pages */
17788 
17789   int iPgno;                      /* Current page number */
17790   u8 *aPage;                      /* Buffer containing page */
17791   int nPage;                      /* Size of aPage[] in bytes */
17792   int nCell;                      /* Number of cells on aPage[] */
17793   int iCell;                      /* Current cell number */
17794   int bOnePage;                   /* True to stop after one page */
17795   int szDb;
17796   sqlite3_int64 iRowid;
17797 
17798   /* Only for the sqlite_dbdata table */
17799   DbdataBuffer rec;
17800   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
17801   sqlite3_int64 nHdr;             /* Size of header in bytes */
17802   int iField;                     /* Current field number */
17803   u8 *pHdrPtr;
17804   u8 *pPtr;
17805   u32 enc;                        /* Text encoding */
17806 
17807   sqlite3_int64 iIntkey;          /* Integer key value */
17808 };
17809 
17810 /* Table object */
17811 struct DbdataTable {
17812   sqlite3_vtab base;              /* Base class.  Must be first */
17813   sqlite3 *db;                    /* The database connection */
17814   sqlite3_stmt *pStmt;            /* For fetching database pages */
17815   int bPtr;                       /* True for sqlite3_dbptr table */
17816 };
17817 
17818 /* Column and schema definitions for sqlite_dbdata */
17819 #define DBDATA_COLUMN_PGNO        0
17820 #define DBDATA_COLUMN_CELL        1
17821 #define DBDATA_COLUMN_FIELD       2
17822 #define DBDATA_COLUMN_VALUE       3
17823 #define DBDATA_COLUMN_SCHEMA      4
17824 #define DBDATA_SCHEMA             \
17825       "CREATE TABLE x("           \
17826       "  pgno INTEGER,"           \
17827       "  cell INTEGER,"           \
17828       "  field INTEGER,"          \
17829       "  value ANY,"              \
17830       "  schema TEXT HIDDEN"      \
17831       ")"
17832 
17833 /* Column and schema definitions for sqlite_dbptr */
17834 #define DBPTR_COLUMN_PGNO         0
17835 #define DBPTR_COLUMN_CHILD        1
17836 #define DBPTR_COLUMN_SCHEMA       2
17837 #define DBPTR_SCHEMA              \
17838       "CREATE TABLE x("           \
17839       "  pgno INTEGER,"           \
17840       "  child INTEGER,"          \
17841       "  schema TEXT HIDDEN"      \
17842       ")"
17843 
17844 /*
17845 ** Ensure the buffer passed as the first argument is at least nMin bytes
17846 ** in size. If an error occurs while attempting to resize the buffer,
17847 ** SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
17848 */
dbdataBufferSize(DbdataBuffer * pBuf,sqlite3_int64 nMin)17849 static int dbdataBufferSize(DbdataBuffer *pBuf, sqlite3_int64 nMin){
17850   if( nMin>pBuf->nBuf ){
17851     sqlite3_int64 nNew = nMin+16384;
17852     u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew);
17853 
17854     if( aNew==0 ) return SQLITE_NOMEM;
17855     pBuf->aBuf = aNew;
17856     pBuf->nBuf = nNew;
17857   }
17858   return SQLITE_OK;
17859 }
17860 
17861 /*
17862 ** Release the allocation managed by buffer pBuf.
17863 */
dbdataBufferFree(DbdataBuffer * pBuf)17864 static void dbdataBufferFree(DbdataBuffer *pBuf){
17865   sqlite3_free(pBuf->aBuf);
17866   memset(pBuf, 0, sizeof(*pBuf));
17867 }
17868 
17869 /*
17870 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
17871 ** table.
17872 */
dbdataConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)17873 static int dbdataConnect(
17874   sqlite3 *db,
17875   void *pAux,
17876   int argc, const char *const*argv,
17877   sqlite3_vtab **ppVtab,
17878   char **pzErr
17879 ){
17880   DbdataTable *pTab = 0;
17881   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
17882 
17883   (void)argc;
17884   (void)argv;
17885   (void)pzErr;
17886   sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
17887   if( rc==SQLITE_OK ){
17888     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
17889     if( pTab==0 ){
17890       rc = SQLITE_NOMEM;
17891     }else{
17892       memset(pTab, 0, sizeof(DbdataTable));
17893       pTab->db = db;
17894       pTab->bPtr = (pAux!=0);
17895     }
17896   }
17897 
17898   *ppVtab = (sqlite3_vtab*)pTab;
17899   return rc;
17900 }
17901 
17902 /*
17903 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
17904 */
dbdataDisconnect(sqlite3_vtab * pVtab)17905 static int dbdataDisconnect(sqlite3_vtab *pVtab){
17906   DbdataTable *pTab = (DbdataTable*)pVtab;
17907   if( pTab ){
17908     sqlite3_finalize(pTab->pStmt);
17909     sqlite3_free(pVtab);
17910   }
17911   return SQLITE_OK;
17912 }
17913 
17914 /*
17915 ** This function interprets two types of constraints:
17916 **
17917 **       schema=?
17918 **       pgno=?
17919 **
17920 ** If neither are present, idxNum is set to 0. If schema=? is present,
17921 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
17922 ** in idxNum is set.
17923 **
17924 ** If both parameters are present, schema is in position 0 and pgno in
17925 ** position 1.
17926 */
dbdataBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdx)17927 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
17928   DbdataTable *pTab = (DbdataTable*)tab;
17929   int i;
17930   int iSchema = -1;
17931   int iPgno = -1;
17932   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
17933 
17934   for(i=0; i<pIdx->nConstraint; i++){
17935     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
17936     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
17937       if( p->iColumn==colSchema ){
17938         if( p->usable==0 ) return SQLITE_CONSTRAINT;
17939         iSchema = i;
17940       }
17941       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
17942         iPgno = i;
17943       }
17944     }
17945   }
17946 
17947   if( iSchema>=0 ){
17948     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
17949     pIdx->aConstraintUsage[iSchema].omit = 1;
17950   }
17951   if( iPgno>=0 ){
17952     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
17953     pIdx->aConstraintUsage[iPgno].omit = 1;
17954     pIdx->estimatedCost = 100;
17955     pIdx->estimatedRows =  50;
17956 
17957     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
17958       int iCol = pIdx->aOrderBy[0].iColumn;
17959       if( pIdx->nOrderBy==1 ){
17960         pIdx->orderByConsumed = (iCol==0 || iCol==1);
17961       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
17962         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
17963       }
17964     }
17965 
17966   }else{
17967     pIdx->estimatedCost = 100000000;
17968     pIdx->estimatedRows = 1000000000;
17969   }
17970   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
17971   return SQLITE_OK;
17972 }
17973 
17974 /*
17975 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
17976 */
dbdataOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)17977 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
17978   DbdataCursor *pCsr;
17979 
17980   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
17981   if( pCsr==0 ){
17982     return SQLITE_NOMEM;
17983   }else{
17984     memset(pCsr, 0, sizeof(DbdataCursor));
17985     pCsr->base.pVtab = pVTab;
17986   }
17987 
17988   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
17989   return SQLITE_OK;
17990 }
17991 
17992 /*
17993 ** Restore a cursor object to the state it was in when first allocated
17994 ** by dbdataOpen().
17995 */
dbdataResetCursor(DbdataCursor * pCsr)17996 static void dbdataResetCursor(DbdataCursor *pCsr){
17997   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
17998   if( pTab->pStmt==0 ){
17999     pTab->pStmt = pCsr->pStmt;
18000   }else{
18001     sqlite3_finalize(pCsr->pStmt);
18002   }
18003   pCsr->pStmt = 0;
18004   pCsr->iPgno = 1;
18005   pCsr->iCell = 0;
18006   pCsr->iField = 0;
18007   pCsr->bOnePage = 0;
18008   sqlite3_free(pCsr->aPage);
18009   dbdataBufferFree(&pCsr->rec);
18010   pCsr->aPage = 0;
18011   pCsr->nRec = 0;
18012 }
18013 
18014 /*
18015 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
18016 */
dbdataClose(sqlite3_vtab_cursor * pCursor)18017 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
18018   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
18019   dbdataResetCursor(pCsr);
18020   sqlite3_free(pCsr);
18021   return SQLITE_OK;
18022 }
18023 
18024 /*
18025 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
18026 */
get_uint16(unsigned char * a)18027 static u32 get_uint16(unsigned char *a){
18028   return (a[0]<<8)|a[1];
18029 }
get_uint32(unsigned char * a)18030 static u32 get_uint32(unsigned char *a){
18031   return ((u32)a[0]<<24)
18032        | ((u32)a[1]<<16)
18033        | ((u32)a[2]<<8)
18034        | ((u32)a[3]);
18035 }
18036 
18037 /*
18038 ** Load page pgno from the database via the sqlite_dbpage virtual table.
18039 ** If successful, set (*ppPage) to point to a buffer containing the page
18040 ** data, (*pnPage) to the size of that buffer in bytes and return
18041 ** SQLITE_OK. In this case it is the responsibility of the caller to
18042 ** eventually free the buffer using sqlite3_free().
18043 **
18044 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
18045 ** return an SQLite error code.
18046 */
dbdataLoadPage(DbdataCursor * pCsr,u32 pgno,u8 ** ppPage,int * pnPage)18047 static int dbdataLoadPage(
18048   DbdataCursor *pCsr,             /* Cursor object */
18049   u32 pgno,                       /* Page number of page to load */
18050   u8 **ppPage,                    /* OUT: pointer to page buffer */
18051   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
18052 ){
18053   int rc2;
18054   int rc = SQLITE_OK;
18055   sqlite3_stmt *pStmt = pCsr->pStmt;
18056 
18057   *ppPage = 0;
18058   *pnPage = 0;
18059   if( pgno>0 ){
18060     sqlite3_bind_int64(pStmt, 2, pgno);
18061     if( SQLITE_ROW==sqlite3_step(pStmt) ){
18062       int nCopy = sqlite3_column_bytes(pStmt, 0);
18063       if( nCopy>0 ){
18064         u8 *pPage;
18065         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
18066         if( pPage==0 ){
18067           rc = SQLITE_NOMEM;
18068         }else{
18069           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
18070           memcpy(pPage, pCopy, nCopy);
18071           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
18072         }
18073         *ppPage = pPage;
18074         *pnPage = nCopy;
18075       }
18076     }
18077     rc2 = sqlite3_reset(pStmt);
18078     if( rc==SQLITE_OK ) rc = rc2;
18079   }
18080 
18081   return rc;
18082 }
18083 
18084 /*
18085 ** Read a varint.  Put the value in *pVal and return the number of bytes.
18086 */
dbdataGetVarint(const u8 * z,sqlite3_int64 * pVal)18087 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
18088   sqlite3_uint64 u = 0;
18089   int i;
18090   for(i=0; i<8; i++){
18091     u = (u<<7) + (z[i]&0x7f);
18092     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
18093   }
18094   u = (u<<8) + (z[i]&0xff);
18095   *pVal = (sqlite3_int64)u;
18096   return 9;
18097 }
18098 
18099 /*
18100 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
18101 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
18102 ** SQLite database except for key values in intkey tables.
18103 */
dbdataGetVarintU32(const u8 * z,sqlite3_int64 * pVal)18104 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
18105   sqlite3_int64 val;
18106   int nRet = dbdataGetVarint(z, &val);
18107   if( val<0 || val>0xFFFFFFFF ) val = 0;
18108   *pVal = val;
18109   return nRet;
18110 }
18111 
18112 /*
18113 ** Return the number of bytes of space used by an SQLite value of type
18114 ** eType.
18115 */
dbdataValueBytes(int eType)18116 static int dbdataValueBytes(int eType){
18117   switch( eType ){
18118     case 0: case 8: case 9:
18119     case 10: case 11:
18120       return 0;
18121     case 1:
18122       return 1;
18123     case 2:
18124       return 2;
18125     case 3:
18126       return 3;
18127     case 4:
18128       return 4;
18129     case 5:
18130       return 6;
18131     case 6:
18132     case 7:
18133       return 8;
18134     default:
18135       if( eType>0 ){
18136         return ((eType-12) / 2);
18137       }
18138       return 0;
18139   }
18140 }
18141 
18142 /*
18143 ** Load a value of type eType from buffer pData and use it to set the
18144 ** result of context object pCtx.
18145 */
dbdataValue(sqlite3_context * pCtx,u32 enc,int eType,u8 * pData,sqlite3_int64 nData)18146 static void dbdataValue(
18147   sqlite3_context *pCtx,
18148   u32 enc,
18149   int eType,
18150   u8 *pData,
18151   sqlite3_int64 nData
18152 ){
18153   if( eType>=0 ){
18154     if( dbdataValueBytes(eType)<=nData ){
18155       switch( eType ){
18156         case 0:
18157         case 10:
18158         case 11:
18159           sqlite3_result_null(pCtx);
18160           break;
18161 
18162         case 8:
18163           sqlite3_result_int(pCtx, 0);
18164           break;
18165         case 9:
18166           sqlite3_result_int(pCtx, 1);
18167           break;
18168 
18169         case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
18170           sqlite3_uint64 v = (signed char)pData[0];
18171           pData++;
18172           switch( eType ){
18173             case 7:
18174             case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
18175             case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
18176             case 4:  v = (v<<8) + pData[0];  pData++;
18177             case 3:  v = (v<<8) + pData[0];  pData++;
18178             case 2:  v = (v<<8) + pData[0];  pData++;
18179           }
18180 
18181           if( eType==7 ){
18182             double r;
18183             memcpy(&r, &v, sizeof(r));
18184             sqlite3_result_double(pCtx, r);
18185           }else{
18186             sqlite3_result_int64(pCtx, (sqlite3_int64)v);
18187           }
18188           break;
18189         }
18190 
18191         default: {
18192           int n = ((eType-12) / 2);
18193           if( eType % 2 ){
18194             switch( enc ){
18195   #ifndef SQLITE_OMIT_UTF16
18196               case SQLITE_UTF16BE:
18197                 sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
18198                 break;
18199               case SQLITE_UTF16LE:
18200                 sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
18201                 break;
18202   #endif
18203               default:
18204                 sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
18205                 break;
18206             }
18207           }else{
18208             sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
18209           }
18210         }
18211       }
18212     }else{
18213       if( eType==7 ){
18214         sqlite3_result_double(pCtx, 0.0);
18215       }else if( eType<7 ){
18216         sqlite3_result_int(pCtx, 0);
18217       }else if( eType%2 ){
18218         sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
18219       }else{
18220         sqlite3_result_blob(pCtx, "", 0, SQLITE_STATIC);
18221       }
18222     }
18223   }
18224 }
18225 
18226 /* This macro is a copy of the MX_CELL() macro in the SQLite core. Given
18227 ** a page-size, it returns the maximum number of cells that may be present
18228 ** on the page.  */
18229 #define DBDATA_MX_CELL(pgsz) ((pgsz-8)/6)
18230 
18231 /* Maximum number of fields that may appear in a single record. This is
18232 ** the "hard-limit", according to comments in sqliteLimit.h. */
18233 #define DBDATA_MX_FIELD 32676
18234 
18235 /*
18236 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
18237 */
dbdataNext(sqlite3_vtab_cursor * pCursor)18238 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
18239   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
18240   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
18241 
18242   pCsr->iRowid++;
18243   while( 1 ){
18244     int rc;
18245     int iOff = (pCsr->iPgno==1 ? 100 : 0);
18246     int bNextPage = 0;
18247 
18248     if( pCsr->aPage==0 ){
18249       while( 1 ){
18250         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
18251         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
18252         if( rc!=SQLITE_OK ) return rc;
18253         if( pCsr->aPage && pCsr->nPage>=256 ) break;
18254         sqlite3_free(pCsr->aPage);
18255         pCsr->aPage = 0;
18256         if( pCsr->bOnePage ) return SQLITE_OK;
18257         pCsr->iPgno++;
18258       }
18259 
18260       assert( iOff+3+2<=pCsr->nPage );
18261       pCsr->iCell = pTab->bPtr ? -2 : 0;
18262       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
18263       if( pCsr->nCell>DBDATA_MX_CELL(pCsr->nPage) ){
18264         pCsr->nCell = DBDATA_MX_CELL(pCsr->nPage);
18265       }
18266     }
18267 
18268     if( pTab->bPtr ){
18269       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
18270         pCsr->iCell = pCsr->nCell;
18271       }
18272       pCsr->iCell++;
18273       if( pCsr->iCell>=pCsr->nCell ){
18274         sqlite3_free(pCsr->aPage);
18275         pCsr->aPage = 0;
18276         if( pCsr->bOnePage ) return SQLITE_OK;
18277         pCsr->iPgno++;
18278       }else{
18279         return SQLITE_OK;
18280       }
18281     }else{
18282       /* If there is no record loaded, load it now. */
18283       assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 );
18284       if( pCsr->nRec==0 ){
18285         int bHasRowid = 0;
18286         int nPointer = 0;
18287         sqlite3_int64 nPayload = 0;
18288         sqlite3_int64 nHdr = 0;
18289         int iHdr;
18290         int U, X;
18291         int nLocal;
18292 
18293         switch( pCsr->aPage[iOff] ){
18294           case 0x02:
18295             nPointer = 4;
18296             break;
18297           case 0x0a:
18298             break;
18299           case 0x0d:
18300             bHasRowid = 1;
18301             break;
18302           default:
18303             /* This is not a b-tree page with records on it. Continue. */
18304             pCsr->iCell = pCsr->nCell;
18305             break;
18306         }
18307 
18308         if( pCsr->iCell>=pCsr->nCell ){
18309           bNextPage = 1;
18310         }else{
18311           int iCellPtr = iOff + 8 + nPointer + pCsr->iCell*2;
18312 
18313           if( iCellPtr>pCsr->nPage ){
18314             bNextPage = 1;
18315           }else{
18316             iOff = get_uint16(&pCsr->aPage[iCellPtr]);
18317           }
18318 
18319           /* For an interior node cell, skip past the child-page number */
18320           iOff += nPointer;
18321 
18322           /* Load the "byte of payload including overflow" field */
18323           if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){
18324             bNextPage = 1;
18325           }else{
18326             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
18327             if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
18328             if( nPayload==0 ) nPayload = 1;
18329           }
18330 
18331           /* If this is a leaf intkey cell, load the rowid */
18332           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
18333             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
18334           }
18335 
18336           /* Figure out how much data to read from the local page */
18337           U = pCsr->nPage;
18338           if( bHasRowid ){
18339             X = U-35;
18340           }else{
18341             X = ((U-12)*64/255)-23;
18342           }
18343           if( nPayload<=X ){
18344             nLocal = nPayload;
18345           }else{
18346             int M, K;
18347             M = ((U-12)*32/255)-23;
18348             K = M+((nPayload-M)%(U-4));
18349             if( K<=X ){
18350               nLocal = K;
18351             }else{
18352               nLocal = M;
18353             }
18354           }
18355 
18356           if( bNextPage || nLocal+iOff>pCsr->nPage ){
18357             bNextPage = 1;
18358           }else{
18359 
18360             /* Allocate space for payload. And a bit more to catch small buffer
18361             ** overruns caused by attempting to read a varint or similar from
18362             ** near the end of a corrupt record.  */
18363             rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES);
18364             if( rc!=SQLITE_OK ) return rc;
18365             assert( pCsr->rec.aBuf!=0 );
18366             assert( nPayload!=0 );
18367 
18368             /* Load the nLocal bytes of payload */
18369             memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal);
18370             iOff += nLocal;
18371 
18372             /* Load content from overflow pages */
18373             if( nPayload>nLocal ){
18374               sqlite3_int64 nRem = nPayload - nLocal;
18375               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
18376               while( nRem>0 ){
18377                 u8 *aOvfl = 0;
18378                 int nOvfl = 0;
18379                 int nCopy;
18380                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
18381                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
18382                 if( rc!=SQLITE_OK ) return rc;
18383                 if( aOvfl==0 ) break;
18384 
18385                 nCopy = U-4;
18386                 if( nCopy>nRem ) nCopy = nRem;
18387                 memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy);
18388                 nRem -= nCopy;
18389 
18390                 pgnoOvfl = get_uint32(aOvfl);
18391                 sqlite3_free(aOvfl);
18392               }
18393               nPayload -= nRem;
18394             }
18395             memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES);
18396             pCsr->nRec = nPayload;
18397 
18398             iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr);
18399             if( nHdr>nPayload ) nHdr = 0;
18400             pCsr->nHdr = nHdr;
18401             pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr];
18402             pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr];
18403             pCsr->iField = (bHasRowid ? -1 : 0);
18404           }
18405         }
18406       }else{
18407         pCsr->iField++;
18408         if( pCsr->iField>0 ){
18409           sqlite3_int64 iType;
18410           if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec]
18411            || pCsr->iField>=DBDATA_MX_FIELD
18412           ){
18413             bNextPage = 1;
18414           }else{
18415             int szField = 0;
18416             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
18417             szField = dbdataValueBytes(iType);
18418             if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))<szField ){
18419               pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nRec];
18420             }else{
18421               pCsr->pPtr += szField;
18422             }
18423           }
18424         }
18425       }
18426 
18427       if( bNextPage ){
18428         sqlite3_free(pCsr->aPage);
18429         pCsr->aPage = 0;
18430         pCsr->nRec = 0;
18431         if( pCsr->bOnePage ) return SQLITE_OK;
18432         pCsr->iPgno++;
18433       }else{
18434         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){
18435           return SQLITE_OK;
18436         }
18437 
18438         /* Advance to the next cell. The next iteration of the loop will load
18439         ** the record and so on. */
18440         pCsr->nRec = 0;
18441         pCsr->iCell++;
18442       }
18443     }
18444   }
18445 
18446   assert( !"can't get here" );
18447   return SQLITE_OK;
18448 }
18449 
18450 /*
18451 ** Return true if the cursor is at EOF.
18452 */
dbdataEof(sqlite3_vtab_cursor * pCursor)18453 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
18454   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
18455   return pCsr->aPage==0;
18456 }
18457 
18458 /*
18459 ** Return true if nul-terminated string zSchema ends in "()". Or false
18460 ** otherwise.
18461 */
dbdataIsFunction(const char * zSchema)18462 static int dbdataIsFunction(const char *zSchema){
18463   size_t n = strlen(zSchema);
18464   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
18465     return (int)n-2;
18466   }
18467   return 0;
18468 }
18469 
18470 /*
18471 ** Determine the size in pages of database zSchema (where zSchema is
18472 ** "main", "temp" or the name of an attached database) and set
18473 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
18474 ** an SQLite error code.
18475 */
dbdataDbsize(DbdataCursor * pCsr,const char * zSchema)18476 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
18477   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
18478   char *zSql = 0;
18479   int rc, rc2;
18480   int nFunc = 0;
18481   sqlite3_stmt *pStmt = 0;
18482 
18483   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
18484     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
18485   }else{
18486     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
18487   }
18488   if( zSql==0 ) return SQLITE_NOMEM;
18489 
18490   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
18491   sqlite3_free(zSql);
18492   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
18493     pCsr->szDb = sqlite3_column_int(pStmt, 0);
18494   }
18495   rc2 = sqlite3_finalize(pStmt);
18496   if( rc==SQLITE_OK ) rc = rc2;
18497   return rc;
18498 }
18499 
18500 /*
18501 ** Attempt to figure out the encoding of the database by retrieving page 1
18502 ** and inspecting the header field. If successful, set the pCsr->enc variable
18503 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
18504 */
dbdataGetEncoding(DbdataCursor * pCsr)18505 static int dbdataGetEncoding(DbdataCursor *pCsr){
18506   int rc = SQLITE_OK;
18507   int nPg1 = 0;
18508   u8 *aPg1 = 0;
18509   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
18510   if( rc==SQLITE_OK && nPg1>=(56+4) ){
18511     pCsr->enc = get_uint32(&aPg1[56]);
18512   }
18513   sqlite3_free(aPg1);
18514   return rc;
18515 }
18516 
18517 
18518 /*
18519 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
18520 */
dbdataFilter(sqlite3_vtab_cursor * pCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)18521 static int dbdataFilter(
18522   sqlite3_vtab_cursor *pCursor,
18523   int idxNum, const char *idxStr,
18524   int argc, sqlite3_value **argv
18525 ){
18526   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
18527   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
18528   int rc = SQLITE_OK;
18529   const char *zSchema = "main";
18530   (void)idxStr;
18531   (void)argc;
18532 
18533   dbdataResetCursor(pCsr);
18534   assert( pCsr->iPgno==1 );
18535   if( idxNum & 0x01 ){
18536     zSchema = (const char*)sqlite3_value_text(argv[0]);
18537     if( zSchema==0 ) zSchema = "";
18538   }
18539   if( idxNum & 0x02 ){
18540     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
18541     pCsr->bOnePage = 1;
18542   }else{
18543     rc = dbdataDbsize(pCsr, zSchema);
18544   }
18545 
18546   if( rc==SQLITE_OK ){
18547     int nFunc = 0;
18548     if( pTab->pStmt ){
18549       pCsr->pStmt = pTab->pStmt;
18550       pTab->pStmt = 0;
18551     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
18552       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
18553       if( zSql==0 ){
18554         rc = SQLITE_NOMEM;
18555       }else{
18556         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
18557         sqlite3_free(zSql);
18558       }
18559     }else{
18560       rc = sqlite3_prepare_v2(pTab->db,
18561           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
18562           &pCsr->pStmt, 0
18563       );
18564     }
18565   }
18566   if( rc==SQLITE_OK ){
18567     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
18568   }
18569 
18570   /* Try to determine the encoding of the db by inspecting the header
18571   ** field on page 1. */
18572   if( rc==SQLITE_OK ){
18573     rc = dbdataGetEncoding(pCsr);
18574   }
18575 
18576   if( rc!=SQLITE_OK ){
18577     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
18578   }
18579 
18580   if( rc==SQLITE_OK ){
18581     rc = dbdataNext(pCursor);
18582   }
18583   return rc;
18584 }
18585 
18586 /*
18587 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
18588 */
dbdataColumn(sqlite3_vtab_cursor * pCursor,sqlite3_context * ctx,int i)18589 static int dbdataColumn(
18590   sqlite3_vtab_cursor *pCursor,
18591   sqlite3_context *ctx,
18592   int i
18593 ){
18594   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
18595   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
18596   if( pTab->bPtr ){
18597     switch( i ){
18598       case DBPTR_COLUMN_PGNO:
18599         sqlite3_result_int64(ctx, pCsr->iPgno);
18600         break;
18601       case DBPTR_COLUMN_CHILD: {
18602         int iOff = pCsr->iPgno==1 ? 100 : 0;
18603         if( pCsr->iCell<0 ){
18604           iOff += 8;
18605         }else{
18606           iOff += 12 + pCsr->iCell*2;
18607           if( iOff>pCsr->nPage ) return SQLITE_OK;
18608           iOff = get_uint16(&pCsr->aPage[iOff]);
18609         }
18610         if( iOff<=pCsr->nPage ){
18611           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
18612         }
18613         break;
18614       }
18615     }
18616   }else{
18617     switch( i ){
18618       case DBDATA_COLUMN_PGNO:
18619         sqlite3_result_int64(ctx, pCsr->iPgno);
18620         break;
18621       case DBDATA_COLUMN_CELL:
18622         sqlite3_result_int(ctx, pCsr->iCell);
18623         break;
18624       case DBDATA_COLUMN_FIELD:
18625         sqlite3_result_int(ctx, pCsr->iField);
18626         break;
18627       case DBDATA_COLUMN_VALUE: {
18628         if( pCsr->iField<0 ){
18629           sqlite3_result_int64(ctx, pCsr->iIntkey);
18630         }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){
18631           sqlite3_int64 iType;
18632           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
18633           dbdataValue(
18634               ctx, pCsr->enc, iType, pCsr->pPtr,
18635               &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr
18636           );
18637         }
18638         break;
18639       }
18640     }
18641   }
18642   return SQLITE_OK;
18643 }
18644 
18645 /*
18646 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
18647 */
dbdataRowid(sqlite3_vtab_cursor * pCursor,sqlite_int64 * pRowid)18648 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
18649   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
18650   *pRowid = pCsr->iRowid;
18651   return SQLITE_OK;
18652 }
18653 
18654 
18655 /*
18656 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
18657 */
sqlite3DbdataRegister(sqlite3 * db)18658 static int sqlite3DbdataRegister(sqlite3 *db){
18659   static sqlite3_module dbdata_module = {
18660     0,                            /* iVersion */
18661     0,                            /* xCreate */
18662     dbdataConnect,                /* xConnect */
18663     dbdataBestIndex,              /* xBestIndex */
18664     dbdataDisconnect,             /* xDisconnect */
18665     0,                            /* xDestroy */
18666     dbdataOpen,                   /* xOpen - open a cursor */
18667     dbdataClose,                  /* xClose - close a cursor */
18668     dbdataFilter,                 /* xFilter - configure scan constraints */
18669     dbdataNext,                   /* xNext - advance a cursor */
18670     dbdataEof,                    /* xEof - check for end of scan */
18671     dbdataColumn,                 /* xColumn - read data */
18672     dbdataRowid,                  /* xRowid - read data */
18673     0,                            /* xUpdate */
18674     0,                            /* xBegin */
18675     0,                            /* xSync */
18676     0,                            /* xCommit */
18677     0,                            /* xRollback */
18678     0,                            /* xFindMethod */
18679     0,                            /* xRename */
18680     0,                            /* xSavepoint */
18681     0,                            /* xRelease */
18682     0,                            /* xRollbackTo */
18683     0,                            /* xShadowName */
18684     0                             /* xIntegrity */
18685   };
18686 
18687   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
18688   if( rc==SQLITE_OK ){
18689     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
18690   }
18691   return rc;
18692 }
18693 
18694 #ifdef _WIN32
18695 
18696 #endif
sqlite3_dbdata_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)18697 int sqlite3_dbdata_init(
18698   sqlite3 *db,
18699   char **pzErrMsg,
18700   const sqlite3_api_routines *pApi
18701 ){
18702   (void)pzErrMsg;
18703   return sqlite3DbdataRegister(db);
18704 }
18705 
18706 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
18707 
18708 /************************* End ../ext/recover/dbdata.c ********************/
18709 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
18710 /*
18711 ** 2022-08-27
18712 **
18713 ** The author disclaims copyright to this source code.  In place of
18714 ** a legal notice, here is a blessing:
18715 **
18716 **    May you do good and not evil.
18717 **    May you find forgiveness for yourself and forgive others.
18718 **    May you share freely, never taking more than you give.
18719 **
18720 *************************************************************************
18721 **
18722 */
18723 
18724 
18725 /* #include "sqlite3recover.h" */
18726 #include <assert.h>
18727 #include <string.h>
18728 
18729 #ifndef SQLITE_OMIT_VIRTUALTABLE
18730 
18731 /*
18732 ** Declaration for public API function in file dbdata.c. This may be called
18733 ** with NULL as the final two arguments to register the sqlite_dbptr and
18734 ** sqlite_dbdata virtual tables with a database handle.
18735 */
18736 #ifdef _WIN32
18737 
18738 #endif
18739 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
18740 
18741 /* typedef unsigned int u32; */
18742 /* typedef unsigned char u8; */
18743 /* typedef sqlite3_int64 i64; */
18744 
18745 /*
18746 ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
18747 ** to avoid complaints from -fsanitize=strict-bounds.
18748 */
18749 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
18750 # define FLEXARRAY
18751 #else
18752 # define FLEXARRAY 1
18753 #endif
18754 
18755 typedef struct RecoverTable RecoverTable;
18756 typedef struct RecoverColumn RecoverColumn;
18757 
18758 /*
18759 ** When recovering rows of data that can be associated with table
18760 ** definitions recovered from the sqlite_schema table, each table is
18761 ** represented by an instance of the following object.
18762 **
18763 ** iRoot:
18764 **   The root page in the original database. Not necessarily (and usually
18765 **   not) the same in the recovered database.
18766 **
18767 ** zTab:
18768 **   Name of the table.
18769 **
18770 ** nCol/aCol[]:
18771 **   aCol[] is an array of nCol columns. In the order in which they appear
18772 **   in the table.
18773 **
18774 ** bIntkey:
18775 **   Set to true for intkey tables, false for WITHOUT ROWID.
18776 **
18777 ** iRowidBind:
18778 **   Each column in the aCol[] array has associated with it the index of
18779 **   the bind parameter its values will be bound to in the INSERT statement
18780 **   used to construct the output database. If the table does has a rowid
18781 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
18782 **   index of the bind paramater to which the rowid value should be bound.
18783 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
18784 **   KEY column, then the rowid value should be bound to the index associated
18785 **   with the column.
18786 **
18787 ** pNext:
18788 **   All RecoverTable objects used by the recovery operation are allocated
18789 **   and populated as part of creating the recovered database schema in
18790 **   the output database, before any non-schema data are recovered. They
18791 **   are then stored in a singly-linked list linked by this variable beginning
18792 **   at sqlite3_recover.pTblList.
18793 */
18794 struct RecoverTable {
18795   u32 iRoot;                      /* Root page in original database */
18796   char *zTab;                     /* Name of table */
18797   int nCol;                       /* Number of columns in table */
18798   RecoverColumn *aCol;            /* Array of columns */
18799   int bIntkey;                    /* True for intkey, false for without rowid */
18800   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
18801   RecoverTable *pNext;
18802 };
18803 
18804 /*
18805 ** Each database column is represented by an instance of the following object
18806 ** stored in the RecoverTable.aCol[] array of the associated table.
18807 **
18808 ** iField:
18809 **   The index of the associated field within database records. Or -1 if
18810 **   there is no associated field (e.g. for virtual generated columns).
18811 **
18812 ** iBind:
18813 **   The bind index of the INSERT statement to bind this columns values
18814 **   to. Or 0 if there is no such index (iff (iField<0)).
18815 **
18816 ** bIPK:
18817 **   True if this is the INTEGER PRIMARY KEY column.
18818 **
18819 ** zCol:
18820 **   Name of column.
18821 **
18822 ** eHidden:
18823 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
18824 */
18825 struct RecoverColumn {
18826   int iField;                     /* Field in record on disk */
18827   int iBind;                      /* Binding to use in INSERT */
18828   int bIPK;                       /* True for IPK column */
18829   char *zCol;
18830   int eHidden;
18831 };
18832 
18833 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
18834 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
18835 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
18836 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
18837 
18838 /*
18839 ** Bitmap object used to track pages in the input database. Allocated
18840 ** and manipulated only by the following functions:
18841 **
18842 **     recoverBitmapAlloc()
18843 **     recoverBitmapFree()
18844 **     recoverBitmapSet()
18845 **     recoverBitmapQuery()
18846 **
18847 ** nPg:
18848 **   Largest page number that may be stored in the bitmap. The range
18849 **   of valid keys is 1 to nPg, inclusive.
18850 **
18851 ** aElem[]:
18852 **   Array large enough to contain a bit for each key. For key value
18853 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
18854 **   In other words, the following is true if bit iKey is set, or
18855 **   false if it is clear:
18856 **
18857 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
18858 */
18859 typedef struct RecoverBitmap RecoverBitmap;
18860 struct RecoverBitmap {
18861   i64 nPg;                        /* Size of bitmap */
18862   u32 aElem[FLEXARRAY];           /* Array of 32-bit bitmasks */
18863 };
18864 
18865 /* Size in bytes of a RecoverBitmap object sufficient to cover 32 pages */
18866 #define SZ_RECOVERBITMAP_32  (16)
18867 
18868 /*
18869 ** State variables (part of the sqlite3_recover structure) used while
18870 ** recovering data for tables identified in the recovered schema (state
18871 ** RECOVER_STATE_WRITING).
18872 */
18873 typedef struct RecoverStateW1 RecoverStateW1;
18874 struct RecoverStateW1 {
18875   sqlite3_stmt *pTbls;
18876   sqlite3_stmt *pSel;
18877   sqlite3_stmt *pInsert;
18878   int nInsert;
18879 
18880   RecoverTable *pTab;             /* Table currently being written */
18881   int nMax;                       /* Max column count in any schema table */
18882   sqlite3_value **apVal;          /* Array of nMax values */
18883   int nVal;                       /* Number of valid entries in apVal[] */
18884   int bHaveRowid;
18885   i64 iRowid;
18886   i64 iPrevPage;
18887   int iPrevCell;
18888 };
18889 
18890 /*
18891 ** State variables (part of the sqlite3_recover structure) used while
18892 ** recovering data destined for the lost and found table (states
18893 ** RECOVER_STATE_LOSTANDFOUND[123]).
18894 */
18895 typedef struct RecoverStateLAF RecoverStateLAF;
18896 struct RecoverStateLAF {
18897   RecoverBitmap *pUsed;
18898   i64 nPg;                        /* Size of db in pages */
18899   sqlite3_stmt *pAllAndParent;
18900   sqlite3_stmt *pMapInsert;
18901   sqlite3_stmt *pMaxField;
18902   sqlite3_stmt *pUsedPages;
18903   sqlite3_stmt *pFindRoot;
18904   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
18905   sqlite3_stmt *pAllPage;
18906   sqlite3_stmt *pPageData;
18907   sqlite3_value **apVal;
18908   int nMaxField;
18909 };
18910 
18911 /*
18912 ** Main recover handle structure.
18913 */
18914 struct sqlite3_recover {
18915   /* Copies of sqlite3_recover_init[_sql]() parameters */
18916   sqlite3 *dbIn;                  /* Input database */
18917   char *zDb;                      /* Name of input db ("main" etc.) */
18918   char *zUri;                     /* URI for output database */
18919   void *pSqlCtx;                  /* SQL callback context */
18920   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
18921 
18922   /* Values configured by sqlite3_recover_config() */
18923   char *zStateDb;                 /* State database to use (or NULL) */
18924   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
18925   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
18926   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
18927   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
18928 
18929   int pgsz;
18930   int detected_pgsz;
18931   int nReserve;
18932   u8 *pPage1Disk;
18933   u8 *pPage1Cache;
18934 
18935   /* Error code and error message */
18936   int errCode;                    /* For sqlite3_recover_errcode() */
18937   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
18938 
18939   int eState;
18940   int bCloseTransaction;
18941 
18942   /* Variables used with eState==RECOVER_STATE_WRITING */
18943   RecoverStateW1 w1;
18944 
18945   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
18946   RecoverStateLAF laf;
18947 
18948   /* Fields used within sqlite3_recover_run() */
18949   sqlite3 *dbOut;                 /* Output database */
18950   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
18951   RecoverTable *pTblList;         /* List of tables recovered from schema */
18952 };
18953 
18954 /*
18955 ** The various states in which an sqlite3_recover object may exist:
18956 **
18957 **   RECOVER_STATE_INIT:
18958 **    The object is initially created in this state. sqlite3_recover_step()
18959 **    has yet to be called. This is the only state in which it is permitted
18960 **    to call sqlite3_recover_config().
18961 **
18962 **   RECOVER_STATE_WRITING:
18963 **
18964 **   RECOVER_STATE_LOSTANDFOUND1:
18965 **    State to populate the bitmap of pages used by other tables or the
18966 **    database freelist.
18967 **
18968 **   RECOVER_STATE_LOSTANDFOUND2:
18969 **    Populate the recovery.map table - used to figure out a "root" page
18970 **    for each lost page from in the database from which records are
18971 **    extracted.
18972 **
18973 **   RECOVER_STATE_LOSTANDFOUND3:
18974 **    Populate the lost-and-found table itself.
18975 */
18976 #define RECOVER_STATE_INIT           0
18977 #define RECOVER_STATE_WRITING        1
18978 #define RECOVER_STATE_LOSTANDFOUND1  2
18979 #define RECOVER_STATE_LOSTANDFOUND2  3
18980 #define RECOVER_STATE_LOSTANDFOUND3  4
18981 #define RECOVER_STATE_SCHEMA2        5
18982 #define RECOVER_STATE_DONE           6
18983 
18984 
18985 /*
18986 ** Global variables used by this extension.
18987 */
18988 typedef struct RecoverGlobal RecoverGlobal;
18989 struct RecoverGlobal {
18990   const sqlite3_io_methods *pMethods;
18991   sqlite3_recover *p;
18992 };
18993 static RecoverGlobal recover_g;
18994 
18995 /*
18996 ** Use this static SQLite mutex to protect the globals during the
18997 ** first call to sqlite3_recover_step().
18998 */
18999 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
19000 
19001 
19002 /*
19003 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
19004 */
19005 #define RECOVER_ROWID_DEFAULT 1
19006 
19007 /*
19008 ** Mutex handling:
19009 **
19010 **    recoverEnterMutex()       -   Enter the recovery mutex
19011 **    recoverLeaveMutex()       -   Leave the recovery mutex
19012 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
19013 */
19014 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
19015 # define recoverEnterMutex()
19016 # define recoverLeaveMutex()
19017 #else
recoverEnterMutex(void)19018 static void recoverEnterMutex(void){
19019   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
19020 }
recoverLeaveMutex(void)19021 static void recoverLeaveMutex(void){
19022   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
19023 }
19024 #endif
19025 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
recoverAssertMutexHeld(void)19026 static void recoverAssertMutexHeld(void){
19027   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
19028 }
19029 #else
19030 # define recoverAssertMutexHeld()
19031 #endif
19032 
19033 
19034 /*
19035 ** Like strlen(). But handles NULL pointer arguments.
19036 */
recoverStrlen(const char * zStr)19037 static int recoverStrlen(const char *zStr){
19038   if( zStr==0 ) return 0;
19039   return (int)(strlen(zStr)&0x7fffffff);
19040 }
19041 
19042 /*
19043 ** This function is a no-op if the recover handle passed as the first
19044 ** argument already contains an error (if p->errCode!=SQLITE_OK).
19045 **
19046 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
19047 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
19048 ** if an OOM error occurs, NULL is returned and the handle error code
19049 ** (p->errCode) set to SQLITE_NOMEM.
19050 */
recoverMalloc(sqlite3_recover * p,i64 nByte)19051 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
19052   void *pRet = 0;
19053   assert( nByte>0 );
19054   if( p->errCode==SQLITE_OK ){
19055     pRet = sqlite3_malloc64(nByte);
19056     if( pRet ){
19057       memset(pRet, 0, nByte);
19058     }else{
19059       p->errCode = SQLITE_NOMEM;
19060     }
19061   }
19062   return pRet;
19063 }
19064 
19065 /*
19066 ** Set the error code and error message for the recover handle passed as
19067 ** the first argument. The error code is set to the value of parameter
19068 ** errCode.
19069 **
19070 ** Parameter zFmt must be a printf() style formatting string. The handle
19071 ** error message is set to the result of using any trailing arguments for
19072 ** parameter substitutions in the formatting string.
19073 **
19074 ** For example:
19075 **
19076 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
19077 */
recoverError(sqlite3_recover * p,int errCode,const char * zFmt,...)19078 static int recoverError(
19079   sqlite3_recover *p,
19080   int errCode,
19081   const char *zFmt, ...
19082 ){
19083   char *z = 0;
19084   va_list ap;
19085   va_start(ap, zFmt);
19086   if( zFmt ){
19087     z = sqlite3_vmprintf(zFmt, ap);
19088   }
19089   va_end(ap);
19090   sqlite3_free(p->zErrMsg);
19091   p->zErrMsg = z;
19092   p->errCode = errCode;
19093   return errCode;
19094 }
19095 
19096 
19097 /*
19098 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
19099 ** In this case it returns NULL.
19100 **
19101 ** Otherwise, an attempt is made to allocate and return a bitmap object
19102 ** large enough to store a bit for all page numbers between 1 and nPg,
19103 ** inclusive. The bitmap is initially zeroed.
19104 */
recoverBitmapAlloc(sqlite3_recover * p,i64 nPg)19105 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
19106   int nElem = (nPg+1+31) / 32;
19107   int nByte = SZ_RECOVERBITMAP_32 + nElem*sizeof(u32);
19108   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
19109 
19110   if( pRet ){
19111     pRet->nPg = nPg;
19112   }
19113   return pRet;
19114 }
19115 
19116 /*
19117 ** Free a bitmap object allocated by recoverBitmapAlloc().
19118 */
recoverBitmapFree(RecoverBitmap * pMap)19119 static void recoverBitmapFree(RecoverBitmap *pMap){
19120   sqlite3_free(pMap);
19121 }
19122 
19123 /*
19124 ** Set the bit associated with page iPg in bitvec pMap.
19125 */
recoverBitmapSet(RecoverBitmap * pMap,i64 iPg)19126 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
19127   if( iPg<=pMap->nPg ){
19128     int iElem = (iPg / 32);
19129     int iBit = (iPg % 32);
19130     pMap->aElem[iElem] |= (((u32)1) << iBit);
19131   }
19132 }
19133 
19134 /*
19135 ** Query bitmap object pMap for the state of the bit associated with page
19136 ** iPg. Return 1 if it is set, or 0 otherwise.
19137 */
recoverBitmapQuery(RecoverBitmap * pMap,i64 iPg)19138 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
19139   int ret = 1;
19140   if( iPg<=pMap->nPg && iPg>0 ){
19141     int iElem = (iPg / 32);
19142     int iBit = (iPg % 32);
19143     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
19144   }
19145   return ret;
19146 }
19147 
19148 /*
19149 ** Set the recover handle error to the error code and message returned by
19150 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
19151 ** handle db.
19152 */
recoverDbError(sqlite3_recover * p,sqlite3 * db)19153 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
19154   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
19155 }
19156 
19157 /*
19158 ** This function is a no-op if recover handle p already contains an error
19159 ** (if p->errCode!=SQLITE_OK).
19160 **
19161 ** Otherwise, it attempts to prepare the SQL statement in zSql against
19162 ** database handle db. If successful, the statement handle is returned.
19163 ** Or, if an error occurs, NULL is returned and an error left in the
19164 ** recover handle.
19165 */
recoverPrepare(sqlite3_recover * p,sqlite3 * db,const char * zSql)19166 static sqlite3_stmt *recoverPrepare(
19167   sqlite3_recover *p,
19168   sqlite3 *db,
19169   const char *zSql
19170 ){
19171   sqlite3_stmt *pStmt = 0;
19172   if( p->errCode==SQLITE_OK ){
19173     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
19174       recoverDbError(p, db);
19175     }
19176   }
19177   return pStmt;
19178 }
19179 
19180 /*
19181 ** This function is a no-op if recover handle p already contains an error
19182 ** (if p->errCode!=SQLITE_OK).
19183 **
19184 ** Otherwise, argument zFmt is used as a printf() style format string,
19185 ** along with any trailing arguments, to create an SQL statement. This
19186 ** SQL statement is prepared against database handle db and, if successful,
19187 ** the statment handle returned. Or, if an error occurs - either during
19188 ** the printf() formatting or when preparing the resulting SQL - an
19189 ** error code and message are left in the recover handle.
19190 */
recoverPreparePrintf(sqlite3_recover * p,sqlite3 * db,const char * zFmt,...)19191 static sqlite3_stmt *recoverPreparePrintf(
19192   sqlite3_recover *p,
19193   sqlite3 *db,
19194   const char *zFmt, ...
19195 ){
19196   sqlite3_stmt *pStmt = 0;
19197   if( p->errCode==SQLITE_OK ){
19198     va_list ap;
19199     char *z;
19200     va_start(ap, zFmt);
19201     z = sqlite3_vmprintf(zFmt, ap);
19202     va_end(ap);
19203     if( z==0 ){
19204       p->errCode = SQLITE_NOMEM;
19205     }else{
19206       pStmt = recoverPrepare(p, db, z);
19207       sqlite3_free(z);
19208     }
19209   }
19210   return pStmt;
19211 }
19212 
19213 /*
19214 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
19215 ** indicates that an error occurred, and there is not already an error
19216 ** in the recover handle passed as the first argument, set the error
19217 ** code and error message appropriately.
19218 **
19219 ** This function returns a copy of the statement handle pointer passed
19220 ** as the second argument.
19221 */
recoverReset(sqlite3_recover * p,sqlite3_stmt * pStmt)19222 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
19223   int rc = sqlite3_reset(pStmt);
19224   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
19225     recoverDbError(p, sqlite3_db_handle(pStmt));
19226   }
19227   return pStmt;
19228 }
19229 
19230 /*
19231 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
19232 ** indicates that an error occurred, and there is not already an error
19233 ** in the recover handle passed as the first argument, set the error
19234 ** code and error message appropriately.
19235 */
recoverFinalize(sqlite3_recover * p,sqlite3_stmt * pStmt)19236 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
19237   sqlite3 *db = sqlite3_db_handle(pStmt);
19238   int rc = sqlite3_finalize(pStmt);
19239   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
19240     recoverDbError(p, db);
19241   }
19242 }
19243 
19244 /*
19245 ** This function is a no-op if recover handle p already contains an error
19246 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
19247 ** case.
19248 **
19249 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
19250 ** Or, if an error occurs, leave an error code and message in the recover
19251 ** handle and return a copy of the error code.
19252 */
recoverExec(sqlite3_recover * p,sqlite3 * db,const char * zSql)19253 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
19254   if( p->errCode==SQLITE_OK ){
19255     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
19256     if( rc ){
19257       recoverDbError(p, db);
19258     }
19259   }
19260   return p->errCode;
19261 }
19262 
19263 /*
19264 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
19265 ** error in the recover handle passed as the first argument if an error
19266 ** (e.g. an OOM) occurs.
19267 */
recoverBindValue(sqlite3_recover * p,sqlite3_stmt * pStmt,int iBind,sqlite3_value * pVal)19268 static void recoverBindValue(
19269   sqlite3_recover *p,
19270   sqlite3_stmt *pStmt,
19271   int iBind,
19272   sqlite3_value *pVal
19273 ){
19274   if( p->errCode==SQLITE_OK ){
19275     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
19276     if( rc ) recoverError(p, rc, 0);
19277   }
19278 }
19279 
19280 /*
19281 ** This function is a no-op if recover handle p already contains an error
19282 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
19283 **
19284 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
19285 ** formatting string and the result of using the trailing arguments for
19286 ** parameter substitution with it written into a buffer obtained from
19287 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
19288 ** It is the responsibility of the caller to eventually free the buffer
19289 ** using sqlite3_free().
19290 **
19291 ** Or, if an error occurs, an error code and message is left in the recover
19292 ** handle and NULL returned.
19293 */
recoverMPrintf(sqlite3_recover * p,const char * zFmt,...)19294 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
19295   va_list ap;
19296   char *z;
19297   va_start(ap, zFmt);
19298   z = sqlite3_vmprintf(zFmt, ap);
19299   va_end(ap);
19300   if( p->errCode==SQLITE_OK ){
19301     if( z==0 ) p->errCode = SQLITE_NOMEM;
19302   }else{
19303     sqlite3_free(z);
19304     z = 0;
19305   }
19306   return z;
19307 }
19308 
19309 /*
19310 ** This function is a no-op if recover handle p already contains an error
19311 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
19312 **
19313 ** Otherwise, execute "PRAGMA page_count" against the input database. If
19314 ** successful, return the integer result. Or, if an error occurs, leave an
19315 ** error code and error message in the sqlite3_recover handle and return
19316 ** zero.
19317 */
recoverPageCount(sqlite3_recover * p)19318 static i64 recoverPageCount(sqlite3_recover *p){
19319   i64 nPg = 0;
19320   if( p->errCode==SQLITE_OK ){
19321     sqlite3_stmt *pStmt = 0;
19322     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
19323     if( pStmt ){
19324       sqlite3_step(pStmt);
19325       nPg = sqlite3_column_int64(pStmt, 0);
19326     }
19327     recoverFinalize(p, pStmt);
19328   }
19329   return nPg;
19330 }
19331 
19332 /*
19333 ** Implementation of SQL scalar function "read_i32". The first argument to
19334 ** this function must be a blob. The second a non-negative integer. This
19335 ** function reads and returns a 32-bit big-endian integer from byte
19336 ** offset (4*<arg2>) of the blob.
19337 **
19338 **     SELECT read_i32(<blob>, <idx>)
19339 */
recoverReadI32(sqlite3_context * context,int argc,sqlite3_value ** argv)19340 static void recoverReadI32(
19341   sqlite3_context *context,
19342   int argc,
19343   sqlite3_value **argv
19344 ){
19345   const unsigned char *pBlob;
19346   int nBlob;
19347   int iInt;
19348 
19349   assert( argc==2 );
19350   nBlob = sqlite3_value_bytes(argv[0]);
19351   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
19352   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
19353 
19354   if( (iInt+1)*4<=nBlob ){
19355     const unsigned char *a = &pBlob[iInt*4];
19356     i64 iVal = ((i64)a[0]<<24)
19357              + ((i64)a[1]<<16)
19358              + ((i64)a[2]<< 8)
19359              + ((i64)a[3]<< 0);
19360     sqlite3_result_int64(context, iVal);
19361   }
19362 }
19363 
19364 /*
19365 ** Implementation of SQL scalar function "page_is_used". This function
19366 ** is used as part of the procedure for locating orphan rows for the
19367 ** lost-and-found table, and it depends on those routines having populated
19368 ** the sqlite3_recover.laf.pUsed variable.
19369 **
19370 ** The only argument to this function is a page-number. It returns true
19371 ** if the page has already been used somehow during data recovery, or false
19372 ** otherwise.
19373 **
19374 **     SELECT page_is_used(<pgno>);
19375 */
recoverPageIsUsed(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)19376 static void recoverPageIsUsed(
19377   sqlite3_context *pCtx,
19378   int nArg,
19379   sqlite3_value **apArg
19380 ){
19381   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
19382   i64 pgno = sqlite3_value_int64(apArg[0]);
19383   assert( nArg==1 );
19384   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
19385 }
19386 
19387 /*
19388 ** The implementation of a user-defined SQL function invoked by the
19389 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
19390 ** of the database being recovered.
19391 **
19392 ** This function always takes a single integer argument. If the argument
19393 ** is zero, then the value returned is the number of pages in the db being
19394 ** recovered. If the argument is greater than zero, it is a page number.
19395 ** The value returned in this case is an SQL blob containing the data for
19396 ** the identified page of the db being recovered. e.g.
19397 **
19398 **     SELECT getpage(0);       -- return number of pages in db
19399 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
19400 */
recoverGetPage(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)19401 static void recoverGetPage(
19402   sqlite3_context *pCtx,
19403   int nArg,
19404   sqlite3_value **apArg
19405 ){
19406   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
19407   i64 pgno = sqlite3_value_int64(apArg[0]);
19408   sqlite3_stmt *pStmt = 0;
19409 
19410   assert( nArg==1 );
19411   if( pgno==0 ){
19412     i64 nPg = recoverPageCount(p);
19413     sqlite3_result_int64(pCtx, nPg);
19414     return;
19415   }else{
19416     if( p->pGetPage==0 ){
19417       pStmt = p->pGetPage = recoverPreparePrintf(
19418           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
19419       );
19420     }else if( p->errCode==SQLITE_OK ){
19421       pStmt = p->pGetPage;
19422     }
19423 
19424     if( pStmt ){
19425       sqlite3_bind_int64(pStmt, 1, pgno);
19426       if( SQLITE_ROW==sqlite3_step(pStmt) ){
19427         const u8 *aPg;
19428         int nPg;
19429         assert( p->errCode==SQLITE_OK );
19430         aPg = sqlite3_column_blob(pStmt, 0);
19431         nPg = sqlite3_column_bytes(pStmt, 0);
19432         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
19433           aPg = p->pPage1Disk;
19434         }
19435         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
19436       }
19437       recoverReset(p, pStmt);
19438     }
19439   }
19440 
19441   if( p->errCode ){
19442     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
19443     sqlite3_result_error_code(pCtx, p->errCode);
19444   }
19445 }
19446 
19447 /*
19448 ** Find a string that is not found anywhere in z[].  Return a pointer
19449 ** to that string.
19450 **
19451 ** Try to use zA and zB first.  If both of those are already found in z[]
19452 ** then make up some string and store it in the buffer zBuf.
19453 */
recoverUnusedString(const char * z,const char * zA,const char * zB,char * zBuf)19454 static const char *recoverUnusedString(
19455   const char *z,                    /* Result must not appear anywhere in z */
19456   const char *zA, const char *zB,   /* Try these first */
19457   char *zBuf                        /* Space to store a generated string */
19458 ){
19459   unsigned i = 0;
19460   if( strstr(z, zA)==0 ) return zA;
19461   if( strstr(z, zB)==0 ) return zB;
19462   do{
19463     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
19464   }while( strstr(z,zBuf)!=0 );
19465   return zBuf;
19466 }
19467 
19468 /*
19469 ** Implementation of scalar SQL function "escape_crlf".  The argument passed to
19470 ** this function is the output of built-in function quote(). If the first
19471 ** character of the input is "'", indicating that the value passed to quote()
19472 ** was a text value, then this function searches the input for "\n" and "\r"
19473 ** characters and adds a wrapper similar to the following:
19474 **
19475 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
19476 **
19477 ** Or, if the first character of the input is not "'", then a copy of the input
19478 ** is returned.
19479 */
recoverEscapeCrlf(sqlite3_context * context,int argc,sqlite3_value ** argv)19480 static void recoverEscapeCrlf(
19481   sqlite3_context *context,
19482   int argc,
19483   sqlite3_value **argv
19484 ){
19485   const char *zText = (const char*)sqlite3_value_text(argv[0]);
19486   (void)argc;
19487   if( zText && zText[0]=='\'' ){
19488     int nText = sqlite3_value_bytes(argv[0]);
19489     int i;
19490     char zBuf1[20];
19491     char zBuf2[20];
19492     const char *zNL = 0;
19493     const char *zCR = 0;
19494     int nCR = 0;
19495     int nNL = 0;
19496 
19497     for(i=0; zText[i]; i++){
19498       if( zNL==0 && zText[i]=='\n' ){
19499         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
19500         nNL = (int)strlen(zNL);
19501       }
19502       if( zCR==0 && zText[i]=='\r' ){
19503         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
19504         nCR = (int)strlen(zCR);
19505       }
19506     }
19507 
19508     if( zNL || zCR ){
19509       int iOut = 0;
19510       i64 nMax = (nNL > nCR) ? nNL : nCR;
19511       i64 nAlloc = nMax * nText + (nMax+64)*2;
19512       char *zOut = (char*)sqlite3_malloc64(nAlloc);
19513       if( zOut==0 ){
19514         sqlite3_result_error_nomem(context);
19515         return;
19516       }
19517 
19518       if( zNL && zCR ){
19519         memcpy(&zOut[iOut], "replace(replace(", 16);
19520         iOut += 16;
19521       }else{
19522         memcpy(&zOut[iOut], "replace(", 8);
19523         iOut += 8;
19524       }
19525       for(i=0; zText[i]; i++){
19526         if( zText[i]=='\n' ){
19527           memcpy(&zOut[iOut], zNL, nNL);
19528           iOut += nNL;
19529         }else if( zText[i]=='\r' ){
19530           memcpy(&zOut[iOut], zCR, nCR);
19531           iOut += nCR;
19532         }else{
19533           zOut[iOut] = zText[i];
19534           iOut++;
19535         }
19536       }
19537 
19538       if( zNL ){
19539         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
19540         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
19541         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
19542       }
19543       if( zCR ){
19544         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
19545         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
19546         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
19547       }
19548 
19549       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
19550       sqlite3_free(zOut);
19551       return;
19552     }
19553   }
19554 
19555   sqlite3_result_value(context, argv[0]);
19556 }
19557 
19558 /*
19559 ** This function is a no-op if recover handle p already contains an error
19560 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
19561 ** this case.
19562 **
19563 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
19564 ** parts of the database schema that can be extracted from the input database.
19565 **
19566 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
19567 ** and error message are left in the recover handle and a copy of the
19568 ** error code returned. It is not considered an error if part of all of
19569 ** the database schema cannot be recovered due to corruption.
19570 */
recoverCacheSchema(sqlite3_recover * p)19571 static int recoverCacheSchema(sqlite3_recover *p){
19572   return recoverExec(p, p->dbOut,
19573     "WITH RECURSIVE pages(p) AS ("
19574     "  SELECT 1"
19575     "    UNION"
19576     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
19577     ")"
19578     "INSERT INTO recovery.schema SELECT"
19579     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
19580     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
19581     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
19582     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
19583     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
19584     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
19585     "  SELECT p FROM pages"
19586     ") GROUP BY pgno, cell"
19587   );
19588 }
19589 
19590 /*
19591 ** If this recover handle is not in SQL callback mode (i.e. was not created
19592 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
19593 ** this function is a no-op. Otherwise, issue a callback with SQL statement
19594 ** zSql as the parameter.
19595 **
19596 ** If the callback returns non-zero, set the recover handle error code to
19597 ** the value returned (so that the caller will abandon processing).
19598 */
recoverSqlCallback(sqlite3_recover * p,const char * zSql)19599 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
19600   if( p->errCode==SQLITE_OK && p->xSql ){
19601     int res = p->xSql(p->pSqlCtx, zSql);
19602     if( res ){
19603       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
19604     }
19605   }
19606 }
19607 
19608 /*
19609 ** Transfer the following settings from the input database to the output
19610 ** database:
19611 **
19612 **   + page-size,
19613 **   + auto-vacuum settings,
19614 **   + database encoding,
19615 **   + user-version (PRAGMA user_version), and
19616 **   + application-id (PRAGMA application_id), and
19617 */
recoverTransferSettings(sqlite3_recover * p)19618 static void recoverTransferSettings(sqlite3_recover *p){
19619   const char *aPragma[] = {
19620     "encoding",
19621     "page_size",
19622     "auto_vacuum",
19623     "user_version",
19624     "application_id"
19625   };
19626   int ii;
19627 
19628   /* Truncate the output database to 0 pages in size. This is done by
19629   ** opening a new, empty, temp db, then using the backup API to clobber
19630   ** any existing output db with a copy of it. */
19631   if( p->errCode==SQLITE_OK ){
19632     sqlite3 *db2 = 0;
19633     int rc = sqlite3_open("", &db2);
19634     if( rc!=SQLITE_OK ){
19635       recoverDbError(p, db2);
19636       return;
19637     }
19638 
19639     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
19640       const char *zPrag = aPragma[ii];
19641       sqlite3_stmt *p1 = 0;
19642       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
19643       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
19644         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
19645         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
19646         recoverSqlCallback(p, z2);
19647         recoverExec(p, db2, z2);
19648         sqlite3_free(z2);
19649         if( zArg==0 ){
19650           recoverError(p, SQLITE_NOMEM, 0);
19651         }
19652       }
19653       recoverFinalize(p, p1);
19654     }
19655     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
19656 
19657     if( p->errCode==SQLITE_OK ){
19658       sqlite3 *db = p->dbOut;
19659       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
19660       if( pBackup ){
19661         sqlite3_backup_step(pBackup, -1);
19662         p->errCode = sqlite3_backup_finish(pBackup);
19663       }else{
19664         recoverDbError(p, db);
19665       }
19666     }
19667 
19668     sqlite3_close(db2);
19669   }
19670 }
19671 
19672 /*
19673 ** This function is a no-op if recover handle p already contains an error
19674 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
19675 ** this case.
19676 **
19677 ** Otherwise, an attempt is made to open the output database, attach
19678 ** and create the schema of the temporary database used to store
19679 ** intermediate data, and to register all required user functions and
19680 ** virtual table modules with the output handle.
19681 **
19682 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
19683 ** and error message are left in the recover handle and a copy of the
19684 ** error code returned.
19685 */
recoverOpenOutput(sqlite3_recover * p)19686 static int recoverOpenOutput(sqlite3_recover *p){
19687   struct Func {
19688     const char *zName;
19689     int nArg;
19690     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
19691   } aFunc[] = {
19692     { "getpage", 1, recoverGetPage },
19693     { "page_is_used", 1, recoverPageIsUsed },
19694     { "read_i32", 2, recoverReadI32 },
19695     { "escape_crlf", 1, recoverEscapeCrlf },
19696   };
19697 
19698   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
19699   sqlite3 *db = 0;                /* New database handle */
19700   int ii;                         /* For iterating through aFunc[] */
19701 
19702   assert( p->dbOut==0 );
19703 
19704   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
19705     recoverDbError(p, db);
19706   }
19707 
19708   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
19709   ** These two are registered with the output database handle - this
19710   ** module depends on the input handle supporting the sqlite_dbpage
19711   ** virtual table only.  */
19712   if( p->errCode==SQLITE_OK ){
19713     p->errCode = sqlite3_dbdata_init(db, 0, 0);
19714   }
19715 
19716   /* Register the custom user-functions with the output handle. */
19717   for(ii=0;
19718       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
19719       ii++){
19720     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
19721         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
19722     );
19723   }
19724 
19725   p->dbOut = db;
19726   return p->errCode;
19727 }
19728 
19729 /*
19730 ** Attach the auxiliary database 'recovery' to the output database handle.
19731 ** This temporary database is used during the recovery process and then
19732 ** discarded.
19733 */
recoverOpenRecovery(sqlite3_recover * p)19734 static void recoverOpenRecovery(sqlite3_recover *p){
19735   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
19736   recoverExec(p, p->dbOut, zSql);
19737   recoverExec(p, p->dbOut,
19738       "PRAGMA writable_schema = 1;"
19739       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
19740       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
19741   );
19742   sqlite3_free(zSql);
19743 }
19744 
19745 
19746 /*
19747 ** This function is a no-op if recover handle p already contains an error
19748 ** (if p->errCode!=SQLITE_OK).
19749 **
19750 ** Otherwise, argument zName must be the name of a table that has just been
19751 ** created in the output database. This function queries the output db
19752 ** for the schema of said table, and creates a RecoverTable object to
19753 ** store the schema in memory. The new RecoverTable object is linked into
19754 ** the list at sqlite3_recover.pTblList.
19755 **
19756 ** Parameter iRoot must be the root page of table zName in the INPUT
19757 ** database.
19758 */
recoverAddTable(sqlite3_recover * p,const char * zName,i64 iRoot)19759 static void recoverAddTable(
19760   sqlite3_recover *p,
19761   const char *zName,              /* Name of table created in output db */
19762   i64 iRoot                       /* Root page of same table in INPUT db */
19763 ){
19764   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
19765       "PRAGMA table_xinfo(%Q)", zName
19766   );
19767 
19768   if( pStmt ){
19769     int iPk = -1;
19770     int iBind = 1;
19771     RecoverTable *pNew = 0;
19772     int nCol = 0;
19773     int nName = recoverStrlen(zName);
19774     int nByte = 0;
19775     while( sqlite3_step(pStmt)==SQLITE_ROW ){
19776       nCol++;
19777       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
19778     }
19779     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
19780     recoverReset(p, pStmt);
19781 
19782     pNew = recoverMalloc(p, nByte);
19783     if( pNew ){
19784       int i = 0;
19785       int iField = 0;
19786       char *csr = 0;
19787       pNew->aCol = (RecoverColumn*)&pNew[1];
19788       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
19789       pNew->nCol = nCol;
19790       pNew->iRoot = iRoot;
19791       memcpy(csr, zName, nName);
19792       csr += nName+1;
19793 
19794       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
19795         int iPKF = sqlite3_column_int(pStmt, 5);
19796         int n = sqlite3_column_bytes(pStmt, 1);
19797         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
19798         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
19799         int eHidden = sqlite3_column_int(pStmt, 6);
19800 
19801         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
19802         if( iPKF>1 ) iPk = -2;
19803         pNew->aCol[i].zCol = csr;
19804         pNew->aCol[i].eHidden = eHidden;
19805         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
19806           pNew->aCol[i].iField = -1;
19807         }else{
19808           pNew->aCol[i].iField = iField++;
19809         }
19810         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
19811          && eHidden!=RECOVER_EHIDDEN_STORED
19812         ){
19813           pNew->aCol[i].iBind = iBind++;
19814         }
19815         memcpy(csr, z, n);
19816         csr += (n+1);
19817       }
19818 
19819       pNew->pNext = p->pTblList;
19820       p->pTblList = pNew;
19821       pNew->bIntkey = 1;
19822     }
19823 
19824     recoverFinalize(p, pStmt);
19825 
19826     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
19827     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
19828       int iField = sqlite3_column_int(pStmt, 0);
19829       int iCol = sqlite3_column_int(pStmt, 1);
19830 
19831       assert( iCol<pNew->nCol );
19832       pNew->aCol[iCol].iField = iField;
19833 
19834       pNew->bIntkey = 0;
19835       iPk = -2;
19836     }
19837     recoverFinalize(p, pStmt);
19838 
19839     if( p->errCode==SQLITE_OK ){
19840       if( iPk>=0 ){
19841         pNew->aCol[iPk].bIPK = 1;
19842       }else if( pNew->bIntkey ){
19843         pNew->iRowidBind = iBind++;
19844       }
19845     }
19846   }
19847 }
19848 
19849 /*
19850 ** This function is called after recoverCacheSchema() has cached those parts
19851 ** of the input database schema that could be recovered in temporary table
19852 ** "recovery.schema". This function creates in the output database copies
19853 ** of all parts of that schema that must be created before the tables can
19854 ** be populated. Specifically, this means:
19855 **
19856 **     * all tables that are not VIRTUAL, and
19857 **     * UNIQUE indexes.
19858 **
19859 ** If the recovery handle uses SQL callbacks, then callbacks containing
19860 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
19861 **
19862 ** Additionally, records are added to the sqlite_schema table of the
19863 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
19864 ** records are written directly to sqlite_schema, not actually executed.
19865 ** If the handle is in SQL callback mode, then callbacks are invoked
19866 ** with equivalent SQL statements.
19867 */
recoverWriteSchema1(sqlite3_recover * p)19868 static int recoverWriteSchema1(sqlite3_recover *p){
19869   sqlite3_stmt *pSelect = 0;
19870   sqlite3_stmt *pTblname = 0;
19871 
19872   pSelect = recoverPrepare(p, p->dbOut,
19873       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
19874       "  SELECT rootpage, name, sql, "
19875       "    type='table', "
19876       "    sql LIKE 'create virtual%',"
19877       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
19878       "  FROM recovery.schema"
19879       ")"
19880       "SELECT rootpage, tbl, isVirtual, name, sql"
19881       " FROM dbschema "
19882       "  WHERE tbl OR isIndex"
19883       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
19884   );
19885 
19886   pTblname = recoverPrepare(p, p->dbOut,
19887       "SELECT name FROM sqlite_schema "
19888       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
19889   );
19890 
19891   if( pSelect ){
19892     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
19893     while( sqlite3_step(pSelect)==SQLITE_ROW ){
19894       i64 iRoot = sqlite3_column_int64(pSelect, 0);
19895       int bTable = sqlite3_column_int(pSelect, 1);
19896       int bVirtual = sqlite3_column_int(pSelect, 2);
19897       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
19898       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
19899       char *zFree = 0;
19900       int rc = SQLITE_OK;
19901 
19902       if( bVirtual ){
19903         zSql = (const char*)(zFree = recoverMPrintf(p,
19904             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
19905             zName, zName, zSql
19906         ));
19907       }
19908       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
19909       if( rc==SQLITE_OK ){
19910         recoverSqlCallback(p, zSql);
19911         if( bTable && !bVirtual ){
19912           if( SQLITE_ROW==sqlite3_step(pTblname) ){
19913             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
19914             if( zTbl ) recoverAddTable(p, zTbl, iRoot);
19915           }
19916           recoverReset(p, pTblname);
19917         }
19918       }else if( rc!=SQLITE_ERROR ){
19919         recoverDbError(p, p->dbOut);
19920       }
19921       sqlite3_free(zFree);
19922     }
19923   }
19924   recoverFinalize(p, pSelect);
19925   recoverFinalize(p, pTblname);
19926 
19927   return p->errCode;
19928 }
19929 
19930 /*
19931 ** This function is called after the output database has been populated. It
19932 ** adds all recovered schema elements that were not created in the output
19933 ** database by recoverWriteSchema1() - everything except for tables and
19934 ** UNIQUE indexes. Specifically:
19935 **
19936 **     * views,
19937 **     * triggers,
19938 **     * non-UNIQUE indexes.
19939 **
19940 ** If the recover handle is in SQL callback mode, then equivalent callbacks
19941 ** are issued to create the schema elements.
19942 */
recoverWriteSchema2(sqlite3_recover * p)19943 static int recoverWriteSchema2(sqlite3_recover *p){
19944   sqlite3_stmt *pSelect = 0;
19945 
19946   pSelect = recoverPrepare(p, p->dbOut,
19947       p->bSlowIndexes ?
19948       "SELECT rootpage, sql FROM recovery.schema "
19949       "  WHERE type!='table' AND type!='index'"
19950       :
19951       "SELECT rootpage, sql FROM recovery.schema "
19952       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
19953   );
19954 
19955   if( pSelect ){
19956     while( sqlite3_step(pSelect)==SQLITE_ROW ){
19957       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
19958       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
19959       if( rc==SQLITE_OK ){
19960         recoverSqlCallback(p, zSql);
19961       }else if( rc!=SQLITE_ERROR ){
19962         recoverDbError(p, p->dbOut);
19963       }
19964     }
19965   }
19966   recoverFinalize(p, pSelect);
19967 
19968   return p->errCode;
19969 }
19970 
19971 /*
19972 ** This function is a no-op if recover handle p already contains an error
19973 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
19974 **
19975 ** Otherwise, if the recover handle is configured to create an output
19976 ** database (was created by sqlite3_recover_init()), then this function
19977 ** prepares and returns an SQL statement to INSERT a new record into table
19978 ** pTab, assuming the first nField fields of a record extracted from disk
19979 ** are valid.
19980 **
19981 ** For example, if table pTab is:
19982 **
19983 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
19984 **
19985 ** And nField is 4, then the SQL statement prepared and returned is:
19986 **
19987 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
19988 **
19989 ** In this case even though 4 values were extracted from the input db,
19990 ** only 3 are written to the output, as the generated STORED column
19991 ** cannot be written.
19992 **
19993 ** If the recover handle is in SQL callback mode, then the SQL statement
19994 ** prepared is such that evaluating it returns a single row containing
19995 ** a single text value - itself an SQL statement similar to the above,
19996 ** except with SQL literals in place of the variables. For example:
19997 **
19998 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
19999 **          || quote(?1) || ', '
20000 **          || quote(?2) || ', '
20001 **          || quote(?3) || ')';
20002 **
20003 ** In either case, it is the responsibility of the caller to eventually
20004 ** free the statement handle using sqlite3_finalize().
20005 */
recoverInsertStmt(sqlite3_recover * p,RecoverTable * pTab,int nField)20006 static sqlite3_stmt *recoverInsertStmt(
20007   sqlite3_recover *p,
20008   RecoverTable *pTab,
20009   int nField
20010 ){
20011   sqlite3_stmt *pRet = 0;
20012   const char *zSep = "";
20013   const char *zSqlSep = "";
20014   char *zSql = 0;
20015   char *zFinal = 0;
20016   char *zBind = 0;
20017   int ii;
20018   int bSql = p->xSql ? 1 : 0;
20019 
20020   if( nField<=0 ) return 0;
20021 
20022   assert( nField<=pTab->nCol );
20023 
20024   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
20025 
20026   if( pTab->iRowidBind ){
20027     assert( pTab->bIntkey );
20028     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
20029     if( bSql ){
20030       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
20031     }else{
20032       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
20033     }
20034     zSqlSep = "||', '||";
20035     zSep = ", ";
20036   }
20037 
20038   for(ii=0; ii<nField; ii++){
20039     int eHidden = pTab->aCol[ii].eHidden;
20040     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
20041      && eHidden!=RECOVER_EHIDDEN_STORED
20042     ){
20043       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
20044       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
20045 
20046       if( bSql ){
20047         zBind = recoverMPrintf(p,
20048             "%z%sescape_crlf(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
20049         );
20050         zSqlSep = "||', '||";
20051       }else{
20052         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
20053       }
20054       zSep = ", ";
20055     }
20056   }
20057 
20058   if( bSql ){
20059     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
20060         zSql, zBind
20061     );
20062   }else{
20063     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
20064   }
20065 
20066   pRet = recoverPrepare(p, p->dbOut, zFinal);
20067   sqlite3_free(zSql);
20068   sqlite3_free(zBind);
20069   sqlite3_free(zFinal);
20070 
20071   return pRet;
20072 }
20073 
20074 
20075 /*
20076 ** Search the list of RecoverTable objects at p->pTblList for one that
20077 ** has root page iRoot in the input database. If such an object is found,
20078 ** return a pointer to it. Otherwise, return NULL.
20079 */
recoverFindTable(sqlite3_recover * p,u32 iRoot)20080 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
20081   RecoverTable *pRet = 0;
20082   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
20083   return pRet;
20084 }
20085 
20086 /*
20087 ** This function attempts to create a lost and found table within the
20088 ** output db. If successful, it returns a pointer to a buffer containing
20089 ** the name of the new table. It is the responsibility of the caller to
20090 ** eventually free this buffer using sqlite3_free().
20091 **
20092 ** If an error occurs, NULL is returned and an error code and error
20093 ** message left in the recover handle.
20094 */
recoverLostAndFoundCreate(sqlite3_recover * p,int nField)20095 static char *recoverLostAndFoundCreate(
20096   sqlite3_recover *p,             /* Recover object */
20097   int nField                      /* Number of column fields in new table */
20098 ){
20099   char *zTbl = 0;
20100   sqlite3_stmt *pProbe = 0;
20101   int ii = 0;
20102 
20103   pProbe = recoverPrepare(p, p->dbOut,
20104     "SELECT 1 FROM sqlite_schema WHERE name=?"
20105   );
20106   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
20107     int bFail = 0;
20108     if( ii<0 ){
20109       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
20110     }else{
20111       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
20112     }
20113 
20114     if( p->errCode==SQLITE_OK ){
20115       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
20116       if( SQLITE_ROW==sqlite3_step(pProbe) ){
20117         bFail = 1;
20118       }
20119       recoverReset(p, pProbe);
20120     }
20121 
20122     if( bFail ){
20123       sqlite3_clear_bindings(pProbe);
20124       sqlite3_free(zTbl);
20125       zTbl = 0;
20126     }
20127   }
20128   recoverFinalize(p, pProbe);
20129 
20130   if( zTbl ){
20131     const char *zSep = 0;
20132     char *zField = 0;
20133     char *zSql = 0;
20134 
20135     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
20136     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
20137       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
20138       zSep = ", ";
20139     }
20140 
20141     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
20142     sqlite3_free(zField);
20143 
20144     recoverExec(p, p->dbOut, zSql);
20145     recoverSqlCallback(p, zSql);
20146     sqlite3_free(zSql);
20147   }else if( p->errCode==SQLITE_OK ){
20148     recoverError(
20149         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
20150     );
20151   }
20152 
20153   return zTbl;
20154 }
20155 
20156 /*
20157 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
20158 ** table in the output database. The name of the table is zTab, and it has
20159 ** nField c* fields.
20160 */
recoverLostAndFoundInsert(sqlite3_recover * p,const char * zTab,int nField)20161 static sqlite3_stmt *recoverLostAndFoundInsert(
20162   sqlite3_recover *p,
20163   const char *zTab,
20164   int nField
20165 ){
20166   int nTotal = nField + 4;
20167   int ii;
20168   char *zBind = 0;
20169   sqlite3_stmt *pRet = 0;
20170 
20171   if( p->xSql==0 ){
20172     for(ii=0; ii<nTotal; ii++){
20173       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
20174     }
20175     pRet = recoverPreparePrintf(
20176         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
20177     );
20178   }else{
20179     const char *zSep = "";
20180     for(ii=0; ii<nTotal; ii++){
20181       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
20182       zSep = "|| ', ' ||";
20183     }
20184     pRet = recoverPreparePrintf(
20185         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
20186     );
20187   }
20188 
20189   sqlite3_free(zBind);
20190   return pRet;
20191 }
20192 
20193 /*
20194 ** Input database page iPg contains data that will be written to the
20195 ** lost-and-found table of the output database. This function attempts
20196 ** to identify the root page of the tree that page iPg belonged to.
20197 ** If successful, it sets output variable (*piRoot) to the page number
20198 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
20199 ** an SQLite error code is returned and the final value of *piRoot
20200 ** undefined.
20201 */
recoverLostAndFoundFindRoot(sqlite3_recover * p,i64 iPg,i64 * piRoot)20202 static int recoverLostAndFoundFindRoot(
20203   sqlite3_recover *p,
20204   i64 iPg,
20205   i64 *piRoot
20206 ){
20207   RecoverStateLAF *pLaf = &p->laf;
20208 
20209   if( pLaf->pFindRoot==0 ){
20210     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
20211         "WITH RECURSIVE p(pgno) AS ("
20212         "  SELECT ?"
20213         "    UNION"
20214         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
20215         ") "
20216         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
20217         "    AND m.parent IS NULL"
20218     );
20219   }
20220   if( p->errCode==SQLITE_OK ){
20221     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
20222     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
20223       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
20224     }else{
20225       *piRoot = iPg;
20226     }
20227     recoverReset(p, pLaf->pFindRoot);
20228   }
20229   return p->errCode;
20230 }
20231 
20232 /*
20233 ** Recover data from page iPage of the input database and write it to
20234 ** the lost-and-found table in the output database.
20235 */
recoverLostAndFoundOnePage(sqlite3_recover * p,i64 iPage)20236 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
20237   RecoverStateLAF *pLaf = &p->laf;
20238   sqlite3_value **apVal = pLaf->apVal;
20239   sqlite3_stmt *pPageData = pLaf->pPageData;
20240   sqlite3_stmt *pInsert = pLaf->pInsert;
20241 
20242   int nVal = -1;
20243   int iPrevCell = 0;
20244   i64 iRoot = 0;
20245   int bHaveRowid = 0;
20246   i64 iRowid = 0;
20247   int ii = 0;
20248 
20249   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
20250   sqlite3_bind_int64(pPageData, 1, iPage);
20251   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
20252     int iCell = sqlite3_column_int64(pPageData, 0);
20253     int iField = sqlite3_column_int64(pPageData, 1);
20254 
20255     if( iPrevCell!=iCell && nVal>=0 ){
20256       /* Insert the new row */
20257       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
20258       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
20259       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
20260       if( bHaveRowid ){
20261         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
20262       }
20263       for(ii=0; ii<nVal; ii++){
20264         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
20265       }
20266       if( sqlite3_step(pInsert)==SQLITE_ROW ){
20267         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
20268       }
20269       recoverReset(p, pInsert);
20270 
20271       /* Discard the accumulated row data */
20272       for(ii=0; ii<nVal; ii++){
20273         sqlite3_value_free(apVal[ii]);
20274         apVal[ii] = 0;
20275       }
20276       sqlite3_clear_bindings(pInsert);
20277       bHaveRowid = 0;
20278       nVal = -1;
20279     }
20280 
20281     if( iCell<0 ) break;
20282 
20283     if( iField<0 ){
20284       assert( nVal==-1 );
20285       iRowid = sqlite3_column_int64(pPageData, 2);
20286       bHaveRowid = 1;
20287       nVal = 0;
20288     }else if( iField<pLaf->nMaxField ){
20289       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
20290       apVal[iField] = sqlite3_value_dup(pVal);
20291       assert( iField==nVal || (nVal==-1 && iField==0) );
20292       nVal = iField+1;
20293       if( apVal[iField]==0 ){
20294         recoverError(p, SQLITE_NOMEM, 0);
20295       }
20296     }
20297 
20298     iPrevCell = iCell;
20299   }
20300   recoverReset(p, pPageData);
20301 
20302   for(ii=0; ii<nVal; ii++){
20303     sqlite3_value_free(apVal[ii]);
20304     apVal[ii] = 0;
20305   }
20306 }
20307 
20308 /*
20309 ** Perform one step (sqlite3_recover_step()) of work for the connection
20310 ** passed as the only argument, which is guaranteed to be in
20311 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
20312 ** table of the output database is populated with recovered data that can
20313 ** not be assigned to any recovered schema object.
20314 */
recoverLostAndFound3Step(sqlite3_recover * p)20315 static int recoverLostAndFound3Step(sqlite3_recover *p){
20316   RecoverStateLAF *pLaf = &p->laf;
20317   if( p->errCode==SQLITE_OK ){
20318     if( pLaf->pInsert==0 ){
20319       return SQLITE_DONE;
20320     }else{
20321       if( p->errCode==SQLITE_OK ){
20322         int res = sqlite3_step(pLaf->pAllPage);
20323         if( res==SQLITE_ROW ){
20324           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
20325           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
20326             recoverLostAndFoundOnePage(p, iPage);
20327           }
20328         }else{
20329           recoverReset(p, pLaf->pAllPage);
20330           return SQLITE_DONE;
20331         }
20332       }
20333     }
20334   }
20335   return SQLITE_OK;
20336 }
20337 
20338 /*
20339 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
20340 ** state - during which the lost-and-found table of the output database
20341 ** is populated with recovered data that can not be assigned to any
20342 ** recovered schema object.
20343 */
recoverLostAndFound3Init(sqlite3_recover * p)20344 static void recoverLostAndFound3Init(sqlite3_recover *p){
20345   RecoverStateLAF *pLaf = &p->laf;
20346 
20347   if( pLaf->nMaxField>0 ){
20348     char *zTab = 0;               /* Name of lost_and_found table */
20349 
20350     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
20351     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
20352     sqlite3_free(zTab);
20353 
20354     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
20355         "WITH RECURSIVE seq(ii) AS ("
20356         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
20357         ")"
20358         "SELECT ii FROM seq" , p->laf.nPg
20359     );
20360     pLaf->pPageData = recoverPrepare(p, p->dbOut,
20361         "SELECT cell, field, value "
20362         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
20363         "UNION ALL "
20364         "SELECT -1, -1, -1"
20365     );
20366 
20367     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
20368         pLaf->nMaxField*sizeof(sqlite3_value*)
20369     );
20370   }
20371 }
20372 
20373 /*
20374 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
20375 ** tables recovered from the schema of the input database are populated with
20376 ** recovered data.
20377 */
recoverWriteDataInit(sqlite3_recover * p)20378 static int recoverWriteDataInit(sqlite3_recover *p){
20379   RecoverStateW1 *p1 = &p->w1;
20380   RecoverTable *pTbl = 0;
20381   int nByte = 0;
20382 
20383   /* Figure out the maximum number of columns for any table in the schema */
20384   assert( p1->nMax==0 );
20385   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
20386     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
20387   }
20388 
20389   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
20390   ** that will be written to the output database in a single row. */
20391   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
20392   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
20393   if( p1->apVal==0 ) return p->errCode;
20394 
20395   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
20396   ** to loop through cells that appear to belong to a single table (pSel). */
20397   p1->pTbls = recoverPrepare(p, p->dbOut,
20398       "SELECT rootpage FROM recovery.schema "
20399       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
20400       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
20401   );
20402   p1->pSel = recoverPrepare(p, p->dbOut,
20403       "WITH RECURSIVE pages(page) AS ("
20404       "  SELECT ?1"
20405       "    UNION"
20406       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
20407       "    WHERE pgno=page"
20408       ") "
20409       "SELECT page, cell, field, value "
20410       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
20411       "UNION ALL "
20412       "SELECT 0, 0, 0, 0"
20413   );
20414 
20415   return p->errCode;
20416 }
20417 
20418 /*
20419 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
20420 ** sqlite3_recover.w1).
20421 */
recoverWriteDataCleanup(sqlite3_recover * p)20422 static void recoverWriteDataCleanup(sqlite3_recover *p){
20423   RecoverStateW1 *p1 = &p->w1;
20424   int ii;
20425   for(ii=0; ii<p1->nVal; ii++){
20426     sqlite3_value_free(p1->apVal[ii]);
20427   }
20428   sqlite3_free(p1->apVal);
20429   recoverFinalize(p, p1->pInsert);
20430   recoverFinalize(p, p1->pTbls);
20431   recoverFinalize(p, p1->pSel);
20432   memset(p1, 0, sizeof(*p1));
20433 }
20434 
20435 /*
20436 ** Perform one step (sqlite3_recover_step()) of work for the connection
20437 ** passed as the only argument, which is guaranteed to be in
20438 ** RECOVER_STATE_WRITING state - during which tables recovered from the
20439 ** schema of the input database are populated with recovered data.
20440 */
recoverWriteDataStep(sqlite3_recover * p)20441 static int recoverWriteDataStep(sqlite3_recover *p){
20442   RecoverStateW1 *p1 = &p->w1;
20443   sqlite3_stmt *pSel = p1->pSel;
20444   sqlite3_value **apVal = p1->apVal;
20445 
20446   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
20447     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
20448       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
20449       p1->pTab = recoverFindTable(p, iRoot);
20450 
20451       recoverFinalize(p, p1->pInsert);
20452       p1->pInsert = 0;
20453 
20454       /* If this table is unknown, return early. The caller will invoke this
20455       ** function again and it will move on to the next table.  */
20456       if( p1->pTab==0 ) return p->errCode;
20457 
20458       /* If this is the sqlite_sequence table, delete any rows added by
20459       ** earlier INSERT statements on tables with AUTOINCREMENT primary
20460       ** keys before recovering its contents. The p1->pTbls SELECT statement
20461       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
20462       ** worry about it being modified after it is recovered. */
20463       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
20464         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
20465         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
20466       }
20467 
20468       /* Bind the root page of this table within the original database to
20469       ** SELECT statement p1->pSel. The SELECT statement will then iterate
20470       ** through cells that look like they belong to table pTab.  */
20471       sqlite3_bind_int64(pSel, 1, iRoot);
20472 
20473       p1->nVal = 0;
20474       p1->bHaveRowid = 0;
20475       p1->iPrevPage = -1;
20476       p1->iPrevCell = -1;
20477     }else{
20478       return SQLITE_DONE;
20479     }
20480   }
20481   assert( p->errCode!=SQLITE_OK || p1->pTab );
20482 
20483   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
20484     RecoverTable *pTab = p1->pTab;
20485 
20486     i64 iPage = sqlite3_column_int64(pSel, 0);
20487     int iCell = sqlite3_column_int(pSel, 1);
20488     int iField = sqlite3_column_int(pSel, 2);
20489     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
20490     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
20491 
20492     assert( bNewCell==0 || (iField==-1 || iField==0) );
20493     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
20494 
20495     if( bNewCell ){
20496       int ii = 0;
20497       if( p1->nVal>=0 ){
20498         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
20499           recoverFinalize(p, p1->pInsert);
20500           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
20501           p1->nInsert = p1->nVal;
20502         }
20503         if( p1->nVal>0 ){
20504           sqlite3_stmt *pInsert = p1->pInsert;
20505           for(ii=0; ii<pTab->nCol; ii++){
20506             RecoverColumn *pCol = &pTab->aCol[ii];
20507             int iBind = pCol->iBind;
20508             if( iBind>0 ){
20509               if( pCol->bIPK ){
20510                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
20511               }else if( pCol->iField<p1->nVal ){
20512                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
20513               }
20514             }
20515           }
20516           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
20517             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
20518           }
20519           if( SQLITE_ROW==sqlite3_step(pInsert) ){
20520             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
20521             recoverSqlCallback(p, z);
20522           }
20523           recoverReset(p, pInsert);
20524           assert( p->errCode || pInsert );
20525           if( pInsert ) sqlite3_clear_bindings(pInsert);
20526         }
20527       }
20528 
20529       for(ii=0; ii<p1->nVal; ii++){
20530         sqlite3_value_free(apVal[ii]);
20531         apVal[ii] = 0;
20532       }
20533       p1->nVal = -1;
20534       p1->bHaveRowid = 0;
20535     }
20536 
20537     if( iPage!=0 ){
20538       if( iField<0 ){
20539         p1->iRowid = sqlite3_column_int64(pSel, 3);
20540         assert( p1->nVal==-1 );
20541         p1->nVal = 0;
20542         p1->bHaveRowid = 1;
20543       }else if( iField<pTab->nCol ){
20544         assert( apVal[iField]==0 );
20545         apVal[iField] = sqlite3_value_dup( pVal );
20546         if( apVal[iField]==0 ){
20547           recoverError(p, SQLITE_NOMEM, 0);
20548         }
20549         p1->nVal = iField+1;
20550       }else if( pTab->nCol==0 ){
20551         p1->nVal = pTab->nCol;
20552       }
20553       p1->iPrevCell = iCell;
20554       p1->iPrevPage = iPage;
20555     }
20556   }else{
20557     recoverReset(p, pSel);
20558     p1->pTab = 0;
20559   }
20560 
20561   return p->errCode;
20562 }
20563 
20564 /*
20565 ** Initialize resources required by sqlite3_recover_step() in
20566 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
20567 ** already allocated to a recovered schema element is determined.
20568 */
recoverLostAndFound1Init(sqlite3_recover * p)20569 static void recoverLostAndFound1Init(sqlite3_recover *p){
20570   RecoverStateLAF *pLaf = &p->laf;
20571   sqlite3_stmt *pStmt = 0;
20572 
20573   assert( p->laf.pUsed==0 );
20574   pLaf->nPg = recoverPageCount(p);
20575   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
20576 
20577   /* Prepare a statement to iterate through all pages that are part of any tree
20578   ** in the recoverable part of the input database schema to the bitmap. And,
20579   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
20580   ** freelist.  */
20581   pStmt = recoverPrepare(
20582       p, p->dbOut,
20583       "WITH trunk(pgno) AS ("
20584       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
20585       "    UNION"
20586       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
20587       "),"
20588       "trunkdata(pgno, data) AS ("
20589       "  SELECT pgno, getpage(pgno) FROM trunk"
20590       "),"
20591       "freelist(data, n, freepgno) AS ("
20592       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
20593       "    UNION ALL"
20594       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
20595       "),"
20596       ""
20597       "roots(r) AS ("
20598       "  SELECT 1 UNION ALL"
20599       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
20600       "),"
20601       "used(page) AS ("
20602       "  SELECT r FROM roots"
20603       "    UNION"
20604       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
20605       "    WHERE pgno=page"
20606       ") "
20607       "SELECT page FROM used"
20608       " UNION ALL "
20609       "SELECT freepgno FROM freelist WHERE NOT ?"
20610   );
20611   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
20612   pLaf->pUsedPages = pStmt;
20613 }
20614 
20615 /*
20616 ** Perform one step (sqlite3_recover_step()) of work for the connection
20617 ** passed as the only argument, which is guaranteed to be in
20618 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
20619 ** already allocated to a recovered schema element is determined.
20620 */
recoverLostAndFound1Step(sqlite3_recover * p)20621 static int recoverLostAndFound1Step(sqlite3_recover *p){
20622   RecoverStateLAF *pLaf = &p->laf;
20623   int rc = p->errCode;
20624   if( rc==SQLITE_OK ){
20625     rc = sqlite3_step(pLaf->pUsedPages);
20626     if( rc==SQLITE_ROW ){
20627       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
20628       recoverBitmapSet(pLaf->pUsed, iPg);
20629       rc = SQLITE_OK;
20630     }else{
20631       recoverFinalize(p, pLaf->pUsedPages);
20632       pLaf->pUsedPages = 0;
20633     }
20634   }
20635   return rc;
20636 }
20637 
20638 /*
20639 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
20640 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
20641 ** are sorted into sets that likely belonged to the same database tree.
20642 */
recoverLostAndFound2Init(sqlite3_recover * p)20643 static void recoverLostAndFound2Init(sqlite3_recover *p){
20644   RecoverStateLAF *pLaf = &p->laf;
20645 
20646   assert( p->laf.pAllAndParent==0 );
20647   assert( p->laf.pMapInsert==0 );
20648   assert( p->laf.pMaxField==0 );
20649   assert( p->laf.nMaxField==0 );
20650 
20651   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
20652       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
20653   );
20654   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
20655       "WITH RECURSIVE seq(ii) AS ("
20656       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
20657       ")"
20658       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
20659       " UNION ALL "
20660       "SELECT NULL, ii FROM seq", p->laf.nPg
20661   );
20662   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
20663       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
20664   );
20665 }
20666 
20667 /*
20668 ** Perform one step (sqlite3_recover_step()) of work for the connection
20669 ** passed as the only argument, which is guaranteed to be in
20670 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
20671 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
20672 ** to the same database tree.
20673 */
recoverLostAndFound2Step(sqlite3_recover * p)20674 static int recoverLostAndFound2Step(sqlite3_recover *p){
20675   RecoverStateLAF *pLaf = &p->laf;
20676   if( p->errCode==SQLITE_OK ){
20677     int res = sqlite3_step(pLaf->pAllAndParent);
20678     if( res==SQLITE_ROW ){
20679       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
20680       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
20681         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
20682         sqlite3_bind_value(pLaf->pMapInsert, 2,
20683             sqlite3_column_value(pLaf->pAllAndParent, 0)
20684         );
20685         sqlite3_step(pLaf->pMapInsert);
20686         recoverReset(p, pLaf->pMapInsert);
20687         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
20688         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
20689           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
20690           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
20691         }
20692         recoverReset(p, pLaf->pMaxField);
20693       }
20694     }else{
20695       recoverFinalize(p, pLaf->pAllAndParent);
20696       pLaf->pAllAndParent =0;
20697       return SQLITE_DONE;
20698     }
20699   }
20700   return p->errCode;
20701 }
20702 
20703 /*
20704 ** Free all resources allocated as part of sqlite3_recover_step() calls
20705 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
20706 */
recoverLostAndFoundCleanup(sqlite3_recover * p)20707 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
20708   recoverBitmapFree(p->laf.pUsed);
20709   p->laf.pUsed = 0;
20710   sqlite3_finalize(p->laf.pUsedPages);
20711   sqlite3_finalize(p->laf.pAllAndParent);
20712   sqlite3_finalize(p->laf.pMapInsert);
20713   sqlite3_finalize(p->laf.pMaxField);
20714   sqlite3_finalize(p->laf.pFindRoot);
20715   sqlite3_finalize(p->laf.pInsert);
20716   sqlite3_finalize(p->laf.pAllPage);
20717   sqlite3_finalize(p->laf.pPageData);
20718   p->laf.pUsedPages = 0;
20719   p->laf.pAllAndParent = 0;
20720   p->laf.pMapInsert = 0;
20721   p->laf.pMaxField = 0;
20722   p->laf.pFindRoot = 0;
20723   p->laf.pInsert = 0;
20724   p->laf.pAllPage = 0;
20725   p->laf.pPageData = 0;
20726   sqlite3_free(p->laf.apVal);
20727   p->laf.apVal = 0;
20728 }
20729 
20730 /*
20731 ** Free all resources allocated as part of sqlite3_recover_step() calls.
20732 */
recoverFinalCleanup(sqlite3_recover * p)20733 static void recoverFinalCleanup(sqlite3_recover *p){
20734   RecoverTable *pTab = 0;
20735   RecoverTable *pNext = 0;
20736 
20737   recoverWriteDataCleanup(p);
20738   recoverLostAndFoundCleanup(p);
20739 
20740   for(pTab=p->pTblList; pTab; pTab=pNext){
20741     pNext = pTab->pNext;
20742     sqlite3_free(pTab);
20743   }
20744   p->pTblList = 0;
20745   sqlite3_finalize(p->pGetPage);
20746   p->pGetPage = 0;
20747   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
20748 
20749   {
20750 #ifndef NDEBUG
20751     int res =
20752 #endif
20753        sqlite3_close(p->dbOut);
20754     assert( res==SQLITE_OK );
20755   }
20756   p->dbOut = 0;
20757 }
20758 
20759 /*
20760 ** Decode and return an unsigned 16-bit big-endian integer value from
20761 ** buffer a[].
20762 */
recoverGetU16(const u8 * a)20763 static u32 recoverGetU16(const u8 *a){
20764   return (((u32)a[0])<<8) + ((u32)a[1]);
20765 }
20766 
20767 /*
20768 ** Decode and return an unsigned 32-bit big-endian integer value from
20769 ** buffer a[].
20770 */
recoverGetU32(const u8 * a)20771 static u32 recoverGetU32(const u8 *a){
20772   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
20773 }
20774 
20775 /*
20776 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
20777 ** and return the number of bytes consumed.
20778 */
recoverGetVarint(const u8 * a,i64 * pVal)20779 static int recoverGetVarint(const u8 *a, i64 *pVal){
20780   sqlite3_uint64 u = 0;
20781   int i;
20782   for(i=0; i<8; i++){
20783     u = (u<<7) + (a[i]&0x7f);
20784     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
20785   }
20786   u = (u<<8) + (a[i]&0xff);
20787   *pVal = (sqlite3_int64)u;
20788   return 9;
20789 }
20790 
20791 /*
20792 ** The second argument points to a buffer n bytes in size. If this buffer
20793 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
20794 ** return the page-size in bytes. Otherwise, if the buffer does not
20795 ** appear to contain a well-formed b-tree page, return 0.
20796 */
recoverIsValidPage(u8 * aTmp,const u8 * a,int n)20797 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
20798   u8 *aUsed = aTmp;
20799   int nFrag = 0;
20800   int nActual = 0;
20801   int iFree = 0;
20802   int nCell = 0;                  /* Number of cells on page */
20803   int iCellOff = 0;               /* Offset of cell array in page */
20804   int iContent = 0;
20805   int eType = 0;
20806   int ii = 0;
20807 
20808   eType = (int)a[0];
20809   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
20810 
20811   iFree = (int)recoverGetU16(&a[1]);
20812   nCell = (int)recoverGetU16(&a[3]);
20813   iContent = (int)recoverGetU16(&a[5]);
20814   if( iContent==0 ) iContent = 65536;
20815   nFrag = (int)a[7];
20816 
20817   if( iContent>n ) return 0;
20818 
20819   memset(aUsed, 0, n);
20820   memset(aUsed, 0xFF, iContent);
20821 
20822   /* Follow the free-list. This is the same format for all b-tree pages. */
20823   if( iFree && iFree<=iContent ) return 0;
20824   while( iFree ){
20825     int iNext = 0;
20826     int nByte = 0;
20827     if( iFree>(n-4) ) return 0;
20828     iNext = recoverGetU16(&a[iFree]);
20829     nByte = recoverGetU16(&a[iFree+2]);
20830     if( iFree+nByte>n || nByte<4 ) return 0;
20831     if( iNext && iNext<iFree+nByte ) return 0;
20832     memset(&aUsed[iFree], 0xFF, nByte);
20833     iFree = iNext;
20834   }
20835 
20836   /* Run through the cells */
20837   if( eType==0x02 || eType==0x05 ){
20838     iCellOff = 12;
20839   }else{
20840     iCellOff = 8;
20841   }
20842   if( (iCellOff + 2*nCell)>iContent ) return 0;
20843   for(ii=0; ii<nCell; ii++){
20844     int iByte;
20845     i64 nPayload = 0;
20846     int nByte = 0;
20847     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
20848     if( iOff<iContent || iOff>n ){
20849       return 0;
20850     }
20851     if( eType==0x05 || eType==0x02 ) nByte += 4;
20852     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
20853     if( eType==0x0D ){
20854       i64 dummy = 0;
20855       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
20856     }
20857     if( eType!=0x05 ){
20858       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
20859       int M = ((n-12)*32/255)-23;
20860       int K = M+((nPayload-M)%(n-4));
20861 
20862       if( nPayload<X ){
20863         nByte += nPayload;
20864       }else if( K<=X ){
20865         nByte += K+4;
20866       }else{
20867         nByte += M+4;
20868       }
20869     }
20870 
20871     if( iOff+nByte>n ){
20872       return 0;
20873     }
20874     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
20875       if( aUsed[iByte]!=0 ){
20876         return 0;
20877       }
20878       aUsed[iByte] = 0xFF;
20879     }
20880   }
20881 
20882   nActual = 0;
20883   for(ii=0; ii<n; ii++){
20884     if( aUsed[ii]==0 ) nActual++;
20885   }
20886   return (nActual==nFrag);
20887 }
20888 
20889 
20890 static int recoverVfsClose(sqlite3_file*);
20891 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
20892 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
20893 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
20894 static int recoverVfsSync(sqlite3_file*, int flags);
20895 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
20896 static int recoverVfsLock(sqlite3_file*, int);
20897 static int recoverVfsUnlock(sqlite3_file*, int);
20898 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
20899 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
20900 static int recoverVfsSectorSize(sqlite3_file*);
20901 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
20902 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
20903 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
20904 static void recoverVfsShmBarrier(sqlite3_file*);
20905 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
20906 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
20907 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
20908 
20909 static sqlite3_io_methods recover_methods = {
20910   2, /* iVersion */
20911   recoverVfsClose,
20912   recoverVfsRead,
20913   recoverVfsWrite,
20914   recoverVfsTruncate,
20915   recoverVfsSync,
20916   recoverVfsFileSize,
20917   recoverVfsLock,
20918   recoverVfsUnlock,
20919   recoverVfsCheckReservedLock,
20920   recoverVfsFileControl,
20921   recoverVfsSectorSize,
20922   recoverVfsDeviceCharacteristics,
20923   recoverVfsShmMap,
20924   recoverVfsShmLock,
20925   recoverVfsShmBarrier,
20926   recoverVfsShmUnmap,
20927   recoverVfsFetch,
20928   recoverVfsUnfetch
20929 };
20930 
recoverVfsClose(sqlite3_file * pFd)20931 static int recoverVfsClose(sqlite3_file *pFd){
20932   assert( pFd->pMethods!=&recover_methods );
20933   return pFd->pMethods->xClose(pFd);
20934 }
20935 
20936 /*
20937 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
20938 */
recoverPutU16(u8 * a,u32 v)20939 static void recoverPutU16(u8 *a, u32 v){
20940   a[0] = (v>>8) & 0x00FF;
20941   a[1] = (v>>0) & 0x00FF;
20942 }
20943 
20944 /*
20945 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
20946 */
recoverPutU32(u8 * a,u32 v)20947 static void recoverPutU32(u8 *a, u32 v){
20948   a[0] = (v>>24) & 0x00FF;
20949   a[1] = (v>>16) & 0x00FF;
20950   a[2] = (v>>8) & 0x00FF;
20951   a[3] = (v>>0) & 0x00FF;
20952 }
20953 
20954 /*
20955 ** Detect the page-size of the database opened by file-handle pFd by
20956 ** searching the first part of the file for a well-formed SQLite b-tree
20957 ** page. If parameter nReserve is non-zero, then as well as searching for
20958 ** a b-tree page with zero reserved bytes, this function searches for one
20959 ** with nReserve reserved bytes at the end of it.
20960 **
20961 ** If successful, set variable p->detected_pgsz to the detected page-size
20962 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
20963 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
20964 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
20965 ** is returned. The final value of p->detected_pgsz is undefined in this
20966 ** case.
20967 */
recoverVfsDetectPagesize(sqlite3_recover * p,sqlite3_file * pFd,u32 nReserve,i64 nSz)20968 static int recoverVfsDetectPagesize(
20969   sqlite3_recover *p,             /* Recover handle */
20970   sqlite3_file *pFd,              /* File-handle open on input database */
20971   u32 nReserve,                   /* Possible nReserve value */
20972   i64 nSz                         /* Size of database file in bytes */
20973 ){
20974   int rc = SQLITE_OK;
20975   const int nMin = 512;
20976   const int nMax = 65536;
20977   const int nMaxBlk = 4;
20978   u32 pgsz = 0;
20979   int iBlk = 0;
20980   u8 *aPg = 0;
20981   u8 *aTmp = 0;
20982   int nBlk = 0;
20983 
20984   aPg = (u8*)sqlite3_malloc(2*nMax);
20985   if( aPg==0 ) return SQLITE_NOMEM;
20986   aTmp = &aPg[nMax];
20987 
20988   nBlk = (nSz+nMax-1)/nMax;
20989   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
20990 
20991   do {
20992     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
20993       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
20994       memset(aPg, 0, nMax);
20995       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
20996       if( rc==SQLITE_OK ){
20997         int pgsz2;
20998         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
20999           int iOff;
21000           for(iOff=0; iOff<nMax; iOff+=pgsz2){
21001             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
21002               pgsz = pgsz2;
21003               break;
21004             }
21005           }
21006         }
21007       }
21008     }
21009     if( pgsz>(u32)p->detected_pgsz ){
21010       p->detected_pgsz = pgsz;
21011       p->nReserve = nReserve;
21012     }
21013     if( nReserve==0 ) break;
21014     nReserve = 0;
21015   }while( 1 );
21016 
21017   p->detected_pgsz = pgsz;
21018   sqlite3_free(aPg);
21019   return rc;
21020 }
21021 
21022 /*
21023 ** The xRead() method of the wrapper VFS. This is used to intercept calls
21024 ** to read page 1 of the input database.
21025 */
recoverVfsRead(sqlite3_file * pFd,void * aBuf,int nByte,i64 iOff)21026 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
21027   int rc = SQLITE_OK;
21028   if( pFd->pMethods==&recover_methods ){
21029     pFd->pMethods = recover_g.pMethods;
21030     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
21031     if( nByte==16 ){
21032       sqlite3_randomness(16, aBuf);
21033     }else
21034     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
21035       /* Ensure that the database has a valid header file. The only fields
21036       ** that really matter to recovery are:
21037       **
21038       **   + Database page size (16-bits at offset 16)
21039       **   + Size of db in pages (32-bits at offset 28)
21040       **   + Database encoding (32-bits at offset 56)
21041       **
21042       ** Also preserved are:
21043       **
21044       **   + first freelist page (32-bits at offset 32)
21045       **   + size of freelist (32-bits at offset 36)
21046       **   + the wal-mode flags (16-bits at offset 18)
21047       **
21048       ** We also try to preserve the auto-vacuum, incr-value, user-version
21049       ** and application-id fields - all 32 bit quantities at offsets
21050       ** 52, 60, 64 and 68. All other fields are set to known good values.
21051       **
21052       ** Byte offset 105 should also contain the page-size as a 16-bit
21053       ** integer.
21054       */
21055       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
21056       u8 aHdr[108] = {
21057         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
21058         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
21059         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
21060         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
21061         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
21062         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
21063         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
21064         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
21065         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
21066         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
21067         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
21068         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
21069         0x00, 0x2e, 0x5b, 0x30,
21070 
21071         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
21072       };
21073       u8 *a = (u8*)aBuf;
21074 
21075       u32 pgsz = recoverGetU16(&a[16]);
21076       u32 nReserve = a[20];
21077       u32 enc = recoverGetU32(&a[56]);
21078       u32 dbsz = 0;
21079       i64 dbFileSize = 0;
21080       int ii;
21081       sqlite3_recover *p = recover_g.p;
21082 
21083       if( pgsz==0x01 ) pgsz = 65536;
21084       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
21085 
21086       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
21087         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
21088       }
21089       if( p->detected_pgsz ){
21090         pgsz = p->detected_pgsz;
21091         nReserve = p->nReserve;
21092       }
21093 
21094       if( pgsz ){
21095         dbsz = dbFileSize / pgsz;
21096       }
21097       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
21098         enc = SQLITE_UTF8;
21099       }
21100 
21101       sqlite3_free(p->pPage1Cache);
21102       p->pPage1Cache = 0;
21103       p->pPage1Disk = 0;
21104 
21105       p->pgsz = nByte;
21106       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
21107       if( p->pPage1Cache ){
21108         p->pPage1Disk = &p->pPage1Cache[nByte];
21109         memcpy(p->pPage1Disk, aBuf, nByte);
21110         aHdr[18] = a[18];
21111         aHdr[19] = a[19];
21112         recoverPutU32(&aHdr[28], dbsz);
21113         recoverPutU32(&aHdr[56], enc);
21114         recoverPutU16(&aHdr[105], pgsz-nReserve);
21115         if( pgsz==65536 ) pgsz = 1;
21116         recoverPutU16(&aHdr[16], pgsz);
21117         aHdr[20] = nReserve;
21118         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
21119           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
21120         }
21121         memcpy(aBuf, aHdr, sizeof(aHdr));
21122         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
21123 
21124         memcpy(p->pPage1Cache, aBuf, nByte);
21125       }else{
21126         rc = p->errCode;
21127       }
21128 
21129     }
21130     pFd->pMethods = &recover_methods;
21131   }else{
21132     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
21133   }
21134   return rc;
21135 }
21136 
21137 /*
21138 ** Used to make sqlite3_io_methods wrapper methods less verbose.
21139 */
21140 #define RECOVER_VFS_WRAPPER(code)                         \
21141   int rc = SQLITE_OK;                                     \
21142   if( pFd->pMethods==&recover_methods ){                  \
21143     pFd->pMethods = recover_g.pMethods;                   \
21144     rc = code;                                            \
21145     pFd->pMethods = &recover_methods;                     \
21146   }else{                                                  \
21147     rc = code;                                            \
21148   }                                                       \
21149   return rc;
21150 
21151 /*
21152 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
21153 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
21154 ** method on the lower level VFS, then reinstall the wrapper before returning.
21155 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
21156 */
recoverVfsWrite(sqlite3_file * pFd,const void * aBuf,int nByte,i64 iOff)21157 static int recoverVfsWrite(
21158   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
21159 ){
21160   RECOVER_VFS_WRAPPER (
21161       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
21162   );
21163 }
recoverVfsTruncate(sqlite3_file * pFd,sqlite3_int64 size)21164 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
21165   RECOVER_VFS_WRAPPER (
21166       pFd->pMethods->xTruncate(pFd, size)
21167   );
21168 }
recoverVfsSync(sqlite3_file * pFd,int flags)21169 static int recoverVfsSync(sqlite3_file *pFd, int flags){
21170   RECOVER_VFS_WRAPPER (
21171       pFd->pMethods->xSync(pFd, flags)
21172   );
21173 }
recoverVfsFileSize(sqlite3_file * pFd,sqlite3_int64 * pSize)21174 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
21175   RECOVER_VFS_WRAPPER (
21176       pFd->pMethods->xFileSize(pFd, pSize)
21177   );
21178 }
recoverVfsLock(sqlite3_file * pFd,int eLock)21179 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
21180   RECOVER_VFS_WRAPPER (
21181       pFd->pMethods->xLock(pFd, eLock)
21182   );
21183 }
recoverVfsUnlock(sqlite3_file * pFd,int eLock)21184 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
21185   RECOVER_VFS_WRAPPER (
21186       pFd->pMethods->xUnlock(pFd, eLock)
21187   );
21188 }
recoverVfsCheckReservedLock(sqlite3_file * pFd,int * pResOut)21189 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
21190   RECOVER_VFS_WRAPPER (
21191       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
21192   );
21193 }
recoverVfsFileControl(sqlite3_file * pFd,int op,void * pArg)21194 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
21195   RECOVER_VFS_WRAPPER (
21196     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
21197   );
21198 }
recoverVfsSectorSize(sqlite3_file * pFd)21199 static int recoverVfsSectorSize(sqlite3_file *pFd){
21200   RECOVER_VFS_WRAPPER (
21201       pFd->pMethods->xSectorSize(pFd)
21202   );
21203 }
recoverVfsDeviceCharacteristics(sqlite3_file * pFd)21204 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
21205   RECOVER_VFS_WRAPPER (
21206       pFd->pMethods->xDeviceCharacteristics(pFd)
21207   );
21208 }
recoverVfsShmMap(sqlite3_file * pFd,int iPg,int pgsz,int bExtend,void volatile ** pp)21209 static int recoverVfsShmMap(
21210   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
21211 ){
21212   RECOVER_VFS_WRAPPER (
21213       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
21214   );
21215 }
recoverVfsShmLock(sqlite3_file * pFd,int offset,int n,int flags)21216 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
21217   RECOVER_VFS_WRAPPER (
21218       pFd->pMethods->xShmLock(pFd, offset, n, flags)
21219   );
21220 }
recoverVfsShmBarrier(sqlite3_file * pFd)21221 static void recoverVfsShmBarrier(sqlite3_file *pFd){
21222   if( pFd->pMethods==&recover_methods ){
21223     pFd->pMethods = recover_g.pMethods;
21224     pFd->pMethods->xShmBarrier(pFd);
21225     pFd->pMethods = &recover_methods;
21226   }else{
21227     pFd->pMethods->xShmBarrier(pFd);
21228   }
21229 }
recoverVfsShmUnmap(sqlite3_file * pFd,int deleteFlag)21230 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
21231   RECOVER_VFS_WRAPPER (
21232       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
21233   );
21234 }
21235 
recoverVfsFetch(sqlite3_file * pFd,sqlite3_int64 iOff,int iAmt,void ** pp)21236 static int recoverVfsFetch(
21237   sqlite3_file *pFd,
21238   sqlite3_int64 iOff,
21239   int iAmt,
21240   void **pp
21241 ){
21242   (void)pFd;
21243   (void)iOff;
21244   (void)iAmt;
21245   *pp = 0;
21246   return SQLITE_OK;
21247 }
recoverVfsUnfetch(sqlite3_file * pFd,sqlite3_int64 iOff,void * p)21248 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
21249   (void)pFd;
21250   (void)iOff;
21251   (void)p;
21252   return SQLITE_OK;
21253 }
21254 
21255 /*
21256 ** Install the VFS wrapper around the file-descriptor open on the input
21257 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
21258 ** when this function is called.
21259 */
recoverInstallWrapper(sqlite3_recover * p)21260 static void recoverInstallWrapper(sqlite3_recover *p){
21261   sqlite3_file *pFd = 0;
21262   assert( recover_g.pMethods==0 );
21263   recoverAssertMutexHeld();
21264   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
21265   assert( pFd==0 || pFd->pMethods!=&recover_methods );
21266   if( pFd && pFd->pMethods ){
21267     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
21268     recover_g.pMethods = pFd->pMethods;
21269     recover_g.p = p;
21270     recover_methods.iVersion = iVersion;
21271     pFd->pMethods = &recover_methods;
21272   }
21273 }
21274 
21275 /*
21276 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
21277 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
21278 ** held when this function is called.
21279 */
recoverUninstallWrapper(sqlite3_recover * p)21280 static void recoverUninstallWrapper(sqlite3_recover *p){
21281   sqlite3_file *pFd = 0;
21282   recoverAssertMutexHeld();
21283   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
21284   if( pFd && pFd->pMethods ){
21285     pFd->pMethods = recover_g.pMethods;
21286     recover_g.pMethods = 0;
21287     recover_g.p = 0;
21288   }
21289 }
21290 
21291 /*
21292 ** This function does the work of a single sqlite3_recover_step() call. It
21293 ** is guaranteed that the handle is not in an error state when this
21294 ** function is called.
21295 */
recoverStep(sqlite3_recover * p)21296 static void recoverStep(sqlite3_recover *p){
21297   assert( p && p->errCode==SQLITE_OK );
21298   switch( p->eState ){
21299     case RECOVER_STATE_INIT: {
21300       int bUseWrapper = 1;
21301       /* This is the very first call to sqlite3_recover_step() on this object.
21302       */
21303       recoverSqlCallback(p, "BEGIN");
21304       recoverSqlCallback(p, "PRAGMA writable_schema = on");
21305       recoverSqlCallback(p, "PRAGMA foreign_keys = off");
21306 
21307       recoverEnterMutex();
21308 
21309       /* Open the output database. And register required virtual tables and
21310       ** user functions with the new handle. */
21311       recoverOpenOutput(p);
21312 
21313       /* Attempt to open a transaction and read page 1 of the input database.
21314       ** Two attempts may be made - one with a wrapper installed to ensure
21315       ** that the database header is sane, and then if that attempt returns
21316       ** SQLITE_NOTADB, then again with no wrapper. The second attempt is
21317       ** required for encrypted databases.  */
21318       if( p->errCode==SQLITE_OK ){
21319         do{
21320           p->errCode = SQLITE_OK;
21321           if( bUseWrapper ) recoverInstallWrapper(p);
21322 
21323           /* Open a transaction on the input database. */
21324           sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
21325           recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
21326           recoverExec(p, p->dbIn, "BEGIN");
21327           if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
21328           recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
21329           recoverTransferSettings(p);
21330           recoverOpenRecovery(p);
21331           recoverCacheSchema(p);
21332 
21333           if( bUseWrapper ) recoverUninstallWrapper(p);
21334         }while( p->errCode==SQLITE_NOTADB
21335              && (bUseWrapper--)
21336              && SQLITE_OK==sqlite3_exec(p->dbIn, "ROLLBACK", 0, 0, 0)
21337         );
21338       }
21339 
21340       recoverLeaveMutex();
21341       recoverExec(p, p->dbOut, "BEGIN");
21342       recoverWriteSchema1(p);
21343       p->eState = RECOVER_STATE_WRITING;
21344       break;
21345     }
21346 
21347     case RECOVER_STATE_WRITING: {
21348       if( p->w1.pTbls==0 ){
21349         recoverWriteDataInit(p);
21350       }
21351       if( SQLITE_DONE==recoverWriteDataStep(p) ){
21352         recoverWriteDataCleanup(p);
21353         if( p->zLostAndFound ){
21354           p->eState = RECOVER_STATE_LOSTANDFOUND1;
21355         }else{
21356           p->eState = RECOVER_STATE_SCHEMA2;
21357         }
21358       }
21359       break;
21360     }
21361 
21362     case RECOVER_STATE_LOSTANDFOUND1: {
21363       if( p->laf.pUsed==0 ){
21364         recoverLostAndFound1Init(p);
21365       }
21366       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
21367         p->eState = RECOVER_STATE_LOSTANDFOUND2;
21368       }
21369       break;
21370     }
21371     case RECOVER_STATE_LOSTANDFOUND2: {
21372       if( p->laf.pAllAndParent==0 ){
21373         recoverLostAndFound2Init(p);
21374       }
21375       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
21376         p->eState = RECOVER_STATE_LOSTANDFOUND3;
21377       }
21378       break;
21379     }
21380 
21381     case RECOVER_STATE_LOSTANDFOUND3: {
21382       if( p->laf.pInsert==0 ){
21383         recoverLostAndFound3Init(p);
21384       }
21385       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
21386         p->eState = RECOVER_STATE_SCHEMA2;
21387       }
21388       break;
21389     }
21390 
21391     case RECOVER_STATE_SCHEMA2: {
21392       int rc = SQLITE_OK;
21393 
21394       recoverWriteSchema2(p);
21395       p->eState = RECOVER_STATE_DONE;
21396 
21397       /* If no error has occurred, commit the write transaction on the output
21398       ** database. Regardless of whether or not an error has occurred, make
21399       ** an attempt to end the read transaction on the input database.  */
21400       recoverExec(p, p->dbOut, "COMMIT");
21401       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
21402       if( p->errCode==SQLITE_OK ) p->errCode = rc;
21403 
21404       recoverSqlCallback(p, "PRAGMA writable_schema = off");
21405       recoverSqlCallback(p, "COMMIT");
21406       p->eState = RECOVER_STATE_DONE;
21407       recoverFinalCleanup(p);
21408       break;
21409     };
21410 
21411     case RECOVER_STATE_DONE: {
21412       /* no-op */
21413       break;
21414     };
21415   }
21416 }
21417 
21418 
21419 /*
21420 ** This is a worker function that does the heavy lifting for both init
21421 ** functions:
21422 **
21423 **     sqlite3_recover_init()
21424 **     sqlite3_recover_init_sql()
21425 **
21426 ** All this function does is allocate space for the recover handle and
21427 ** take copies of the input parameters. All the real work is done within
21428 ** sqlite3_recover_run().
21429 */
recoverInit(sqlite3 * db,const char * zDb,const char * zUri,int (* xSql)(void *,const char *),void * pSqlCtx)21430 sqlite3_recover *recoverInit(
21431   sqlite3* db,
21432   const char *zDb,
21433   const char *zUri,               /* Output URI for _recover_init() */
21434   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
21435   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
21436 ){
21437   sqlite3_recover *pRet = 0;
21438   int nDb = 0;
21439   int nUri = 0;
21440   int nByte = 0;
21441 
21442   if( zDb==0 ){ zDb = "main"; }
21443 
21444   nDb = recoverStrlen(zDb);
21445   nUri = recoverStrlen(zUri);
21446 
21447   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
21448   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
21449   if( pRet ){
21450     memset(pRet, 0, nByte);
21451     pRet->dbIn = db;
21452     pRet->zDb = (char*)&pRet[1];
21453     pRet->zUri = &pRet->zDb[nDb+1];
21454     memcpy(pRet->zDb, zDb, nDb);
21455     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
21456     pRet->xSql = xSql;
21457     pRet->pSqlCtx = pSqlCtx;
21458     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
21459   }
21460 
21461   return pRet;
21462 }
21463 
21464 /*
21465 ** Initialize a recovery handle that creates a new database containing
21466 ** the recovered data.
21467 */
sqlite3_recover_init(sqlite3 * db,const char * zDb,const char * zUri)21468 sqlite3_recover *sqlite3_recover_init(
21469   sqlite3* db,
21470   const char *zDb,
21471   const char *zUri
21472 ){
21473   return recoverInit(db, zDb, zUri, 0, 0);
21474 }
21475 
21476 /*
21477 ** Initialize a recovery handle that returns recovered data in the
21478 ** form of SQL statements via a callback.
21479 */
sqlite3_recover_init_sql(sqlite3 * db,const char * zDb,int (* xSql)(void *,const char *),void * pSqlCtx)21480 sqlite3_recover *sqlite3_recover_init_sql(
21481   sqlite3* db,
21482   const char *zDb,
21483   int (*xSql)(void*, const char*),
21484   void *pSqlCtx
21485 ){
21486   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
21487 }
21488 
21489 /*
21490 ** Return the handle error message, if any.
21491 */
sqlite3_recover_errmsg(sqlite3_recover * p)21492 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
21493   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
21494 }
21495 
21496 /*
21497 ** Return the handle error code.
21498 */
sqlite3_recover_errcode(sqlite3_recover * p)21499 int sqlite3_recover_errcode(sqlite3_recover *p){
21500   return p ? p->errCode : SQLITE_NOMEM;
21501 }
21502 
21503 /*
21504 ** Configure the handle.
21505 */
sqlite3_recover_config(sqlite3_recover * p,int op,void * pArg)21506 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
21507   int rc = SQLITE_OK;
21508   if( p==0 ){
21509     rc = SQLITE_NOMEM;
21510   }else if( p->eState!=RECOVER_STATE_INIT ){
21511     rc = SQLITE_MISUSE;
21512   }else{
21513     switch( op ){
21514       case 789:
21515         /* This undocumented magic configuration option is used to set the
21516         ** name of the auxiliary database that is ATTACH-ed to the database
21517         ** connection and used to hold state information during the
21518         ** recovery process.  This option is for debugging use only and
21519         ** is subject to change or removal at any time. */
21520         sqlite3_free(p->zStateDb);
21521         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
21522         break;
21523 
21524       case SQLITE_RECOVER_LOST_AND_FOUND: {
21525         const char *zArg = (const char*)pArg;
21526         sqlite3_free(p->zLostAndFound);
21527         if( zArg ){
21528           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
21529         }else{
21530           p->zLostAndFound = 0;
21531         }
21532         break;
21533       }
21534 
21535       case SQLITE_RECOVER_FREELIST_CORRUPT:
21536         p->bFreelistCorrupt = *(int*)pArg;
21537         break;
21538 
21539       case SQLITE_RECOVER_ROWIDS:
21540         p->bRecoverRowid = *(int*)pArg;
21541         break;
21542 
21543       case SQLITE_RECOVER_SLOWINDEXES:
21544         p->bSlowIndexes = *(int*)pArg;
21545         break;
21546 
21547       default:
21548         rc = SQLITE_NOTFOUND;
21549         break;
21550     }
21551   }
21552 
21553   return rc;
21554 }
21555 
21556 /*
21557 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
21558 ** no error has occurred but database recovery is not finished, SQLITE_DONE
21559 ** if database recovery has been successfully completed, or an SQLite
21560 ** error code if an error has occurred.
21561 */
sqlite3_recover_step(sqlite3_recover * p)21562 int sqlite3_recover_step(sqlite3_recover *p){
21563   if( p==0 ) return SQLITE_NOMEM;
21564   if( p->errCode==SQLITE_OK ) recoverStep(p);
21565   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
21566     return SQLITE_DONE;
21567   }
21568   return p->errCode;
21569 }
21570 
21571 /*
21572 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
21573 ** else an SQLite error code.
21574 */
sqlite3_recover_run(sqlite3_recover * p)21575 int sqlite3_recover_run(sqlite3_recover *p){
21576   while( SQLITE_OK==sqlite3_recover_step(p) );
21577   return sqlite3_recover_errcode(p);
21578 }
21579 
21580 
21581 /*
21582 ** Free all resources associated with the recover handle passed as the only
21583 ** argument. The results of using a handle with any sqlite3_recover_**
21584 ** API function after it has been passed to this function are undefined.
21585 **
21586 ** A copy of the value returned by the first call made to sqlite3_recover_run()
21587 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
21588 ** not been called on this handle.
21589 */
sqlite3_recover_finish(sqlite3_recover * p)21590 int sqlite3_recover_finish(sqlite3_recover *p){
21591   int rc;
21592   if( p==0 ){
21593     rc = SQLITE_NOMEM;
21594   }else{
21595     recoverFinalCleanup(p);
21596     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
21597       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
21598       if( p->errCode==SQLITE_OK ) p->errCode = rc;
21599     }
21600     rc = p->errCode;
21601     sqlite3_free(p->zErrMsg);
21602     sqlite3_free(p->zStateDb);
21603     sqlite3_free(p->zLostAndFound);
21604     sqlite3_free(p->pPage1Cache);
21605     sqlite3_free(p);
21606   }
21607   return rc;
21608 }
21609 
21610 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
21611 
21612 /************************* End ../ext/recover/sqlite3recover.c ********************/
21613 # endif /* SQLITE_HAVE_SQLITE3R */
21614 #endif
21615 #ifdef SQLITE_SHELL_EXTSRC
21616 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
21617 #endif
21618 
21619 #if defined(SQLITE_ENABLE_SESSION)
21620 /*
21621 ** State information for a single open session
21622 */
21623 typedef struct OpenSession OpenSession;
21624 struct OpenSession {
21625   char *zName;             /* Symbolic name for this session */
21626   int nFilter;             /* Number of xFilter rejection GLOB patterns */
21627   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
21628   sqlite3_session *p;      /* The open session */
21629 };
21630 #endif
21631 
21632 typedef struct ExpertInfo ExpertInfo;
21633 struct ExpertInfo {
21634   sqlite3expert *pExpert;
21635   int bVerbose;
21636 };
21637 
21638 /* A single line in the EQP output */
21639 typedef struct EQPGraphRow EQPGraphRow;
21640 struct EQPGraphRow {
21641   int iEqpId;           /* ID for this row */
21642   int iParentId;        /* ID of the parent row */
21643   EQPGraphRow *pNext;   /* Next row in sequence */
21644   char zText[1];        /* Text to display for this row */
21645 };
21646 
21647 /* All EQP output is collected into an instance of the following */
21648 typedef struct EQPGraph EQPGraph;
21649 struct EQPGraph {
21650   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
21651   EQPGraphRow *pLast;   /* Last element of the pRow list */
21652   char zPrefix[100];    /* Graph prefix */
21653 };
21654 
21655 /* Parameters affecting columnar mode result display (defaulting together) */
21656 typedef struct ColModeOpts {
21657   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
21658   u8 bQuote;            /* Quote results for .mode box and table */
21659   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
21660 } ColModeOpts;
21661 #define ColModeOpts_default { 60, 0, 0 }
21662 #define ColModeOpts_default_qbox { 60, 1, 0 }
21663 
21664 /*
21665 ** State information about the database connection is contained in an
21666 ** instance of the following structure.
21667 */
21668 typedef struct ShellState ShellState;
21669 struct ShellState {
21670   sqlite3 *db;           /* The database */
21671   u8 autoExplain;        /* Automatically turn on .explain mode */
21672   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
21673   u8 autoEQPtest;        /* autoEQP is in test mode */
21674   u8 autoEQPtrace;       /* autoEQP is in trace mode */
21675   u8 scanstatsOn;        /* True to display scan stats before each finalize */
21676   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
21677   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
21678   u8 nEqpLevel;          /* Depth of the EQP output graph */
21679   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
21680   u8 bSafeMode;          /* True to prohibit unsafe operations */
21681   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
21682   u8 eRestoreState;      /* See comments above doAutoDetectRestore() */
21683   u8 crlfMode;           /* Do NL-to-CRLF translations when enabled (maybe) */
21684   u8 eEscMode;           /* Escape mode for text output */
21685   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
21686   unsigned statsOn;      /* True to display memory stats before each finalize */
21687   unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
21688   int inputNesting;      /* Track nesting level of .read and other redirects */
21689   int outCount;          /* Revert to stdout when reaching zero */
21690   int cnt;               /* Number of records displayed so far */
21691   int lineno;            /* Line number of last line read from in */
21692   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
21693   FILE *in;              /* Read commands from this stream */
21694   FILE *out;             /* Write results here */
21695   FILE *traceOut;        /* Output for sqlite3_trace() */
21696   int nErr;              /* Number of errors seen */
21697   int mode;              /* An output mode setting */
21698   int modePrior;         /* Saved mode */
21699   int cMode;             /* temporary output mode for the current query */
21700   int normalMode;        /* Output mode before ".explain on" */
21701   int writableSchema;    /* True if PRAGMA writable_schema=ON */
21702   int showHeader;        /* True to show column names in List or Column mode */
21703   int nCheck;            /* Number of ".check" commands run */
21704   unsigned nProgress;    /* Number of progress callbacks encountered */
21705   unsigned mxProgress;   /* Maximum progress callbacks before failing */
21706   unsigned flgProgress;  /* Flags for the progress callback */
21707   unsigned shellFlgs;    /* Various flags */
21708   unsigned priorShFlgs;  /* Saved copy of flags */
21709   sqlite3_int64 szMax;   /* --maxsize argument to .open */
21710   char *zDestTable;      /* Name of destination table when MODE_Insert */
21711   char *zTempFile;       /* Temporary file that might need deleting */
21712   char zTestcase[30];    /* Name of current test case */
21713   char colSeparator[20]; /* Column separator character for several modes */
21714   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
21715   char colSepPrior[20];  /* Saved column separator */
21716   char rowSepPrior[20];  /* Saved row separator */
21717   int *colWidth;         /* Requested width of each column in columnar modes */
21718   int *actualWidth;      /* Actual width of each column */
21719   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
21720   char nullValue[20];    /* The text to print when a NULL comes back from
21721                          ** the database */
21722   char outfile[FILENAME_MAX]; /* Filename for *out */
21723   sqlite3_stmt *pStmt;   /* Current statement if any. */
21724   FILE *pLog;            /* Write log output here */
21725   struct AuxDb {         /* Storage space for auxiliary database connections */
21726     sqlite3 *db;               /* Connection pointer */
21727     const char *zDbFilename;   /* Filename used to open the connection */
21728     char *zFreeOnClose;        /* Free this memory allocation on close */
21729 #if defined(SQLITE_ENABLE_SESSION)
21730     int nSession;              /* Number of active sessions */
21731     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
21732 #endif
21733   } aAuxDb[5],           /* Array of all database connections */
21734     *pAuxDb;             /* Currently active database connection */
21735   int *aiIndent;         /* Array of indents used in MODE_Explain */
21736   int nIndent;           /* Size of array aiIndent[] */
21737   int iIndent;           /* Index of current op in aiIndent[] */
21738   char *zNonce;          /* Nonce for temporary safe-mode escapes */
21739   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
21740   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
21741 #ifdef SQLITE_SHELL_FIDDLE
21742   struct {
21743     const char * zInput; /* Input string from wasm/JS proxy */
21744     const char * zPos;   /* Cursor pos into zInput */
21745     const char * zDefaultDbName; /* Default name for db file */
21746   } wasm;
21747 #endif
21748 };
21749 
21750 #ifdef SQLITE_SHELL_FIDDLE
21751 static ShellState shellState;
21752 #endif
21753 
21754 
21755 /* Allowed values for ShellState.autoEQP
21756 */
21757 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
21758 #define AUTOEQP_on       1           /* Automatic EQP is on */
21759 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
21760 #define AUTOEQP_full     3           /* Show full EXPLAIN */
21761 
21762 /* Allowed values for ShellState.openMode
21763 */
21764 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
21765 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
21766 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
21767 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
21768 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
21769 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
21770 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
21771 
21772 /* Allowed values for ShellState.eTraceType
21773 */
21774 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
21775 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
21776 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
21777 
21778 /* Bits in the ShellState.flgProgress variable */
21779 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
21780 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
21781                                    ** callback limit is reached, and for each
21782                                    ** top-level SQL statement */
21783 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
21784 
21785 /* Allowed values for ShellState.eEscMode.  The default value should
21786 ** be 0, so to change the default, reorder the names.
21787 */
21788 #define SHELL_ESC_ASCII        0      /* Substitute ^Y for X where Y=X+0x40 */
21789 #define SHELL_ESC_SYMBOL       1      /* Substitute U+2400 graphics */
21790 #define SHELL_ESC_OFF          2      /* Send characters verbatim */
21791 
21792 static const char *shell_EscModeNames[] = { "ascii", "symbol", "off" };
21793 
21794 /*
21795 ** These are the allowed shellFlgs values
21796 */
21797 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
21798 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
21799 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
21800 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
21801 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
21802 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
21803 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
21804 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
21805 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
21806 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
21807 #define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
21808 
21809 /*
21810 ** Macros for testing and setting shellFlgs
21811 */
21812 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
21813 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
21814 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
21815 
21816 /*
21817 ** These are the allowed modes.
21818 */
21819 #define MODE_Line     0  /* One column per line.  Blank line between records */
21820 #define MODE_Column   1  /* One record per line in neat columns */
21821 #define MODE_List     2  /* One record per line with a separator */
21822 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
21823 #define MODE_Html     4  /* Generate an XHTML table */
21824 #define MODE_Insert   5  /* Generate SQL "insert" statements */
21825 #define MODE_Quote    6  /* Quote values as for SQL */
21826 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
21827 #define MODE_Csv      8  /* Quote strings, numbers are plain */
21828 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
21829 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
21830 #define MODE_Pretty  11  /* Pretty-print schemas */
21831 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
21832 #define MODE_Json    13  /* Output JSON */
21833 #define MODE_Markdown 14 /* Markdown formatting */
21834 #define MODE_Table   15  /* MySQL-style table formatting */
21835 #define MODE_Box     16  /* Unicode box-drawing characters */
21836 #define MODE_Count   17  /* Output only a count of the rows of output */
21837 #define MODE_Off     18  /* No query output shown */
21838 #define MODE_ScanExp 19  /* Like MODE_Explain, but for ".scanstats vm" */
21839 #define MODE_Www     20  /* Full web-page output */
21840 
21841 static const char *modeDescr[] = {
21842   "line",
21843   "column",
21844   "list",
21845   "semi",
21846   "html",
21847   "insert",
21848   "quote",
21849   "tcl",
21850   "csv",
21851   "explain",
21852   "ascii",
21853   "prettyprint",
21854   "eqp",
21855   "json",
21856   "markdown",
21857   "table",
21858   "box",
21859   "count",
21860   "off",
21861   "scanexp",
21862   "www",
21863 };
21864 
21865 /*
21866 ** These are the column/row/line separators used by the various
21867 ** import/export modes.
21868 */
21869 #define SEP_Column    "|"
21870 #define SEP_Row       "\n"
21871 #define SEP_Tab       "\t"
21872 #define SEP_Space     " "
21873 #define SEP_Comma     ","
21874 #define SEP_CrLf      "\r\n"
21875 #define SEP_Unit      "\x1F"
21876 #define SEP_Record    "\x1E"
21877 
21878 /*
21879 ** Limit input nesting via .read or any other input redirect.
21880 ** It's not too expensive, so a generous allowance can be made.
21881 */
21882 #define MAX_INPUT_NESTING 25
21883 
21884 /*
21885 ** A callback for the sqlite3_log() interface.
21886 */
shellLog(void * pArg,int iErrCode,const char * zMsg)21887 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
21888   ShellState *p = (ShellState*)pArg;
21889   if( p->pLog==0 ) return;
21890   sqlite3_fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
21891   fflush(p->pLog);
21892 }
21893 
21894 /*
21895 ** SQL function:  shell_putsnl(X)
21896 **
21897 ** Write the text X to the screen (or whatever output is being directed)
21898 ** adding a newline at the end, and then return X.
21899 */
shellPutsFunc(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)21900 static void shellPutsFunc(
21901   sqlite3_context *pCtx,
21902   int nVal,
21903   sqlite3_value **apVal
21904 ){
21905   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
21906   (void)nVal;
21907   sqlite3_fprintf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
21908   sqlite3_result_value(pCtx, apVal[0]);
21909 }
21910 
21911 /*
21912 ** If in safe mode, print an error message described by the arguments
21913 ** and exit immediately.
21914 */
failIfSafeMode(ShellState * p,const char * zErrMsg,...)21915 static void failIfSafeMode(
21916   ShellState *p,
21917   const char *zErrMsg,
21918   ...
21919 ){
21920   if( p->bSafeMode ){
21921     va_list ap;
21922     char *zMsg;
21923     va_start(ap, zErrMsg);
21924     zMsg = sqlite3_vmprintf(zErrMsg, ap);
21925     va_end(ap);
21926     sqlite3_fprintf(stderr, "line %d: %s\n", p->lineno, zMsg);
21927     exit(1);
21928   }
21929 }
21930 
21931 /*
21932 ** SQL function:   edit(VALUE)
21933 **                 edit(VALUE,EDITOR)
21934 **
21935 ** These steps:
21936 **
21937 **     (1) Write VALUE into a temporary file.
21938 **     (2) Run program EDITOR on that temporary file.
21939 **     (3) Read the temporary file back and return its content as the result.
21940 **     (4) Delete the temporary file
21941 **
21942 ** If the EDITOR argument is omitted, use the value in the VISUAL
21943 ** environment variable.  If still there is no EDITOR, through an error.
21944 **
21945 ** Also throw an error if the EDITOR program returns a non-zero exit code.
21946 */
21947 #ifndef SQLITE_NOHAVE_SYSTEM
editFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)21948 static void editFunc(
21949   sqlite3_context *context,
21950   int argc,
21951   sqlite3_value **argv
21952 ){
21953   const char *zEditor;
21954   char *zTempFile = 0;
21955   sqlite3 *db;
21956   char *zCmd = 0;
21957   int bBin;
21958   int rc;
21959   int hasCRLF = 0;
21960   FILE *f = 0;
21961   sqlite3_int64 sz;
21962   sqlite3_int64 x;
21963   unsigned char *p = 0;
21964 
21965   if( argc==2 ){
21966     zEditor = (const char*)sqlite3_value_text(argv[1]);
21967   }else{
21968     zEditor = getenv("VISUAL");
21969   }
21970   if( zEditor==0 ){
21971     sqlite3_result_error(context, "no editor for edit()", -1);
21972     return;
21973   }
21974   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
21975     sqlite3_result_error(context, "NULL input to edit()", -1);
21976     return;
21977   }
21978   db = sqlite3_context_db_handle(context);
21979   zTempFile = 0;
21980   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
21981   if( zTempFile==0 ){
21982     sqlite3_uint64 r = 0;
21983     sqlite3_randomness(sizeof(r), &r);
21984     zTempFile = sqlite3_mprintf("temp%llx", r);
21985     if( zTempFile==0 ){
21986       sqlite3_result_error_nomem(context);
21987       return;
21988     }
21989   }
21990   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
21991   /* When writing the file to be edited, do \n to \r\n conversions on systems
21992   ** that want \r\n line endings */
21993   f = sqlite3_fopen(zTempFile, bBin ? "wb" : "w");
21994   if( f==0 ){
21995     sqlite3_result_error(context, "edit() cannot open temp file", -1);
21996     goto edit_func_end;
21997   }
21998   sz = sqlite3_value_bytes(argv[0]);
21999   if( bBin ){
22000     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
22001   }else{
22002     const char *z = (const char*)sqlite3_value_text(argv[0]);
22003     /* Remember whether or not the value originally contained \r\n */
22004     if( z && strstr(z,"\r\n")!=0 ) hasCRLF = 1;
22005     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
22006   }
22007   fclose(f);
22008   f = 0;
22009   if( x!=sz ){
22010     sqlite3_result_error(context, "edit() could not write the whole file", -1);
22011     goto edit_func_end;
22012   }
22013   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
22014   if( zCmd==0 ){
22015     sqlite3_result_error_nomem(context);
22016     goto edit_func_end;
22017   }
22018   rc = system(zCmd);
22019   sqlite3_free(zCmd);
22020   if( rc ){
22021     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
22022     goto edit_func_end;
22023   }
22024   f = sqlite3_fopen(zTempFile, "rb");
22025   if( f==0 ){
22026     sqlite3_result_error(context,
22027       "edit() cannot reopen temp file after edit", -1);
22028     goto edit_func_end;
22029   }
22030   fseek(f, 0, SEEK_END);
22031   sz = ftell(f);
22032   rewind(f);
22033   p = sqlite3_malloc64( sz+1 );
22034   if( p==0 ){
22035     sqlite3_result_error_nomem(context);
22036     goto edit_func_end;
22037   }
22038   x = fread(p, 1, (size_t)sz, f);
22039   fclose(f);
22040   f = 0;
22041   if( x!=sz ){
22042     sqlite3_result_error(context, "could not read back the whole file", -1);
22043     goto edit_func_end;
22044   }
22045   if( bBin ){
22046     sqlite3_result_blob64(context, p, sz, sqlite3_free);
22047   }else{
22048     sqlite3_int64 i, j;
22049     if( hasCRLF ){
22050       /* If the original contains \r\n then do no conversions back to \n */
22051     }else{
22052       /* If the file did not originally contain \r\n then convert any new
22053       ** \r\n back into \n */
22054       p[sz] = 0;
22055       for(i=j=0; i<sz; i++){
22056         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
22057         p[j++] = p[i];
22058       }
22059       sz = j;
22060       p[sz] = 0;
22061     }
22062     sqlite3_result_text64(context, (const char*)p, sz,
22063                           sqlite3_free, SQLITE_UTF8);
22064   }
22065   p = 0;
22066 
22067 edit_func_end:
22068   if( f ) fclose(f);
22069   unlink(zTempFile);
22070   sqlite3_free(zTempFile);
22071   sqlite3_free(p);
22072 }
22073 #endif /* SQLITE_NOHAVE_SYSTEM */
22074 
22075 /*
22076 ** Save or restore the current output mode
22077 */
outputModePush(ShellState * p)22078 static void outputModePush(ShellState *p){
22079   p->modePrior = p->mode;
22080   p->priorShFlgs = p->shellFlgs;
22081   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
22082   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
22083 }
outputModePop(ShellState * p)22084 static void outputModePop(ShellState *p){
22085   p->mode = p->modePrior;
22086   p->shellFlgs = p->priorShFlgs;
22087   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
22088   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
22089 }
22090 
22091 /*
22092 ** Set output mode to text or binary for Windows.
22093 */
setCrlfMode(ShellState * p)22094 static void setCrlfMode(ShellState *p){
22095 #ifdef _WIN32
22096   if( p->crlfMode ){
22097     sqlite3_fsetmode(p->out, _O_TEXT);
22098   }else{
22099     sqlite3_fsetmode(p->out, _O_BINARY);
22100   }
22101 #else
22102   UNUSED_PARAMETER(p);
22103 #endif
22104 }
22105 
22106 /*
22107 ** Output the given string as a hex-encoded blob (eg. X'1234' )
22108 */
output_hex_blob(FILE * out,const void * pBlob,int nBlob)22109 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
22110   int i;
22111   unsigned char *aBlob = (unsigned char*)pBlob;
22112 
22113   char *zStr = sqlite3_malloc(nBlob*2 + 1);
22114   shell_check_oom(zStr);
22115 
22116   for(i=0; i<nBlob; i++){
22117     static const char aHex[] = {
22118         '0', '1', '2', '3', '4', '5', '6', '7',
22119         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
22120     };
22121     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
22122     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
22123   }
22124   zStr[i*2] = '\0';
22125 
22126   sqlite3_fprintf(out, "X'%s'", zStr);
22127   sqlite3_free(zStr);
22128 }
22129 
22130 /*
22131 ** Output the given string as a quoted string using SQL quoting conventions:
22132 **
22133 **   (1)   Single quotes (') within the string are doubled
22134 **   (2)   The whle string is enclosed in '...'
22135 **   (3)   Control characters other than \n, \t, and \r\n are escaped
22136 **         using \u00XX notation and if such substitutions occur,
22137 **         the whole string is enclosed in unistr('...') instead of '...'.
22138 **
22139 ** Step (3) is omitted if the control-character escape mode is OFF.
22140 **
22141 ** See also: output_quoted_escaped_string() which does the same except
22142 ** that it does not make exceptions for \n, \t, and \r\n in step (3).
22143 */
output_quoted_string(ShellState * p,const char * zInX)22144 static void output_quoted_string(ShellState *p, const char *zInX){
22145   int i;
22146   int needUnistr = 0;
22147   int needDblQuote = 0;
22148   const unsigned char *z = (const unsigned char*)zInX;
22149   unsigned char c;
22150   FILE *out = p->out;
22151   sqlite3_fsetmode(out, _O_BINARY);
22152   if( z==0 ) return;
22153   for(i=0; (c = z[i])!=0; i++){
22154     if( c=='\'' ){ needDblQuote = 1; }
22155     if( c>0x1f ) continue;
22156     if( c=='\t' || c=='\n' ) continue;
22157     if( c=='\r' && z[i+1]=='\n' ) continue;
22158     needUnistr = 1;
22159     break;
22160   }
22161   if( (needDblQuote==0 && needUnistr==0)
22162    || (needDblQuote==0 && p->eEscMode==SHELL_ESC_OFF)
22163   ){
22164     sqlite3_fprintf(out, "'%s'",z);
22165   }else if( p->eEscMode==SHELL_ESC_OFF ){
22166     char *zEncoded = sqlite3_mprintf("%Q", z);
22167     sqlite3_fputs(zEncoded, out);
22168     sqlite3_free(zEncoded);
22169   }else{
22170     if( needUnistr ){
22171       sqlite3_fputs("unistr('", out);
22172     }else{
22173       sqlite3_fputs("'", out);
22174     }
22175     while( *z ){
22176       for(i=0; (c = z[i])!=0; i++){
22177         if( c=='\'' ) break;
22178         if( c>0x1f ) continue;
22179         if( c=='\t' || c=='\n' ) continue;
22180         if( c=='\r' && z[i+1]=='\n' ) continue;
22181         break;
22182       }
22183       if( i ){
22184         sqlite3_fprintf(out, "%.*s", i, z);
22185         z += i;
22186       }
22187       if( c==0 ) break;
22188       if( c=='\'' ){
22189         sqlite3_fputs("''", out);
22190       }else{
22191         sqlite3_fprintf(out, "\\u%04x", c);
22192       }
22193       z++;
22194     }
22195     if( needUnistr ){
22196       sqlite3_fputs("')", out);
22197     }else{
22198       sqlite3_fputs("'", out);
22199     }
22200   }
22201   setCrlfMode(p);
22202 }
22203 
22204 /*
22205 ** Output the given string as a quoted string using SQL quoting conventions.
22206 ** Additionallly , escape the "\n" and "\r" characters so that they do not
22207 ** get corrupted by end-of-line translation facilities in some operating
22208 ** systems.
22209 **
22210 ** This is like output_quoted_string() but with the addition of the \r\n
22211 ** escape mechanism.
22212 */
output_quoted_escaped_string(ShellState * p,const char * z)22213 static void output_quoted_escaped_string(ShellState *p, const char *z){
22214   char *zEscaped;
22215   sqlite3_fsetmode(p->out, _O_BINARY);
22216   if( p->eEscMode==SHELL_ESC_OFF ){
22217     zEscaped = sqlite3_mprintf("%Q", z);
22218   }else{
22219     zEscaped = sqlite3_mprintf("%#Q", z);
22220   }
22221   sqlite3_fputs(zEscaped, p->out);
22222   sqlite3_free(zEscaped);
22223   setCrlfMode(p);
22224 }
22225 
22226 /*
22227 ** Find earliest of chars within s specified in zAny.
22228 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
22229 */
anyOfInStr(const char * s,const char * zAny,size_t ns)22230 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
22231   const char *pcFirst = 0;
22232   if( ns == ~(size_t)0 ) ns = strlen(s);
22233   while(*zAny){
22234     const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
22235     if( pc ){
22236       pcFirst = pc;
22237       ns = pcFirst - s;
22238     }
22239     ++zAny;
22240   }
22241   return pcFirst;
22242 }
22243 
22244 /* Skip over as much z[] input char sequence as is valid UTF-8,
22245 ** limited per nAccept char's or whole characters and containing
22246 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
22247 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
22248 ** Limit: nAccept>=0 => char count, nAccept<0 => character
22249  */
zSkipValidUtf8(const char * z,int nAccept,long ccm)22250 const char *zSkipValidUtf8(const char *z, int nAccept, long ccm){
22251   int ng = (nAccept<0)? -nAccept : 0;
22252   const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
22253   assert(z!=0);
22254   while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
22255     unsigned char c = *(u8*)z;
22256     if( c<0x7f ){
22257       if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
22258       ++z; /* ASCII */
22259     }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
22260     else{
22261       const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
22262       do{
22263         if( pcLimit && zt >= pcLimit ) return z;
22264         else{
22265           char ct = *zt++;
22266           if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
22267             /* Trailing bytes are too few, too many, or invalid. */
22268             return z;
22269           }
22270         }
22271       } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
22272       z = zt;
22273     }
22274   }
22275   return z;
22276 }
22277 
22278 
22279 /*
22280 ** Output the given string as a quoted according to C or TCL quoting rules.
22281 */
output_c_string(FILE * out,const char * z)22282 static void output_c_string(FILE *out, const char *z){
22283   char c;
22284   static const char *zq = "\"";
22285   static long ctrlMask = ~0L;
22286   static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
22287   char ace[3] = "\\?";
22288   char cbsSay;
22289   sqlite3_fputs(zq, out);
22290   while( *z!=0 ){
22291     const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
22292     const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
22293     const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
22294     if( pcEnd > z ){
22295       sqlite3_fprintf(out, "%.*s", (int)(pcEnd-z), z);
22296     }
22297     if( (c = *pcEnd)==0 ) break;
22298     ++pcEnd;
22299     switch( c ){
22300     case '\\': case '"':
22301       cbsSay = (char)c;
22302       break;
22303     case '\t': cbsSay = 't'; break;
22304     case '\n': cbsSay = 'n'; break;
22305     case '\r': cbsSay = 'r'; break;
22306     case '\f': cbsSay = 'f'; break;
22307     default: cbsSay = 0; break;
22308     }
22309     if( cbsSay ){
22310       ace[1] = cbsSay;
22311       sqlite3_fputs(ace, out);
22312     }else if( !isprint(c&0xff) ){
22313       sqlite3_fprintf(out, "\\%03o", c&0xff);
22314     }else{
22315       ace[1] = (char)c;
22316       sqlite3_fputs(ace+1, out);
22317     }
22318     z = pcEnd;
22319   }
22320   sqlite3_fputs(zq, out);
22321 }
22322 
22323 /*
22324 ** Output the given string as quoted according to JSON quoting rules.
22325 */
output_json_string(FILE * out,const char * z,i64 n)22326 static void output_json_string(FILE *out, const char *z, i64 n){
22327   unsigned char c;
22328   static const char *zq = "\"";
22329   static long ctrlMask = ~0L;
22330   static const char *zDQBS = "\"\\";
22331   const char *pcLimit;
22332   char ace[3] = "\\?";
22333   char cbsSay;
22334 
22335   if( z==0 ) z = "";
22336   pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
22337   sqlite3_fputs(zq, out);
22338   while( z < pcLimit ){
22339     const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
22340     const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
22341     const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
22342     if( pcEnd > z ){
22343       sqlite3_fprintf(out, "%.*s", (int)(pcEnd-z), z);
22344       z = pcEnd;
22345     }
22346     if( z >= pcLimit ) break;
22347     c = (unsigned char)*(z++);
22348     switch( c ){
22349     case '"': case '\\':
22350       cbsSay = (char)c;
22351       break;
22352     case '\b': cbsSay = 'b'; break;
22353     case '\f': cbsSay = 'f'; break;
22354     case '\n': cbsSay = 'n'; break;
22355     case '\r': cbsSay = 'r'; break;
22356     case '\t': cbsSay = 't'; break;
22357     default: cbsSay = 0; break;
22358     }
22359     if( cbsSay ){
22360       ace[1] = cbsSay;
22361       sqlite3_fputs(ace, out);
22362     }else if( c<=0x1f || c>=0x7f ){
22363       sqlite3_fprintf(out, "\\u%04x", c);
22364     }else{
22365       ace[1] = (char)c;
22366       sqlite3_fputs(ace+1, out);
22367     }
22368   }
22369   sqlite3_fputs(zq, out);
22370 }
22371 
22372 /*
22373 ** Escape the input string if it is needed and in accordance with
22374 ** eEscMode.
22375 **
22376 ** Escaping is needed if the string contains any control characters
22377 ** other than \t, \n, and \r\n
22378 **
22379 ** If no escaping is needed (the common case) then set *ppFree to NULL
22380 ** and return the original string.  If escapingn is needed, write the
22381 ** escaped string into memory obtained from sqlite3_malloc64() or the
22382 ** equivalent, and return the new string and set *ppFree to the new string
22383 ** as well.
22384 **
22385 ** The caller is responsible for freeing *ppFree if it is non-NULL in order
22386 ** to reclaim memory.
22387 */
escapeOutput(ShellState * p,const char * zInX,char ** ppFree)22388 static const char *escapeOutput(
22389   ShellState *p,
22390   const char *zInX,
22391   char **ppFree
22392 ){
22393   i64 i, j;
22394   i64 nCtrl = 0;
22395   unsigned char *zIn;
22396   unsigned char c;
22397   unsigned char *zOut;
22398 
22399 
22400   /* No escaping if disabled */
22401   if( p->eEscMode==SHELL_ESC_OFF ){
22402     *ppFree = 0;
22403      return zInX;
22404   }
22405 
22406   /* Count the number of control characters in the string. */
22407   zIn = (unsigned char*)zInX;
22408   for(i=0; (c = zIn[i])!=0; i++){
22409     if( c<=0x1f
22410      && c!='\t'
22411      && c!='\n'
22412      && (c!='\r' || zIn[i+1]!='\n')
22413     ){
22414       nCtrl++;
22415     }
22416   }
22417   if( nCtrl==0 ){
22418     *ppFree = 0;
22419     return zInX;
22420   }
22421   if( p->eEscMode==SHELL_ESC_SYMBOL ) nCtrl *= 2;
22422   zOut = sqlite3_malloc64( i + nCtrl + 1 );
22423   shell_check_oom(zOut);
22424   for(i=j=0; (c = zIn[i])!=0; i++){
22425     if( c>0x1f
22426      || c=='\t'
22427      || c=='\n'
22428      || (c=='\r' && zIn[i+1]=='\n')
22429     ){
22430       continue;
22431     }
22432     if( i>0 ){
22433       memcpy(&zOut[j], zIn, i);
22434       j += i;
22435     }
22436     zIn += i+1;
22437     i = -1;
22438     switch( p->eEscMode ){
22439       case SHELL_ESC_SYMBOL:
22440         zOut[j++] = 0xe2;
22441         zOut[j++] = 0x90;
22442         zOut[j++] = 0x80+c;
22443         break;
22444       case SHELL_ESC_ASCII:
22445         zOut[j++] = '^';
22446         zOut[j++] = 0x40+c;
22447         break;
22448     }
22449   }
22450   if( i>0 ){
22451     memcpy(&zOut[j], zIn, i);
22452     j += i;
22453   }
22454   zOut[j] = 0;
22455   *ppFree = (char*)zOut;
22456   return (char*)zOut;
22457 }
22458 
22459 /*
22460 ** Output the given string with characters that are special to
22461 ** HTML escaped.
22462 */
output_html_string(FILE * out,const char * z)22463 static void output_html_string(FILE *out, const char *z){
22464   int i;
22465   if( z==0 ) z = "";
22466   while( *z ){
22467     for(i=0;   z[i]
22468             && z[i]!='<'
22469             && z[i]!='&'
22470             && z[i]!='>'
22471             && z[i]!='\"'
22472             && z[i]!='\'';
22473         i++){}
22474     if( i>0 ){
22475       sqlite3_fprintf(out, "%.*s",i,z);
22476     }
22477     if( z[i]=='<' ){
22478       sqlite3_fputs("&lt;", out);
22479     }else if( z[i]=='&' ){
22480       sqlite3_fputs("&amp;", out);
22481     }else if( z[i]=='>' ){
22482       sqlite3_fputs("&gt;", out);
22483     }else if( z[i]=='\"' ){
22484       sqlite3_fputs("&quot;", out);
22485     }else if( z[i]=='\'' ){
22486       sqlite3_fputs("&#39;", out);
22487     }else{
22488       break;
22489     }
22490     z += i + 1;
22491   }
22492 }
22493 
22494 /*
22495 ** If a field contains any character identified by a 1 in the following
22496 ** array, then the string must be quoted for CSV.
22497 */
22498 static const char needCsvQuote[] = {
22499   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22500   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22501   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
22502   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
22503   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
22504   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
22505   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
22506   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
22507   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22508   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22509   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22510   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22511   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22512   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22513   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22514   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
22515 };
22516 
22517 /*
22518 ** Output a single term of CSV.  Actually, p->colSeparator is used for
22519 ** the separator, which may or may not be a comma.  p->nullValue is
22520 ** the null value.  Strings are quoted if necessary.  The separator
22521 ** is only issued if bSep is true.
22522 */
output_csv(ShellState * p,const char * z,int bSep)22523 static void output_csv(ShellState *p, const char *z, int bSep){
22524   if( z==0 ){
22525     sqlite3_fprintf(p->out, "%s",p->nullValue);
22526   }else{
22527     unsigned i;
22528     for(i=0; z[i]; i++){
22529       if( needCsvQuote[((unsigned char*)z)[i]] ){
22530         i = 0;
22531         break;
22532       }
22533     }
22534     if( i==0 || strstr(z, p->colSeparator)!=0 ){
22535       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
22536       shell_check_oom(zQuoted);
22537       sqlite3_fputs(zQuoted, p->out);
22538       sqlite3_free(zQuoted);
22539     }else{
22540       sqlite3_fputs(z, p->out);
22541     }
22542   }
22543   if( bSep ){
22544     sqlite3_fputs(p->colSeparator, p->out);
22545   }
22546 }
22547 
22548 /*
22549 ** This routine runs when the user presses Ctrl-C
22550 */
interrupt_handler(int NotUsed)22551 static void interrupt_handler(int NotUsed){
22552   UNUSED_PARAMETER(NotUsed);
22553   if( ++seenInterrupt>1 ) exit(1);
22554   if( globalDb ) sqlite3_interrupt(globalDb);
22555 }
22556 
22557 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
22558 /*
22559 ** This routine runs for console events (e.g. Ctrl-C) on Win32
22560 */
ConsoleCtrlHandler(DWORD dwCtrlType)22561 static BOOL WINAPI ConsoleCtrlHandler(
22562   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
22563 ){
22564   if( dwCtrlType==CTRL_C_EVENT ){
22565     interrupt_handler(0);
22566     return TRUE;
22567   }
22568   return FALSE;
22569 }
22570 #endif
22571 
22572 #ifndef SQLITE_OMIT_AUTHORIZATION
22573 /*
22574 ** This authorizer runs in safe mode.
22575 */
safeModeAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)22576 static int safeModeAuth(
22577   void *pClientData,
22578   int op,
22579   const char *zA1,
22580   const char *zA2,
22581   const char *zA3,
22582   const char *zA4
22583 ){
22584   ShellState *p = (ShellState*)pClientData;
22585   static const char *azProhibitedFunctions[] = {
22586     "edit",
22587     "fts3_tokenizer",
22588     "load_extension",
22589     "readfile",
22590     "writefile",
22591     "zipfile",
22592     "zipfile_cds",
22593   };
22594   UNUSED_PARAMETER(zA1);
22595   UNUSED_PARAMETER(zA3);
22596   UNUSED_PARAMETER(zA4);
22597   switch( op ){
22598     case SQLITE_ATTACH: {
22599 #ifndef SQLITE_SHELL_FIDDLE
22600       /* In WASM builds the filesystem is a virtual sandbox, so
22601       ** there's no harm in using ATTACH. */
22602       failIfSafeMode(p, "cannot run ATTACH in safe mode");
22603 #endif
22604       break;
22605     }
22606     case SQLITE_FUNCTION: {
22607       int i;
22608       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
22609         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
22610           failIfSafeMode(p, "cannot use the %s() function in safe mode",
22611                          azProhibitedFunctions[i]);
22612         }
22613       }
22614       break;
22615     }
22616   }
22617   return SQLITE_OK;
22618 }
22619 
22620 /*
22621 ** When the ".auth ON" is set, the following authorizer callback is
22622 ** invoked.  It always returns SQLITE_OK.
22623 */
shellAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)22624 static int shellAuth(
22625   void *pClientData,
22626   int op,
22627   const char *zA1,
22628   const char *zA2,
22629   const char *zA3,
22630   const char *zA4
22631 ){
22632   ShellState *p = (ShellState*)pClientData;
22633   static const char *azAction[] = { 0,
22634      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
22635      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
22636      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
22637      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
22638      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
22639      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
22640      "PRAGMA",               "READ",                 "SELECT",
22641      "TRANSACTION",          "UPDATE",               "ATTACH",
22642      "DETACH",               "ALTER_TABLE",          "REINDEX",
22643      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
22644      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
22645   };
22646   int i;
22647   const char *az[4];
22648   az[0] = zA1;
22649   az[1] = zA2;
22650   az[2] = zA3;
22651   az[3] = zA4;
22652   sqlite3_fprintf(p->out, "authorizer: %s", azAction[op]);
22653   for(i=0; i<4; i++){
22654     sqlite3_fputs(" ", p->out);
22655     if( az[i] ){
22656       output_c_string(p->out, az[i]);
22657     }else{
22658       sqlite3_fputs("NULL", p->out);
22659     }
22660   }
22661   sqlite3_fputs("\n", p->out);
22662   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
22663   return SQLITE_OK;
22664 }
22665 #endif
22666 
22667 /*
22668 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
22669 **
22670 ** This routine converts some CREATE TABLE statements for shadow tables
22671 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
22672 **
22673 ** If the schema statement in z[] contains a start-of-comment and if
22674 ** sqlite3_complete() returns false, try to terminate the comment before
22675 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
22676 */
printSchemaLine(FILE * out,const char * z,const char * zTail)22677 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
22678   char *zToFree = 0;
22679   if( z==0 ) return;
22680   if( zTail==0 ) return;
22681   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
22682     const char *zOrig = z;
22683     static const char *azTerm[] = { "", "*/", "\n" };
22684     int i;
22685     for(i=0; i<ArraySize(azTerm); i++){
22686       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
22687       shell_check_oom(zNew);
22688       if( sqlite3_complete(zNew) ){
22689         size_t n = strlen(zNew);
22690         zNew[n-1] = 0;
22691         zToFree = zNew;
22692         z = zNew;
22693         break;
22694       }
22695       sqlite3_free(zNew);
22696     }
22697   }
22698   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
22699     sqlite3_fprintf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
22700   }else{
22701     sqlite3_fprintf(out, "%s%s", z, zTail);
22702   }
22703   sqlite3_free(zToFree);
22704 }
printSchemaLineN(FILE * out,char * z,int n,const char * zTail)22705 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
22706   char c = z[n];
22707   z[n] = 0;
22708   printSchemaLine(out, z, zTail);
22709   z[n] = c;
22710 }
22711 
22712 /*
22713 ** Return true if string z[] has nothing but whitespace and comments to the
22714 ** end of the first line.
22715 */
wsToEol(const char * z)22716 static int wsToEol(const char *z){
22717   int i;
22718   for(i=0; z[i]; i++){
22719     if( z[i]=='\n' ) return 1;
22720     if( IsSpace(z[i]) ) continue;
22721     if( z[i]=='-' && z[i+1]=='-' ) return 1;
22722     return 0;
22723   }
22724   return 1;
22725 }
22726 
22727 /*
22728 ** Add a new entry to the EXPLAIN QUERY PLAN data
22729 */
eqp_append(ShellState * p,int iEqpId,int p2,const char * zText)22730 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
22731   EQPGraphRow *pNew;
22732   i64 nText;
22733   if( zText==0 ) return;
22734   nText = strlen(zText);
22735   if( p->autoEQPtest ){
22736     sqlite3_fprintf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
22737   }
22738   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
22739   shell_check_oom(pNew);
22740   pNew->iEqpId = iEqpId;
22741   pNew->iParentId = p2;
22742   memcpy(pNew->zText, zText, nText+1);
22743   pNew->pNext = 0;
22744   if( p->sGraph.pLast ){
22745     p->sGraph.pLast->pNext = pNew;
22746   }else{
22747     p->sGraph.pRow = pNew;
22748   }
22749   p->sGraph.pLast = pNew;
22750 }
22751 
22752 /*
22753 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
22754 ** in p->sGraph.
22755 */
eqp_reset(ShellState * p)22756 static void eqp_reset(ShellState *p){
22757   EQPGraphRow *pRow, *pNext;
22758   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
22759     pNext = pRow->pNext;
22760     sqlite3_free(pRow);
22761   }
22762   memset(&p->sGraph, 0, sizeof(p->sGraph));
22763 }
22764 
22765 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
22766 ** pOld, or return the first such line if pOld is NULL
22767 */
eqp_next_row(ShellState * p,int iEqpId,EQPGraphRow * pOld)22768 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
22769   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
22770   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
22771   return pRow;
22772 }
22773 
22774 /* Render a single level of the graph that has iEqpId as its parent.  Called
22775 ** recursively to render sublevels.
22776 */
eqp_render_level(ShellState * p,int iEqpId)22777 static void eqp_render_level(ShellState *p, int iEqpId){
22778   EQPGraphRow *pRow, *pNext;
22779   i64 n = strlen(p->sGraph.zPrefix);
22780   char *z;
22781   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
22782     pNext = eqp_next_row(p, iEqpId, pRow);
22783     z = pRow->zText;
22784     sqlite3_fprintf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
22785                             pNext ? "|--" : "`--", z);
22786     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
22787       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
22788       eqp_render_level(p, pRow->iEqpId);
22789       p->sGraph.zPrefix[n] = 0;
22790     }
22791   }
22792 }
22793 
22794 /*
22795 ** Display and reset the EXPLAIN QUERY PLAN data
22796 */
eqp_render(ShellState * p,i64 nCycle)22797 static void eqp_render(ShellState *p, i64 nCycle){
22798   EQPGraphRow *pRow = p->sGraph.pRow;
22799   if( pRow ){
22800     if( pRow->zText[0]=='-' ){
22801       if( pRow->pNext==0 ){
22802         eqp_reset(p);
22803         return;
22804       }
22805       sqlite3_fprintf(p->out, "%s\n", pRow->zText+3);
22806       p->sGraph.pRow = pRow->pNext;
22807       sqlite3_free(pRow);
22808     }else if( nCycle>0 ){
22809       sqlite3_fprintf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
22810     }else{
22811       sqlite3_fputs("QUERY PLAN\n", p->out);
22812     }
22813     p->sGraph.zPrefix[0] = 0;
22814     eqp_render_level(p, 0);
22815     eqp_reset(p);
22816   }
22817 }
22818 
22819 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
22820 /*
22821 ** Progress handler callback.
22822 */
progress_handler(void * pClientData)22823 static int progress_handler(void *pClientData) {
22824   ShellState *p = (ShellState*)pClientData;
22825   p->nProgress++;
22826   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
22827     sqlite3_fprintf(p->out, "Progress limit reached (%u)\n", p->nProgress);
22828     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
22829     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
22830     return 1;
22831   }
22832   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
22833     sqlite3_fprintf(p->out, "Progress %u\n", p->nProgress);
22834   }
22835   return 0;
22836 }
22837 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
22838 
22839 /*
22840 ** Print N dashes
22841 */
print_dashes(FILE * out,int N)22842 static void print_dashes(FILE *out, int N){
22843   const char zDash[] = "--------------------------------------------------";
22844   const int nDash = sizeof(zDash) - 1;
22845   while( N>nDash ){
22846     sqlite3_fputs(zDash, out);
22847     N -= nDash;
22848   }
22849   sqlite3_fprintf(out, "%.*s", N, zDash);
22850 }
22851 
22852 /*
22853 ** Print a markdown or table-style row separator using ascii-art
22854 */
print_row_separator(ShellState * p,int nArg,const char * zSep)22855 static void print_row_separator(
22856   ShellState *p,
22857   int nArg,
22858   const char *zSep
22859 ){
22860   int i;
22861   if( nArg>0 ){
22862     sqlite3_fputs(zSep, p->out);
22863     print_dashes(p->out, p->actualWidth[0]+2);
22864     for(i=1; i<nArg; i++){
22865       sqlite3_fputs(zSep, p->out);
22866       print_dashes(p->out, p->actualWidth[i]+2);
22867     }
22868     sqlite3_fputs(zSep, p->out);
22869   }
22870   sqlite3_fputs("\n", p->out);
22871 }
22872 
22873 /*
22874 ** This is the callback routine that the shell
22875 ** invokes for each row of a query result.
22876 */
shell_callback(void * pArg,int nArg,char ** azArg,char ** azCol,int * aiType)22877 static int shell_callback(
22878   void *pArg,
22879   int nArg,        /* Number of result columns */
22880   char **azArg,    /* Text of each result column */
22881   char **azCol,    /* Column names */
22882   int *aiType      /* Column types.  Might be NULL */
22883 ){
22884   int i;
22885   ShellState *p = (ShellState*)pArg;
22886 
22887   if( azArg==0 ) return 0;
22888   switch( p->cMode ){
22889     case MODE_Count:
22890     case MODE_Off: {
22891       break;
22892     }
22893     case MODE_Line: {
22894       int w = 5;
22895       if( azArg==0 ) break;
22896       for(i=0; i<nArg; i++){
22897         int len = strlen30(azCol[i] ? azCol[i] : "");
22898         if( len>w ) w = len;
22899       }
22900       if( p->cnt++>0 ) sqlite3_fputs(p->rowSeparator, p->out);
22901       for(i=0; i<nArg; i++){
22902         char *pFree = 0;
22903         const char *pDisplay;
22904         pDisplay = escapeOutput(p, azArg[i] ? azArg[i] : p->nullValue, &pFree);
22905         sqlite3_fprintf(p->out, "%*s = %s%s", w, azCol[i],
22906                         pDisplay, p->rowSeparator);
22907         if( pFree ) sqlite3_free(pFree);
22908       }
22909       break;
22910     }
22911     case MODE_ScanExp:
22912     case MODE_Explain: {
22913       static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
22914       static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
22915       static const int aScanExpWidth[] = {4, 15, 6, 13, 4, 4, 4, 13, 2, 13};
22916       static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
22917 
22918       const int *aWidth = aExplainWidth;
22919       const int *aMap = aExplainMap;
22920       int nWidth = ArraySize(aExplainWidth);
22921       int iIndent = 1;
22922 
22923       if( p->cMode==MODE_ScanExp ){
22924         aWidth = aScanExpWidth;
22925         aMap = aScanExpMap;
22926         nWidth = ArraySize(aScanExpWidth);
22927         iIndent = 3;
22928       }
22929       if( nArg>nWidth ) nArg = nWidth;
22930 
22931       /* If this is the first row seen, print out the headers */
22932       if( p->cnt++==0 ){
22933         for(i=0; i<nArg; i++){
22934           utf8_width_print(p->out, aWidth[i], azCol[ aMap[i] ]);
22935           sqlite3_fputs(i==nArg-1 ? "\n" : "  ", p->out);
22936         }
22937         for(i=0; i<nArg; i++){
22938           print_dashes(p->out, aWidth[i]);
22939           sqlite3_fputs(i==nArg-1 ? "\n" : "  ", p->out);
22940         }
22941       }
22942 
22943       /* If there is no data, exit early. */
22944       if( azArg==0 ) break;
22945 
22946       for(i=0; i<nArg; i++){
22947         const char *zSep = "  ";
22948         int w = aWidth[i];
22949         const char *zVal = azArg[ aMap[i] ];
22950         if( i==nArg-1 ) w = 0;
22951         if( zVal && strlenChar(zVal)>w ){
22952           w = strlenChar(zVal);
22953           zSep = " ";
22954         }
22955         if( i==iIndent && p->aiIndent && p->pStmt ){
22956           if( p->iIndent<p->nIndent ){
22957             sqlite3_fprintf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
22958           }
22959           p->iIndent++;
22960         }
22961         utf8_width_print(p->out, w, zVal ? zVal : p->nullValue);
22962         sqlite3_fputs(i==nArg-1 ? "\n" : zSep, p->out);
22963       }
22964       break;
22965     }
22966     case MODE_Semi: {   /* .schema and .fullschema output */
22967       printSchemaLine(p->out, azArg[0], ";\n");
22968       break;
22969     }
22970     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
22971       char *z;
22972       int j;
22973       int nParen = 0;
22974       char cEnd = 0;
22975       char c;
22976       int nLine = 0;
22977       int isIndex;
22978       int isWhere = 0;
22979       assert( nArg==1 );
22980       if( azArg[0]==0 ) break;
22981       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
22982        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
22983       ){
22984         sqlite3_fprintf(p->out, "%s;\n", azArg[0]);
22985         break;
22986       }
22987       isIndex = sqlite3_strlike("CREATE INDEX%", azArg[0], 0)==0
22988              || sqlite3_strlike("CREATE UNIQUE INDEX%", azArg[0], 0)==0;
22989       z = sqlite3_mprintf("%s", azArg[0]);
22990       shell_check_oom(z);
22991       j = 0;
22992       for(i=0; IsSpace(z[i]); i++){}
22993       for(; (c = z[i])!=0; i++){
22994         if( IsSpace(c) ){
22995           if( z[j-1]=='\r' ) z[j-1] = '\n';
22996           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
22997         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
22998           j--;
22999         }
23000         z[j++] = c;
23001       }
23002       while( j>0 && IsSpace(z[j-1]) ){ j--; }
23003       z[j] = 0;
23004       if( strlen30(z)>=79 ){
23005         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
23006           if( c==cEnd ){
23007             cEnd = 0;
23008           }else if( c=='"' || c=='\'' || c=='`' ){
23009             cEnd = c;
23010           }else if( c=='[' ){
23011             cEnd = ']';
23012           }else if( c=='-' && z[i+1]=='-' ){
23013             cEnd = '\n';
23014           }else if( c=='(' ){
23015             nParen++;
23016           }else if( c==')' ){
23017             nParen--;
23018             if( nLine>0 && nParen==0 && j>0 && !isWhere ){
23019               printSchemaLineN(p->out, z, j, "\n");
23020               j = 0;
23021             }
23022           }else if( (c=='w' || c=='W')
23023                  && nParen==0 && isIndex
23024                  && sqlite3_strnicmp("WHERE",&z[i],5)==0
23025                  && !IsAlnum(z[i+5]) && z[i+5]!='_' ){
23026             isWhere = 1;
23027           }else if( isWhere && (c=='A' || c=='a')
23028                  && nParen==0
23029                  && sqlite3_strnicmp("AND",&z[i],3)==0
23030                  && !IsAlnum(z[i+3]) && z[i+3]!='_' ){
23031             printSchemaLineN(p->out, z, j, "\n    ");
23032             j = 0;
23033           }
23034           z[j++] = c;
23035           if( nParen==1 && cEnd==0
23036            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
23037            && !isWhere
23038           ){
23039             if( c=='\n' ) j--;
23040             printSchemaLineN(p->out, z, j, "\n  ");
23041             j = 0;
23042             nLine++;
23043             while( IsSpace(z[i+1]) ){ i++; }
23044           }
23045         }
23046         z[j] = 0;
23047       }
23048       printSchemaLine(p->out, z, ";\n");
23049       sqlite3_free(z);
23050       break;
23051     }
23052     case MODE_List: {
23053       if( p->cnt++==0 && p->showHeader ){
23054         for(i=0; i<nArg; i++){
23055           char *z = azCol[i];
23056           char *pFree;
23057           const char *zOut = escapeOutput(p, z, &pFree);
23058           sqlite3_fprintf(p->out, "%s%s", zOut,
23059                           i==nArg-1 ? p->rowSeparator : p->colSeparator);
23060           if( pFree ) sqlite3_free(pFree);
23061         }
23062       }
23063       if( azArg==0 ) break;
23064       for(i=0; i<nArg; i++){
23065         char *z = azArg[i];
23066         char *pFree;
23067         const char *zOut;
23068         if( z==0 ) z = p->nullValue;
23069         zOut = escapeOutput(p, z, &pFree);
23070         sqlite3_fputs(zOut, p->out);
23071         if( pFree ) sqlite3_free(pFree);
23072         sqlite3_fputs((i<nArg-1)? p->colSeparator : p->rowSeparator, p->out);
23073       }
23074       break;
23075     }
23076     case MODE_Www:
23077     case MODE_Html: {
23078       if( p->cnt==0 && p->cMode==MODE_Www ){
23079         sqlite3_fputs(
23080           "</PRE>\n"
23081           "<TABLE border='1' cellspacing='0' cellpadding='2'>\n"
23082           ,p->out
23083         );
23084       }
23085       if( p->cnt==0 && (p->showHeader || p->cMode==MODE_Www) ){
23086         sqlite3_fputs("<TR>", p->out);
23087         for(i=0; i<nArg; i++){
23088           sqlite3_fputs("<TH>", p->out);
23089           output_html_string(p->out, azCol[i]);
23090           sqlite3_fputs("</TH>\n", p->out);
23091         }
23092         sqlite3_fputs("</TR>\n", p->out);
23093       }
23094       p->cnt++;
23095       if( azArg==0 ) break;
23096       sqlite3_fputs("<TR>", p->out);
23097       for(i=0; i<nArg; i++){
23098         sqlite3_fputs("<TD>", p->out);
23099         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
23100         sqlite3_fputs("</TD>\n", p->out);
23101       }
23102       sqlite3_fputs("</TR>\n", p->out);
23103       break;
23104     }
23105     case MODE_Tcl: {
23106       if( p->cnt++==0 && p->showHeader ){
23107         for(i=0; i<nArg; i++){
23108           output_c_string(p->out, azCol[i] ? azCol[i] : "");
23109           if(i<nArg-1) sqlite3_fputs(p->colSeparator, p->out);
23110         }
23111         sqlite3_fputs(p->rowSeparator, p->out);
23112       }
23113       if( azArg==0 ) break;
23114       for(i=0; i<nArg; i++){
23115         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
23116         if(i<nArg-1) sqlite3_fputs(p->colSeparator, p->out);
23117       }
23118       sqlite3_fputs(p->rowSeparator, p->out);
23119       break;
23120     }
23121     case MODE_Csv: {
23122       sqlite3_fsetmode(p->out, _O_BINARY);
23123       if( p->cnt++==0 && p->showHeader ){
23124         for(i=0; i<nArg; i++){
23125           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
23126         }
23127         sqlite3_fputs(p->rowSeparator, p->out);
23128       }
23129       if( nArg>0 ){
23130         for(i=0; i<nArg; i++){
23131           output_csv(p, azArg[i], i<nArg-1);
23132         }
23133         sqlite3_fputs(p->rowSeparator, p->out);
23134       }
23135       setCrlfMode(p);
23136       break;
23137     }
23138     case MODE_Insert: {
23139       if( azArg==0 ) break;
23140       sqlite3_fprintf(p->out, "INSERT INTO %s",p->zDestTable);
23141       if( p->showHeader ){
23142         sqlite3_fputs("(", p->out);
23143         for(i=0; i<nArg; i++){
23144           if( i>0 ) sqlite3_fputs(",", p->out);
23145           if( quoteChar(azCol[i]) ){
23146             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
23147             shell_check_oom(z);
23148             sqlite3_fputs(z, p->out);
23149             sqlite3_free(z);
23150           }else{
23151             sqlite3_fprintf(p->out, "%s", azCol[i]);
23152           }
23153         }
23154         sqlite3_fputs(")", p->out);
23155       }
23156       p->cnt++;
23157       for(i=0; i<nArg; i++){
23158         sqlite3_fputs(i>0 ? "," : " VALUES(", p->out);
23159         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
23160           sqlite3_fputs("NULL", p->out);
23161         }else if( aiType && aiType[i]==SQLITE_TEXT ){
23162           if( ShellHasFlag(p, SHFLG_Newlines) ){
23163             output_quoted_string(p, azArg[i]);
23164           }else{
23165             output_quoted_escaped_string(p, azArg[i]);
23166           }
23167         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
23168           sqlite3_fputs(azArg[i], p->out);
23169         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
23170           char z[50];
23171           double r = sqlite3_column_double(p->pStmt, i);
23172           sqlite3_uint64 ur;
23173           memcpy(&ur,&r,sizeof(r));
23174           if( ur==0x7ff0000000000000LL ){
23175             sqlite3_fputs("9.0e+999", p->out);
23176           }else if( ur==0xfff0000000000000LL ){
23177             sqlite3_fputs("-9.0e+999", p->out);
23178           }else{
23179             sqlite3_int64 ir = (sqlite3_int64)r;
23180             if( r==(double)ir ){
23181               sqlite3_snprintf(50,z,"%lld.0", ir);
23182             }else{
23183               sqlite3_snprintf(50,z,"%!.20g", r);
23184             }
23185             sqlite3_fputs(z, p->out);
23186           }
23187         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
23188           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
23189           int nBlob = sqlite3_column_bytes(p->pStmt, i);
23190           output_hex_blob(p->out, pBlob, nBlob);
23191         }else if( isNumber(azArg[i], 0) ){
23192           sqlite3_fputs(azArg[i], p->out);
23193         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
23194           output_quoted_string(p, azArg[i]);
23195         }else{
23196           output_quoted_escaped_string(p, azArg[i]);
23197         }
23198       }
23199       sqlite3_fputs(");\n", p->out);
23200       break;
23201     }
23202     case MODE_Json: {
23203       if( azArg==0 ) break;
23204       if( p->cnt==0 ){
23205         sqlite3_fputs("[{", p->out);
23206       }else{
23207         sqlite3_fputs(",\n{", p->out);
23208       }
23209       p->cnt++;
23210       for(i=0; i<nArg; i++){
23211         output_json_string(p->out, azCol[i], -1);
23212         sqlite3_fputs(":", p->out);
23213         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
23214           sqlite3_fputs("null", p->out);
23215         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
23216           char z[50];
23217           double r = sqlite3_column_double(p->pStmt, i);
23218           sqlite3_uint64 ur;
23219           memcpy(&ur,&r,sizeof(r));
23220           if( ur==0x7ff0000000000000LL ){
23221             sqlite3_fputs("9.0e+999", p->out);
23222           }else if( ur==0xfff0000000000000LL ){
23223             sqlite3_fputs("-9.0e+999", p->out);
23224           }else{
23225             sqlite3_snprintf(50,z,"%!.20g", r);
23226             sqlite3_fputs(z, p->out);
23227           }
23228         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
23229           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
23230           int nBlob = sqlite3_column_bytes(p->pStmt, i);
23231           output_json_string(p->out, pBlob, nBlob);
23232         }else if( aiType && aiType[i]==SQLITE_TEXT ){
23233           output_json_string(p->out, azArg[i], -1);
23234         }else{
23235           sqlite3_fputs(azArg[i], p->out);
23236         }
23237         if( i<nArg-1 ){
23238           sqlite3_fputs(",", p->out);
23239         }
23240       }
23241       sqlite3_fputs("}", p->out);
23242       break;
23243     }
23244     case MODE_Quote: {
23245       if( azArg==0 ) break;
23246       if( p->cnt==0 && p->showHeader ){
23247         for(i=0; i<nArg; i++){
23248           if( i>0 ) sqlite3_fputs(p->colSeparator, p->out);
23249           output_quoted_string(p, azCol[i]);
23250         }
23251         sqlite3_fputs(p->rowSeparator, p->out);
23252       }
23253       p->cnt++;
23254       for(i=0; i<nArg; i++){
23255         if( i>0 ) sqlite3_fputs(p->colSeparator, p->out);
23256         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
23257           sqlite3_fputs("NULL", p->out);
23258         }else if( aiType && aiType[i]==SQLITE_TEXT ){
23259           output_quoted_string(p, azArg[i]);
23260         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
23261           sqlite3_fputs(azArg[i], p->out);
23262         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
23263           char z[50];
23264           double r = sqlite3_column_double(p->pStmt, i);
23265           sqlite3_snprintf(50,z,"%!.20g", r);
23266           sqlite3_fputs(z, p->out);
23267         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
23268           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
23269           int nBlob = sqlite3_column_bytes(p->pStmt, i);
23270           output_hex_blob(p->out, pBlob, nBlob);
23271         }else if( isNumber(azArg[i], 0) ){
23272           sqlite3_fputs(azArg[i], p->out);
23273         }else{
23274           output_quoted_string(p, azArg[i]);
23275         }
23276       }
23277       sqlite3_fputs(p->rowSeparator, p->out);
23278       break;
23279     }
23280     case MODE_Ascii: {
23281       if( p->cnt++==0 && p->showHeader ){
23282         for(i=0; i<nArg; i++){
23283           if( i>0 ) sqlite3_fputs(p->colSeparator, p->out);
23284           sqlite3_fputs(azCol[i] ? azCol[i] : "", p->out);
23285         }
23286         sqlite3_fputs(p->rowSeparator, p->out);
23287       }
23288       if( azArg==0 ) break;
23289       for(i=0; i<nArg; i++){
23290         if( i>0 ) sqlite3_fputs(p->colSeparator, p->out);
23291         sqlite3_fputs(azArg[i] ? azArg[i] : p->nullValue, p->out);
23292       }
23293       sqlite3_fputs(p->rowSeparator, p->out);
23294       break;
23295     }
23296     case MODE_EQP: {
23297       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
23298       break;
23299     }
23300   }
23301   return 0;
23302 }
23303 
23304 /*
23305 ** This is the callback routine that the SQLite library
23306 ** invokes for each row of a query result.
23307 */
callback(void * pArg,int nArg,char ** azArg,char ** azCol)23308 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
23309   /* since we don't have type info, call the shell_callback with a NULL value */
23310   return shell_callback(pArg, nArg, azArg, azCol, NULL);
23311 }
23312 
23313 /*
23314 ** This is the callback routine from sqlite3_exec() that appends all
23315 ** output onto the end of a ShellText object.
23316 */
captureOutputCallback(void * pArg,int nArg,char ** azArg,char ** az)23317 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
23318   ShellText *p = (ShellText*)pArg;
23319   int i;
23320   UNUSED_PARAMETER(az);
23321   if( azArg==0 ) return 0;
23322   if( p->n ) appendText(p, "|", 0);
23323   for(i=0; i<nArg; i++){
23324     if( i ) appendText(p, ",", 0);
23325     if( azArg[i] ) appendText(p, azArg[i], 0);
23326   }
23327   return 0;
23328 }
23329 
23330 /*
23331 ** Generate an appropriate SELFTEST table in the main database.
23332 */
createSelftestTable(ShellState * p)23333 static void createSelftestTable(ShellState *p){
23334   char *zErrMsg = 0;
23335   sqlite3_exec(p->db,
23336     "SAVEPOINT selftest_init;\n"
23337     "CREATE TABLE IF NOT EXISTS selftest(\n"
23338     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
23339     "  op TEXT,\n"                   /* Operator:  memo run */
23340     "  cmd TEXT,\n"                  /* Command text */
23341     "  ans TEXT\n"                   /* Desired answer */
23342     ");"
23343     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
23344     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
23345     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
23346     "         'memo','Tests generated by --init');\n"
23347     "INSERT INTO [_shell$self]\n"
23348     "  SELECT 'run',\n"
23349     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
23350                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
23351     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
23352                           "FROM sqlite_schema ORDER BY 2',224));\n"
23353     "INSERT INTO [_shell$self]\n"
23354     "  SELECT 'run',"
23355     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
23356     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
23357     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
23358     "  FROM (\n"
23359     "    SELECT name FROM sqlite_schema\n"
23360     "     WHERE type='table'\n"
23361     "       AND name<>'selftest'\n"
23362     "       AND coalesce(rootpage,0)>0\n"
23363     "  )\n"
23364     " ORDER BY name;\n"
23365     "INSERT INTO [_shell$self]\n"
23366     "  VALUES('run','PRAGMA integrity_check','ok');\n"
23367     "INSERT INTO selftest(tno,op,cmd,ans)"
23368     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
23369     "DROP TABLE [_shell$self];"
23370     ,0,0,&zErrMsg);
23371   if( zErrMsg ){
23372     sqlite3_fprintf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
23373     sqlite3_free(zErrMsg);
23374   }
23375   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
23376 }
23377 
23378 
23379 /*
23380 ** Set the destination table field of the ShellState structure to
23381 ** the name of the table given.  Escape any quote characters in the
23382 ** table name.
23383 */
set_table_name(ShellState * p,const char * zName)23384 static void set_table_name(ShellState *p, const char *zName){
23385   int i, n;
23386   char cQuote;
23387   char *z;
23388 
23389   if( p->zDestTable ){
23390     free(p->zDestTable);
23391     p->zDestTable = 0;
23392   }
23393   if( zName==0 ) return;
23394   cQuote = quoteChar(zName);
23395   n = strlen30(zName);
23396   if( cQuote ) n += n+2;
23397   z = p->zDestTable = malloc( n+1 );
23398   shell_check_oom(z);
23399   n = 0;
23400   if( cQuote ) z[n++] = cQuote;
23401   for(i=0; zName[i]; i++){
23402     z[n++] = zName[i];
23403     if( zName[i]==cQuote ) z[n++] = cQuote;
23404   }
23405   if( cQuote ) z[n++] = cQuote;
23406   z[n] = 0;
23407 }
23408 
23409 /*
23410 ** Maybe construct two lines of text that point out the position of a
23411 ** syntax error.  Return a pointer to the text, in memory obtained from
23412 ** sqlite3_malloc().  Or, if the most recent error does not involve a
23413 ** specific token that we can point to, return an empty string.
23414 **
23415 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
23416 ** and should be released by the caller invoking sqlite3_free().
23417 */
shell_error_context(const char * zSql,sqlite3 * db)23418 static char *shell_error_context(const char *zSql, sqlite3 *db){
23419   int iOffset;
23420   size_t len;
23421   char *zCode;
23422   char *zMsg;
23423   int i;
23424   if( db==0
23425    || zSql==0
23426    || (iOffset = sqlite3_error_offset(db))<0
23427    || iOffset>=(int)strlen(zSql)
23428   ){
23429     return sqlite3_mprintf("");
23430   }
23431   while( iOffset>50 ){
23432     iOffset--;
23433     zSql++;
23434     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
23435   }
23436   len = strlen(zSql);
23437   if( len>78 ){
23438     len = 78;
23439     while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
23440   }
23441   zCode = sqlite3_mprintf("%.*s", len, zSql);
23442   shell_check_oom(zCode);
23443   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
23444   if( iOffset<25 ){
23445     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
23446   }else{
23447     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
23448   }
23449   return zMsg;
23450 }
23451 
23452 
23453 /*
23454 ** Execute a query statement that will generate SQL output.  Print
23455 ** the result columns, comma-separated, on a line and then add a
23456 ** semicolon terminator to the end of that line.
23457 **
23458 ** If the number of columns is 1 and that column contains text "--"
23459 ** then write the semicolon on a separate line.  That way, if a
23460 ** "--" comment occurs at the end of the statement, the comment
23461 ** won't consume the semicolon terminator.
23462 */
run_table_dump_query(ShellState * p,const char * zSelect)23463 static int run_table_dump_query(
23464   ShellState *p,           /* Query context */
23465   const char *zSelect      /* SELECT statement to extract content */
23466 ){
23467   sqlite3_stmt *pSelect;
23468   int rc;
23469   int nResult;
23470   int i;
23471   const char *z;
23472   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
23473   if( rc!=SQLITE_OK || !pSelect ){
23474     char *zContext = shell_error_context(zSelect, p->db);
23475     sqlite3_fprintf(p->out, "/**** ERROR: (%d) %s *****/\n%s",
23476           rc, sqlite3_errmsg(p->db), zContext);
23477     sqlite3_free(zContext);
23478     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
23479     return rc;
23480   }
23481   rc = sqlite3_step(pSelect);
23482   nResult = sqlite3_column_count(pSelect);
23483   while( rc==SQLITE_ROW ){
23484     z = (const char*)sqlite3_column_text(pSelect, 0);
23485     sqlite3_fprintf(p->out, "%s", z);
23486     for(i=1; i<nResult; i++){
23487       sqlite3_fprintf(p->out, ",%s", sqlite3_column_text(pSelect, i));
23488     }
23489     if( z==0 ) z = "";
23490     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
23491     if( z[0] ){
23492       sqlite3_fputs("\n;\n", p->out);
23493     }else{
23494       sqlite3_fputs(";\n", p->out);
23495     }
23496     rc = sqlite3_step(pSelect);
23497   }
23498   rc = sqlite3_finalize(pSelect);
23499   if( rc!=SQLITE_OK ){
23500     sqlite3_fprintf(p->out, "/**** ERROR: (%d) %s *****/\n",
23501                     rc, sqlite3_errmsg(p->db));
23502     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
23503   }
23504   return rc;
23505 }
23506 
23507 /*
23508 ** Allocate space and save off string indicating current error.
23509 */
save_err_msg(sqlite3 * db,const char * zPhase,int rc,const char * zSql)23510 static char *save_err_msg(
23511   sqlite3 *db,           /* Database to query */
23512   const char *zPhase,    /* When the error occurs */
23513   int rc,                /* Error code returned from API */
23514   const char *zSql       /* SQL string, or NULL */
23515 ){
23516   char *zErr;
23517   char *zContext;
23518   sqlite3_str *pStr = sqlite3_str_new(0);
23519   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
23520   if( rc>1 ){
23521     sqlite3_str_appendf(pStr, " (%d)", rc);
23522   }
23523   zContext = shell_error_context(zSql, db);
23524   if( zContext ){
23525     sqlite3_str_appendall(pStr, zContext);
23526     sqlite3_free(zContext);
23527   }
23528   zErr = sqlite3_str_finish(pStr);
23529   shell_check_oom(zErr);
23530   return zErr;
23531 }
23532 
23533 #ifdef __linux__
23534 /*
23535 ** Attempt to display I/O stats on Linux using /proc/PID/io
23536 */
displayLinuxIoStats(FILE * out)23537 static void displayLinuxIoStats(FILE *out){
23538   FILE *in;
23539   char z[200];
23540   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
23541   in = sqlite3_fopen(z, "rb");
23542   if( in==0 ) return;
23543   while( sqlite3_fgets(z, sizeof(z), in)!=0 ){
23544     static const struct {
23545       const char *zPattern;
23546       const char *zDesc;
23547     } aTrans[] = {
23548       { "rchar: ",                  "Bytes received by read():" },
23549       { "wchar: ",                  "Bytes sent to write():"    },
23550       { "syscr: ",                  "Read() system calls:"      },
23551       { "syscw: ",                  "Write() system calls:"     },
23552       { "read_bytes: ",             "Bytes read from storage:"  },
23553       { "write_bytes: ",            "Bytes written to storage:" },
23554       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
23555     };
23556     int i;
23557     for(i=0; i<ArraySize(aTrans); i++){
23558       int n = strlen30(aTrans[i].zPattern);
23559       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
23560         sqlite3_fprintf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
23561         break;
23562       }
23563     }
23564   }
23565   fclose(in);
23566 }
23567 #endif
23568 
23569 /*
23570 ** Display a single line of status using 64-bit values.
23571 */
displayStatLine(FILE * out,char * zLabel,char * zFormat,int iStatusCtrl,int bReset)23572 static void displayStatLine(
23573   FILE *out,                /* Write to this channel */
23574   char *zLabel,             /* Label for this one line */
23575   char *zFormat,            /* Format for the result */
23576   int iStatusCtrl,          /* Which status to display */
23577   int bReset                /* True to reset the stats */
23578 ){
23579   sqlite3_int64 iCur = -1;
23580   sqlite3_int64 iHiwtr = -1;
23581   int i, nPercent;
23582   char zLine[200];
23583   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
23584   for(i=0, nPercent=0; zFormat[i]; i++){
23585     if( zFormat[i]=='%' ) nPercent++;
23586   }
23587   if( nPercent>1 ){
23588     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
23589   }else{
23590     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
23591   }
23592   sqlite3_fprintf(out, "%-36s %s\n", zLabel, zLine);
23593 }
23594 
23595 /*
23596 ** Display memory stats.
23597 */
display_stats(sqlite3 * db,ShellState * pArg,int bReset)23598 static int display_stats(
23599   sqlite3 *db,                /* Database to query */
23600   ShellState *pArg,           /* Pointer to ShellState */
23601   int bReset                  /* True to reset the stats */
23602 ){
23603   int iCur;
23604   int iHiwtr;
23605   FILE *out;
23606   if( pArg==0 || pArg->out==0 ) return 0;
23607   out = pArg->out;
23608 
23609   if( pArg->pStmt && pArg->statsOn==2 ){
23610     int nCol, i, x;
23611     sqlite3_stmt *pStmt = pArg->pStmt;
23612     char z[100];
23613     nCol = sqlite3_column_count(pStmt);
23614     sqlite3_fprintf(out, "%-36s %d\n", "Number of output columns:", nCol);
23615     for(i=0; i<nCol; i++){
23616       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
23617       sqlite3_fprintf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
23618 #ifndef SQLITE_OMIT_DECLTYPE
23619       sqlite3_snprintf(30, z+x, "declared type:");
23620       sqlite3_fprintf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
23621 #endif
23622 #ifdef SQLITE_ENABLE_COLUMN_METADATA
23623       sqlite3_snprintf(30, z+x, "database name:");
23624       sqlite3_fprintf(out, "%-36s %s\n", z,
23625                            sqlite3_column_database_name(pStmt,i));
23626       sqlite3_snprintf(30, z+x, "table name:");
23627       sqlite3_fprintf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
23628       sqlite3_snprintf(30, z+x, "origin name:");
23629       sqlite3_fprintf(out, "%-36s %s\n", z,sqlite3_column_origin_name(pStmt,i));
23630 #endif
23631     }
23632   }
23633 
23634   if( pArg->statsOn==3 ){
23635     if( pArg->pStmt ){
23636       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
23637       sqlite3_fprintf(out, "VM-steps: %d\n", iCur);
23638     }
23639     return 0;
23640   }
23641 
23642   displayStatLine(out, "Memory Used:",
23643      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
23644   displayStatLine(out, "Number of Outstanding Allocations:",
23645      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
23646   if( pArg->shellFlgs & SHFLG_Pagecache ){
23647     displayStatLine(out, "Number of Pcache Pages Used:",
23648        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
23649   }
23650   displayStatLine(out, "Number of Pcache Overflow Bytes:",
23651      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
23652   displayStatLine(out, "Largest Allocation:",
23653      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
23654   displayStatLine(out, "Largest Pcache Allocation:",
23655      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
23656 #ifdef YYTRACKMAXSTACKDEPTH
23657   displayStatLine(out, "Deepest Parser Stack:",
23658      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
23659 #endif
23660 
23661   if( db ){
23662     if( pArg->shellFlgs & SHFLG_Lookaside ){
23663       iHiwtr = iCur = -1;
23664       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
23665                         &iCur, &iHiwtr, bReset);
23666       sqlite3_fprintf(out,
23667            "Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
23668       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
23669                         &iCur, &iHiwtr, bReset);
23670       sqlite3_fprintf(out,
23671            "Successful lookaside attempts:       %d\n", iHiwtr);
23672       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
23673                         &iCur, &iHiwtr, bReset);
23674       sqlite3_fprintf(out,
23675            "Lookaside failures due to size:      %d\n", iHiwtr);
23676       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
23677                         &iCur, &iHiwtr, bReset);
23678       sqlite3_fprintf(out,
23679            "Lookaside failures due to OOM:       %d\n", iHiwtr);
23680     }
23681     iHiwtr = iCur = -1;
23682     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
23683     sqlite3_fprintf(out,
23684            "Pager Heap Usage:                    %d bytes\n", iCur);
23685     iHiwtr = iCur = -1;
23686     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
23687     sqlite3_fprintf(out,
23688            "Page cache hits:                     %d\n", iCur);
23689     iHiwtr = iCur = -1;
23690     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
23691     sqlite3_fprintf(out,
23692            "Page cache misses:                   %d\n", iCur);
23693     iHiwtr = iCur = -1;
23694     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
23695     sqlite3_fprintf(out,
23696            "Page cache writes:                   %d\n", iCur);
23697     iHiwtr = iCur = -1;
23698     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
23699     sqlite3_fprintf(out,
23700            "Page cache spills:                   %d\n", iCur);
23701     iHiwtr = iCur = -1;
23702     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
23703     sqlite3_fprintf(out,
23704            "Schema Heap Usage:                   %d bytes\n", iCur);
23705     iHiwtr = iCur = -1;
23706     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
23707     sqlite3_fprintf(out,
23708            "Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
23709   }
23710 
23711   if( pArg->pStmt ){
23712     int iHit, iMiss;
23713     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
23714                                bReset);
23715     sqlite3_fprintf(out,
23716            "Fullscan Steps:                      %d\n", iCur);
23717     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
23718     sqlite3_fprintf(out,
23719            "Sort Operations:                     %d\n", iCur);
23720     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
23721     sqlite3_fprintf(out,
23722            "Autoindex Inserts:                   %d\n", iCur);
23723     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
23724                                bReset);
23725     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
23726                                 bReset);
23727     if( iHit || iMiss ){
23728       sqlite3_fprintf(out,
23729            "Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
23730     }
23731     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
23732     sqlite3_fprintf(out,
23733            "Virtual Machine Steps:               %d\n", iCur);
23734     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
23735     sqlite3_fprintf(out,
23736            "Reprepare operations:                %d\n", iCur);
23737     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
23738     sqlite3_fprintf(out,
23739            "Number of times run:                 %d\n", iCur);
23740     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
23741     sqlite3_fprintf(out,
23742            "Memory used by prepared stmt:        %d\n", iCur);
23743   }
23744 
23745 #ifdef __linux__
23746   displayLinuxIoStats(pArg->out);
23747 #endif
23748 
23749   /* Do not remove this machine readable comment: extra-stats-output-here */
23750 
23751   return 0;
23752 }
23753 
23754 
23755 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
scanStatsHeight(sqlite3_stmt * p,int iEntry)23756 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
23757   int iPid = 0;
23758   int ret = 1;
23759   sqlite3_stmt_scanstatus_v2(p, iEntry,
23760       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
23761   );
23762   while( iPid!=0 ){
23763     int ii;
23764     for(ii=0; 1; ii++){
23765       int iId;
23766       int res;
23767       res = sqlite3_stmt_scanstatus_v2(p, ii,
23768           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
23769       );
23770       if( res ) break;
23771       if( iId==iPid ){
23772         sqlite3_stmt_scanstatus_v2(p, ii,
23773             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
23774         );
23775       }
23776     }
23777     ret++;
23778   }
23779   return ret;
23780 }
23781 #endif
23782 
23783 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
display_explain_scanstats(sqlite3 * db,ShellState * pArg)23784 static void display_explain_scanstats(
23785   sqlite3 *db,                    /* Database to query */
23786   ShellState *pArg                /* Pointer to ShellState */
23787 ){
23788   static const int f = SQLITE_SCANSTAT_COMPLEX;
23789   sqlite3_stmt *p = pArg->pStmt;
23790   int ii = 0;
23791   i64 nTotal = 0;
23792   int nWidth = 0;
23793   eqp_reset(pArg);
23794 
23795   for(ii=0; 1; ii++){
23796     const char *z = 0;
23797     int n = 0;
23798     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
23799       break;
23800     }
23801     n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
23802     if( n>nWidth ) nWidth = n;
23803   }
23804   nWidth += 4;
23805 
23806   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
23807   for(ii=0; 1; ii++){
23808     i64 nLoop = 0;
23809     i64 nRow = 0;
23810     i64 nCycle = 0;
23811     int iId = 0;
23812     int iPid = 0;
23813     const char *zo = 0;
23814     const char *zName = 0;
23815     char *zText = 0;
23816     double rEst = 0.0;
23817 
23818     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
23819       break;
23820     }
23821     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
23822     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
23823     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
23824     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
23825     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
23826     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
23827     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
23828 
23829     zText = sqlite3_mprintf("%s", zo);
23830     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
23831       char *z = 0;
23832       if( nCycle>=0 && nTotal>0 ){
23833         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
23834             nCycle, ((nCycle*100)+nTotal/2) / nTotal
23835         );
23836       }
23837       if( nLoop>=0 ){
23838         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
23839       }
23840       if( nRow>=0 ){
23841         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
23842       }
23843 
23844       if( zName && pArg->scanstatsOn>1 ){
23845         double rpl = (double)nRow / (double)nLoop;
23846         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
23847       }
23848 
23849       zText = sqlite3_mprintf(
23850           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
23851       );
23852     }
23853 
23854     eqp_append(pArg, iId, iPid, zText);
23855     sqlite3_free(zText);
23856   }
23857 
23858   eqp_render(pArg, nTotal);
23859 }
23860 #endif
23861 
23862 
23863 /*
23864 ** Parameter azArray points to a zero-terminated array of strings. zStr
23865 ** points to a single nul-terminated string. Return non-zero if zStr
23866 ** is equal, according to strcmp(), to any of the strings in the array.
23867 ** Otherwise, return zero.
23868 */
str_in_array(const char * zStr,const char ** azArray)23869 static int str_in_array(const char *zStr, const char **azArray){
23870   int i;
23871   for(i=0; azArray[i]; i++){
23872     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
23873   }
23874   return 0;
23875 }
23876 
23877 /*
23878 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
23879 ** and populate the ShellState.aiIndent[] array with the number of
23880 ** spaces each opcode should be indented before it is output.
23881 **
23882 ** The indenting rules are:
23883 **
23884 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
23885 **       all opcodes that occur between the p2 jump destination and the opcode
23886 **       itself by 2 spaces.
23887 **
23888 **     * Do the previous for "Return" instructions for when P2 is positive.
23889 **       See tag-20220407a in wherecode.c and vdbe.c.
23890 **
23891 **     * For each "Goto", if the jump destination is earlier in the program
23892 **       and ends on one of:
23893 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
23894 **       or if the P1 parameter is one instead of zero,
23895 **       then indent all opcodes between the earlier instruction
23896 **       and "Goto" by 2 spaces.
23897 */
explain_data_prepare(ShellState * p,sqlite3_stmt * pSql)23898 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
23899   int *abYield = 0;               /* True if op is an OP_Yield */
23900   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
23901   int iOp;                        /* Index of operation in p->aiIndent[] */
23902 
23903   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
23904                            "Return", 0 };
23905   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
23906                             "Rewind", 0 };
23907   const char *azGoto[] = { "Goto", 0 };
23908 
23909   /* The caller guarantees that the leftmost 4 columns of the statement
23910   ** passed to this function are equivalent to the leftmost 4 columns
23911   ** of EXPLAIN statement output. In practice the statement may be
23912   ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
23913   assert( sqlite3_column_count(pSql)>=4 );
23914   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
23915   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
23916   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
23917   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
23918 
23919   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
23920     int i;
23921     int iAddr = sqlite3_column_int(pSql, 0);
23922     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
23923     int p1 = sqlite3_column_int(pSql, 2);
23924     int p2 = sqlite3_column_int(pSql, 3);
23925 
23926     /* Assuming that p2 is an instruction address, set variable p2op to the
23927     ** index of that instruction in the aiIndent[] array. p2 and p2op may be
23928     ** different if the current instruction is part of a sub-program generated
23929     ** by an SQL trigger or foreign key.  */
23930     int p2op = (p2 + (iOp-iAddr));
23931 
23932     /* Grow the p->aiIndent array as required */
23933     if( iOp>=nAlloc ){
23934       nAlloc += 100;
23935       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
23936       shell_check_oom(p->aiIndent);
23937       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
23938       shell_check_oom(abYield);
23939     }
23940 
23941     abYield[iOp] = str_in_array(zOp, azYield);
23942     p->aiIndent[iOp] = 0;
23943     p->nIndent = iOp+1;
23944     if( str_in_array(zOp, azNext) && p2op>0 ){
23945       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
23946     }
23947     if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
23948       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
23949     }
23950   }
23951 
23952   p->iIndent = 0;
23953   sqlite3_free(abYield);
23954   sqlite3_reset(pSql);
23955 }
23956 
23957 /*
23958 ** Free the array allocated by explain_data_prepare().
23959 */
explain_data_delete(ShellState * p)23960 static void explain_data_delete(ShellState *p){
23961   sqlite3_free(p->aiIndent);
23962   p->aiIndent = 0;
23963   p->nIndent = 0;
23964   p->iIndent = 0;
23965 }
23966 
23967 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
23968 
23969 /*
23970 ** Display scan stats.
23971 */
display_scanstats(sqlite3 * db,ShellState * pArg)23972 static void display_scanstats(
23973   sqlite3 *db,                    /* Database to query */
23974   ShellState *pArg                /* Pointer to ShellState */
23975 ){
23976 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
23977   UNUSED_PARAMETER(db);
23978   UNUSED_PARAMETER(pArg);
23979 #else
23980   if( pArg->scanstatsOn==3 ){
23981     const char *zSql =
23982       "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
23983       "   format('% 6s (%.2f%%)',"
23984       "      CASE WHEN ncycle<100_000 THEN ncycle || ' '"
23985       "         WHEN ncycle<100_000_000 THEN (ncycle/1_000) || 'K'"
23986       "         WHEN ncycle<100_000_000_000 THEN (ncycle/1_000_000) || 'M'"
23987       "         ELSE (ncycle/1000_000_000) || 'G' END,"
23988       "       ncycle*100.0/(sum(ncycle) OVER ())"
23989       "   )  AS cycles"
23990       "   FROM bytecode(?)";
23991 
23992     int rc = SQLITE_OK;
23993     sqlite3_stmt *pStmt = 0;
23994     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
23995     if( rc==SQLITE_OK ){
23996       sqlite3_stmt *pSave = pArg->pStmt;
23997       pArg->pStmt = pStmt;
23998       sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
23999 
24000       pArg->cnt = 0;
24001       pArg->cMode = MODE_ScanExp;
24002       explain_data_prepare(pArg, pStmt);
24003       exec_prepared_stmt(pArg, pStmt);
24004       explain_data_delete(pArg);
24005 
24006       sqlite3_finalize(pStmt);
24007       pArg->pStmt = pSave;
24008     }
24009   }else{
24010     display_explain_scanstats(db, pArg);
24011   }
24012 #endif
24013 }
24014 
24015 /*
24016 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
24017 */
24018 static unsigned int savedSelectTrace;
24019 static unsigned int savedWhereTrace;
disable_debug_trace_modes(void)24020 static void disable_debug_trace_modes(void){
24021   unsigned int zero = 0;
24022   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
24023   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
24024   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
24025   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
24026 }
restore_debug_trace_modes(void)24027 static void restore_debug_trace_modes(void){
24028   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
24029   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
24030 }
24031 
24032 /* Create the TEMP table used to store parameter bindings */
bind_table_init(ShellState * p)24033 static void bind_table_init(ShellState *p){
24034   int wrSchema = 0;
24035   int defensiveMode = 0;
24036   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
24037   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
24038   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
24039   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
24040   sqlite3_exec(p->db,
24041     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
24042     "  key TEXT PRIMARY KEY,\n"
24043     "  value\n"
24044     ") WITHOUT ROWID;",
24045     0, 0, 0);
24046   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
24047   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
24048 }
24049 
24050 /*
24051 ** Bind parameters on a prepared statement.
24052 **
24053 ** Parameter bindings are taken from a TEMP table of the form:
24054 **
24055 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
24056 **    WITHOUT ROWID;
24057 **
24058 ** No bindings occur if this table does not exist.  The name of the table
24059 ** begins with "sqlite_" so that it will not collide with ordinary application
24060 ** tables.  The table must be in the TEMP schema.
24061 */
bind_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)24062 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
24063   int nVar;
24064   int i;
24065   int rc;
24066   sqlite3_stmt *pQ = 0;
24067 
24068   nVar = sqlite3_bind_parameter_count(pStmt);
24069   if( nVar==0 ) return;  /* Nothing to do */
24070   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
24071                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
24072     rc = SQLITE_NOTFOUND;
24073     pQ = 0;
24074   }else{
24075     rc = sqlite3_prepare_v2(pArg->db,
24076             "SELECT value FROM temp.sqlite_parameters"
24077             " WHERE key=?1", -1, &pQ, 0);
24078   }
24079   for(i=1; i<=nVar; i++){
24080     char zNum[30];
24081     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
24082     if( zVar==0 ){
24083       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
24084       zVar = zNum;
24085     }
24086     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
24087     if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
24088       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
24089 #ifdef NAN
24090     }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
24091       sqlite3_bind_double(pStmt, i, NAN);
24092 #endif
24093 #ifdef INFINITY
24094     }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
24095       sqlite3_bind_double(pStmt, i, INFINITY);
24096 #endif
24097     }else if( strncmp(zVar, "$int_", 5)==0 ){
24098       sqlite3_bind_int(pStmt, i, atoi(&zVar[5]));
24099     }else if( strncmp(zVar, "$text_", 6)==0 ){
24100       size_t szVar = strlen(zVar);
24101       char *zBuf = sqlite3_malloc64( szVar-5 );
24102       if( zBuf ){
24103         memcpy(zBuf, &zVar[6], szVar-5);
24104         sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8);
24105       }
24106     }else{
24107       sqlite3_bind_null(pStmt, i);
24108     }
24109     sqlite3_reset(pQ);
24110   }
24111   sqlite3_finalize(pQ);
24112 }
24113 
24114 /*
24115 ** UTF8 box-drawing characters.  Imagine box lines like this:
24116 **
24117 **           1
24118 **           |
24119 **       4 --+-- 2
24120 **           |
24121 **           3
24122 **
24123 ** Each box characters has between 2 and 4 of the lines leading from
24124 ** the center.  The characters are here identified by the numbers of
24125 ** their corresponding lines.
24126 */
24127 #define BOX_24   "\342\224\200"  /* U+2500 --- */
24128 #define BOX_13   "\342\224\202"  /* U+2502  |  */
24129 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
24130 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
24131 #define BOX_12   "\342\224\224"  /* U+2514  '- */
24132 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
24133 #define BOX_123  "\342\224\234"  /* U+251c  |- */
24134 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
24135 #define BOX_234  "\342\224\254"  /* U+252c -,- */
24136 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
24137 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
24138 
24139 /* Draw horizontal line N characters long using unicode box
24140 ** characters
24141 */
print_box_line(FILE * out,int N)24142 static void print_box_line(FILE *out, int N){
24143   const char zDash[] =
24144       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
24145       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
24146   const int nDash = sizeof(zDash) - 1;
24147   N *= 3;
24148   while( N>nDash ){
24149     sqlite3_fputs(zDash, out);
24150     N -= nDash;
24151   }
24152   sqlite3_fprintf(out, "%.*s", N, zDash);
24153 }
24154 
24155 /*
24156 ** Draw a horizontal separator for a MODE_Box table.
24157 */
print_box_row_separator(ShellState * p,int nArg,const char * zSep1,const char * zSep2,const char * zSep3)24158 static void print_box_row_separator(
24159   ShellState *p,
24160   int nArg,
24161   const char *zSep1,
24162   const char *zSep2,
24163   const char *zSep3
24164 ){
24165   int i;
24166   if( nArg>0 ){
24167     sqlite3_fputs(zSep1, p->out);
24168     print_box_line(p->out, p->actualWidth[0]+2);
24169     for(i=1; i<nArg; i++){
24170       sqlite3_fputs(zSep2, p->out);
24171       print_box_line(p->out, p->actualWidth[i]+2);
24172     }
24173     sqlite3_fputs(zSep3, p->out);
24174   }
24175   sqlite3_fputs("\n", p->out);
24176 }
24177 
24178 /*
24179 ** z[] is a line of text that is to be displayed the .mode box or table or
24180 ** similar tabular formats.  z[] might contain control characters such
24181 ** as \n, \t, \f, or \r.
24182 **
24183 ** Compute characters to display on the first line of z[].  Stop at the
24184 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
24185 ** from malloc()) of that first line, which caller should free sometime.
24186 ** Write anything to display on the next line into *pzTail.  If this is
24187 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
24188 */
translateForDisplayAndDup(ShellState * p,const unsigned char * z,const unsigned char ** pzTail,int mxWidth,u8 bWordWrap)24189 static char *translateForDisplayAndDup(
24190   ShellState *p,                     /* To access current settings */
24191   const unsigned char *z,            /* Input text to be transformed */
24192   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
24193   int mxWidth,                       /* Max width.  0 means no limit */
24194   u8 bWordWrap                       /* If true, avoid breaking mid-word */
24195 ){
24196   int i;                 /* Input bytes consumed */
24197   int j;                 /* Output bytes generated */
24198   int k;                 /* Input bytes to be displayed */
24199   int n;                 /* Output column number */
24200   unsigned char *zOut;   /* Output text */
24201 
24202   if( z==0 ){
24203     *pzTail = 0;
24204     return 0;
24205   }
24206   if( mxWidth<0 ) mxWidth = -mxWidth;
24207   if( mxWidth==0 ) mxWidth = 1000000;
24208   i = j = n = 0;
24209   while( n<mxWidth ){
24210     unsigned char c = z[i];
24211     if( c>=0xc0 ){
24212       int u;
24213       int len = decodeUtf8(&z[i], &u);
24214       i += len;
24215       j += len;
24216       n += cli_wcwidth(u);
24217       continue;
24218     }
24219     if( c>=' ' ){
24220       n++;
24221       i++;
24222       j++;
24223       continue;
24224     }
24225     if( c==0 || c=='\n' || (c=='\r' && z[i+1]=='\n') ) break;
24226     if( c=='\t' ){
24227       do{
24228         n++;
24229         j++;
24230       }while( (n&7)!=0 && n<mxWidth );
24231       i++;
24232       continue;
24233     }
24234     if( c==0x1b && p->eEscMode==SHELL_ESC_OFF && (k = isVt100(&z[i]))>0 ){
24235       i += k;
24236       j += k;
24237     }else{
24238       n++;
24239       j += 3;
24240       i++;
24241     }
24242   }
24243   if( n>=mxWidth && bWordWrap  ){
24244     /* Perhaps try to back up to a better place to break the line */
24245     for(k=i; k>i/2; k--){
24246       if( IsSpace(z[k-1]) ) break;
24247     }
24248     if( k<=i/2 ){
24249       for(k=i; k>i/2; k--){
24250         if( IsAlnum(z[k-1])!=IsAlnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
24251       }
24252     }
24253     if( k<=i/2 ){
24254       k = i;
24255     }else{
24256       i = k;
24257       while( z[i]==' ' ) i++;
24258     }
24259   }else{
24260     k = i;
24261   }
24262   if( n>=mxWidth && z[i]>=' ' ){
24263    *pzTail = &z[i];
24264   }else if( z[i]=='\r' && z[i+1]=='\n' ){
24265     *pzTail = z[i+2] ? &z[i+2] : 0;
24266   }else if( z[i]==0 || z[i+1]==0 ){
24267     *pzTail = 0;
24268   }else{
24269     *pzTail = &z[i+1];
24270   }
24271   zOut = malloc( j+1 );
24272   shell_check_oom(zOut);
24273   i = j = n = 0;
24274   while( i<k ){
24275     unsigned char c = z[i];
24276     if( c>=0xc0 ){
24277       int u;
24278       int len = decodeUtf8(&z[i], &u);
24279       do{ zOut[j++] = z[i++]; }while( (--len)>0 );
24280       n += cli_wcwidth(u);
24281       continue;
24282     }
24283     if( c>=' ' ){
24284       n++;
24285       zOut[j++] = z[i++];
24286       continue;
24287     }
24288     if( c==0 ) break;
24289     if( z[i]=='\t' ){
24290       do{
24291         n++;
24292         zOut[j++] = ' ';
24293       }while( (n&7)!=0 && n<mxWidth );
24294       i++;
24295       continue;
24296     }
24297     switch( p->eEscMode ){
24298       case SHELL_ESC_SYMBOL:
24299         zOut[j++] = 0xe2;
24300         zOut[j++] = 0x90;
24301         zOut[j++] = 0x80 + c;
24302         break;
24303       case SHELL_ESC_ASCII:
24304         zOut[j++] = '^';
24305         zOut[j++] = 0x40 + c;
24306         break;
24307       case SHELL_ESC_OFF: {
24308         int nn;
24309         if( c==0x1b && (nn = isVt100(&z[i]))>0 ){
24310           memcpy(&zOut[j], &z[i], nn);
24311           j += nn;
24312           i += nn - 1;
24313         }else{
24314           zOut[j++] = c;
24315         }
24316         break;
24317       }
24318     }
24319     i++;
24320   }
24321   zOut[j] = 0;
24322   return (char*)zOut;
24323 }
24324 
24325 /* Return true if the text string z[] contains characters that need
24326 ** unistr() escaping.
24327 */
needUnistr(const unsigned char * z)24328 static int needUnistr(const unsigned char *z){
24329   unsigned char c;
24330   if( z==0 ) return 0;
24331   while( (c = *z)>0x1f || c=='\t' || c=='\n' || (c=='\r' && z[1]=='\n') ){ z++; }
24332   return c!=0;
24333 }
24334 
24335 /* Extract the value of the i-th current column for pStmt as an SQL literal
24336 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
24337 ** the caller.
24338 */
quoted_column(sqlite3_stmt * pStmt,int i)24339 static char *quoted_column(sqlite3_stmt *pStmt, int i){
24340   switch( sqlite3_column_type(pStmt, i) ){
24341     case SQLITE_NULL: {
24342       return sqlite3_mprintf("NULL");
24343     }
24344     case SQLITE_INTEGER:
24345     case SQLITE_FLOAT: {
24346       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
24347     }
24348     case SQLITE_TEXT: {
24349       const unsigned char *zText = sqlite3_column_text(pStmt,i);
24350       return sqlite3_mprintf(needUnistr(zText)?"%#Q":"%Q",zText);
24351     }
24352     case SQLITE_BLOB: {
24353       int j;
24354       sqlite3_str *pStr = sqlite3_str_new(0);
24355       const unsigned char *a = sqlite3_column_blob(pStmt,i);
24356       int n = sqlite3_column_bytes(pStmt,i);
24357       sqlite3_str_append(pStr, "x'", 2);
24358       for(j=0; j<n; j++){
24359         sqlite3_str_appendf(pStr, "%02x", a[j]);
24360       }
24361       sqlite3_str_append(pStr, "'", 1);
24362       return sqlite3_str_finish(pStr);
24363     }
24364   }
24365   return 0; /* Not reached */
24366 }
24367 
24368 /*
24369 ** Run a prepared statement and output the result in one of the
24370 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
24371 ** or MODE_Box.
24372 **
24373 ** This is different from ordinary exec_prepared_stmt() in that
24374 ** it has to run the entire query and gather the results into memory
24375 ** first, in order to determine column widths, before providing
24376 ** any output.
24377 */
exec_prepared_stmt_columnar(ShellState * p,sqlite3_stmt * pStmt)24378 static void exec_prepared_stmt_columnar(
24379   ShellState *p,                        /* Pointer to ShellState */
24380   sqlite3_stmt *pStmt                   /* Statement to run */
24381 ){
24382   sqlite3_int64 nRow = 0;
24383   int nColumn = 0;
24384   char **azData = 0;
24385   sqlite3_int64 nAlloc = 0;
24386   char *abRowDiv = 0;
24387   const unsigned char *uz;
24388   const char *z;
24389   char **azQuoted = 0;
24390   int rc;
24391   sqlite3_int64 i, nData;
24392   int j, nTotal, w, n;
24393   const char *colSep = 0;
24394   const char *rowSep = 0;
24395   const unsigned char **azNextLine = 0;
24396   int bNextLine = 0;
24397   int bMultiLineRowExists = 0;
24398   int bw = p->cmOpts.bWordWrap;
24399   const char *zEmpty = "";
24400   const char *zShowNull = p->nullValue;
24401 
24402   rc = sqlite3_step(pStmt);
24403   if( rc!=SQLITE_ROW ) return;
24404   nColumn = sqlite3_column_count(pStmt);
24405   if( nColumn==0 ) goto columnar_end;
24406   nAlloc = nColumn*4;
24407   if( nAlloc<=0 ) nAlloc = 1;
24408   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
24409   shell_check_oom(azData);
24410   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
24411   shell_check_oom(azNextLine);
24412   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
24413   if( p->cmOpts.bQuote ){
24414     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
24415     shell_check_oom(azQuoted);
24416     memset(azQuoted, 0, nColumn*sizeof(char*) );
24417   }
24418   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
24419   shell_check_oom(abRowDiv);
24420   if( nColumn>p->nWidth ){
24421     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
24422     shell_check_oom(p->colWidth);
24423     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
24424     p->nWidth = nColumn;
24425     p->actualWidth = &p->colWidth[nColumn];
24426   }
24427   memset(p->actualWidth, 0, nColumn*sizeof(int));
24428   for(i=0; i<nColumn; i++){
24429     w = p->colWidth[i];
24430     if( w<0 ) w = -w;
24431     p->actualWidth[i] = w;
24432   }
24433   for(i=0; i<nColumn; i++){
24434     const unsigned char *zNotUsed;
24435     int wx = p->colWidth[i];
24436     if( wx==0 ){
24437       wx = p->cmOpts.iWrap;
24438     }
24439     if( wx<0 ) wx = -wx;
24440     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
24441     if( uz==0 ) uz = (u8*)"";
24442     azData[i] = translateForDisplayAndDup(p, uz, &zNotUsed, wx, bw);
24443   }
24444   do{
24445     int useNextLine = bNextLine;
24446     bNextLine = 0;
24447     if( (nRow+2)*nColumn >= nAlloc ){
24448       nAlloc *= 2;
24449       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
24450       shell_check_oom(azData);
24451       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
24452       shell_check_oom(abRowDiv);
24453     }
24454     abRowDiv[nRow] = 1;
24455     nRow++;
24456     for(i=0; i<nColumn; i++){
24457       int wx = p->colWidth[i];
24458       if( wx==0 ){
24459         wx = p->cmOpts.iWrap;
24460       }
24461       if( wx<0 ) wx = -wx;
24462       if( useNextLine ){
24463         uz = azNextLine[i];
24464         if( uz==0 ) uz = (u8*)zEmpty;
24465       }else if( p->cmOpts.bQuote ){
24466         assert( azQuoted!=0 );
24467         sqlite3_free(azQuoted[i]);
24468         azQuoted[i] = quoted_column(pStmt,i);
24469         uz = (const unsigned char*)azQuoted[i];
24470       }else{
24471         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
24472         if( uz==0 ) uz = (u8*)zShowNull;
24473       }
24474       azData[nRow*nColumn + i]
24475         = translateForDisplayAndDup(p, uz, &azNextLine[i], wx, bw);
24476       if( azNextLine[i] ){
24477         bNextLine = 1;
24478         abRowDiv[nRow-1] = 0;
24479         bMultiLineRowExists = 1;
24480       }
24481     }
24482   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
24483   nTotal = nColumn*(nRow+1);
24484   for(i=0; i<nTotal; i++){
24485     z = azData[i];
24486     if( z==0 ) z = (char*)zEmpty;
24487     n = strlenChar(z);
24488     j = i%nColumn;
24489     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
24490   }
24491   if( seenInterrupt ) goto columnar_end;
24492   switch( p->cMode ){
24493     case MODE_Column: {
24494       colSep = "  ";
24495       rowSep = "\n";
24496       if( p->showHeader ){
24497         for(i=0; i<nColumn; i++){
24498           w = p->actualWidth[i];
24499           if( p->colWidth[i]<0 ) w = -w;
24500           utf8_width_print(p->out, w, azData[i]);
24501           sqlite3_fputs(i==nColumn-1?"\n":"  ", p->out);
24502         }
24503         for(i=0; i<nColumn; i++){
24504           print_dashes(p->out, p->actualWidth[i]);
24505           sqlite3_fputs(i==nColumn-1?"\n":"  ", p->out);
24506         }
24507       }
24508       break;
24509     }
24510     case MODE_Table: {
24511       colSep = " | ";
24512       rowSep = " |\n";
24513       print_row_separator(p, nColumn, "+");
24514       sqlite3_fputs("| ", p->out);
24515       for(i=0; i<nColumn; i++){
24516         w = p->actualWidth[i];
24517         n = strlenChar(azData[i]);
24518         sqlite3_fprintf(p->out, "%*s%s%*s", (w-n)/2, "",
24519                         azData[i], (w-n+1)/2, "");
24520         sqlite3_fputs(i==nColumn-1?" |\n":" | ", p->out);
24521       }
24522       print_row_separator(p, nColumn, "+");
24523       break;
24524     }
24525     case MODE_Markdown: {
24526       colSep = " | ";
24527       rowSep = " |\n";
24528       sqlite3_fputs("| ", p->out);
24529       for(i=0; i<nColumn; i++){
24530         w = p->actualWidth[i];
24531         n = strlenChar(azData[i]);
24532         sqlite3_fprintf(p->out, "%*s%s%*s", (w-n)/2, "",
24533                         azData[i], (w-n+1)/2, "");
24534         sqlite3_fputs(i==nColumn-1?" |\n":" | ", p->out);
24535       }
24536       print_row_separator(p, nColumn, "|");
24537       break;
24538     }
24539     case MODE_Box: {
24540       colSep = " " BOX_13 " ";
24541       rowSep = " " BOX_13 "\n";
24542       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
24543       sqlite3_fputs(BOX_13 " ", p->out);
24544       for(i=0; i<nColumn; i++){
24545         w = p->actualWidth[i];
24546         n = strlenChar(azData[i]);
24547         sqlite3_fprintf(p->out, "%*s%s%*s%s",
24548               (w-n)/2, "", azData[i], (w-n+1)/2, "",
24549               i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
24550       }
24551       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
24552       break;
24553     }
24554   }
24555   for(i=nColumn, j=0; i<nTotal; i++, j++){
24556     if( j==0 && p->cMode!=MODE_Column ){
24557       sqlite3_fputs(p->cMode==MODE_Box?BOX_13" ":"| ", p->out);
24558     }
24559     z = azData[i];
24560     if( z==0 ) z = p->nullValue;
24561     w = p->actualWidth[j];
24562     if( p->colWidth[j]<0 ) w = -w;
24563     utf8_width_print(p->out, w, z);
24564     if( j==nColumn-1 ){
24565       sqlite3_fputs(rowSep, p->out);
24566       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
24567         if( p->cMode==MODE_Table ){
24568           print_row_separator(p, nColumn, "+");
24569         }else if( p->cMode==MODE_Box ){
24570           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
24571         }else if( p->cMode==MODE_Column ){
24572           sqlite3_fputs("\n", p->out);
24573         }
24574       }
24575       j = -1;
24576       if( seenInterrupt ) goto columnar_end;
24577     }else{
24578       sqlite3_fputs(colSep, p->out);
24579     }
24580   }
24581   if( p->cMode==MODE_Table ){
24582     print_row_separator(p, nColumn, "+");
24583   }else if( p->cMode==MODE_Box ){
24584     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
24585   }
24586 columnar_end:
24587   if( seenInterrupt ){
24588     sqlite3_fputs("Interrupt\n", p->out);
24589   }
24590   nData = (nRow+1)*nColumn;
24591   for(i=0; i<nData; i++){
24592     z = azData[i];
24593     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
24594   }
24595   sqlite3_free(azData);
24596   sqlite3_free((void*)azNextLine);
24597   sqlite3_free(abRowDiv);
24598   if( azQuoted ){
24599     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
24600     sqlite3_free(azQuoted);
24601   }
24602 }
24603 
24604 /*
24605 ** Run a prepared statement
24606 */
exec_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)24607 static void exec_prepared_stmt(
24608   ShellState *pArg,                                /* Pointer to ShellState */
24609   sqlite3_stmt *pStmt                              /* Statement to run */
24610 ){
24611   int rc;
24612   sqlite3_uint64 nRow = 0;
24613 
24614   if( pArg->cMode==MODE_Column
24615    || pArg->cMode==MODE_Table
24616    || pArg->cMode==MODE_Box
24617    || pArg->cMode==MODE_Markdown
24618   ){
24619     exec_prepared_stmt_columnar(pArg, pStmt);
24620     return;
24621   }
24622 
24623   /* perform the first step.  this will tell us if we
24624   ** have a result set or not and how wide it is.
24625   */
24626   rc = sqlite3_step(pStmt);
24627   /* if we have a result set... */
24628   if( SQLITE_ROW == rc ){
24629     /* allocate space for col name ptr, value ptr, and type */
24630     int nCol = sqlite3_column_count(pStmt);
24631     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
24632     if( !pData ){
24633       shell_out_of_memory();
24634     }else{
24635       char **azCols = (char **)pData;      /* Names of result columns */
24636       char **azVals = &azCols[nCol];       /* Results */
24637       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
24638       int i, x;
24639       assert(sizeof(int) <= sizeof(char *));
24640       /* save off ptrs to column names */
24641       for(i=0; i<nCol; i++){
24642         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
24643       }
24644       do{
24645         nRow++;
24646         /* extract the data and data types */
24647         for(i=0; i<nCol; i++){
24648           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
24649           if( x==SQLITE_BLOB
24650            && pArg
24651            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
24652           ){
24653             azVals[i] = "";
24654           }else{
24655             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
24656           }
24657           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
24658             rc = SQLITE_NOMEM;
24659             break; /* from for */
24660           }
24661         } /* end for */
24662 
24663         /* if data and types extracted successfully... */
24664         if( SQLITE_ROW == rc ){
24665           /* call the supplied callback with the result row data */
24666           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
24667             rc = SQLITE_ABORT;
24668           }else{
24669             rc = sqlite3_step(pStmt);
24670           }
24671         }
24672       } while( SQLITE_ROW == rc );
24673       sqlite3_free(pData);
24674       if( pArg->cMode==MODE_Json ){
24675         sqlite3_fputs("]\n", pArg->out);
24676       }else if( pArg->cMode==MODE_Www ){
24677         sqlite3_fputs("</TABLE>\n<PRE>\n", pArg->out);
24678       }else if( pArg->cMode==MODE_Count ){
24679         char zBuf[200];
24680         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
24681                          nRow, nRow!=1 ? "s" : "");
24682         printf("%s", zBuf);
24683       }
24684     }
24685   }
24686 }
24687 
24688 #ifndef SQLITE_OMIT_VIRTUALTABLE
24689 /*
24690 ** This function is called to process SQL if the previous shell command
24691 ** was ".expert". It passes the SQL in the second argument directly to
24692 ** the sqlite3expert object.
24693 **
24694 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
24695 ** code. In this case, (*pzErr) may be set to point to a buffer containing
24696 ** an English language error message. It is the responsibility of the
24697 ** caller to eventually free this buffer using sqlite3_free().
24698 */
expertHandleSQL(ShellState * pState,const char * zSql,char ** pzErr)24699 static int expertHandleSQL(
24700   ShellState *pState,
24701   const char *zSql,
24702   char **pzErr
24703 ){
24704   assert( pState->expert.pExpert );
24705   assert( pzErr==0 || *pzErr==0 );
24706   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
24707 }
24708 
24709 /*
24710 ** This function is called either to silently clean up the object
24711 ** created by the ".expert" command (if bCancel==1), or to generate a
24712 ** report from it and then clean it up (if bCancel==0).
24713 **
24714 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
24715 ** code. In this case, (*pzErr) may be set to point to a buffer containing
24716 ** an English language error message. It is the responsibility of the
24717 ** caller to eventually free this buffer using sqlite3_free().
24718 */
expertFinish(ShellState * pState,int bCancel,char ** pzErr)24719 static int expertFinish(
24720   ShellState *pState,
24721   int bCancel,
24722   char **pzErr
24723 ){
24724   int rc = SQLITE_OK;
24725   sqlite3expert *p = pState->expert.pExpert;
24726   FILE *out = pState->out;
24727   assert( p );
24728   assert( bCancel || pzErr==0 || *pzErr==0 );
24729   if( bCancel==0 ){
24730     int bVerbose = pState->expert.bVerbose;
24731 
24732     rc = sqlite3_expert_analyze(p, pzErr);
24733     if( rc==SQLITE_OK ){
24734       int nQuery = sqlite3_expert_count(p);
24735       int i;
24736 
24737       if( bVerbose ){
24738         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
24739         sqlite3_fputs("-- Candidates -----------------------------\n", out);
24740         sqlite3_fprintf(out, "%s\n", zCand);
24741       }
24742       for(i=0; i<nQuery; i++){
24743         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
24744         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
24745         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
24746         if( zIdx==0 ) zIdx = "(no new indexes)\n";
24747         if( bVerbose ){
24748           sqlite3_fprintf(out,
24749               "-- Query %d --------------------------------\n"
24750               "%s\n\n"
24751               ,i+1, zSql);
24752         }
24753         sqlite3_fprintf(out, "%s\n%s\n", zIdx, zEQP);
24754       }
24755     }
24756   }
24757   sqlite3_expert_destroy(p);
24758   pState->expert.pExpert = 0;
24759   return rc;
24760 }
24761 
24762 /*
24763 ** Implementation of ".expert" dot command.
24764 */
expertDotCommand(ShellState * pState,char ** azArg,int nArg)24765 static int expertDotCommand(
24766   ShellState *pState,             /* Current shell tool state */
24767   char **azArg,                   /* Array of arguments passed to dot command */
24768   int nArg                        /* Number of entries in azArg[] */
24769 ){
24770   int rc = SQLITE_OK;
24771   char *zErr = 0;
24772   int i;
24773   int iSample = 0;
24774 
24775   assert( pState->expert.pExpert==0 );
24776   memset(&pState->expert, 0, sizeof(ExpertInfo));
24777 
24778   for(i=1; rc==SQLITE_OK && i<nArg; i++){
24779     char *z = azArg[i];
24780     int n;
24781     if( z[0]=='-' && z[1]=='-' ) z++;
24782     n = strlen30(z);
24783     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
24784       pState->expert.bVerbose = 1;
24785     }
24786     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
24787       if( i==(nArg-1) ){
24788         sqlite3_fprintf(stderr, "option requires an argument: %s\n", z);
24789         rc = SQLITE_ERROR;
24790       }else{
24791         iSample = (int)integerValue(azArg[++i]);
24792         if( iSample<0 || iSample>100 ){
24793           sqlite3_fprintf(stderr,"value out of range: %s\n", azArg[i]);
24794           rc = SQLITE_ERROR;
24795         }
24796       }
24797     }
24798     else{
24799       sqlite3_fprintf(stderr,"unknown option: %s\n", z);
24800       rc = SQLITE_ERROR;
24801     }
24802   }
24803 
24804   if( rc==SQLITE_OK ){
24805     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
24806     if( pState->expert.pExpert==0 ){
24807       sqlite3_fprintf(stderr,
24808           "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
24809       rc = SQLITE_ERROR;
24810     }else{
24811       sqlite3_expert_config(
24812           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
24813       );
24814     }
24815   }
24816   sqlite3_free(zErr);
24817 
24818   return rc;
24819 }
24820 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
24821 
24822 /*
24823 ** Execute a statement or set of statements.  Print
24824 ** any result rows/columns depending on the current mode
24825 ** set via the supplied callback.
24826 **
24827 ** This is very similar to SQLite's built-in sqlite3_exec()
24828 ** function except it takes a slightly different callback
24829 ** and callback data argument.
24830 */
shell_exec(ShellState * pArg,const char * zSql,char ** pzErrMsg)24831 static int shell_exec(
24832   ShellState *pArg,                         /* Pointer to ShellState */
24833   const char *zSql,                         /* SQL to be evaluated */
24834   char **pzErrMsg                           /* Error msg written here */
24835 ){
24836   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
24837   int rc = SQLITE_OK;             /* Return Code */
24838   int rc2;
24839   const char *zLeftover;          /* Tail of unprocessed SQL */
24840   sqlite3 *db = pArg->db;
24841 
24842   if( pzErrMsg ){
24843     *pzErrMsg = NULL;
24844   }
24845 
24846 #ifndef SQLITE_OMIT_VIRTUALTABLE
24847   if( pArg->expert.pExpert ){
24848     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
24849     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
24850   }
24851 #endif
24852 
24853   while( zSql[0] && (SQLITE_OK == rc) ){
24854     static const char *zStmtSql;
24855     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
24856     if( SQLITE_OK != rc ){
24857       if( pzErrMsg ){
24858         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
24859       }
24860     }else{
24861       if( !pStmt ){
24862         /* this happens for a comment or white-space */
24863         zSql = zLeftover;
24864         while( IsSpace(zSql[0]) ) zSql++;
24865         continue;
24866       }
24867       zStmtSql = sqlite3_sql(pStmt);
24868       if( zStmtSql==0 ) zStmtSql = "";
24869       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
24870 
24871       /* save off the prepared statement handle and reset row count */
24872       if( pArg ){
24873         pArg->pStmt = pStmt;
24874         pArg->cnt = 0;
24875       }
24876 
24877       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
24878       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
24879         sqlite3_stmt *pExplain;
24880         int triggerEQP = 0;
24881         disable_debug_trace_modes();
24882         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
24883         if( pArg->autoEQP>=AUTOEQP_trigger ){
24884           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
24885         }
24886         pExplain = pStmt;
24887         sqlite3_reset(pExplain);
24888         rc = sqlite3_stmt_explain(pExplain, 2);
24889         if( rc==SQLITE_OK ){
24890           bind_prepared_stmt(pArg, pExplain);
24891           while( sqlite3_step(pExplain)==SQLITE_ROW ){
24892             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
24893             int iEqpId = sqlite3_column_int(pExplain, 0);
24894             int iParentId = sqlite3_column_int(pExplain, 1);
24895             if( zEQPLine==0 ) zEQPLine = "";
24896             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
24897             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
24898           }
24899           eqp_render(pArg, 0);
24900         }
24901         if( pArg->autoEQP>=AUTOEQP_full ){
24902           /* Also do an EXPLAIN for ".eqp full" mode */
24903           sqlite3_reset(pExplain);
24904           rc = sqlite3_stmt_explain(pExplain, 1);
24905           if( rc==SQLITE_OK ){
24906             pArg->cMode = MODE_Explain;
24907             assert( sqlite3_stmt_isexplain(pExplain)==1 );
24908             bind_prepared_stmt(pArg, pExplain);
24909             explain_data_prepare(pArg, pExplain);
24910             exec_prepared_stmt(pArg, pExplain);
24911             explain_data_delete(pArg);
24912           }
24913         }
24914         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
24915           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
24916         }
24917         sqlite3_reset(pStmt);
24918         sqlite3_stmt_explain(pStmt, 0);
24919         restore_debug_trace_modes();
24920       }
24921 
24922       if( pArg ){
24923         int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
24924         pArg->cMode = pArg->mode;
24925         if( pArg->autoExplain ){
24926           if( bIsExplain ){
24927             pArg->cMode = MODE_Explain;
24928           }
24929           if( sqlite3_stmt_isexplain(pStmt)==2 ){
24930             pArg->cMode = MODE_EQP;
24931           }
24932         }
24933 
24934         /* If the shell is currently in ".explain" mode, gather the extra
24935         ** data required to add indents to the output.*/
24936         if( pArg->cMode==MODE_Explain && bIsExplain ){
24937           explain_data_prepare(pArg, pStmt);
24938         }
24939       }
24940 
24941       bind_prepared_stmt(pArg, pStmt);
24942       exec_prepared_stmt(pArg, pStmt);
24943       explain_data_delete(pArg);
24944       eqp_render(pArg, 0);
24945 
24946       /* print usage stats if stats on */
24947       if( pArg && pArg->statsOn ){
24948         display_stats(db, pArg, 0);
24949       }
24950 
24951       /* print loop-counters if required */
24952       if( pArg && pArg->scanstatsOn ){
24953         display_scanstats(db, pArg);
24954       }
24955 
24956       /* Finalize the statement just executed. If this fails, save a
24957       ** copy of the error message. Otherwise, set zSql to point to the
24958       ** next statement to execute. */
24959       rc2 = sqlite3_finalize(pStmt);
24960       if( rc!=SQLITE_NOMEM ) rc = rc2;
24961       if( rc==SQLITE_OK ){
24962         zSql = zLeftover;
24963         while( IsSpace(zSql[0]) ) zSql++;
24964       }else if( pzErrMsg ){
24965         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
24966       }
24967 
24968       /* clear saved stmt handle */
24969       if( pArg ){
24970         pArg->pStmt = NULL;
24971       }
24972     }
24973   } /* end while */
24974 
24975   return rc;
24976 }
24977 
24978 /*
24979 ** Release memory previously allocated by tableColumnList().
24980 */
freeColumnList(char ** azCol)24981 static void freeColumnList(char **azCol){
24982   int i;
24983   for(i=1; azCol[i]; i++){
24984     sqlite3_free(azCol[i]);
24985   }
24986   /* azCol[0] is a static string */
24987   sqlite3_free(azCol);
24988 }
24989 
24990 /*
24991 ** Return a list of pointers to strings which are the names of all
24992 ** columns in table zTab.   The memory to hold the names is dynamically
24993 ** allocated and must be released by the caller using a subsequent call
24994 ** to freeColumnList().
24995 **
24996 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
24997 ** value that needs to be preserved, then azCol[0] is filled in with the
24998 ** name of the rowid column.
24999 **
25000 ** The first regular column in the table is azCol[1].  The list is terminated
25001 ** by an entry with azCol[i]==0.
25002 */
tableColumnList(ShellState * p,const char * zTab)25003 static char **tableColumnList(ShellState *p, const char *zTab){
25004   char **azCol = 0;
25005   sqlite3_stmt *pStmt;
25006   char *zSql;
25007   int nCol = 0;
25008   int nAlloc = 0;
25009   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
25010   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
25011   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
25012   int rc;
25013 
25014   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
25015   shell_check_oom(zSql);
25016   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25017   sqlite3_free(zSql);
25018   if( rc ) return 0;
25019   while( sqlite3_step(pStmt)==SQLITE_ROW ){
25020     if( nCol>=nAlloc-2 ){
25021       nAlloc = nAlloc*2 + nCol + 10;
25022       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
25023       shell_check_oom(azCol);
25024     }
25025     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
25026     shell_check_oom(azCol[nCol]);
25027     if( sqlite3_column_int(pStmt, 5) ){
25028       nPK++;
25029       if( nPK==1
25030        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
25031                           "INTEGER")==0
25032       ){
25033         isIPK = 1;
25034       }else{
25035         isIPK = 0;
25036       }
25037     }
25038   }
25039   sqlite3_finalize(pStmt);
25040   if( azCol==0 ) return 0;
25041   azCol[0] = 0;
25042   azCol[nCol+1] = 0;
25043 
25044   /* The decision of whether or not a rowid really needs to be preserved
25045   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
25046   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
25047   ** rowids on tables where the rowid is inaccessible because there are other
25048   ** columns in the table named "rowid", "_rowid_", and "oid".
25049   */
25050   if( preserveRowid && isIPK ){
25051     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
25052     ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
25053     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
25054     ** ROWID aliases.  To distinguish these cases, check to see if
25055     ** there is a "pk" entry in "PRAGMA index_list".  There will be
25056     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
25057     */
25058     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
25059                            " WHERE origin='pk'", zTab);
25060     shell_check_oom(zSql);
25061     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25062     sqlite3_free(zSql);
25063     if( rc ){
25064       freeColumnList(azCol);
25065       return 0;
25066     }
25067     rc = sqlite3_step(pStmt);
25068     sqlite3_finalize(pStmt);
25069     preserveRowid = rc==SQLITE_ROW;
25070   }
25071   if( preserveRowid ){
25072     /* Only preserve the rowid if we can find a name to use for the
25073     ** rowid */
25074     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
25075     int i, j;
25076     for(j=0; j<3; j++){
25077       for(i=1; i<=nCol; i++){
25078         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
25079       }
25080       if( i>nCol ){
25081         /* At this point, we know that azRowid[j] is not the name of any
25082         ** ordinary column in the table.  Verify that azRowid[j] is a valid
25083         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
25084         ** tables will fail this last check */
25085         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
25086         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
25087         break;
25088       }
25089     }
25090   }
25091   return azCol;
25092 }
25093 
25094 /*
25095 ** Toggle the reverse_unordered_selects setting.
25096 */
toggleSelectOrder(sqlite3 * db)25097 static void toggleSelectOrder(sqlite3 *db){
25098   sqlite3_stmt *pStmt = 0;
25099   int iSetting = 0;
25100   char zStmt[100];
25101   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
25102   if( sqlite3_step(pStmt)==SQLITE_ROW ){
25103     iSetting = sqlite3_column_int(pStmt, 0);
25104   }
25105   sqlite3_finalize(pStmt);
25106   sqlite3_snprintf(sizeof(zStmt), zStmt,
25107        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
25108   sqlite3_exec(db, zStmt, 0, 0, 0);
25109 }
25110 
25111 /*
25112 ** This is a different callback routine used for dumping the database.
25113 ** Each row received by this callback consists of a table name,
25114 ** the table type ("index" or "table") and SQL to create the table.
25115 ** This routine should print text sufficient to recreate the table.
25116 */
dump_callback(void * pArg,int nArg,char ** azArg,char ** azNotUsed)25117 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
25118   int rc;
25119   const char *zTable;
25120   const char *zType;
25121   const char *zSql;
25122   ShellState *p = (ShellState *)pArg;
25123   int dataOnly;
25124   int noSys;
25125 
25126   UNUSED_PARAMETER(azNotUsed);
25127   if( nArg!=3 || azArg==0 ) return 0;
25128   zTable = azArg[0];
25129   zType = azArg[1];
25130   zSql = azArg[2];
25131   if( zTable==0 ) return 0;
25132   if( zType==0 ) return 0;
25133   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
25134   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
25135 
25136   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
25137     /* no-op */
25138   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
25139     if( !dataOnly ) sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out);
25140   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
25141     return 0;
25142   }else if( dataOnly ){
25143     /* no-op */
25144   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
25145     char *zIns;
25146     if( !p->writableSchema ){
25147       sqlite3_fputs("PRAGMA writable_schema=ON;\n", p->out);
25148       p->writableSchema = 1;
25149     }
25150     zIns = sqlite3_mprintf(
25151        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
25152        "VALUES('table','%q','%q',0,'%q');",
25153        zTable, zTable, zSql);
25154     shell_check_oom(zIns);
25155     sqlite3_fprintf(p->out, "%s\n", zIns);
25156     sqlite3_free(zIns);
25157     return 0;
25158   }else{
25159     printSchemaLine(p->out, zSql, ";\n");
25160   }
25161 
25162   if( cli_strcmp(zType, "table")==0 ){
25163     ShellText sSelect;
25164     ShellText sTable;
25165     char **azCol;
25166     int i;
25167     char *savedDestTable;
25168     int savedMode;
25169 
25170     azCol = tableColumnList(p, zTable);
25171     if( azCol==0 ){
25172       p->nErr++;
25173       return 0;
25174     }
25175 
25176     /* Always quote the table name, even if it appears to be pure ascii,
25177     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
25178     initText(&sTable);
25179     appendText(&sTable, zTable, quoteChar(zTable));
25180     /* If preserving the rowid, add a column list after the table name.
25181     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
25182     ** instead of the usual "INSERT INTO tab VALUES(...)".
25183     */
25184     if( azCol[0] ){
25185       appendText(&sTable, "(", 0);
25186       appendText(&sTable, azCol[0], 0);
25187       for(i=1; azCol[i]; i++){
25188         appendText(&sTable, ",", 0);
25189         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
25190       }
25191       appendText(&sTable, ")", 0);
25192     }
25193 
25194     /* Build an appropriate SELECT statement */
25195     initText(&sSelect);
25196     appendText(&sSelect, "SELECT ", 0);
25197     if( azCol[0] ){
25198       appendText(&sSelect, azCol[0], 0);
25199       appendText(&sSelect, ",", 0);
25200     }
25201     for(i=1; azCol[i]; i++){
25202       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
25203       if( azCol[i+1] ){
25204         appendText(&sSelect, ",", 0);
25205       }
25206     }
25207     freeColumnList(azCol);
25208     appendText(&sSelect, " FROM ", 0);
25209     appendText(&sSelect, zTable, quoteChar(zTable));
25210 
25211     savedDestTable = p->zDestTable;
25212     savedMode = p->mode;
25213     p->zDestTable = sTable.z;
25214     p->mode = p->cMode = MODE_Insert;
25215     rc = shell_exec(p, sSelect.z, 0);
25216     if( (rc&0xff)==SQLITE_CORRUPT ){
25217       sqlite3_fputs("/****** CORRUPTION ERROR *******/\n", p->out);
25218       toggleSelectOrder(p->db);
25219       shell_exec(p, sSelect.z, 0);
25220       toggleSelectOrder(p->db);
25221     }
25222     p->zDestTable = savedDestTable;
25223     p->mode = savedMode;
25224     freeText(&sTable);
25225     freeText(&sSelect);
25226     if( rc ) p->nErr++;
25227   }
25228   return 0;
25229 }
25230 
25231 /*
25232 ** Run zQuery.  Use dump_callback() as the callback routine so that
25233 ** the contents of the query are output as SQL statements.
25234 **
25235 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
25236 ** "ORDER BY rowid DESC" to the end.
25237 */
run_schema_dump_query(ShellState * p,const char * zQuery)25238 static int run_schema_dump_query(
25239   ShellState *p,
25240   const char *zQuery
25241 ){
25242   int rc;
25243   char *zErr = 0;
25244   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
25245   if( rc==SQLITE_CORRUPT ){
25246     char *zQ2;
25247     int len = strlen30(zQuery);
25248     sqlite3_fputs("/****** CORRUPTION ERROR *******/\n", p->out);
25249     if( zErr ){
25250       sqlite3_fprintf(p->out, "/****** %s ******/\n", zErr);
25251       sqlite3_free(zErr);
25252       zErr = 0;
25253     }
25254     zQ2 = malloc( len+100 );
25255     if( zQ2==0 ) return rc;
25256     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
25257     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
25258     if( rc ){
25259       sqlite3_fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
25260     }else{
25261       rc = SQLITE_CORRUPT;
25262     }
25263     free(zQ2);
25264   }
25265   sqlite3_free(zErr);
25266   return rc;
25267 }
25268 
25269 /*
25270 ** Text of help messages.
25271 **
25272 ** The help text for each individual command begins with a line that starts
25273 ** with ".".  Subsequent lines are supplemental information.
25274 **
25275 ** There must be two or more spaces between the end of the command and the
25276 ** start of the description of what that command does.
25277 */
25278 static const char *(azHelp[]) = {
25279 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
25280   && !defined(SQLITE_SHELL_FIDDLE)
25281   ".archive ...             Manage SQL archives",
25282   "   Each command must have exactly one of the following options:",
25283   "     -c, --create               Create a new archive",
25284   "     -u, --update               Add or update files with changed mtime",
25285   "     -i, --insert               Like -u but always add even if unchanged",
25286   "     -r, --remove               Remove files from archive",
25287   "     -t, --list                 List contents of archive",
25288   "     -x, --extract              Extract files from archive",
25289   "   Optional arguments:",
25290   "     -v, --verbose              Print each filename as it is processed",
25291   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
25292   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
25293   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
25294   "     -g, --glob                 Use glob matching for names in archive",
25295   "     -n, --dryrun               Show the SQL that would have occurred",
25296   "   Examples:",
25297   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
25298   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
25299   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
25300   "   See also:",
25301   "      http://sqlite.org/cli.html#sqlite_archive_support",
25302 #endif
25303 #ifndef SQLITE_OMIT_AUTHORIZATION
25304   ".auth ON|OFF             Show authorizer callbacks",
25305 #endif
25306 #ifndef SQLITE_SHELL_FIDDLE
25307   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
25308   "   Options:",
25309   "       --append            Use the appendvfs",
25310   "       --async             Write to FILE without journal and fsync()",
25311 #endif
25312   ".bail on|off             Stop after hitting an error.  Default OFF",
25313 #ifndef SQLITE_SHELL_FIDDLE
25314   ".cd DIRECTORY            Change the working directory to DIRECTORY",
25315 #endif
25316   ".changes on|off          Show number of rows changed by SQL",
25317 #ifndef SQLITE_SHELL_FIDDLE
25318   ".check GLOB              Fail if output since .testcase does not match",
25319   ".clone NEWDB             Clone data into NEWDB from the existing database",
25320 #endif
25321   ".connection [close] [#]  Open or close an auxiliary database connection",
25322   ".crlf ?on|off?           Whether or not to use \\r\\n line endings",
25323   ".databases               List names and files of attached databases",
25324   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
25325 #if SQLITE_SHELL_HAVE_RECOVER
25326   ".dbinfo ?DB?             Show status information about the database",
25327 #endif
25328   ".dbtotxt                 Hex dump of the database file",
25329   ".dump ?OBJECTS?          Render database content as SQL",
25330   "   Options:",
25331   "     --data-only            Output only INSERT statements",
25332   "     --newlines             Allow unescaped newline characters in output",
25333   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
25334   "     --preserve-rowids      Include ROWID values in the output",
25335   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
25336   "   Additional LIKE patterns can be given in subsequent arguments",
25337   ".echo on|off             Turn command echo on or off",
25338   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
25339   "   Other Modes:",
25340 #ifdef SQLITE_DEBUG
25341   "      test                  Show raw EXPLAIN QUERY PLAN output",
25342   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
25343 #endif
25344   "      trigger               Like \"full\" but also show trigger bytecode",
25345 #ifndef SQLITE_SHELL_FIDDLE
25346   ".excel                   Display the output of next command in spreadsheet",
25347   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
25348 #endif
25349 #ifndef SQLITE_SHELL_FIDDLE
25350   ".exit ?CODE?             Exit this program with return-code CODE",
25351 #endif
25352   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
25353   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
25354   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
25355   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
25356   "   --help                  Show CMD details",
25357   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
25358   ".headers on|off          Turn display of headers on or off",
25359   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
25360 #ifndef SQLITE_SHELL_FIDDLE
25361   ".import FILE TABLE       Import data from FILE into TABLE",
25362   "   Options:",
25363   "     --ascii               Use \\037 and \\036 as column and row separators",
25364   "     --csv                 Use , and \\n as column and row separators",
25365   "     --skip N              Skip the first N rows of input",
25366   "     --schema S            Target table to be S.TABLE",
25367   "     -v                    \"Verbose\" - increase auxiliary output",
25368   "   Notes:",
25369   "     *  If TABLE does not exist, it is created.  The first row of input",
25370   "        determines the column names.",
25371   "     *  If neither --csv or --ascii are used, the input mode is derived",
25372   "        from the \".mode\" output mode",
25373   "     *  If FILE begins with \"|\" then it is a command that generates the",
25374   "        input text.",
25375 #endif
25376 #ifndef SQLITE_OMIT_TEST_CONTROL
25377   ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
25378 #endif
25379   ".indexes ?TABLE?         Show names of indexes",
25380   "                           If TABLE is specified, only show indexes for",
25381   "                           tables matching TABLE using the LIKE operator.",
25382   ".intck ?STEPS_PER_UNLOCK?  Run an incremental integrity check on the db",
25383 #ifdef SQLITE_ENABLE_IOTRACE
25384   ",iotrace FILE            Enable I/O diagnostic logging to FILE",
25385 #endif
25386   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
25387   ".lint OPTIONS            Report potential schema issues.",
25388   "     Options:",
25389   "        fkey-indexes     Find missing foreign key indexes",
25390 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
25391   ".load FILE ?ENTRY?       Load an extension library",
25392 #endif
25393 #if !defined(SQLITE_SHELL_FIDDLE)
25394   ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
25395 #else
25396   ".log on|off              Turn logging on or off.",
25397 #endif
25398   ".mode ?MODE? ?OPTIONS?   Set output mode",
25399   "   MODE is one of:",
25400   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
25401   "     box         Tables using unicode box-drawing characters",
25402   "     csv         Comma-separated values",
25403   "     column      Output in columns.  (See .width)",
25404   "     html        HTML <table> code",
25405   "     insert      SQL insert statements for TABLE",
25406   "     json        Results in a JSON array",
25407   "     line        One value per line",
25408   "     list        Values delimited by \"|\"",
25409   "     markdown    Markdown table format",
25410   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
25411   "     quote       Escape answers as for SQL",
25412   "     table       ASCII-art table",
25413   "     tabs        Tab-separated values",
25414   "     tcl         TCL list elements",
25415   "   OPTIONS: (for columnar modes or insert mode):",
25416   "     --escape T     ctrl-char escape; T is one of: symbol, ascii, off",
25417   "     --wrap N       Wrap output lines to no longer than N characters",
25418   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
25419   "     --ww           Shorthand for \"--wordwrap 1\"",
25420   "     --quote        Quote output text as SQL literals",
25421   "     --noquote      Do not quote output text",
25422   "     TABLE          The name of SQL table used for \"insert\" mode",
25423 #ifndef SQLITE_SHELL_FIDDLE
25424   ".nonce STRING            Suspend safe mode for one command if nonce matches",
25425 #endif
25426   ".nullvalue STRING        Use STRING in place of NULL values",
25427 #ifndef SQLITE_SHELL_FIDDLE
25428   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
25429   "     If FILE begins with '|' then open as a pipe",
25430   "       --bom    Put a UTF8 byte-order mark at the beginning",
25431   "       -e       Send output to the system text editor",
25432   "       --plain  Use text/plain output instead of HTML for -w option",
25433   "       -w       Send output as HTML to a web browser (same as \".www\")",
25434   "       -x       Send output as CSV to a spreadsheet (same as \".excel\")",
25435   /* Note that .open is (partially) available in WASM builds but is
25436   ** currently only intended to be used by the fiddle tool, not
25437   ** end users, so is "undocumented." */
25438   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
25439   "     Options:",
25440   "        --append        Use appendvfs to append database to the end of FILE",
25441 #endif
25442 #ifndef SQLITE_OMIT_DESERIALIZE
25443   "        --deserialize   Load into memory using sqlite3_deserialize()",
25444   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
25445   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
25446 #endif
25447   "        --new           Initialize FILE to an empty database",
25448   "        --nofollow      Do not follow symbolic links",
25449   "        --readonly      Open FILE readonly",
25450   "        --zip           FILE is a ZIP archive",
25451 #ifndef SQLITE_SHELL_FIDDLE
25452   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
25453   "   If FILE begins with '|' then open it as a pipe.",
25454   "   If FILE is 'off' then output is disabled.",
25455   "   Options:",
25456   "     --bom                 Prefix output with a UTF8 byte-order mark",
25457   "     -e                    Send output to the system text editor",
25458   "     --plain               Use text/plain for -w option",
25459   "     -w                    Send output to a web browser",
25460   "     -x                    Send output as CSV to a spreadsheet",
25461 #endif
25462   ".parameter CMD ...       Manage SQL parameter bindings",
25463   "   clear                   Erase all bindings",
25464   "   init                    Initialize the TEMP table that holds bindings",
25465   "   list                    List the current parameter bindings",
25466   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
25467   "                           PARAMETER should start with one of: $ : @ ?",
25468   "   unset PARAMETER         Remove PARAMETER from the binding table",
25469   ".print STRING...         Print literal STRING",
25470 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
25471   ".progress N              Invoke progress handler after every N opcodes",
25472   "   --limit N                 Interrupt after N progress callbacks",
25473   "   --once                    Do no more than one progress interrupt",
25474   "   --quiet|-q                No output except at interrupts",
25475   "   --reset                   Reset the count for each input and interrupt",
25476 #endif
25477   ".prompt MAIN CONTINUE    Replace the standard prompts",
25478 #ifndef SQLITE_SHELL_FIDDLE
25479   ".quit                    Stop interpreting input stream, exit if primary.",
25480   ".read FILE               Read input from FILE or command output",
25481   "    If FILE begins with \"|\", it is a command that generates the input.",
25482 #endif
25483 #if SQLITE_SHELL_HAVE_RECOVER
25484   ".recover                 Recover as much data as possible from corrupt db.",
25485   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
25486   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
25487   "   --no-rowids              Do not attempt to recover rowid values",
25488   "                            that are not also INTEGER PRIMARY KEYs",
25489 #endif
25490 #ifndef SQLITE_SHELL_FIDDLE
25491   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
25492   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
25493 #endif
25494   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
25495   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
25496   "   Options:",
25497   "      --indent             Try to pretty-print the schema",
25498   "      --nosys              Omit objects whose names start with \"sqlite_\"",
25499   ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
25500   "    Options:",
25501   "       --init               Create a new SELFTEST table",
25502   "       -v                   Verbose output",
25503   ".separator COL ?ROW?     Change the column and row separators",
25504 #if defined(SQLITE_ENABLE_SESSION)
25505   ".session ?NAME? CMD ...  Create or control sessions",
25506   "   Subcommands:",
25507   "     attach TABLE             Attach TABLE",
25508   "     changeset FILE           Write a changeset into FILE",
25509   "     close                    Close one session",
25510   "     enable ?BOOLEAN?         Set or query the enable bit",
25511   "     filter GLOB...           Reject tables matching GLOBs",
25512   "     indirect ?BOOLEAN?       Mark or query the indirect status",
25513   "     isempty                  Query whether the session is empty",
25514   "     list                     List currently open session names",
25515   "     open DB NAME             Open a new session on DB",
25516   "     patchset FILE            Write a patchset into FILE",
25517   "   If ?NAME? is omitted, the first defined session is used.",
25518 #endif
25519   ".sha3sum ...             Compute a SHA3 hash of database content",
25520   "    Options:",
25521   "      --schema              Also hash the sqlite_schema table",
25522   "      --sha3-224            Use the sha3-224 algorithm",
25523   "      --sha3-256            Use the sha3-256 algorithm (default)",
25524   "      --sha3-384            Use the sha3-384 algorithm",
25525   "      --sha3-512            Use the sha3-512 algorithm",
25526   "    Any other argument is a LIKE pattern for tables to hash",
25527 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
25528   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
25529 #endif
25530   ".show                    Show the current values for various settings",
25531   ".stats ?ARG?             Show stats or turn stats on or off",
25532   "   off                      Turn off automatic stat display",
25533   "   on                       Turn on automatic stat display",
25534   "   stmt                     Show statement stats",
25535   "   vmstep                   Show the virtual machine step count only",
25536 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
25537   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
25538 #endif
25539   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
25540 #ifndef SQLITE_SHELL_FIDDLE
25541   ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
25542 #endif
25543   ",testctrl CMD ...        Run various sqlite3_test_control() operations",
25544   "                           Run \".testctrl\" with no arguments for details",
25545   ".timeout MS              Try opening locked tables for MS milliseconds",
25546   ".timer on|off            Turn SQL timer on or off",
25547 #ifndef SQLITE_OMIT_TRACE
25548   ".trace ?OPTIONS?         Output each SQL statement as it is run",
25549   "    FILE                    Send output to FILE",
25550   "    stdout                  Send output to stdout",
25551   "    stderr                  Send output to stderr",
25552   "    off                     Disable tracing",
25553   "    --expanded              Expand query parameters",
25554 #ifdef SQLITE_ENABLE_NORMALIZE
25555   "    --normalized            Normal the SQL statements",
25556 #endif
25557   "    --plain                 Show SQL as it is input",
25558   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
25559   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
25560   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
25561   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
25562 #endif /* SQLITE_OMIT_TRACE */
25563 #ifdef SQLITE_DEBUG
25564   ".unmodule NAME ...       Unregister virtual table modules",
25565   "    --allexcept             Unregister everything except those named",
25566 #endif
25567   ".version                 Show source, library and compiler versions",
25568   ".vfsinfo ?AUX?           Information about the top-level VFS",
25569   ".vfslist                 List all available VFSes",
25570   ".vfsname ?AUX?           Print the name of the VFS stack",
25571   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
25572   "     Negative values right-justify",
25573 #ifndef SQLITE_SHELL_FIDDLE
25574   ".www                     Display output of the next command in web browser",
25575   "    --plain                 Show results as text/plain, not as HTML",
25576 #endif
25577 };
25578 
25579 /*
25580 ** Output help text for commands that match zPattern.
25581 **
25582 **    *   If zPattern is NULL, then show all documented commands, but
25583 **        only give a one-line summary of each.
25584 **
25585 **    *   If zPattern is "-a" or "-all" or "--all" then show all help text
25586 **        for all commands except undocumented commands.
25587 **
25588 **    *   If zPattern is "0" then show all help for undocumented commands.
25589 **        Undocumented commands begin with "," instead of "." in the azHelp[]
25590 **        array.
25591 **
25592 **    *   If zPattern is a prefix for one or more documented commands, then
25593 **        show help for those commands.  If only a single command matches the
25594 **        prefix, show the full text of the help.  If multiple commands match,
25595 **        Only show just the first line of each.
25596 **
25597 **    *   Otherwise, show the complete text of any documented command for which
25598 **        zPattern is a LIKE match for any text within that command help
25599 **        text.
25600 **
25601 ** Return the number commands that match zPattern.
25602 */
showHelp(FILE * out,const char * zPattern)25603 static int showHelp(FILE *out, const char *zPattern){
25604   int i = 0;
25605   int j = 0;
25606   int n = 0;
25607   char *zPat;
25608   if( zPattern==0 ){
25609     /* Show just the first line for all help topics */
25610     zPattern = "[a-z]";
25611   }else if( cli_strcmp(zPattern,"-a")==0
25612          || cli_strcmp(zPattern,"-all")==0
25613          || cli_strcmp(zPattern,"--all")==0
25614   ){
25615     /* Show everything except undocumented commands */
25616     zPattern = ".";
25617   }else if( cli_strcmp(zPattern,"0")==0 ){
25618     /* Show complete help text of undocumented commands */
25619     int show = 0;
25620     for(i=0; i<ArraySize(azHelp); i++){
25621       if( azHelp[i][0]=='.' ){
25622         show = 0;
25623       }else if( azHelp[i][0]==',' ){
25624         show = 1;
25625         sqlite3_fprintf(out, ".%s\n", &azHelp[i][1]);
25626         n++;
25627       }else if( show ){
25628         sqlite3_fprintf(out, "%s\n", azHelp[i]);
25629       }
25630     }
25631     return n;
25632   }
25633 
25634   /* Seek documented commands for which zPattern is an exact prefix */
25635   zPat = sqlite3_mprintf(".%s*", zPattern);
25636   shell_check_oom(zPat);
25637   for(i=0; i<ArraySize(azHelp); i++){
25638     if( sqlite3_strglob(zPat, azHelp[i])==0 ){
25639       sqlite3_fprintf(out, "%s\n", azHelp[i]);
25640       j = i+1;
25641       n++;
25642     }
25643   }
25644   sqlite3_free(zPat);
25645   if( n ){
25646     if( n==1 ){
25647       /* when zPattern is a prefix of exactly one command, then include
25648       ** the details of that command, which should begin at offset j */
25649       while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
25650         sqlite3_fprintf(out, "%s\n", azHelp[j]);
25651         j++;
25652       }
25653     }
25654     return n;
25655   }
25656 
25657   /* Look for documented commands that contain zPattern anywhere.
25658   ** Show complete text of all documented commands that match. */
25659   zPat = sqlite3_mprintf("%%%s%%", zPattern);
25660   shell_check_oom(zPat);
25661   for(i=0; i<ArraySize(azHelp); i++){
25662     if( azHelp[i][0]==',' ){
25663       while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
25664       continue;
25665     }
25666     if( azHelp[i][0]=='.' ) j = i;
25667     if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
25668       sqlite3_fprintf(out, "%s\n", azHelp[j]);
25669       while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
25670         j++;
25671         sqlite3_fprintf(out, "%s\n", azHelp[j]);
25672       }
25673       i = j;
25674       n++;
25675     }
25676   }
25677   sqlite3_free(zPat);
25678   return n;
25679 }
25680 
25681 /* Forward reference */
25682 static int process_input(ShellState *p);
25683 
25684 /*
25685 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
25686 ** and return a pointer to the buffer. The caller is responsible for freeing
25687 ** the memory.
25688 **
25689 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
25690 ** read.
25691 **
25692 ** For convenience, a nul-terminator byte is always appended to the data read
25693 ** from the file before the buffer is returned. This byte is not included in
25694 ** the final value of (*pnByte), if applicable.
25695 **
25696 ** NULL is returned if any error is encountered. The final value of *pnByte
25697 ** is undefined in this case.
25698 */
readFile(const char * zName,int * pnByte)25699 static char *readFile(const char *zName, int *pnByte){
25700   FILE *in = sqlite3_fopen(zName, "rb");
25701   long nIn;
25702   size_t nRead;
25703   char *pBuf;
25704   int rc;
25705   if( in==0 ) return 0;
25706   rc = fseek(in, 0, SEEK_END);
25707   if( rc!=0 ){
25708     sqlite3_fprintf(stderr,"Error: '%s' not seekable\n", zName);
25709     fclose(in);
25710     return 0;
25711   }
25712   nIn = ftell(in);
25713   rewind(in);
25714   pBuf = sqlite3_malloc64( nIn+1 );
25715   if( pBuf==0 ){
25716     sqlite3_fputs("Error: out of memory\n", stderr);
25717     fclose(in);
25718     return 0;
25719   }
25720   nRead = fread(pBuf, nIn, 1, in);
25721   fclose(in);
25722   if( nRead!=1 ){
25723     sqlite3_free(pBuf);
25724     sqlite3_fprintf(stderr,"Error: cannot read '%s'\n", zName);
25725     return 0;
25726   }
25727   pBuf[nIn] = 0;
25728   if( pnByte ) *pnByte = nIn;
25729   return pBuf;
25730 }
25731 
25732 #if defined(SQLITE_ENABLE_SESSION)
25733 /*
25734 ** Close a single OpenSession object and release all of its associated
25735 ** resources.
25736 */
session_close(OpenSession * pSession)25737 static void session_close(OpenSession *pSession){
25738   int i;
25739   sqlite3session_delete(pSession->p);
25740   sqlite3_free(pSession->zName);
25741   for(i=0; i<pSession->nFilter; i++){
25742     sqlite3_free(pSession->azFilter[i]);
25743   }
25744   sqlite3_free(pSession->azFilter);
25745   memset(pSession, 0, sizeof(OpenSession));
25746 }
25747 #endif
25748 
25749 /*
25750 ** Close all OpenSession objects and release all associated resources.
25751 */
25752 #if defined(SQLITE_ENABLE_SESSION)
session_close_all(ShellState * p,int i)25753 static void session_close_all(ShellState *p, int i){
25754   int j;
25755   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
25756   for(j=0; j<pAuxDb->nSession; j++){
25757     session_close(&pAuxDb->aSession[j]);
25758   }
25759   pAuxDb->nSession = 0;
25760 }
25761 #else
25762 # define session_close_all(X,Y)
25763 #endif
25764 
25765 /*
25766 ** Implementation of the xFilter function for an open session.  Omit
25767 ** any tables named by ".session filter" but let all other table through.
25768 */
25769 #if defined(SQLITE_ENABLE_SESSION)
session_filter(void * pCtx,const char * zTab)25770 static int session_filter(void *pCtx, const char *zTab){
25771   OpenSession *pSession = (OpenSession*)pCtx;
25772   int i;
25773   for(i=0; i<pSession->nFilter; i++){
25774     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
25775   }
25776   return 1;
25777 }
25778 #endif
25779 
25780 /*
25781 ** Try to deduce the type of file for zName based on its content.  Return
25782 ** one of the SHELL_OPEN_* constants.
25783 **
25784 ** If the file does not exist or is empty but its name looks like a ZIP
25785 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
25786 ** Otherwise, assume an ordinary database regardless of the filename if
25787 ** the type cannot be determined from content.
25788 */
deduceDatabaseType(const char * zName,int dfltZip)25789 int deduceDatabaseType(const char *zName, int dfltZip){
25790   FILE *f = sqlite3_fopen(zName, "rb");
25791   size_t n;
25792   int rc = SHELL_OPEN_UNSPEC;
25793   char zBuf[100];
25794   if( f==0 ){
25795     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
25796        return SHELL_OPEN_ZIPFILE;
25797     }else{
25798        return SHELL_OPEN_NORMAL;
25799     }
25800   }
25801   n = fread(zBuf, 16, 1, f);
25802   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
25803     fclose(f);
25804     return SHELL_OPEN_NORMAL;
25805   }
25806   fseek(f, -25, SEEK_END);
25807   n = fread(zBuf, 25, 1, f);
25808   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
25809     rc = SHELL_OPEN_APPENDVFS;
25810   }else{
25811     fseek(f, -22, SEEK_END);
25812     n = fread(zBuf, 22, 1, f);
25813     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
25814        && zBuf[3]==0x06 ){
25815       rc = SHELL_OPEN_ZIPFILE;
25816     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
25817       rc = SHELL_OPEN_ZIPFILE;
25818     }
25819   }
25820   fclose(f);
25821   return rc;
25822 }
25823 
25824 #ifndef SQLITE_OMIT_DESERIALIZE
25825 /*
25826 ** Reconstruct an in-memory database using the output from the "dbtotxt"
25827 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
25828 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
25829 */
readHexDb(ShellState * p,int * pnData)25830 static unsigned char *readHexDb(ShellState *p, int *pnData){
25831   unsigned char *a = 0;
25832   int nLine;
25833   int n = 0;
25834   int pgsz = 0;
25835   int iOffset = 0;
25836   int j, k;
25837   int rc;
25838   FILE *in;
25839   const char *zDbFilename = p->pAuxDb->zDbFilename;
25840   unsigned int x[16];
25841   char zLine[1000];
25842   if( zDbFilename ){
25843     in = sqlite3_fopen(zDbFilename, "r");
25844     if( in==0 ){
25845       sqlite3_fprintf(stderr,"cannot open \"%s\" for reading\n", zDbFilename);
25846       return 0;
25847     }
25848     nLine = 0;
25849   }else{
25850     in = p->in;
25851     nLine = p->lineno;
25852     if( in==0 ) in = stdin;
25853   }
25854   *pnData = 0;
25855   nLine++;
25856   if( sqlite3_fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
25857   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
25858   if( rc!=2 ) goto readHexDb_error;
25859   if( n<0 ) goto readHexDb_error;
25860   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
25861   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
25862   a = sqlite3_malloc( n ? n : 1 );
25863   shell_check_oom(a);
25864   memset(a, 0, n);
25865   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
25866     sqlite3_fputs("invalid pagesize\n", stderr);
25867     goto readHexDb_error;
25868   }
25869   for(nLine++; sqlite3_fgets(zLine, sizeof(zLine), in)!=0; nLine++){
25870     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
25871     if( rc==2 ){
25872       iOffset = k;
25873       continue;
25874     }
25875     if( cli_strncmp(zLine, "| end ", 6)==0 ){
25876       break;
25877     }
25878     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
25879                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
25880                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
25881     if( rc==17 ){
25882       k = iOffset+j;
25883       if( k+16<=n && k>=0 ){
25884         int ii;
25885         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
25886       }
25887     }
25888   }
25889   *pnData = n;
25890   if( in!=p->in ){
25891     fclose(in);
25892   }else{
25893     p->lineno = nLine;
25894   }
25895   return a;
25896 
25897 readHexDb_error:
25898   if( in!=p->in ){
25899     fclose(in);
25900   }else{
25901     while( sqlite3_fgets(zLine, sizeof(zLine), p->in)!=0 ){
25902       nLine++;
25903       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
25904     }
25905     p->lineno = nLine;
25906   }
25907   sqlite3_free(a);
25908   sqlite3_fprintf(stderr,"Error on line %d of --hexdb input\n", nLine);
25909   return 0;
25910 }
25911 #endif /* SQLITE_OMIT_DESERIALIZE */
25912 
25913 /*
25914 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
25915 */
shellUSleepFunc(sqlite3_context * context,int argcUnused,sqlite3_value ** argv)25916 static void shellUSleepFunc(
25917   sqlite3_context *context,
25918   int argcUnused,
25919   sqlite3_value **argv
25920 ){
25921   int sleep = sqlite3_value_int(argv[0]);
25922   (void)argcUnused;
25923   sqlite3_sleep(sleep/1000);
25924   sqlite3_result_int(context, sleep);
25925 }
25926 
25927 /*
25928 ** SQL function:  shell_module_schema(X)
25929 **
25930 ** Return a fake schema for the table-valued function or eponymous virtual
25931 ** table X.
25932 */
shellModuleSchema(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)25933 static void shellModuleSchema(
25934   sqlite3_context *pCtx,
25935   int nVal,
25936   sqlite3_value **apVal
25937 ){
25938   const char *zName;
25939   char *zFake;
25940   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
25941   FILE *pSavedLog = p->pLog;
25942   UNUSED_PARAMETER(nVal);
25943   zName = (const char*)sqlite3_value_text(apVal[0]);
25944 
25945   /* Temporarily disable the ".log" when calling shellFakeSchema() because
25946   ** shellFakeSchema() might generate failures for some ephemeral virtual
25947   ** tables due to missing arguments.  Example: fts4aux.
25948   ** https://sqlite.org/forum/forumpost/42fe6520b803be51 */
25949   p->pLog = 0;
25950   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
25951   p->pLog = pSavedLog;
25952 
25953   if( zFake ){
25954     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
25955                         -1, sqlite3_free);
25956     free(zFake);
25957   }
25958 }
25959 
25960 /* Flags for open_db().
25961 **
25962 ** The default behavior of open_db() is to exit(1) if the database fails to
25963 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
25964 ** but still returns without calling exit.
25965 **
25966 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
25967 ** ZIP archive if the file does not exist or is empty and its name matches
25968 ** the *.zip pattern.
25969 */
25970 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
25971 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
25972 
25973 /*
25974 ** Make sure the database is open.  If it is not, then open it.  If
25975 ** the database fails to open, print an error message and exit.
25976 */
open_db(ShellState * p,int openFlags)25977 static void open_db(ShellState *p, int openFlags){
25978   if( p->db==0 ){
25979     const char *zDbFilename = p->pAuxDb->zDbFilename;
25980     if( p->openMode==SHELL_OPEN_UNSPEC ){
25981       if( zDbFilename==0 || zDbFilename[0]==0 ){
25982         p->openMode = SHELL_OPEN_NORMAL;
25983       }else{
25984         p->openMode = (u8)deduceDatabaseType(zDbFilename,
25985                              (openFlags & OPEN_DB_ZIPFILE)!=0);
25986       }
25987     }
25988     switch( p->openMode ){
25989       case SHELL_OPEN_APPENDVFS: {
25990         sqlite3_open_v2(zDbFilename, &p->db,
25991            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
25992         break;
25993       }
25994       case SHELL_OPEN_HEXDB:
25995       case SHELL_OPEN_DESERIALIZE: {
25996         sqlite3_open(0, &p->db);
25997         break;
25998       }
25999       case SHELL_OPEN_ZIPFILE: {
26000         sqlite3_open(":memory:", &p->db);
26001         break;
26002       }
26003       case SHELL_OPEN_READONLY: {
26004         sqlite3_open_v2(zDbFilename, &p->db,
26005             SQLITE_OPEN_READONLY|p->openFlags, 0);
26006         break;
26007       }
26008       case SHELL_OPEN_UNSPEC:
26009       case SHELL_OPEN_NORMAL: {
26010         sqlite3_open_v2(zDbFilename, &p->db,
26011            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
26012         break;
26013       }
26014     }
26015     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
26016       sqlite3_fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
26017             zDbFilename, sqlite3_errmsg(p->db));
26018       if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
26019         exit(1);
26020       }
26021       sqlite3_close(p->db);
26022       sqlite3_open(":memory:", &p->db);
26023       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
26024         sqlite3_fputs("Also: unable to open substitute in-memory database.\n",
26025                       stderr);
26026         exit(1);
26027       }else{
26028         sqlite3_fprintf(stderr,
26029               "Notice: using substitute in-memory database instead of \"%s\"\n",
26030               zDbFilename);
26031       }
26032     }
26033     globalDb = p->db;
26034     sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
26035 
26036     /* Reflect the use or absence of --unsafe-testing invocation. */
26037     {
26038       int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
26039       sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
26040       sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
26041     }
26042 
26043 #ifndef SQLITE_OMIT_LOAD_EXTENSION
26044     sqlite3_enable_load_extension(p->db, 1);
26045 #endif
26046     sqlite3_sha_init(p->db, 0, 0);
26047     sqlite3_shathree_init(p->db, 0, 0);
26048     sqlite3_uint_init(p->db, 0, 0);
26049     sqlite3_stmtrand_init(p->db, 0, 0);
26050     sqlite3_decimal_init(p->db, 0, 0);
26051     sqlite3_percentile_init(p->db, 0, 0);
26052     sqlite3_base64_init(p->db, 0, 0);
26053     sqlite3_base85_init(p->db, 0, 0);
26054     sqlite3_regexp_init(p->db, 0, 0);
26055     sqlite3_ieee_init(p->db, 0, 0);
26056     sqlite3_series_init(p->db, 0, 0);
26057 #ifndef SQLITE_SHELL_FIDDLE
26058     sqlite3_fileio_init(p->db, 0, 0);
26059     sqlite3_completion_init(p->db, 0, 0);
26060 #endif
26061 #ifdef SQLITE_HAVE_ZLIB
26062     if( !p->bSafeModePersist ){
26063       sqlite3_zipfile_init(p->db, 0, 0);
26064       sqlite3_sqlar_init(p->db, 0, 0);
26065     }
26066 #endif
26067 #ifdef SQLITE_SHELL_EXTFUNCS
26068     /* Create a preprocessing mechanism for extensions to make
26069      * their own provisions for being built into the shell.
26070      * This is a short-span macro. See further below for usage.
26071      */
26072 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
26073 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
26074     /* Let custom-included extensions get their ..._init() called.
26075      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
26076      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
26077      * initialization routine to be called.
26078      */
26079     {
26080       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
26081     /* Let custom-included extensions expose their functionality.
26082      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
26083      * the SQL functions, virtual tables, collating sequences or
26084      * VFS's implemented by the extension to be registered.
26085      */
26086       if( irc==SQLITE_OK
26087           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
26088         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
26089       }
26090 #undef SHELL_SUB_MACRO
26091 #undef SHELL_SUBMACRO
26092     }
26093 #endif
26094 
26095     sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
26096                             shellStrtod, 0, 0);
26097     sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
26098                             shellDtostr, 0, 0);
26099     sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
26100                             shellDtostr, 0, 0);
26101     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
26102                             shellAddSchemaName, 0, 0);
26103     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, p,
26104                             shellModuleSchema, 0, 0);
26105     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
26106                             shellPutsFunc, 0, 0);
26107     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
26108                             shellUSleepFunc, 0, 0);
26109 #ifndef SQLITE_NOHAVE_SYSTEM
26110     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
26111                             editFunc, 0, 0);
26112     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
26113                             editFunc, 0, 0);
26114 #endif
26115 
26116     if( p->openMode==SHELL_OPEN_ZIPFILE ){
26117       char *zSql = sqlite3_mprintf(
26118          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
26119       shell_check_oom(zSql);
26120       sqlite3_exec(p->db, zSql, 0, 0, 0);
26121       sqlite3_free(zSql);
26122     }
26123 #ifndef SQLITE_OMIT_DESERIALIZE
26124     else
26125     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
26126       int rc;
26127       int nData = 0;
26128       unsigned char *aData;
26129       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
26130         aData = (unsigned char*)readFile(zDbFilename, &nData);
26131       }else{
26132         aData = readHexDb(p, &nData);
26133       }
26134       if( aData==0 ){
26135         return;
26136       }
26137       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
26138                    SQLITE_DESERIALIZE_RESIZEABLE |
26139                    SQLITE_DESERIALIZE_FREEONCLOSE);
26140       if( rc ){
26141         sqlite3_fprintf(stderr,"Error: sqlite3_deserialize() returns %d\n", rc);
26142       }
26143       if( p->szMax>0 ){
26144         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
26145       }
26146     }
26147 #endif
26148   }
26149   if( p->db!=0 ){
26150     if( p->bSafeModePersist ){
26151       sqlite3_set_authorizer(p->db, safeModeAuth, p);
26152     }
26153     sqlite3_db_config(
26154         p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
26155     );
26156   }
26157 }
26158 
26159 /*
26160 ** Attempt to close the database connection.  Report errors.
26161 */
close_db(sqlite3 * db)26162 void close_db(sqlite3 *db){
26163   int rc = sqlite3_close(db);
26164   if( rc ){
26165     sqlite3_fprintf(stderr,
26166         "Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
26167   }
26168 }
26169 
26170 #if (HAVE_READLINE || HAVE_EDITLINE) \
26171   && !defined(SQLITE_OMIT_READLINE_COMPLETION)
26172 /*
26173 ** Readline completion callbacks
26174 */
readline_completion_generator(const char * text,int state)26175 static char *readline_completion_generator(const char *text, int state){
26176   static sqlite3_stmt *pStmt = 0;
26177   char *zRet;
26178   if( state==0 ){
26179     char *zSql;
26180     sqlite3_finalize(pStmt);
26181     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
26182                            "  FROM completion(%Q) ORDER BY 1", text);
26183     shell_check_oom(zSql);
26184     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
26185     sqlite3_free(zSql);
26186   }
26187   if( sqlite3_step(pStmt)==SQLITE_ROW ){
26188     const char *z = (const char*)sqlite3_column_text(pStmt,0);
26189     zRet = z ? strdup(z) : 0;
26190   }else{
26191     sqlite3_finalize(pStmt);
26192     pStmt = 0;
26193     zRet = 0;
26194   }
26195   return zRet;
26196 }
readline_completion(const char * zText,int iStart,int iEnd)26197 static char **readline_completion(const char *zText, int iStart, int iEnd){
26198   (void)iStart;
26199   (void)iEnd;
26200   rl_attempted_completion_over = 1;
26201   return rl_completion_matches(zText, readline_completion_generator);
26202 }
26203 
26204 #elif HAVE_LINENOISE
26205 /*
26206 ** Linenoise completion callback. Note that the 3rd argument is from
26207 ** the "msteveb" version of linenoise, not the "antirez" version.
26208 */
linenoise_completion(const char * zLine,linenoiseCompletions * lc,void * pUserData)26209 static void linenoise_completion(
26210   const char *zLine,
26211   linenoiseCompletions *lc
26212 #if HAVE_LINENOISE==2
26213   ,void *pUserData
26214 #endif
26215 ){
26216   i64 nLine = strlen(zLine);
26217   i64 i, iStart;
26218   sqlite3_stmt *pStmt = 0;
26219   char *zSql;
26220   char zBuf[1000];
26221 
26222 #if HAVE_LINENOISE==2
26223   UNUSED_PARAMETER(pUserData);
26224 #endif
26225   if( nLine>(i64)sizeof(zBuf)-30 ) return;
26226   if( zLine[0]=='.' || zLine[0]=='#') return;
26227   for(i=nLine-1; i>=0 && (IsAlnum(zLine[i]) || zLine[i]=='_'); i--){}
26228   if( i==nLine-1 ) return;
26229   iStart = i+1;
26230   memcpy(zBuf, zLine, iStart);
26231   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
26232                          "  FROM completion(%Q,%Q) ORDER BY 1",
26233                          &zLine[iStart], zLine);
26234   shell_check_oom(zSql);
26235   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
26236   sqlite3_free(zSql);
26237   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
26238   while( sqlite3_step(pStmt)==SQLITE_ROW ){
26239     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
26240     int nCompletion = sqlite3_column_bytes(pStmt, 0);
26241     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
26242       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
26243       linenoiseAddCompletion(lc, zBuf);
26244     }
26245   }
26246   sqlite3_finalize(pStmt);
26247 }
26248 #endif
26249 
26250 /*
26251 ** Do C-language style dequoting.
26252 **
26253 **    \a    -> alarm
26254 **    \b    -> backspace
26255 **    \t    -> tab
26256 **    \n    -> newline
26257 **    \v    -> vertical tab
26258 **    \f    -> form feed
26259 **    \r    -> carriage return
26260 **    \s    -> space
26261 **    \"    -> "
26262 **    \'    -> '
26263 **    \\    -> backslash
26264 **    \NNN  -> ascii character NNN in octal
26265 **    \xHH  -> ascii character HH in hexadecimal
26266 */
resolve_backslashes(char * z)26267 static void resolve_backslashes(char *z){
26268   int i, j;
26269   char c;
26270   while( *z && *z!='\\' ) z++;
26271   for(i=j=0; (c = z[i])!=0; i++, j++){
26272     if( c=='\\' && z[i+1]!=0 ){
26273       c = z[++i];
26274       if( c=='a' ){
26275         c = '\a';
26276       }else if( c=='b' ){
26277         c = '\b';
26278       }else if( c=='t' ){
26279         c = '\t';
26280       }else if( c=='n' ){
26281         c = '\n';
26282       }else if( c=='v' ){
26283         c = '\v';
26284       }else if( c=='f' ){
26285         c = '\f';
26286       }else if( c=='r' ){
26287         c = '\r';
26288       }else if( c=='"' ){
26289         c = '"';
26290       }else if( c=='\'' ){
26291         c = '\'';
26292       }else if( c=='\\' ){
26293         c = '\\';
26294       }else if( c=='x' ){
26295         int nhd = 0, hdv;
26296         u8 hv = 0;
26297         while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
26298           hv = (u8)((hv<<4)|hdv);
26299           ++nhd;
26300         }
26301         i += nhd;
26302         c = (u8)hv;
26303       }else if( c>='0' && c<='7' ){
26304         c -= '0';
26305         if( z[i+1]>='0' && z[i+1]<='7' ){
26306           i++;
26307           c = (c<<3) + z[i] - '0';
26308           if( z[i+1]>='0' && z[i+1]<='7' ){
26309             i++;
26310             c = (c<<3) + z[i] - '0';
26311           }
26312         }
26313       }
26314     }
26315     z[j] = c;
26316   }
26317   if( j<i ) z[j] = 0;
26318 }
26319 
26320 /*
26321 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
26322 ** for TRUE and FALSE.  Return the integer value if appropriate.
26323 */
booleanValue(const char * zArg)26324 static int booleanValue(const char *zArg){
26325   int i;
26326   if( zArg[0]=='0' && zArg[1]=='x' ){
26327     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
26328   }else{
26329     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
26330   }
26331   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
26332   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
26333     return 1;
26334   }
26335   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
26336     return 0;
26337   }
26338   sqlite3_fprintf(stderr,
26339        "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
26340   return 0;
26341 }
26342 
26343 /*
26344 ** Set or clear a shell flag according to a boolean value.
26345 */
setOrClearFlag(ShellState * p,unsigned mFlag,const char * zArg)26346 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
26347   if( booleanValue(zArg) ){
26348     ShellSetFlag(p, mFlag);
26349   }else{
26350     ShellClearFlag(p, mFlag);
26351   }
26352 }
26353 
26354 /*
26355 ** Close an output file, assuming it is not stderr or stdout
26356 */
output_file_close(FILE * f)26357 static void output_file_close(FILE *f){
26358   if( f && f!=stdout && f!=stderr ) fclose(f);
26359 }
26360 
26361 /*
26362 ** Try to open an output file.   The names "stdout" and "stderr" are
26363 ** recognized and do the right thing.  NULL is returned if the output
26364 ** filename is "off".
26365 */
output_file_open(const char * zFile)26366 static FILE *output_file_open(const char *zFile){
26367   FILE *f;
26368   if( cli_strcmp(zFile,"stdout")==0 ){
26369     f = stdout;
26370   }else if( cli_strcmp(zFile, "stderr")==0 ){
26371     f = stderr;
26372   }else if( cli_strcmp(zFile, "off")==0 ){
26373     f = 0;
26374   }else{
26375     f = sqlite3_fopen(zFile, "w");
26376     if( f==0 ){
26377       sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", zFile);
26378     }
26379   }
26380   return f;
26381 }
26382 
26383 #ifndef SQLITE_OMIT_TRACE
26384 /*
26385 ** A routine for handling output from sqlite3_trace().
26386 */
sql_trace_callback(unsigned mType,void * pArg,void * pP,void * pX)26387 static int sql_trace_callback(
26388   unsigned mType,         /* The trace type */
26389   void *pArg,             /* The ShellState pointer */
26390   void *pP,               /* Usually a pointer to sqlite_stmt */
26391   void *pX                /* Auxiliary output */
26392 ){
26393   ShellState *p = (ShellState*)pArg;
26394   sqlite3_stmt *pStmt;
26395   const char *zSql;
26396   i64 nSql;
26397   if( p->traceOut==0 ) return 0;
26398   if( mType==SQLITE_TRACE_CLOSE ){
26399     sputz(p->traceOut, "-- closing database connection\n");
26400     return 0;
26401   }
26402   if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
26403     zSql = (const char*)pX;
26404   }else{
26405     pStmt = (sqlite3_stmt*)pP;
26406     switch( p->eTraceType ){
26407       case SHELL_TRACE_EXPANDED: {
26408         zSql = sqlite3_expanded_sql(pStmt);
26409         break;
26410       }
26411 #ifdef SQLITE_ENABLE_NORMALIZE
26412       case SHELL_TRACE_NORMALIZED: {
26413         zSql = sqlite3_normalized_sql(pStmt);
26414         break;
26415       }
26416 #endif
26417       default: {
26418         zSql = sqlite3_sql(pStmt);
26419         break;
26420       }
26421     }
26422   }
26423   if( zSql==0 ) return 0;
26424   nSql = strlen(zSql);
26425   if( nSql>1000000000 ) nSql = 1000000000;
26426   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
26427   switch( mType ){
26428     case SQLITE_TRACE_ROW:
26429     case SQLITE_TRACE_STMT: {
26430       sqlite3_fprintf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
26431       break;
26432     }
26433     case SQLITE_TRACE_PROFILE: {
26434       sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
26435       sqlite3_fprintf(p->traceOut,
26436                       "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
26437       break;
26438     }
26439   }
26440   return 0;
26441 }
26442 #endif
26443 
26444 /*
26445 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
26446 ** a useful spot to set a debugger breakpoint.
26447 **
26448 ** This routine does not do anything practical.  The code are there simply
26449 ** to prevent the compiler from optimizing this routine out.
26450 */
test_breakpoint(void)26451 static void test_breakpoint(void){
26452   static unsigned int nCall = 0;
26453   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
26454 }
26455 
26456 /*
26457 ** An object used to read a CSV and other files for import.
26458 */
26459 typedef struct ImportCtx ImportCtx;
26460 struct ImportCtx {
26461   const char *zFile;  /* Name of the input file */
26462   FILE *in;           /* Read the CSV text from this input stream */
26463   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
26464   char *z;            /* Accumulated text for a field */
26465   int n;              /* Number of bytes in z */
26466   int nAlloc;         /* Space allocated for z[] */
26467   int nLine;          /* Current line number */
26468   int nRow;           /* Number of rows imported */
26469   int nErr;           /* Number of errors encountered */
26470   int bNotFirst;      /* True if one or more bytes already read */
26471   int cTerm;          /* Character that terminated the most recent field */
26472   int cColSep;        /* The column separator character.  (Usually ",") */
26473   int cRowSep;        /* The row separator character.  (Usually "\n") */
26474 };
26475 
26476 /* Clean up resourced used by an ImportCtx */
import_cleanup(ImportCtx * p)26477 static void import_cleanup(ImportCtx *p){
26478   if( p->in!=0 && p->xCloser!=0 ){
26479     p->xCloser(p->in);
26480     p->in = 0;
26481   }
26482   sqlite3_free(p->z);
26483   p->z = 0;
26484 }
26485 
26486 /* Append a single byte to z[] */
import_append_char(ImportCtx * p,int c)26487 static void import_append_char(ImportCtx *p, int c){
26488   if( p->n+1>=p->nAlloc ){
26489     p->nAlloc += p->nAlloc + 100;
26490     p->z = sqlite3_realloc64(p->z, p->nAlloc);
26491     shell_check_oom(p->z);
26492   }
26493   p->z[p->n++] = (char)c;
26494 }
26495 
26496 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
26497 ** with the option of having a separator other than ",".
26498 **
26499 **   +  Input comes from p->in.
26500 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
26501 **      from sqlite3_malloc64().
26502 **   +  Use p->cSep as the column separator.  The default is ",".
26503 **   +  Use p->rSep as the row separator.  The default is "\n".
26504 **   +  Keep track of the line number in p->nLine.
26505 **   +  Store the character that terminates the field in p->cTerm.  Store
26506 **      EOF on end-of-file.
26507 **   +  Report syntax errors on stderr
26508 */
csv_read_one_field(ImportCtx * p)26509 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
26510   int c;
26511   int cSep = (u8)p->cColSep;
26512   int rSep = (u8)p->cRowSep;
26513   p->n = 0;
26514   c = fgetc(p->in);
26515   if( c==EOF || seenInterrupt ){
26516     p->cTerm = EOF;
26517     return 0;
26518   }
26519   if( c=='"' ){
26520     int pc, ppc;
26521     int startLine = p->nLine;
26522     int cQuote = c;
26523     pc = ppc = 0;
26524     while( 1 ){
26525       c = fgetc(p->in);
26526       if( c==rSep ) p->nLine++;
26527       if( c==cQuote ){
26528         if( pc==cQuote ){
26529           pc = 0;
26530           continue;
26531         }
26532       }
26533       if( (c==cSep && pc==cQuote)
26534        || (c==rSep && pc==cQuote)
26535        || (c==rSep && pc=='\r' && ppc==cQuote)
26536        || (c==EOF && pc==cQuote)
26537       ){
26538         do{ p->n--; }while( p->z[p->n]!=cQuote );
26539         p->cTerm = c;
26540         break;
26541       }
26542       if( pc==cQuote && c!='\r' ){
26543         sqlite3_fprintf(stderr,"%s:%d: unescaped %c character\n",
26544                         p->zFile, p->nLine, cQuote);
26545       }
26546       if( c==EOF ){
26547         sqlite3_fprintf(stderr,"%s:%d: unterminated %c-quoted field\n",
26548               p->zFile, startLine, cQuote);
26549         p->cTerm = c;
26550         break;
26551       }
26552       import_append_char(p, c);
26553       ppc = pc;
26554       pc = c;
26555     }
26556   }else{
26557     /* If this is the first field being parsed and it begins with the
26558     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
26559     if( (c&0xff)==0xef && p->bNotFirst==0 ){
26560       import_append_char(p, c);
26561       c = fgetc(p->in);
26562       if( (c&0xff)==0xbb ){
26563         import_append_char(p, c);
26564         c = fgetc(p->in);
26565         if( (c&0xff)==0xbf ){
26566           p->bNotFirst = 1;
26567           p->n = 0;
26568           return csv_read_one_field(p);
26569         }
26570       }
26571     }
26572     while( c!=EOF && c!=cSep && c!=rSep ){
26573       import_append_char(p, c);
26574       c = fgetc(p->in);
26575     }
26576     if( c==rSep ){
26577       p->nLine++;
26578       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
26579     }
26580     p->cTerm = c;
26581   }
26582   if( p->z ) p->z[p->n] = 0;
26583   p->bNotFirst = 1;
26584   return p->z;
26585 }
26586 
26587 /* Read a single field of ASCII delimited text.
26588 **
26589 **   +  Input comes from p->in.
26590 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
26591 **      from sqlite3_malloc64().
26592 **   +  Use p->cSep as the column separator.  The default is "\x1F".
26593 **   +  Use p->rSep as the row separator.  The default is "\x1E".
26594 **   +  Keep track of the row number in p->nLine.
26595 **   +  Store the character that terminates the field in p->cTerm.  Store
26596 **      EOF on end-of-file.
26597 **   +  Report syntax errors on stderr
26598 */
ascii_read_one_field(ImportCtx * p)26599 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
26600   int c;
26601   int cSep = (u8)p->cColSep;
26602   int rSep = (u8)p->cRowSep;
26603   p->n = 0;
26604   c = fgetc(p->in);
26605   if( c==EOF || seenInterrupt ){
26606     p->cTerm = EOF;
26607     return 0;
26608   }
26609   while( c!=EOF && c!=cSep && c!=rSep ){
26610     import_append_char(p, c);
26611     c = fgetc(p->in);
26612   }
26613   if( c==rSep ){
26614     p->nLine++;
26615   }
26616   p->cTerm = c;
26617   if( p->z ) p->z[p->n] = 0;
26618   return p->z;
26619 }
26620 
26621 /*
26622 ** Try to transfer data for table zTable.  If an error is seen while
26623 ** moving forward, try to go backwards.  The backwards movement won't
26624 ** work for WITHOUT ROWID tables.
26625 */
tryToCloneData(ShellState * p,sqlite3 * newDb,const char * zTable)26626 static void tryToCloneData(
26627   ShellState *p,
26628   sqlite3 *newDb,
26629   const char *zTable
26630 ){
26631   sqlite3_stmt *pQuery = 0;
26632   sqlite3_stmt *pInsert = 0;
26633   char *zQuery = 0;
26634   char *zInsert = 0;
26635   int rc;
26636   int i, j, n;
26637   int nTable = strlen30(zTable);
26638   int k = 0;
26639   int cnt = 0;
26640   const int spinRate = 10000;
26641 
26642   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
26643   shell_check_oom(zQuery);
26644   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
26645   if( rc ){
26646     sqlite3_fprintf(stderr,"Error %d: %s on [%s]\n",
26647           sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
26648     goto end_data_xfer;
26649   }
26650   n = sqlite3_column_count(pQuery);
26651   zInsert = sqlite3_malloc64(200 + nTable + n*3);
26652   shell_check_oom(zInsert);
26653   sqlite3_snprintf(200+nTable,zInsert,
26654                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
26655   i = strlen30(zInsert);
26656   for(j=1; j<n; j++){
26657     memcpy(zInsert+i, ",?", 2);
26658     i += 2;
26659   }
26660   memcpy(zInsert+i, ");", 3);
26661   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
26662   if( rc ){
26663     sqlite3_fprintf(stderr,"Error %d: %s on [%s]\n",
26664           sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
26665     goto end_data_xfer;
26666   }
26667   for(k=0; k<2; k++){
26668     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
26669       for(i=0; i<n; i++){
26670         switch( sqlite3_column_type(pQuery, i) ){
26671           case SQLITE_NULL: {
26672             sqlite3_bind_null(pInsert, i+1);
26673             break;
26674           }
26675           case SQLITE_INTEGER: {
26676             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
26677             break;
26678           }
26679           case SQLITE_FLOAT: {
26680             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
26681             break;
26682           }
26683           case SQLITE_TEXT: {
26684             sqlite3_bind_text(pInsert, i+1,
26685                              (const char*)sqlite3_column_text(pQuery,i),
26686                              -1, SQLITE_STATIC);
26687             break;
26688           }
26689           case SQLITE_BLOB: {
26690             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
26691                                             sqlite3_column_bytes(pQuery,i),
26692                                             SQLITE_STATIC);
26693             break;
26694           }
26695         }
26696       } /* End for */
26697       rc = sqlite3_step(pInsert);
26698       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
26699         sqlite3_fprintf(stderr,"Error %d: %s\n",
26700               sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
26701       }
26702       sqlite3_reset(pInsert);
26703       cnt++;
26704       if( (cnt%spinRate)==0 ){
26705         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
26706         fflush(stdout);
26707       }
26708     } /* End while */
26709     if( rc==SQLITE_DONE ) break;
26710     sqlite3_finalize(pQuery);
26711     sqlite3_free(zQuery);
26712     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
26713                              zTable);
26714     shell_check_oom(zQuery);
26715     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
26716     if( rc ){
26717       sqlite3_fprintf(stderr,"Warning: cannot step \"%s\" backwards", zTable);
26718       break;
26719     }
26720   } /* End for(k=0...) */
26721 
26722 end_data_xfer:
26723   sqlite3_finalize(pQuery);
26724   sqlite3_finalize(pInsert);
26725   sqlite3_free(zQuery);
26726   sqlite3_free(zInsert);
26727 }
26728 
26729 
26730 /*
26731 ** Try to transfer all rows of the schema that match zWhere.  For
26732 ** each row, invoke xForEach() on the object defined by that row.
26733 ** If an error is encountered while moving forward through the
26734 ** sqlite_schema table, try again moving backwards.
26735 */
tryToCloneSchema(ShellState * p,sqlite3 * newDb,const char * zWhere,void (* xForEach)(ShellState *,sqlite3 *,const char *))26736 static void tryToCloneSchema(
26737   ShellState *p,
26738   sqlite3 *newDb,
26739   const char *zWhere,
26740   void (*xForEach)(ShellState*,sqlite3*,const char*)
26741 ){
26742   sqlite3_stmt *pQuery = 0;
26743   char *zQuery = 0;
26744   int rc;
26745   const unsigned char *zName;
26746   const unsigned char *zSql;
26747   char *zErrMsg = 0;
26748 
26749   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
26750                            " WHERE %s ORDER BY rowid ASC", zWhere);
26751   shell_check_oom(zQuery);
26752   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
26753   if( rc ){
26754     sqlite3_fprintf(stderr,
26755           "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
26756           sqlite3_errmsg(p->db), zQuery);
26757     goto end_schema_xfer;
26758   }
26759   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
26760     zName = sqlite3_column_text(pQuery, 0);
26761     zSql = sqlite3_column_text(pQuery, 1);
26762     if( zName==0 || zSql==0 ) continue;
26763     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
26764       sqlite3_fprintf(stdout, "%s... ", zName); fflush(stdout);
26765       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
26766       if( zErrMsg ){
26767         sqlite3_fprintf(stderr,"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
26768         sqlite3_free(zErrMsg);
26769         zErrMsg = 0;
26770       }
26771     }
26772     if( xForEach ){
26773       xForEach(p, newDb, (const char*)zName);
26774     }
26775     sputz(stdout, "done\n");
26776   }
26777   if( rc!=SQLITE_DONE ){
26778     sqlite3_finalize(pQuery);
26779     sqlite3_free(zQuery);
26780     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
26781                              " WHERE %s ORDER BY rowid DESC", zWhere);
26782     shell_check_oom(zQuery);
26783     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
26784     if( rc ){
26785       sqlite3_fprintf(stderr,"Error: (%d) %s on [%s]\n",
26786             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
26787       goto end_schema_xfer;
26788     }
26789     while( sqlite3_step(pQuery)==SQLITE_ROW ){
26790       zName = sqlite3_column_text(pQuery, 0);
26791       zSql = sqlite3_column_text(pQuery, 1);
26792       if( zName==0 || zSql==0 ) continue;
26793       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
26794       sqlite3_fprintf(stdout, "%s... ", zName); fflush(stdout);
26795       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
26796       if( zErrMsg ){
26797         sqlite3_fprintf(stderr,"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
26798         sqlite3_free(zErrMsg);
26799         zErrMsg = 0;
26800       }
26801       if( xForEach ){
26802         xForEach(p, newDb, (const char*)zName);
26803       }
26804       sputz(stdout, "done\n");
26805     }
26806   }
26807 end_schema_xfer:
26808   sqlite3_finalize(pQuery);
26809   sqlite3_free(zQuery);
26810 }
26811 
26812 /*
26813 ** Open a new database file named "zNewDb".  Try to recover as much information
26814 ** as possible out of the main database (which might be corrupt) and write it
26815 ** into zNewDb.
26816 */
tryToClone(ShellState * p,const char * zNewDb)26817 static void tryToClone(ShellState *p, const char *zNewDb){
26818   int rc;
26819   sqlite3 *newDb = 0;
26820   if( access(zNewDb,0)==0 ){
26821     sqlite3_fprintf(stderr,"File \"%s\" already exists.\n", zNewDb);
26822     return;
26823   }
26824   rc = sqlite3_open(zNewDb, &newDb);
26825   if( rc ){
26826     sqlite3_fprintf(stderr,
26827         "Cannot create output database: %s\n", sqlite3_errmsg(newDb));
26828   }else{
26829     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
26830     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
26831     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
26832     tryToCloneSchema(p, newDb, "type!='table'", 0);
26833     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
26834     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
26835   }
26836   close_db(newDb);
26837 }
26838 
26839 #ifndef SQLITE_SHELL_FIDDLE
26840 /*
26841 ** Change the output stream (file or pipe or console) to something else.
26842 */
output_redir(ShellState * p,FILE * pfNew)26843 static void output_redir(ShellState *p, FILE *pfNew){
26844   if( p->out != stdout ){
26845     sqlite3_fputs("Output already redirected.\n", stderr);
26846   }else{
26847     p->out = pfNew;
26848     setCrlfMode(p);
26849     if( p->mode==MODE_Www ){
26850       sqlite3_fputs(
26851         "<!DOCTYPE html>\n"
26852         "<HTML><BODY><PRE>\n",
26853         p->out
26854       );
26855     }
26856   }
26857 }
26858 
26859 /*
26860 ** Change the output file back to stdout.
26861 **
26862 ** If the p->doXdgOpen flag is set, that means the output was being
26863 ** redirected to a temporary file named by p->zTempFile.  In that case,
26864 ** launch start/open/xdg-open on that temporary file.
26865 */
output_reset(ShellState * p)26866 static void output_reset(ShellState *p){
26867   if( p->outfile[0]=='|' ){
26868 #ifndef SQLITE_OMIT_POPEN
26869     pclose(p->out);
26870 #endif
26871   }else{
26872     if( p->mode==MODE_Www ){
26873       sqlite3_fputs("</PRE></BODY></HTML>\n", p->out);
26874     }
26875     output_file_close(p->out);
26876 #ifndef SQLITE_NOHAVE_SYSTEM
26877     if( p->doXdgOpen ){
26878       const char *zXdgOpenCmd =
26879 #if defined(_WIN32)
26880       "start";
26881 #elif defined(__APPLE__)
26882       "open";
26883 #else
26884       "xdg-open";
26885 #endif
26886       char *zCmd;
26887       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
26888       if( system(zCmd) ){
26889         sqlite3_fprintf(stderr,"Failed: [%s]\n", zCmd);
26890       }else{
26891         /* Give the start/open/xdg-open command some time to get
26892         ** going before we continue, and potential delete the
26893         ** p->zTempFile data file out from under it */
26894         sqlite3_sleep(2000);
26895       }
26896       sqlite3_free(zCmd);
26897       outputModePop(p);
26898       p->doXdgOpen = 0;
26899     }
26900 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
26901   }
26902   p->outfile[0] = 0;
26903   p->out = stdout;
26904   setCrlfMode(p);
26905 }
26906 #else
26907 # define output_redir(SS,pfO)
26908 # define output_reset(SS)
26909 #endif
26910 
26911 /*
26912 ** Run an SQL command and return the single integer result.
26913 */
db_int(sqlite3 * db,const char * zSql,...)26914 static int db_int(sqlite3 *db, const char *zSql, ...){
26915   sqlite3_stmt *pStmt;
26916   int res = 0;
26917   char *z;
26918   va_list ap;
26919   va_start(ap, zSql);
26920   z = sqlite3_vmprintf(zSql, ap);
26921   va_end(ap);
26922   sqlite3_prepare_v2(db, z, -1, &pStmt, 0);
26923   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
26924     res = sqlite3_column_int(pStmt,0);
26925   }
26926   sqlite3_finalize(pStmt);
26927   sqlite3_free(z);
26928   return res;
26929 }
26930 
26931 #if SQLITE_SHELL_HAVE_RECOVER
26932 /*
26933 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
26934 */
get2byteInt(unsigned char * a)26935 static unsigned int get2byteInt(unsigned char *a){
26936   return (a[0]<<8) + a[1];
26937 }
get4byteInt(unsigned char * a)26938 static unsigned int get4byteInt(unsigned char *a){
26939   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
26940 }
26941 
26942 /*
26943 ** Implementation of the ".dbinfo" command.
26944 **
26945 ** Return 1 on error, 2 to exit, and 0 otherwise.
26946 */
shell_dbinfo_command(ShellState * p,int nArg,char ** azArg)26947 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
26948   static const struct { const char *zName; int ofst; } aField[] = {
26949      { "file change counter:",  24  },
26950      { "database page count:",  28  },
26951      { "freelist page count:",  36  },
26952      { "schema cookie:",        40  },
26953      { "schema format:",        44  },
26954      { "default cache size:",   48  },
26955      { "autovacuum top root:",  52  },
26956      { "incremental vacuum:",   64  },
26957      { "text encoding:",        56  },
26958      { "user version:",         60  },
26959      { "application id:",       68  },
26960      { "software version:",     96  },
26961   };
26962   static const struct { const char *zName; const char *zSql; } aQuery[] = {
26963      { "number of tables:",
26964        "SELECT count(*) FROM %s WHERE type='table'" },
26965      { "number of indexes:",
26966        "SELECT count(*) FROM %s WHERE type='index'" },
26967      { "number of triggers:",
26968        "SELECT count(*) FROM %s WHERE type='trigger'" },
26969      { "number of views:",
26970        "SELECT count(*) FROM %s WHERE type='view'" },
26971      { "schema size:",
26972        "SELECT total(length(sql)) FROM %s" },
26973   };
26974   int i, rc;
26975   unsigned iDataVersion;
26976   char *zSchemaTab;
26977   char *zDb = nArg>=2 ? azArg[1] : "main";
26978   sqlite3_stmt *pStmt = 0;
26979   unsigned char aHdr[100];
26980   open_db(p, 0);
26981   if( p->db==0 ) return 1;
26982   rc = sqlite3_prepare_v2(p->db,
26983              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
26984              -1, &pStmt, 0);
26985   if( rc ){
26986     sqlite3_fprintf(stderr,"error: %s\n", sqlite3_errmsg(p->db));
26987     sqlite3_finalize(pStmt);
26988     return 1;
26989   }
26990   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
26991   if( sqlite3_step(pStmt)==SQLITE_ROW
26992    && sqlite3_column_bytes(pStmt,0)>100
26993   ){
26994     const u8 *pb = sqlite3_column_blob(pStmt,0);
26995     shell_check_oom(pb);
26996     memcpy(aHdr, pb, 100);
26997     sqlite3_finalize(pStmt);
26998   }else{
26999     sqlite3_fputs("unable to read database header\n", stderr);
27000     sqlite3_finalize(pStmt);
27001     return 1;
27002   }
27003   i = get2byteInt(aHdr+16);
27004   if( i==1 ) i = 65536;
27005   sqlite3_fprintf(p->out, "%-20s %d\n", "database page size:", i);
27006   sqlite3_fprintf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
27007   sqlite3_fprintf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
27008   sqlite3_fprintf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
27009   for(i=0; i<ArraySize(aField); i++){
27010     int ofst = aField[i].ofst;
27011     unsigned int val = get4byteInt(aHdr + ofst);
27012     sqlite3_fprintf(p->out, "%-20s %u", aField[i].zName, val);
27013     switch( ofst ){
27014       case 56: {
27015         if( val==1 ) sqlite3_fputs(" (utf8)", p->out);
27016         if( val==2 ) sqlite3_fputs(" (utf16le)", p->out);
27017         if( val==3 ) sqlite3_fputs(" (utf16be)", p->out);
27018       }
27019     }
27020     sqlite3_fputs("\n", p->out);
27021   }
27022   if( zDb==0 ){
27023     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
27024   }else if( cli_strcmp(zDb,"temp")==0 ){
27025     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
27026   }else{
27027     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
27028   }
27029   for(i=0; i<ArraySize(aQuery); i++){
27030     int val = db_int(p->db, aQuery[i].zSql, zSchemaTab);
27031     sqlite3_fprintf(p->out, "%-20s %d\n", aQuery[i].zName, val);
27032   }
27033   sqlite3_free(zSchemaTab);
27034   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
27035   sqlite3_fprintf(p->out, "%-20s %u\n", "data version", iDataVersion);
27036   return 0;
27037 }
27038 #endif /* SQLITE_SHELL_HAVE_RECOVER */
27039 
27040 /*
27041 ** Implementation of the ".dbtotxt" command.
27042 **
27043 ** Return 1 on error, 2 to exit, and 0 otherwise.
27044 */
shell_dbtotxt_command(ShellState * p,int nArg,char ** azArg)27045 static int shell_dbtotxt_command(ShellState *p, int nArg, char **azArg){
27046   sqlite3_stmt *pStmt = 0;
27047   sqlite3_int64 nPage = 0;
27048   int pgSz = 0;
27049   const char *zTail;
27050   char *zName = 0;
27051   int rc, i, j;
27052   unsigned char bShow[256];   /* Characters ok to display */
27053 
27054   UNUSED_PARAMETER(nArg);
27055   UNUSED_PARAMETER(azArg);
27056   memset(bShow, '.', sizeof(bShow));
27057   for(i=' '; i<='~'; i++){
27058     if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = (unsigned char)i;
27059   }
27060   rc = sqlite3_prepare_v2(p->db, "PRAGMA page_size", -1, &pStmt, 0);
27061   if( rc ) goto dbtotxt_error;
27062   rc = 0;
27063   if( sqlite3_step(pStmt)!=SQLITE_ROW ) goto dbtotxt_error;
27064   pgSz = sqlite3_column_int(pStmt, 0);
27065   sqlite3_finalize(pStmt);
27066   pStmt = 0;
27067   if( pgSz<512 || pgSz>65536 || (pgSz&(pgSz-1))!=0 ) goto dbtotxt_error;
27068   rc = sqlite3_prepare_v2(p->db, "PRAGMA page_count", -1, &pStmt, 0);
27069   if( rc ) goto dbtotxt_error;
27070   rc = 0;
27071   if( sqlite3_step(pStmt)!=SQLITE_ROW ) goto dbtotxt_error;
27072   nPage = sqlite3_column_int64(pStmt, 0);
27073   sqlite3_finalize(pStmt);
27074   pStmt = 0;
27075   if( nPage<1 ) goto dbtotxt_error;
27076   rc = sqlite3_prepare_v2(p->db, "PRAGMA databases", -1, &pStmt, 0);
27077   if( rc ) goto dbtotxt_error;
27078   if( sqlite3_step(pStmt)!=SQLITE_ROW ){
27079     zTail = "unk.db";
27080   }else{
27081     const char *zFilename = (const char*)sqlite3_column_text(pStmt, 2);
27082     if( zFilename==0 || zFilename[0]==0 ) zFilename = "unk.db";
27083     zTail = strrchr(zFilename, '/');
27084 #if defined(_WIN32)
27085     if( zTail==0 ) zTail = strrchr(zFilename, '\\');
27086 #endif
27087   }
27088   zName = strdup(zTail);
27089   shell_check_oom(zName);
27090   sqlite3_fprintf(p->out, "| size %lld pagesize %d filename %s\n",
27091                   nPage*pgSz, pgSz, zName);
27092   sqlite3_finalize(pStmt);
27093   pStmt = 0;
27094   rc = sqlite3_prepare_v2(p->db,
27095            "SELECT pgno, data FROM sqlite_dbpage ORDER BY pgno", -1, &pStmt, 0);
27096   if( rc ) goto dbtotxt_error;
27097   while( sqlite3_step(pStmt)==SQLITE_ROW ){
27098     sqlite3_int64 pgno = sqlite3_column_int64(pStmt, 0);
27099     const u8 *aData = sqlite3_column_blob(pStmt, 1);
27100     int seenPageLabel = 0;
27101     for(i=0; i<pgSz; i+=16){
27102       const u8 *aLine = aData+i;
27103       for(j=0; j<16 && aLine[j]==0; j++){}
27104       if( j==16 ) continue;
27105       if( !seenPageLabel ){
27106         sqlite3_fprintf(p->out, "| page %lld offset %lld\n",pgno,(pgno-1)*pgSz);
27107         seenPageLabel = 1;
27108       }
27109       sqlite3_fprintf(p->out, "|  %5d:", i);
27110       for(j=0; j<16; j++) sqlite3_fprintf(p->out, " %02x", aLine[j]);
27111       sqlite3_fprintf(p->out, "   ");
27112       for(j=0; j<16; j++){
27113         unsigned char c = (unsigned char)aLine[j];
27114         sqlite3_fprintf(p->out, "%c", bShow[c]);
27115       }
27116       sqlite3_fprintf(p->out, "\n");
27117     }
27118   }
27119   sqlite3_finalize(pStmt);
27120   sqlite3_fprintf(p->out, "| end %s\n", zName);
27121   free(zName);
27122   return 0;
27123 
27124 dbtotxt_error:
27125   if( rc ){
27126     sqlite3_fprintf(stderr, "ERROR: %s\n", sqlite3_errmsg(p->db));
27127   }
27128   sqlite3_finalize(pStmt);
27129   free(zName);
27130   return 1;
27131 }
27132 
27133 /*
27134 ** Print the given string as an error message.
27135 */
shellEmitError(const char * zErr)27136 static void shellEmitError(const char *zErr){
27137   sqlite3_fprintf(stderr,"Error: %s\n", zErr);
27138 }
27139 /*
27140 ** Print the current sqlite3_errmsg() value to stderr and return 1.
27141 */
shellDatabaseError(sqlite3 * db)27142 static int shellDatabaseError(sqlite3 *db){
27143   shellEmitError(sqlite3_errmsg(db));
27144   return 1;
27145 }
27146 
27147 /*
27148 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
27149 ** if they match and FALSE (0) if they do not match.
27150 **
27151 ** Globbing rules:
27152 **
27153 **      '*'       Matches any sequence of zero or more characters.
27154 **
27155 **      '?'       Matches exactly one character.
27156 **
27157 **     [...]      Matches one character from the enclosed list of
27158 **                characters.
27159 **
27160 **     [^...]     Matches one character not in the enclosed list.
27161 **
27162 **      '#'       Matches any sequence of one or more digits with an
27163 **                optional + or - sign in front
27164 **
27165 **      ' '       Any span of whitespace matches any other span of
27166 **                whitespace.
27167 **
27168 ** Extra whitespace at the end of z[] is ignored.
27169 */
testcase_glob(const char * zGlob,const char * z)27170 static int testcase_glob(const char *zGlob, const char *z){
27171   int c, c2;
27172   int invert;
27173   int seen;
27174 
27175   while( (c = (*(zGlob++)))!=0 ){
27176     if( IsSpace(c) ){
27177       if( !IsSpace(*z) ) return 0;
27178       while( IsSpace(*zGlob) ) zGlob++;
27179       while( IsSpace(*z) ) z++;
27180     }else if( c=='*' ){
27181       while( (c=(*(zGlob++))) == '*' || c=='?' ){
27182         if( c=='?' && (*(z++))==0 ) return 0;
27183       }
27184       if( c==0 ){
27185         return 1;
27186       }else if( c=='[' ){
27187         while( *z && testcase_glob(zGlob-1,z)==0 ){
27188           z++;
27189         }
27190         return (*z)!=0;
27191       }
27192       while( (c2 = (*(z++)))!=0 ){
27193         while( c2!=c ){
27194           c2 = *(z++);
27195           if( c2==0 ) return 0;
27196         }
27197         if( testcase_glob(zGlob,z) ) return 1;
27198       }
27199       return 0;
27200     }else if( c=='?' ){
27201       if( (*(z++))==0 ) return 0;
27202     }else if( c=='[' ){
27203       int prior_c = 0;
27204       seen = 0;
27205       invert = 0;
27206       c = *(z++);
27207       if( c==0 ) return 0;
27208       c2 = *(zGlob++);
27209       if( c2=='^' ){
27210         invert = 1;
27211         c2 = *(zGlob++);
27212       }
27213       if( c2==']' ){
27214         if( c==']' ) seen = 1;
27215         c2 = *(zGlob++);
27216       }
27217       while( c2 && c2!=']' ){
27218         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
27219           c2 = *(zGlob++);
27220           if( c>=prior_c && c<=c2 ) seen = 1;
27221           prior_c = 0;
27222         }else{
27223           if( c==c2 ){
27224             seen = 1;
27225           }
27226           prior_c = c2;
27227         }
27228         c2 = *(zGlob++);
27229       }
27230       if( c2==0 || (seen ^ invert)==0 ) return 0;
27231     }else if( c=='#' ){
27232       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
27233       if( !IsDigit(z[0]) ) return 0;
27234       z++;
27235       while( IsDigit(z[0]) ){ z++; }
27236     }else{
27237       if( c!=(*(z++)) ) return 0;
27238     }
27239   }
27240   while( IsSpace(*z) ){ z++; }
27241   return *z==0;
27242 }
27243 
27244 
27245 /*
27246 ** Compare the string as a command-line option with either one or two
27247 ** initial "-" characters.
27248 */
optionMatch(const char * zStr,const char * zOpt)27249 static int optionMatch(const char *zStr, const char *zOpt){
27250   if( zStr[0]!='-' ) return 0;
27251   zStr++;
27252   if( zStr[0]=='-' ) zStr++;
27253   return cli_strcmp(zStr, zOpt)==0;
27254 }
27255 
27256 /*
27257 ** Delete a file.
27258 */
shellDeleteFile(const char * zFilename)27259 int shellDeleteFile(const char *zFilename){
27260   int rc;
27261 #ifdef _WIN32
27262   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
27263   rc = _wunlink(z);
27264   sqlite3_free(z);
27265 #else
27266   rc = unlink(zFilename);
27267 #endif
27268   return rc;
27269 }
27270 
27271 /*
27272 ** Try to delete the temporary file (if there is one) and free the
27273 ** memory used to hold the name of the temp file.
27274 */
clearTempFile(ShellState * p)27275 static void clearTempFile(ShellState *p){
27276   if( p->zTempFile==0 ) return;
27277   if( p->doXdgOpen ) return;
27278   if( shellDeleteFile(p->zTempFile) ) return;
27279   sqlite3_free(p->zTempFile);
27280   p->zTempFile = 0;
27281 }
27282 
27283 /*
27284 ** Create a new temp file name with the given suffix.
27285 */
newTempFile(ShellState * p,const char * zSuffix)27286 static void newTempFile(ShellState *p, const char *zSuffix){
27287   clearTempFile(p);
27288   sqlite3_free(p->zTempFile);
27289   p->zTempFile = 0;
27290   if( p->db ){
27291     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
27292   }
27293   if( p->zTempFile==0 ){
27294     /* If p->db is an in-memory database then the TEMPFILENAME file-control
27295     ** will not work and we will need to fallback to guessing */
27296     char *zTemp;
27297     sqlite3_uint64 r;
27298     sqlite3_randomness(sizeof(r), &r);
27299     zTemp = getenv("TEMP");
27300     if( zTemp==0 ) zTemp = getenv("TMP");
27301     if( zTemp==0 ){
27302 #ifdef _WIN32
27303       zTemp = "\\tmp";
27304 #else
27305       zTemp = "/tmp";
27306 #endif
27307     }
27308     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
27309   }else{
27310     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
27311   }
27312   shell_check_oom(p->zTempFile);
27313 }
27314 
27315 
27316 /*
27317 ** The implementation of SQL scalar function fkey_collate_clause(), used
27318 ** by the ".lint fkey-indexes" command. This scalar function is always
27319 ** called with four arguments - the parent table name, the parent column name,
27320 ** the child table name and the child column name.
27321 **
27322 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
27323 **
27324 ** If either of the named tables or columns do not exist, this function
27325 ** returns an empty string. An empty string is also returned if both tables
27326 ** and columns exist but have the same default collation sequence. Or,
27327 ** if both exist but the default collation sequences are different, this
27328 ** function returns the string " COLLATE <parent-collation>", where
27329 ** <parent-collation> is the default collation sequence of the parent column.
27330 */
shellFkeyCollateClause(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)27331 static void shellFkeyCollateClause(
27332   sqlite3_context *pCtx,
27333   int nVal,
27334   sqlite3_value **apVal
27335 ){
27336   sqlite3 *db = sqlite3_context_db_handle(pCtx);
27337   const char *zParent;
27338   const char *zParentCol;
27339   const char *zParentSeq;
27340   const char *zChild;
27341   const char *zChildCol;
27342   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
27343   int rc;
27344 
27345   assert( nVal==4 );
27346   zParent = (const char*)sqlite3_value_text(apVal[0]);
27347   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
27348   zChild = (const char*)sqlite3_value_text(apVal[2]);
27349   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
27350 
27351   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
27352   rc = sqlite3_table_column_metadata(
27353       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
27354   );
27355   if( rc==SQLITE_OK ){
27356     rc = sqlite3_table_column_metadata(
27357         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
27358     );
27359   }
27360 
27361   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
27362     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
27363     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
27364     sqlite3_free(z);
27365   }
27366 }
27367 
27368 
27369 /*
27370 ** The implementation of dot-command ".lint fkey-indexes".
27371 */
lintFkeyIndexes(ShellState * pState,char ** azArg,int nArg)27372 static int lintFkeyIndexes(
27373   ShellState *pState,             /* Current shell tool state */
27374   char **azArg,                   /* Array of arguments passed to dot command */
27375   int nArg                        /* Number of entries in azArg[] */
27376 ){
27377   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
27378   int bVerbose = 0;               /* If -verbose is present */
27379   int bGroupByParent = 0;         /* If -groupbyparent is present */
27380   int i;                          /* To iterate through azArg[] */
27381   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
27382   int rc;                         /* Return code */
27383   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
27384   FILE *out = pState->out;        /* Send output here */
27385 
27386   /*
27387   ** This SELECT statement returns one row for each foreign key constraint
27388   ** in the schema of the main database. The column values are:
27389   **
27390   ** 0. The text of an SQL statement similar to:
27391   **
27392   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
27393   **
27394   **    This SELECT is similar to the one that the foreign keys implementation
27395   **    needs to run internally on child tables. If there is an index that can
27396   **    be used to optimize this query, then it can also be used by the FK
27397   **    implementation to optimize DELETE or UPDATE statements on the parent
27398   **    table.
27399   **
27400   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
27401   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
27402   **    contains an index that can be used to optimize the query.
27403   **
27404   ** 2. Human readable text that describes the child table and columns. e.g.
27405   **
27406   **       "child_table(child_key1, child_key2)"
27407   **
27408   ** 3. Human readable text that describes the parent table and columns. e.g.
27409   **
27410   **       "parent_table(parent_key1, parent_key2)"
27411   **
27412   ** 4. A full CREATE INDEX statement for an index that could be used to
27413   **    optimize DELETE or UPDATE statements on the parent table. e.g.
27414   **
27415   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
27416   **
27417   ** 5. The name of the parent table.
27418   **
27419   ** These six values are used by the C logic below to generate the report.
27420   */
27421   const char *zSql =
27422   "SELECT "
27423     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
27424     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
27425     "  || fkey_collate_clause("
27426     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
27427     ", "
27428     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
27429     "  || group_concat('*=?', ' AND ') || ')'"
27430     ", "
27431     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
27432     ", "
27433     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
27434     ", "
27435     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
27436     "  || ' ON ' || quote(s.name) || '('"
27437     "  || group_concat(quote(f.[from]) ||"
27438     "        fkey_collate_clause("
27439     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
27440     "  || ');'"
27441     ", "
27442     "     f.[table] "
27443     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
27444     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
27445     "GROUP BY s.name, f.id "
27446     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
27447   ;
27448   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
27449 
27450   for(i=2; i<nArg; i++){
27451     int n = strlen30(azArg[i]);
27452     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
27453       bVerbose = 1;
27454     }
27455     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
27456       bGroupByParent = 1;
27457       zIndent = "    ";
27458     }
27459     else{
27460       sqlite3_fprintf(stderr,
27461            "Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
27462       return SQLITE_ERROR;
27463     }
27464   }
27465 
27466   /* Register the fkey_collate_clause() SQL function */
27467   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
27468       0, shellFkeyCollateClause, 0, 0
27469   );
27470 
27471 
27472   if( rc==SQLITE_OK ){
27473     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
27474   }
27475   if( rc==SQLITE_OK ){
27476     sqlite3_bind_int(pSql, 1, bGroupByParent);
27477   }
27478 
27479   if( rc==SQLITE_OK ){
27480     int rc2;
27481     char *zPrev = 0;
27482     while( SQLITE_ROW==sqlite3_step(pSql) ){
27483       int res = -1;
27484       sqlite3_stmt *pExplain = 0;
27485       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
27486       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
27487       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
27488       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
27489       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
27490       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
27491 
27492       if( zEQP==0 ) continue;
27493       if( zGlob==0 ) continue;
27494       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
27495       if( rc!=SQLITE_OK ) break;
27496       if( SQLITE_ROW==sqlite3_step(pExplain) ){
27497         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
27498         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
27499                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
27500       }
27501       rc = sqlite3_finalize(pExplain);
27502       if( rc!=SQLITE_OK ) break;
27503 
27504       if( res<0 ){
27505         sqlite3_fputs("Error: internal error", stderr);
27506         break;
27507       }else{
27508         if( bGroupByParent
27509         && (bVerbose || res==0)
27510         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
27511         ){
27512           sqlite3_fprintf(out, "-- Parent table %s\n", zParent);
27513           sqlite3_free(zPrev);
27514           zPrev = sqlite3_mprintf("%s", zParent);
27515         }
27516 
27517         if( res==0 ){
27518           sqlite3_fprintf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
27519         }else if( bVerbose ){
27520           sqlite3_fprintf(out,
27521                 "%s/* no extra indexes required for %s -> %s */\n",
27522                 zIndent, zFrom, zTarget
27523           );
27524         }
27525       }
27526     }
27527     sqlite3_free(zPrev);
27528 
27529     if( rc!=SQLITE_OK ){
27530       sqlite3_fprintf(stderr,"%s\n", sqlite3_errmsg(db));
27531     }
27532 
27533     rc2 = sqlite3_finalize(pSql);
27534     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
27535       rc = rc2;
27536       sqlite3_fprintf(stderr,"%s\n", sqlite3_errmsg(db));
27537     }
27538   }else{
27539     sqlite3_fprintf(stderr,"%s\n", sqlite3_errmsg(db));
27540   }
27541 
27542   return rc;
27543 }
27544 
27545 /*
27546 ** Implementation of ".lint" dot command.
27547 */
lintDotCommand(ShellState * pState,char ** azArg,int nArg)27548 static int lintDotCommand(
27549   ShellState *pState,             /* Current shell tool state */
27550   char **azArg,                   /* Array of arguments passed to dot command */
27551   int nArg                        /* Number of entries in azArg[] */
27552 ){
27553   int n;
27554   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
27555   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
27556   return lintFkeyIndexes(pState, azArg, nArg);
27557 
27558  usage:
27559   sqlite3_fprintf(stderr,"Usage %s sub-command ?switches...?\n", azArg[0]);
27560   sqlite3_fprintf(stderr, "Where sub-commands are:\n");
27561   sqlite3_fprintf(stderr, "    fkey-indexes\n");
27562   return SQLITE_ERROR;
27563 }
27564 
shellPrepare(sqlite3 * db,int * pRc,const char * zSql,sqlite3_stmt ** ppStmt)27565 static void shellPrepare(
27566   sqlite3 *db,
27567   int *pRc,
27568   const char *zSql,
27569   sqlite3_stmt **ppStmt
27570 ){
27571   *ppStmt = 0;
27572   if( *pRc==SQLITE_OK ){
27573     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
27574     if( rc!=SQLITE_OK ){
27575       sqlite3_fprintf(stderr,
27576          "sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
27577       *pRc = rc;
27578     }
27579   }
27580 }
27581 
27582 /*
27583 ** Create a prepared statement using printf-style arguments for the SQL.
27584 */
shellPreparePrintf(sqlite3 * db,int * pRc,sqlite3_stmt ** ppStmt,const char * zFmt,...)27585 static void shellPreparePrintf(
27586   sqlite3 *db,
27587   int *pRc,
27588   sqlite3_stmt **ppStmt,
27589   const char *zFmt,
27590   ...
27591 ){
27592   *ppStmt = 0;
27593   if( *pRc==SQLITE_OK ){
27594     va_list ap;
27595     char *z;
27596     va_start(ap, zFmt);
27597     z = sqlite3_vmprintf(zFmt, ap);
27598     va_end(ap);
27599     if( z==0 ){
27600       *pRc = SQLITE_NOMEM;
27601     }else{
27602       shellPrepare(db, pRc, z, ppStmt);
27603       sqlite3_free(z);
27604     }
27605   }
27606 }
27607 
27608 /*
27609 ** Finalize the prepared statement created using shellPreparePrintf().
27610 */
shellFinalize(int * pRc,sqlite3_stmt * pStmt)27611 static void shellFinalize(
27612   int *pRc,
27613   sqlite3_stmt *pStmt
27614 ){
27615   if( pStmt ){
27616     sqlite3 *db = sqlite3_db_handle(pStmt);
27617     int rc = sqlite3_finalize(pStmt);
27618     if( *pRc==SQLITE_OK ){
27619       if( rc!=SQLITE_OK ){
27620         sqlite3_fprintf(stderr,"SQL error: %s\n", sqlite3_errmsg(db));
27621       }
27622       *pRc = rc;
27623     }
27624   }
27625 }
27626 
27627 #if !defined SQLITE_OMIT_VIRTUALTABLE
27628 /* Reset the prepared statement created using shellPreparePrintf().
27629 **
27630 ** This routine is could be marked "static".  But it is not always used,
27631 ** depending on compile-time options.  By omitting the "static", we avoid
27632 ** nuisance compiler warnings about "defined but not used".
27633 */
shellReset(int * pRc,sqlite3_stmt * pStmt)27634 void shellReset(
27635   int *pRc,
27636   sqlite3_stmt *pStmt
27637 ){
27638   int rc = sqlite3_reset(pStmt);
27639   if( *pRc==SQLITE_OK ){
27640     if( rc!=SQLITE_OK ){
27641       sqlite3 *db = sqlite3_db_handle(pStmt);
27642       sqlite3_fprintf(stderr,"SQL error: %s\n", sqlite3_errmsg(db));
27643     }
27644     *pRc = rc;
27645   }
27646 }
27647 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
27648 
27649 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
27650 /******************************************************************************
27651 ** The ".archive" or ".ar" command.
27652 */
27653 /*
27654 ** Structure representing a single ".ar" command.
27655 */
27656 typedef struct ArCommand ArCommand;
27657 struct ArCommand {
27658   u8 eCmd;                        /* An AR_CMD_* value */
27659   u8 bVerbose;                    /* True if --verbose */
27660   u8 bZip;                        /* True if the archive is a ZIP */
27661   u8 bDryRun;                     /* True if --dry-run */
27662   u8 bAppend;                     /* True if --append */
27663   u8 bGlob;                       /* True if --glob */
27664   u8 fromCmdLine;                 /* Run from -A instead of .archive */
27665   int nArg;                       /* Number of command arguments */
27666   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
27667   const char *zFile;              /* --file argument, or NULL */
27668   const char *zDir;               /* --directory argument, or NULL */
27669   char **azArg;                   /* Array of command arguments */
27670   ShellState *p;                  /* Shell state */
27671   FILE *out;                      /* Output to this stream */
27672   sqlite3 *db;                    /* Database containing the archive */
27673 };
27674 
27675 /*
27676 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
27677 */
arUsage(FILE * f)27678 static int arUsage(FILE *f){
27679   showHelp(f,"archive");
27680   return SQLITE_ERROR;
27681 }
27682 
27683 /*
27684 ** Print an error message for the .ar command to stderr and return
27685 ** SQLITE_ERROR.
27686 */
arErrorMsg(ArCommand * pAr,const char * zFmt,...)27687 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
27688   va_list ap;
27689   char *z;
27690   va_start(ap, zFmt);
27691   z = sqlite3_vmprintf(zFmt, ap);
27692   va_end(ap);
27693   shellEmitError(z);
27694   if( pAr->fromCmdLine ){
27695     sqlite3_fputs("Use \"-A\" for more help\n", stderr);
27696   }else{
27697     sqlite3_fputs("Use \".archive --help\" for more help\n", stderr);
27698   }
27699   sqlite3_free(z);
27700   return SQLITE_ERROR;
27701 }
27702 
27703 /*
27704 ** Values for ArCommand.eCmd.
27705 */
27706 #define AR_CMD_CREATE       1
27707 #define AR_CMD_UPDATE       2
27708 #define AR_CMD_INSERT       3
27709 #define AR_CMD_EXTRACT      4
27710 #define AR_CMD_LIST         5
27711 #define AR_CMD_HELP         6
27712 #define AR_CMD_REMOVE       7
27713 
27714 /*
27715 ** Other (non-command) switches.
27716 */
27717 #define AR_SWITCH_VERBOSE     8
27718 #define AR_SWITCH_FILE        9
27719 #define AR_SWITCH_DIRECTORY  10
27720 #define AR_SWITCH_APPEND     11
27721 #define AR_SWITCH_DRYRUN     12
27722 #define AR_SWITCH_GLOB       13
27723 
arProcessSwitch(ArCommand * pAr,int eSwitch,const char * zArg)27724 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
27725   switch( eSwitch ){
27726     case AR_CMD_CREATE:
27727     case AR_CMD_EXTRACT:
27728     case AR_CMD_LIST:
27729     case AR_CMD_REMOVE:
27730     case AR_CMD_UPDATE:
27731     case AR_CMD_INSERT:
27732     case AR_CMD_HELP:
27733       if( pAr->eCmd ){
27734         return arErrorMsg(pAr, "multiple command options");
27735       }
27736       pAr->eCmd = eSwitch;
27737       break;
27738 
27739     case AR_SWITCH_DRYRUN:
27740       pAr->bDryRun = 1;
27741       break;
27742     case AR_SWITCH_GLOB:
27743       pAr->bGlob = 1;
27744       break;
27745     case AR_SWITCH_VERBOSE:
27746       pAr->bVerbose = 1;
27747       break;
27748     case AR_SWITCH_APPEND:
27749       pAr->bAppend = 1;
27750       deliberate_fall_through; /* FALLTHRU */
27751     case AR_SWITCH_FILE:
27752       pAr->zFile = zArg;
27753       break;
27754     case AR_SWITCH_DIRECTORY:
27755       pAr->zDir = zArg;
27756       break;
27757   }
27758 
27759   return SQLITE_OK;
27760 }
27761 
27762 /*
27763 ** Parse the command line for an ".ar" command. The results are written into
27764 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
27765 ** successfully, otherwise an error message is written to stderr and
27766 ** SQLITE_ERROR returned.
27767 */
arParseCommand(char ** azArg,int nArg,ArCommand * pAr)27768 static int arParseCommand(
27769   char **azArg,                   /* Array of arguments passed to dot command */
27770   int nArg,                       /* Number of entries in azArg[] */
27771   ArCommand *pAr                  /* Populate this object */
27772 ){
27773   struct ArSwitch {
27774     const char *zLong;
27775     char cShort;
27776     u8 eSwitch;
27777     u8 bArg;
27778   } aSwitch[] = {
27779     { "create",    'c', AR_CMD_CREATE,       0 },
27780     { "extract",   'x', AR_CMD_EXTRACT,      0 },
27781     { "insert",    'i', AR_CMD_INSERT,       0 },
27782     { "list",      't', AR_CMD_LIST,         0 },
27783     { "remove",    'r', AR_CMD_REMOVE,       0 },
27784     { "update",    'u', AR_CMD_UPDATE,       0 },
27785     { "help",      'h', AR_CMD_HELP,         0 },
27786     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
27787     { "file",      'f', AR_SWITCH_FILE,      1 },
27788     { "append",    'a', AR_SWITCH_APPEND,    1 },
27789     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
27790     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
27791     { "glob",      'g', AR_SWITCH_GLOB,      0 },
27792   };
27793   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
27794   struct ArSwitch *pEnd = &aSwitch[nSwitch];
27795 
27796   if( nArg<=1 ){
27797     sqlite3_fprintf(stderr, "Wrong number of arguments.  Usage:\n");
27798     return arUsage(stderr);
27799   }else{
27800     char *z = azArg[1];
27801     if( z[0]!='-' ){
27802       /* Traditional style [tar] invocation */
27803       int i;
27804       int iArg = 2;
27805       for(i=0; z[i]; i++){
27806         const char *zArg = 0;
27807         struct ArSwitch *pOpt;
27808         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
27809           if( z[i]==pOpt->cShort ) break;
27810         }
27811         if( pOpt==pEnd ){
27812           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
27813         }
27814         if( pOpt->bArg ){
27815           if( iArg>=nArg ){
27816             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
27817           }
27818           zArg = azArg[iArg++];
27819         }
27820         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
27821       }
27822       pAr->nArg = nArg-iArg;
27823       if( pAr->nArg>0 ){
27824         pAr->azArg = &azArg[iArg];
27825       }
27826     }else{
27827       /* Non-traditional invocation */
27828       int iArg;
27829       for(iArg=1; iArg<nArg; iArg++){
27830         int n;
27831         z = azArg[iArg];
27832         if( z[0]!='-' ){
27833           /* All remaining command line words are command arguments. */
27834           pAr->azArg = &azArg[iArg];
27835           pAr->nArg = nArg-iArg;
27836           break;
27837         }
27838         n = strlen30(z);
27839 
27840         if( z[1]!='-' ){
27841           int i;
27842           /* One or more short options */
27843           for(i=1; i<n; i++){
27844             const char *zArg = 0;
27845             struct ArSwitch *pOpt;
27846             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
27847               if( z[i]==pOpt->cShort ) break;
27848             }
27849             if( pOpt==pEnd ){
27850               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
27851             }
27852             if( pOpt->bArg ){
27853               if( i<(n-1) ){
27854                 zArg = &z[i+1];
27855                 i = n;
27856               }else{
27857                 if( iArg>=(nArg-1) ){
27858                   return arErrorMsg(pAr, "option requires an argument: %c",
27859                                     z[i]);
27860                 }
27861                 zArg = azArg[++iArg];
27862               }
27863             }
27864             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
27865           }
27866         }else if( z[2]=='\0' ){
27867           /* A -- option, indicating that all remaining command line words
27868           ** are command arguments.  */
27869           pAr->azArg = &azArg[iArg+1];
27870           pAr->nArg = nArg-iArg-1;
27871           break;
27872         }else{
27873           /* A long option */
27874           const char *zArg = 0;             /* Argument for option, if any */
27875           struct ArSwitch *pMatch = 0;      /* Matching option */
27876           struct ArSwitch *pOpt;            /* Iterator */
27877           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
27878             const char *zLong = pOpt->zLong;
27879             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
27880               if( pMatch ){
27881                 return arErrorMsg(pAr, "ambiguous option: %s",z);
27882               }else{
27883                 pMatch = pOpt;
27884               }
27885             }
27886           }
27887 
27888           if( pMatch==0 ){
27889             return arErrorMsg(pAr, "unrecognized option: %s", z);
27890           }
27891           if( pMatch->bArg ){
27892             if( iArg>=(nArg-1) ){
27893               return arErrorMsg(pAr, "option requires an argument: %s", z);
27894             }
27895             zArg = azArg[++iArg];
27896           }
27897           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
27898         }
27899       }
27900     }
27901   }
27902   if( pAr->eCmd==0 ){
27903     sqlite3_fprintf(stderr, "Required argument missing.  Usage:\n");
27904     return arUsage(stderr);
27905   }
27906   return SQLITE_OK;
27907 }
27908 
27909 /*
27910 ** This function assumes that all arguments within the ArCommand.azArg[]
27911 ** array refer to archive members, as for the --extract, --list or --remove
27912 ** commands. It checks that each of them are "present". If any specified
27913 ** file is not present in the archive, an error is printed to stderr and an
27914 ** error code returned. Otherwise, if all specified arguments are present
27915 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
27916 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
27917 ** when pAr->bGlob is true.
27918 **
27919 ** This function strips any trailing '/' characters from each argument.
27920 ** This is consistent with the way the [tar] command seems to work on
27921 ** Linux.
27922 */
arCheckEntries(ArCommand * pAr)27923 static int arCheckEntries(ArCommand *pAr){
27924   int rc = SQLITE_OK;
27925   if( pAr->nArg ){
27926     int i, j;
27927     sqlite3_stmt *pTest = 0;
27928     const char *zSel = (pAr->bGlob)
27929       ? "SELECT name FROM %s WHERE glob($name,name)"
27930       : "SELECT name FROM %s WHERE name=$name";
27931 
27932     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
27933     j = sqlite3_bind_parameter_index(pTest, "$name");
27934     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
27935       char *z = pAr->azArg[i];
27936       int n = strlen30(z);
27937       int bOk = 0;
27938       while( n>0 && z[n-1]=='/' ) n--;
27939       z[n] = '\0';
27940       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
27941       if( SQLITE_ROW==sqlite3_step(pTest) ){
27942         bOk = 1;
27943       }
27944       shellReset(&rc, pTest);
27945       if( rc==SQLITE_OK && bOk==0 ){
27946         sqlite3_fprintf(stderr,"not found in archive: %s\n", z);
27947         rc = SQLITE_ERROR;
27948       }
27949     }
27950     shellFinalize(&rc, pTest);
27951   }
27952   return rc;
27953 }
27954 
27955 /*
27956 ** Format a WHERE clause that can be used against the "sqlar" table to
27957 ** identify all archive members that match the command arguments held
27958 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
27959 ** The caller is responsible for eventually calling sqlite3_free() on
27960 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
27961 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
27962 */
arWhereClause(int * pRc,ArCommand * pAr,char ** pzWhere)27963 static void arWhereClause(
27964   int *pRc,
27965   ArCommand *pAr,
27966   char **pzWhere                  /* OUT: New WHERE clause */
27967 ){
27968   char *zWhere = 0;
27969   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
27970   if( *pRc==SQLITE_OK ){
27971     if( pAr->nArg==0 ){
27972       zWhere = sqlite3_mprintf("1");
27973     }else{
27974       int i;
27975       const char *zSep = "";
27976       for(i=0; i<pAr->nArg; i++){
27977         const char *z = pAr->azArg[i];
27978         zWhere = sqlite3_mprintf(
27979           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
27980           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
27981         );
27982         if( zWhere==0 ){
27983           *pRc = SQLITE_NOMEM;
27984           break;
27985         }
27986         zSep = " OR ";
27987       }
27988     }
27989   }
27990   *pzWhere = zWhere;
27991 }
27992 
27993 /*
27994 ** Implementation of .ar "lisT" command.
27995 */
arListCommand(ArCommand * pAr)27996 static int arListCommand(ArCommand *pAr){
27997   const char *zSql = "SELECT %s FROM %s WHERE %s";
27998   const char *azCols[] = {
27999     "name",
28000     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
28001   };
28002 
28003   char *zWhere = 0;
28004   sqlite3_stmt *pSql = 0;
28005   int rc;
28006 
28007   rc = arCheckEntries(pAr);
28008   arWhereClause(&rc, pAr, &zWhere);
28009 
28010   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
28011                      pAr->zSrcTable, zWhere);
28012   if( pAr->bDryRun ){
28013     sqlite3_fprintf(pAr->out, "%s\n", sqlite3_sql(pSql));
28014   }else{
28015     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
28016       if( pAr->bVerbose ){
28017         sqlite3_fprintf(pAr->out, "%s % 10d  %s  %s\n",
28018               sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
28019               sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
28020       }else{
28021         sqlite3_fprintf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
28022       }
28023     }
28024   }
28025   shellFinalize(&rc, pSql);
28026   sqlite3_free(zWhere);
28027   return rc;
28028 }
28029 
28030 /*
28031 ** Implementation of .ar "Remove" command.
28032 */
arRemoveCommand(ArCommand * pAr)28033 static int arRemoveCommand(ArCommand *pAr){
28034   int rc = 0;
28035   char *zSql = 0;
28036   char *zWhere = 0;
28037 
28038   if( pAr->nArg ){
28039     /* Verify that args actually exist within the archive before proceeding.
28040     ** And formulate a WHERE clause to match them.  */
28041     rc = arCheckEntries(pAr);
28042     arWhereClause(&rc, pAr, &zWhere);
28043   }
28044   if( rc==SQLITE_OK ){
28045     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
28046                            pAr->zSrcTable, zWhere);
28047     if( pAr->bDryRun ){
28048       sqlite3_fprintf(pAr->out, "%s\n", zSql);
28049     }else{
28050       char *zErr = 0;
28051       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
28052       if( rc==SQLITE_OK ){
28053         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
28054         if( rc!=SQLITE_OK ){
28055           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
28056         }else{
28057           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
28058         }
28059       }
28060       if( zErr ){
28061         sqlite3_fprintf(stdout, "ERROR: %s\n", zErr); /* stdout? */
28062         sqlite3_free(zErr);
28063       }
28064     }
28065   }
28066   sqlite3_free(zWhere);
28067   sqlite3_free(zSql);
28068   return rc;
28069 }
28070 
28071 /*
28072 ** Implementation of .ar "eXtract" command.
28073 */
arExtractCommand(ArCommand * pAr)28074 static int arExtractCommand(ArCommand *pAr){
28075   const char *zSql1 =
28076     "SELECT "
28077     " ($dir || name),"
28078     " writefile(($dir || name), %s, mode, mtime) "
28079     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
28080     " AND name NOT GLOB '*..[/\\]*'";
28081 
28082   const char *azExtraArg[] = {
28083     "sqlar_uncompress(data, sz)",
28084     "data"
28085   };
28086 
28087   sqlite3_stmt *pSql = 0;
28088   int rc = SQLITE_OK;
28089   char *zDir = 0;
28090   char *zWhere = 0;
28091   int i, j;
28092 
28093   /* If arguments are specified, check that they actually exist within
28094   ** the archive before proceeding. And formulate a WHERE clause to
28095   ** match them.  */
28096   rc = arCheckEntries(pAr);
28097   arWhereClause(&rc, pAr, &zWhere);
28098 
28099   if( rc==SQLITE_OK ){
28100     if( pAr->zDir ){
28101       zDir = sqlite3_mprintf("%s/", pAr->zDir);
28102     }else{
28103       zDir = sqlite3_mprintf("");
28104     }
28105     if( zDir==0 ) rc = SQLITE_NOMEM;
28106   }
28107 
28108   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
28109       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
28110   );
28111 
28112   if( rc==SQLITE_OK ){
28113     j = sqlite3_bind_parameter_index(pSql, "$dir");
28114     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
28115 
28116     /* Run the SELECT statement twice. The first time, writefile() is called
28117     ** for all archive members that should be extracted. The second time,
28118     ** only for the directories. This is because the timestamps for
28119     ** extracted directories must be reset after they are populated (as
28120     ** populating them changes the timestamp).  */
28121     for(i=0; i<2; i++){
28122       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
28123       sqlite3_bind_int(pSql, j, i);
28124       if( pAr->bDryRun ){
28125         sqlite3_fprintf(pAr->out, "%s\n", sqlite3_sql(pSql));
28126       }else{
28127         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
28128           if( i==0 && pAr->bVerbose ){
28129             sqlite3_fprintf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
28130           }
28131         }
28132       }
28133       shellReset(&rc, pSql);
28134     }
28135     shellFinalize(&rc, pSql);
28136   }
28137 
28138   sqlite3_free(zDir);
28139   sqlite3_free(zWhere);
28140   return rc;
28141 }
28142 
28143 /*
28144 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
28145 */
arExecSql(ArCommand * pAr,const char * zSql)28146 static int arExecSql(ArCommand *pAr, const char *zSql){
28147   int rc;
28148   if( pAr->bDryRun ){
28149     sqlite3_fprintf(pAr->out, "%s\n", zSql);
28150     rc = SQLITE_OK;
28151   }else{
28152     char *zErr = 0;
28153     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
28154     if( zErr ){
28155       sqlite3_fprintf(stdout, "ERROR: %s\n", zErr);
28156       sqlite3_free(zErr);
28157     }
28158   }
28159   return rc;
28160 }
28161 
28162 
28163 /*
28164 ** Implementation of .ar "create", "insert", and "update" commands.
28165 **
28166 **     create    ->     Create a new SQL archive
28167 **     insert    ->     Insert or reinsert all files listed
28168 **     update    ->     Insert files that have changed or that were not
28169 **                      previously in the archive
28170 **
28171 ** Create the "sqlar" table in the database if it does not already exist.
28172 ** Then add each file in the azFile[] array to the archive. Directories
28173 ** are added recursively. If argument bVerbose is non-zero, a message is
28174 ** printed on stdout for each file archived.
28175 **
28176 ** The create command is the same as update, except that it drops
28177 ** any existing "sqlar" table before beginning.  The "insert" command
28178 ** always overwrites every file named on the command-line, where as
28179 ** "update" only overwrites if the size or mtime or mode has changed.
28180 */
arCreateOrUpdateCommand(ArCommand * pAr,int bUpdate,int bOnlyIfChanged)28181 static int arCreateOrUpdateCommand(
28182   ArCommand *pAr,                 /* Command arguments and options */
28183   int bUpdate,                    /* true for a --create. */
28184   int bOnlyIfChanged              /* Only update if file has changed */
28185 ){
28186   const char *zCreate =
28187       "CREATE TABLE IF NOT EXISTS sqlar(\n"
28188       "  name TEXT PRIMARY KEY,  -- name of the file\n"
28189       "  mode INT,               -- access permissions\n"
28190       "  mtime INT,              -- last modification time\n"
28191       "  sz INT,                 -- original file size\n"
28192       "  data BLOB               -- compressed content\n"
28193       ")";
28194   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
28195   const char *zInsertFmt[2] = {
28196      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
28197      "  SELECT\n"
28198      "    %s,\n"
28199      "    mode,\n"
28200      "    mtime,\n"
28201      "    CASE substr(lsmode(mode),1,1)\n"
28202      "      WHEN '-' THEN length(data)\n"
28203      "      WHEN 'd' THEN 0\n"
28204      "      ELSE -1 END,\n"
28205      "    sqlar_compress(data)\n"
28206      "  FROM fsdir(%Q,%Q) AS disk\n"
28207      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
28208      ,
28209      "REPLACE INTO %s(name,mode,mtime,data)\n"
28210      "  SELECT\n"
28211      "    %s,\n"
28212      "    mode,\n"
28213      "    mtime,\n"
28214      "    data\n"
28215      "  FROM fsdir(%Q,%Q) AS disk\n"
28216      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
28217   };
28218   int i;                          /* For iterating through azFile[] */
28219   int rc;                         /* Return code */
28220   const char *zTab = 0;           /* SQL table into which to insert */
28221   char *zSql;
28222   char zTemp[50];
28223   char *zExists = 0;
28224 
28225   arExecSql(pAr, "PRAGMA page_size=512");
28226   rc = arExecSql(pAr, "SAVEPOINT ar;");
28227   if( rc!=SQLITE_OK ) return rc;
28228   zTemp[0] = 0;
28229   if( pAr->bZip ){
28230     /* Initialize the zipfile virtual table, if necessary */
28231     if( pAr->zFile ){
28232       sqlite3_uint64 r;
28233       sqlite3_randomness(sizeof(r),&r);
28234       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
28235       zTab = zTemp;
28236       zSql = sqlite3_mprintf(
28237          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
28238          zTab, pAr->zFile
28239       );
28240       rc = arExecSql(pAr, zSql);
28241       sqlite3_free(zSql);
28242     }else{
28243       zTab = "zip";
28244     }
28245   }else{
28246     /* Initialize the table for an SQLAR */
28247     zTab = "sqlar";
28248     if( bUpdate==0 ){
28249       rc = arExecSql(pAr, zDrop);
28250       if( rc!=SQLITE_OK ) goto end_ar_transaction;
28251     }
28252     rc = arExecSql(pAr, zCreate);
28253   }
28254   if( bOnlyIfChanged ){
28255     zExists = sqlite3_mprintf(
28256       " AND NOT EXISTS("
28257           "SELECT 1 FROM %s AS mem"
28258           " WHERE mem.name=disk.name"
28259           " AND mem.mtime=disk.mtime"
28260           " AND mem.mode=disk.mode)", zTab);
28261   }else{
28262     zExists = sqlite3_mprintf("");
28263   }
28264   if( zExists==0 ) rc = SQLITE_NOMEM;
28265   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
28266     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
28267         pAr->bVerbose ? "shell_putsnl(name)" : "name",
28268         pAr->azArg[i], pAr->zDir, zExists);
28269     rc = arExecSql(pAr, zSql2);
28270     sqlite3_free(zSql2);
28271   }
28272 end_ar_transaction:
28273   if( rc!=SQLITE_OK ){
28274     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
28275   }else{
28276     rc = arExecSql(pAr, "RELEASE ar;");
28277     if( pAr->bZip && pAr->zFile ){
28278       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
28279       arExecSql(pAr, zSql);
28280       sqlite3_free(zSql);
28281     }
28282   }
28283   sqlite3_free(zExists);
28284   return rc;
28285 }
28286 
28287 /*
28288 ** Implementation of ".ar" dot command.
28289 */
arDotCommand(ShellState * pState,int fromCmdLine,char ** azArg,int nArg)28290 static int arDotCommand(
28291   ShellState *pState,          /* Current shell tool state */
28292   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
28293   char **azArg,                /* Array of arguments passed to dot command */
28294   int nArg                     /* Number of entries in azArg[] */
28295 ){
28296   ArCommand cmd;
28297   int rc;
28298   memset(&cmd, 0, sizeof(cmd));
28299   cmd.fromCmdLine = fromCmdLine;
28300   rc = arParseCommand(azArg, nArg, &cmd);
28301   if( rc==SQLITE_OK ){
28302     int eDbType = SHELL_OPEN_UNSPEC;
28303     cmd.p = pState;
28304     cmd.out = pState->out;
28305     cmd.db = pState->db;
28306     if( cmd.zFile ){
28307       eDbType = deduceDatabaseType(cmd.zFile, 1);
28308     }else{
28309       eDbType = pState->openMode;
28310     }
28311     if( eDbType==SHELL_OPEN_ZIPFILE ){
28312       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
28313         if( cmd.zFile==0 ){
28314           cmd.zSrcTable = sqlite3_mprintf("zip");
28315         }else{
28316           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
28317         }
28318       }
28319       cmd.bZip = 1;
28320     }else if( cmd.zFile ){
28321       int flags;
28322       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
28323       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
28324            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
28325         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
28326       }else{
28327         flags = SQLITE_OPEN_READONLY;
28328       }
28329       cmd.db = 0;
28330       if( cmd.bDryRun ){
28331         sqlite3_fprintf(cmd.out, "-- open database '%s'%s\n", cmd.zFile,
28332               eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
28333       }
28334       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
28335              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
28336       if( rc!=SQLITE_OK ){
28337         sqlite3_fprintf(stderr, "cannot open file: %s (%s)\n",
28338                         cmd.zFile, sqlite3_errmsg(cmd.db));
28339         goto end_ar_command;
28340       }
28341       sqlite3_fileio_init(cmd.db, 0, 0);
28342       sqlite3_sqlar_init(cmd.db, 0, 0);
28343       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
28344                               shellPutsFunc, 0, 0);
28345 
28346     }
28347     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
28348       if( cmd.eCmd!=AR_CMD_CREATE
28349        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
28350       ){
28351         sqlite3_fprintf(stderr, "database does not contain an 'sqlar' table\n");
28352         rc = SQLITE_ERROR;
28353         goto end_ar_command;
28354       }
28355       cmd.zSrcTable = sqlite3_mprintf("sqlar");
28356     }
28357 
28358     switch( cmd.eCmd ){
28359       case AR_CMD_CREATE:
28360         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
28361         break;
28362 
28363       case AR_CMD_EXTRACT:
28364         rc = arExtractCommand(&cmd);
28365         break;
28366 
28367       case AR_CMD_LIST:
28368         rc = arListCommand(&cmd);
28369         break;
28370 
28371       case AR_CMD_HELP:
28372         arUsage(pState->out);
28373         break;
28374 
28375       case AR_CMD_INSERT:
28376         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
28377         break;
28378 
28379       case AR_CMD_REMOVE:
28380         rc = arRemoveCommand(&cmd);
28381         break;
28382 
28383       default:
28384         assert( cmd.eCmd==AR_CMD_UPDATE );
28385         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
28386         break;
28387     }
28388   }
28389 end_ar_command:
28390   if( cmd.db!=pState->db ){
28391     close_db(cmd.db);
28392   }
28393   sqlite3_free(cmd.zSrcTable);
28394 
28395   return rc;
28396 }
28397 /* End of the ".archive" or ".ar" command logic
28398 *******************************************************************************/
28399 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
28400 
28401 #if SQLITE_SHELL_HAVE_RECOVER
28402 
28403 /*
28404 ** This function is used as a callback by the recover extension. Simply
28405 ** print the supplied SQL statement to stdout.
28406 */
recoverSqlCb(void * pCtx,const char * zSql)28407 static int recoverSqlCb(void *pCtx, const char *zSql){
28408   ShellState *pState = (ShellState*)pCtx;
28409   sqlite3_fprintf(pState->out, "%s;\n", zSql);
28410   return SQLITE_OK;
28411 }
28412 
28413 /*
28414 ** This function is called to recover data from the database. A script
28415 ** to construct a new database containing all recovered data is output
28416 ** on stream pState->out.
28417 */
recoverDatabaseCmd(ShellState * pState,int nArg,char ** azArg)28418 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
28419   int rc = SQLITE_OK;
28420   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
28421   const char *zLAF = "lost_and_found";
28422   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
28423   int bRowids = 1;                /* 0 if --no-rowids */
28424   sqlite3_recover *p = 0;
28425   int i = 0;
28426 
28427   for(i=1; i<nArg; i++){
28428     char *z = azArg[i];
28429     int n;
28430     if( z[0]=='-' && z[1]=='-' ) z++;
28431     n = strlen30(z);
28432     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
28433       bFreelist = 0;
28434     }else
28435     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
28436       /* This option determines the name of the ATTACH-ed database used
28437       ** internally by the recovery extension.  The default is "" which
28438       ** means to use a temporary database that is automatically deleted
28439       ** when closed.  This option is undocumented and might disappear at
28440       ** any moment. */
28441       i++;
28442       zRecoveryDb = azArg[i];
28443     }else
28444     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
28445       i++;
28446       zLAF = azArg[i];
28447     }else
28448     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
28449       bRowids = 0;
28450     }
28451     else{
28452       sqlite3_fprintf(stderr,"unexpected option: %s\n", azArg[i]);
28453       showHelp(pState->out, azArg[0]);
28454       return 1;
28455     }
28456   }
28457 
28458   p = sqlite3_recover_init_sql(
28459       pState->db, "main", recoverSqlCb, (void*)pState
28460   );
28461 
28462   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
28463   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
28464   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
28465   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
28466 
28467   sqlite3_fprintf(pState->out, ".dbconfig defensive off\n");
28468   sqlite3_recover_run(p);
28469   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
28470     const char *zErr = sqlite3_recover_errmsg(p);
28471     int errCode = sqlite3_recover_errcode(p);
28472     sqlite3_fprintf(stderr,"sql error: %s (%d)\n", zErr, errCode);
28473   }
28474   rc = sqlite3_recover_finish(p);
28475   return rc;
28476 }
28477 #endif /* SQLITE_SHELL_HAVE_RECOVER */
28478 
28479 /*
28480 ** Implementation of ".intck STEPS_PER_UNLOCK" command.
28481 */
intckDatabaseCmd(ShellState * pState,i64 nStepPerUnlock)28482 static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){
28483   sqlite3_intck *p = 0;
28484   int rc = SQLITE_OK;
28485 
28486   rc = sqlite3_intck_open(pState->db, "main", &p);
28487   if( rc==SQLITE_OK ){
28488     i64 nStep = 0;
28489     i64 nError = 0;
28490     const char *zErr = 0;
28491     while( SQLITE_OK==sqlite3_intck_step(p) ){
28492       const char *zMsg = sqlite3_intck_message(p);
28493       if( zMsg ){
28494         sqlite3_fprintf(pState->out, "%s\n", zMsg);
28495         nError++;
28496       }
28497       nStep++;
28498       if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){
28499         sqlite3_intck_unlock(p);
28500       }
28501     }
28502     rc = sqlite3_intck_error(p, &zErr);
28503     if( zErr ){
28504       sqlite3_fprintf(stderr,"%s\n", zErr);
28505     }
28506     sqlite3_intck_close(p);
28507 
28508     sqlite3_fprintf(pState->out, "%lld steps, %lld errors\n", nStep, nError);
28509   }
28510 
28511   return rc;
28512 }
28513 
28514 /*
28515  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
28516  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
28517  *   close db and set it to 0, and return the columns spec, to later
28518  *   be sqlite3_free()'ed by the caller.
28519  * The return is 0 when either:
28520  *   (a) The db was not initialized and zCol==0 (There are no columns.)
28521  *   (b) zCol!=0  (Column was added, db initialized as needed.)
28522  * The 3rd argument, pRenamed, references an out parameter. If the
28523  * pointer is non-zero, its referent will be set to a summary of renames
28524  * done if renaming was necessary, or set to 0 if none was done. The out
28525  * string (if any) must be sqlite3_free()'ed by the caller.
28526  */
28527 #ifdef SHELL_DEBUG
28528 #define rc_err_oom_die(rc) \
28529   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
28530   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
28531     sqlite3_fprintf(stderr,"E:%d\n",rc), assert(0)
28532 #else
rc_err_oom_die(int rc)28533 static void rc_err_oom_die(int rc){
28534   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
28535   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
28536 }
28537 #endif
28538 
28539 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
28540 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
28541 #else  /* Otherwise, memory is faster/better for the transient DB. */
28542 static const char *zCOL_DB = ":memory:";
28543 #endif
28544 
28545 /* Define character (as C string) to separate generated column ordinal
28546  * from protected part of incoming column names. This defaults to "_"
28547  * so that incoming column identifiers that did not need not be quoted
28548  * remain usable without being quoted. It must be one character.
28549  */
28550 #ifndef SHELL_AUTOCOLUMN_SEP
28551 # define AUTOCOLUMN_SEP "_"
28552 #else
28553 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
28554 #endif
28555 
zAutoColumn(const char * zColNew,sqlite3 ** pDb,char ** pzRenamed)28556 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
28557   /* Queries and D{D,M}L used here */
28558   static const char * const zTabMake = "\
28559 CREATE TABLE ColNames(\
28560  cpos INTEGER PRIMARY KEY,\
28561  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
28562 CREATE VIEW RepeatedNames AS \
28563 SELECT DISTINCT t.name FROM ColNames t \
28564 WHERE t.name COLLATE NOCASE IN (\
28565  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
28566 );\
28567 ";
28568   static const char * const zTabFill = "\
28569 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
28570  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
28571 ";
28572   static const char * const zHasDupes = "\
28573 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
28574  <count(name) FROM ColNames\
28575 ";
28576 #ifdef SHELL_COLUMN_RENAME_CLEAN
28577   static const char * const zDedoctor = "\
28578 UPDATE ColNames SET chop=iif(\
28579   (substring(name,nlen,1) BETWEEN '0' AND '9')\
28580   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
28581  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
28582  0\
28583 )\
28584 ";
28585 #endif
28586   static const char * const zSetReps = "\
28587 UPDATE ColNames AS t SET reps=\
28588 (SELECT count(*) FROM ColNames d \
28589  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
28590  COLLATE NOCASE\
28591 )\
28592 ";
28593 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
28594   static const char * const zColDigits = "\
28595 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
28596 ";
28597 #else
28598   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
28599   static const char * const zColDigits = "\
28600 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
28601  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
28602  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
28603 ";
28604 #endif
28605   static const char * const zRenameRank =
28606 #ifdef SHELL_COLUMN_RENAME_CLEAN
28607     "UPDATE ColNames AS t SET suff="
28608     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
28609 #else /* ...RENAME_MINIMAL_ONE_PASS */
28610 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
28611 "  SELECT 0 AS nlz"
28612 "  UNION"
28613 "  SELECT nlz+1 AS nlz FROM Lzn"
28614 "  WHERE EXISTS("
28615 "   SELECT 1"
28616 "   FROM ColNames t, ColNames o"
28617 "   WHERE"
28618 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
28619 "     printf('%s"AUTOCOLUMN_SEP"%s',"
28620 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
28621 "     t.name"
28622 "    )"
28623 "    ="
28624 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
28625 "     printf('%s"AUTOCOLUMN_SEP"%s',"
28626 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
28627 "     o.name"
28628 "    )"
28629 "    COLLATE NOCASE"
28630 "    AND o.cpos<>t.cpos"
28631 "   GROUP BY t.cpos"
28632 "  )"
28633 ") UPDATE Colnames AS t SET"
28634 " chop = 0," /* No chopping, never touch incoming names. */
28635 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
28636 "  printf('"AUTOCOLUMN_SEP"%s', substring("
28637 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
28638 "  ''"
28639 " )"
28640 #endif
28641     ;
28642   static const char * const zCollectVar = "\
28643 SELECT\
28644  '('||x'0a'\
28645  || group_concat(\
28646   cname||' TEXT',\
28647   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
28648  ||')' AS ColsSpec \
28649 FROM (\
28650  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
28651  FROM ColNames ORDER BY cpos\
28652 )";
28653   static const char * const zRenamesDone =
28654     "SELECT group_concat("
28655     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
28656     " ','||x'0a')"
28657     "FROM ColNames WHERE suff<>'' OR chop!=0"
28658     ;
28659   int rc;
28660   sqlite3_stmt *pStmt = 0;
28661   assert(pDb!=0);
28662   if( zColNew ){
28663     /* Add initial or additional column. Init db if necessary. */
28664     if( *pDb==0 ){
28665       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
28666 #ifdef SHELL_COLFIX_DB
28667       if(*zCOL_DB!=':')
28668         sqlite3_exec(*pDb,"drop table if exists ColNames;"
28669                      "drop view if exists RepeatedNames;",0,0,0);
28670 #endif
28671 #undef SHELL_COLFIX_DB
28672       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
28673       rc_err_oom_die(rc);
28674     }
28675     assert(*pDb!=0);
28676     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
28677     rc_err_oom_die(rc);
28678     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
28679     rc_err_oom_die(rc);
28680     rc = sqlite3_step(pStmt);
28681     rc_err_oom_die(rc);
28682     sqlite3_finalize(pStmt);
28683     return 0;
28684   }else if( *pDb==0 ){
28685     return 0;
28686   }else{
28687     /* Formulate the columns spec, close the DB, zero *pDb. */
28688     char *zColsSpec = 0;
28689     int hasDupes = db_int(*pDb, "%s", zHasDupes);
28690     int nDigits = (hasDupes)? db_int(*pDb, "%s", zColDigits) : 0;
28691     if( hasDupes ){
28692 #ifdef SHELL_COLUMN_RENAME_CLEAN
28693       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
28694       rc_err_oom_die(rc);
28695 #endif
28696       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
28697       rc_err_oom_die(rc);
28698       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
28699       rc_err_oom_die(rc);
28700       sqlite3_bind_int(pStmt, 1, nDigits);
28701       rc = sqlite3_step(pStmt);
28702       sqlite3_finalize(pStmt);
28703       if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
28704     }
28705     assert(db_int(*pDb, "%s", zHasDupes)==0); /* Consider: remove this */
28706     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
28707     rc_err_oom_die(rc);
28708     rc = sqlite3_step(pStmt);
28709     if( rc==SQLITE_ROW ){
28710       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
28711     }else{
28712       zColsSpec = 0;
28713     }
28714     if( pzRenamed!=0 ){
28715       if( !hasDupes ) *pzRenamed = 0;
28716       else{
28717         sqlite3_finalize(pStmt);
28718         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
28719             && SQLITE_ROW==sqlite3_step(pStmt) ){
28720           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
28721         }else
28722           *pzRenamed = 0;
28723       }
28724     }
28725     sqlite3_finalize(pStmt);
28726     sqlite3_close(*pDb);
28727     *pDb = 0;
28728     return zColsSpec;
28729   }
28730 }
28731 
28732 /*
28733 ** Check if the sqlite_schema table contains one or more virtual tables. If
28734 ** parameter zLike is not NULL, then it is an SQL expression that the
28735 ** sqlite_schema row must also match. If one or more such rows are found,
28736 ** print the following warning to the output:
28737 **
28738 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
28739 */
outputDumpWarning(ShellState * p,const char * zLike)28740 static int outputDumpWarning(ShellState *p, const char *zLike){
28741   int rc = SQLITE_OK;
28742   sqlite3_stmt *pStmt = 0;
28743   shellPreparePrintf(p->db, &rc, &pStmt,
28744     "SELECT 1 FROM sqlite_schema o WHERE "
28745     "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
28746   );
28747   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
28748     sqlite3_fputs("/* WARNING: "
28749           "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n",
28750           p->out
28751     );
28752   }
28753   shellFinalize(&rc, pStmt);
28754   return rc;
28755 }
28756 
28757 /*
28758 ** Fault-Simulator state and logic.
28759 */
28760 static struct {
28761   int iId;           /* ID that triggers a simulated fault.  -1 means "any" */
28762   int iErr;          /* The error code to return on a fault */
28763   int iCnt;          /* Trigger the fault only if iCnt is already zero */
28764   int iInterval;     /* Reset iCnt to this value after each fault */
28765   int eVerbose;      /* When to print output */
28766   int nHit;          /* Number of hits seen so far */
28767   int nRepeat;       /* Turn off after this many hits.  0 for never */
28768   int nSkip;         /* Skip this many before first fault */
28769 } faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};
28770 
28771 /*
28772 ** This is the fault-sim callback
28773 */
faultsim_callback(int iArg)28774 static int faultsim_callback(int iArg){
28775   if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
28776     return SQLITE_OK;
28777   }
28778   if( faultsim_state.iCnt ){
28779     if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--;
28780     if( faultsim_state.eVerbose>=2 ){
28781       sqlite3_fprintf(stdout,
28782          "FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
28783     }
28784     return SQLITE_OK;
28785   }
28786   if( faultsim_state.eVerbose>=1 ){
28787     sqlite3_fprintf(stdout,
28788          "FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
28789   }
28790   faultsim_state.iCnt = faultsim_state.iInterval;
28791   faultsim_state.nHit++;
28792   if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){
28793     faultsim_state.iCnt = -1;
28794   }
28795   return faultsim_state.iErr;
28796 }
28797 
28798 /*
28799 ** If an input line begins with "." then invoke this routine to
28800 ** process that line.
28801 **
28802 ** Return 1 on error, 2 to exit, and 0 otherwise.
28803 */
do_meta_command(char * zLine,ShellState * p)28804 static int do_meta_command(char *zLine, ShellState *p){
28805   int h = 1;
28806   int nArg = 0;
28807   int n, c;
28808   int rc = 0;
28809   char *azArg[52];
28810 
28811 #ifndef SQLITE_OMIT_VIRTUALTABLE
28812   if( p->expert.pExpert ){
28813     expertFinish(p, 1, 0);
28814   }
28815 #endif
28816 
28817   /* Parse the input line into tokens.
28818   */
28819   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
28820     while( IsSpace(zLine[h]) ){ h++; }
28821     if( zLine[h]==0 ) break;
28822     if( zLine[h]=='\'' || zLine[h]=='"' ){
28823       int delim = zLine[h++];
28824       azArg[nArg++] = &zLine[h];
28825       while( zLine[h] && zLine[h]!=delim ){
28826         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
28827         h++;
28828       }
28829       if( zLine[h]==delim ){
28830         zLine[h++] = 0;
28831       }
28832       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
28833     }else{
28834       azArg[nArg++] = &zLine[h];
28835       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
28836       if( zLine[h] ) zLine[h++] = 0;
28837     }
28838   }
28839   azArg[nArg] = 0;
28840 
28841   /* Process the input line.
28842   */
28843   if( nArg==0 ) return 0; /* no tokens, no error */
28844   n = strlen30(azArg[0]);
28845   c = azArg[0][0];
28846   clearTempFile(p);
28847 
28848 #ifndef SQLITE_OMIT_AUTHORIZATION
28849   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
28850     if( nArg!=2 ){
28851       sqlite3_fprintf(stderr, "Usage: .auth ON|OFF\n");
28852       rc = 1;
28853       goto meta_command_exit;
28854     }
28855     open_db(p, 0);
28856     if( booleanValue(azArg[1]) ){
28857       sqlite3_set_authorizer(p->db, shellAuth, p);
28858     }else if( p->bSafeModePersist ){
28859       sqlite3_set_authorizer(p->db, safeModeAuth, p);
28860     }else{
28861       sqlite3_set_authorizer(p->db, 0, 0);
28862     }
28863   }else
28864 #endif
28865 
28866 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
28867   && !defined(SQLITE_SHELL_FIDDLE)
28868   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
28869     open_db(p, 0);
28870     failIfSafeMode(p, "cannot run .archive in safe mode");
28871     rc = arDotCommand(p, 0, azArg, nArg);
28872   }else
28873 #endif
28874 
28875 #ifndef SQLITE_SHELL_FIDDLE
28876   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
28877    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
28878   ){
28879     const char *zDestFile = 0;
28880     const char *zDb = 0;
28881     sqlite3 *pDest;
28882     sqlite3_backup *pBackup;
28883     int j;
28884     int bAsync = 0;
28885     const char *zVfs = 0;
28886     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
28887     for(j=1; j<nArg; j++){
28888       const char *z = azArg[j];
28889       if( z[0]=='-' ){
28890         if( z[1]=='-' ) z++;
28891         if( cli_strcmp(z, "-append")==0 ){
28892           zVfs = "apndvfs";
28893         }else
28894         if( cli_strcmp(z, "-async")==0 ){
28895           bAsync = 1;
28896         }else
28897         {
28898           sqlite3_fprintf(stderr,"unknown option: %s\n", azArg[j]);
28899           return 1;
28900         }
28901       }else if( zDestFile==0 ){
28902         zDestFile = azArg[j];
28903       }else if( zDb==0 ){
28904         zDb = zDestFile;
28905         zDestFile = azArg[j];
28906       }else{
28907         sqlite3_fprintf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
28908         return 1;
28909       }
28910     }
28911     if( zDestFile==0 ){
28912       sqlite3_fprintf(stderr, "missing FILENAME argument on .backup\n");
28913       return 1;
28914     }
28915     if( zDb==0 ) zDb = "main";
28916     rc = sqlite3_open_v2(zDestFile, &pDest,
28917                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
28918     if( rc!=SQLITE_OK ){
28919       sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", zDestFile);
28920       close_db(pDest);
28921       return 1;
28922     }
28923     if( bAsync ){
28924       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
28925                    0, 0, 0);
28926     }
28927     open_db(p, 0);
28928     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
28929     if( pBackup==0 ){
28930       shellDatabaseError(pDest);
28931       close_db(pDest);
28932       return 1;
28933     }
28934     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
28935     sqlite3_backup_finish(pBackup);
28936     if( rc==SQLITE_DONE ){
28937       rc = 0;
28938     }else{
28939       shellDatabaseError(pDest);
28940       rc = 1;
28941     }
28942     close_db(pDest);
28943   }else
28944 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
28945 
28946   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
28947     if( nArg==2 ){
28948       bail_on_error = booleanValue(azArg[1]);
28949     }else{
28950       eputz("Usage: .bail on|off\n");
28951       rc = 1;
28952     }
28953   }else
28954 
28955   /* Undocumented.  Legacy only.  See "crlf" below */
28956   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
28957     eputz("The \".binary\" command is deprecated.\n");
28958     rc = 1;
28959   }else
28960 
28961   /* The undocumented ".breakpoint" command causes a call to the no-op
28962   ** routine named test_breakpoint().
28963   */
28964   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
28965     test_breakpoint();
28966   }else
28967 
28968 #ifndef SQLITE_SHELL_FIDDLE
28969   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
28970     failIfSafeMode(p, "cannot run .cd in safe mode");
28971     if( nArg==2 ){
28972 #if defined(_WIN32) || defined(WIN32)
28973       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
28974       rc = !SetCurrentDirectoryW(z);
28975       sqlite3_free(z);
28976 #else
28977       rc = chdir(azArg[1]);
28978 #endif
28979       if( rc ){
28980         sqlite3_fprintf(stderr,"Cannot change to directory \"%s\"\n", azArg[1]);
28981         rc = 1;
28982       }
28983     }else{
28984       eputz("Usage: .cd DIRECTORY\n");
28985       rc = 1;
28986     }
28987   }else
28988 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
28989 
28990   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
28991     if( nArg==2 ){
28992       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
28993     }else{
28994       eputz("Usage: .changes on|off\n");
28995       rc = 1;
28996     }
28997   }else
28998 
28999 #ifndef SQLITE_SHELL_FIDDLE
29000   /* Cancel output redirection, if it is currently set (by .testcase)
29001   ** Then read the content of the testcase-out.txt file and compare against
29002   ** azArg[1].  If there are differences, report an error and exit.
29003   */
29004   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
29005     char *zRes = 0;
29006     output_reset(p);
29007     if( nArg!=2 ){
29008       eputz("Usage: .check GLOB-PATTERN\n");
29009       rc = 2;
29010     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
29011       rc = 2;
29012     }else if( testcase_glob(azArg[1],zRes)==0 ){
29013       sqlite3_fprintf(stderr,
29014             "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
29015             p->zTestcase, azArg[1], zRes);
29016       rc = 1;
29017     }else{
29018       sqlite3_fprintf(p->out, "testcase-%s ok\n", p->zTestcase);
29019       p->nCheck++;
29020     }
29021     sqlite3_free(zRes);
29022   }else
29023 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
29024 
29025 #ifndef SQLITE_SHELL_FIDDLE
29026   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
29027     failIfSafeMode(p, "cannot run .clone in safe mode");
29028     if( nArg==2 ){
29029       tryToClone(p, azArg[1]);
29030     }else{
29031       eputz("Usage: .clone FILENAME\n");
29032       rc = 1;
29033     }
29034   }else
29035 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
29036 
29037   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
29038     if( nArg==1 ){
29039       /* List available connections */
29040       int i;
29041       for(i=0; i<ArraySize(p->aAuxDb); i++){
29042         const char *zFile = p->aAuxDb[i].zDbFilename;
29043         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
29044           zFile = "(not open)";
29045         }else if( zFile==0 ){
29046           zFile = "(memory)";
29047         }else if( zFile[0]==0 ){
29048           zFile = "(temporary-file)";
29049         }
29050         if( p->pAuxDb == &p->aAuxDb[i] ){
29051           sqlite3_fprintf(stdout, "ACTIVE %d: %s\n", i, zFile);
29052         }else if( p->aAuxDb[i].db!=0 ){
29053           sqlite3_fprintf(stdout, "       %d: %s\n", i, zFile);
29054         }
29055       }
29056     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
29057       int i = azArg[1][0] - '0';
29058       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
29059         p->pAuxDb->db = p->db;
29060         p->pAuxDb = &p->aAuxDb[i];
29061         globalDb = p->db = p->pAuxDb->db;
29062         p->pAuxDb->db = 0;
29063       }
29064     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
29065            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
29066       int i = azArg[2][0] - '0';
29067       if( i<0 || i>=ArraySize(p->aAuxDb) ){
29068         /* No-op */
29069       }else if( p->pAuxDb == &p->aAuxDb[i] ){
29070         eputz("cannot close the active database connection\n");
29071         rc = 1;
29072       }else if( p->aAuxDb[i].db ){
29073         session_close_all(p, i);
29074         close_db(p->aAuxDb[i].db);
29075         p->aAuxDb[i].db = 0;
29076       }
29077     }else{
29078       eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
29079       rc = 1;
29080     }
29081   }else
29082 
29083   if( c=='c' && n==4
29084    && (cli_strncmp(azArg[0], "crlf", n)==0
29085        || cli_strncmp(azArg[0], "crnl",n)==0)
29086   ){
29087     if( nArg==2 ){
29088 #ifdef _WIN32
29089       p->crlfMode = booleanValue(azArg[1]);
29090 #else
29091       p->crlfMode = 0;
29092 #endif
29093     }
29094     sqlite3_fprintf(stderr, "crlf is %s\n", p->crlfMode ? "ON" : "OFF");
29095   }else
29096 
29097   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
29098     char **azName = 0;
29099     int nName = 0;
29100     sqlite3_stmt *pStmt;
29101     int i;
29102     open_db(p, 0);
29103     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
29104     if( rc ){
29105       shellDatabaseError(p->db);
29106       rc = 1;
29107     }else{
29108       while( sqlite3_step(pStmt)==SQLITE_ROW ){
29109         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
29110         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
29111         if( zSchema==0 || zFile==0 ) continue;
29112         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
29113         shell_check_oom(azName);
29114         azName[nName*2] = strdup(zSchema);
29115         azName[nName*2+1] = strdup(zFile);
29116         nName++;
29117       }
29118     }
29119     sqlite3_finalize(pStmt);
29120     for(i=0; i<nName; i++){
29121       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
29122       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
29123       const char *z = azName[i*2+1];
29124       sqlite3_fprintf(p->out, "%s: %s %s%s\n",
29125             azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
29126             eTxn==SQLITE_TXN_NONE ? "" :
29127             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
29128       free(azName[i*2]);
29129       free(azName[i*2+1]);
29130     }
29131     sqlite3_free(azName);
29132   }else
29133 
29134   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
29135     static const struct DbConfigChoices {
29136       const char *zName;
29137       int op;
29138     } aDbConfig[] = {
29139         { "attach_create",      SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE  },
29140         { "attach_write",       SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE   },
29141         { "comments",           SQLITE_DBCONFIG_ENABLE_COMMENTS       },
29142         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
29143         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
29144         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
29145         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
29146         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
29147         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
29148         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
29149         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
29150         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
29151         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
29152         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
29153         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
29154         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
29155         { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
29156         { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
29157         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
29158         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
29159         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
29160     };
29161     int ii, v;
29162     open_db(p, 0);
29163     for(ii=0; ii<ArraySize(aDbConfig); ii++){
29164       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
29165       if( nArg>=3 ){
29166         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
29167       }
29168       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
29169       sqlite3_fprintf(p->out, "%19s %s\n",
29170                       aDbConfig[ii].zName, v ? "on" : "off");
29171       if( nArg>1 ) break;
29172     }
29173     if( nArg>1 && ii==ArraySize(aDbConfig) ){
29174       sqlite3_fprintf(stderr,"Error: unknown dbconfig \"%s\"\n", azArg[1]);
29175       eputz("Enter \".dbconfig\" with no arguments for a list\n");
29176     }
29177   }else
29178 
29179 #if SQLITE_SHELL_HAVE_RECOVER
29180   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
29181     rc = shell_dbinfo_command(p, nArg, azArg);
29182   }else
29183 
29184   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
29185     open_db(p, 0);
29186     rc = recoverDatabaseCmd(p, nArg, azArg);
29187   }else
29188 #endif /* SQLITE_SHELL_HAVE_RECOVER */
29189 
29190   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
29191     char *zLike = 0;
29192     char *zSql;
29193     int i;
29194     int savedShowHeader = p->showHeader;
29195     int savedShellFlags = p->shellFlgs;
29196     ShellClearFlag(p,
29197        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
29198        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
29199     for(i=1; i<nArg; i++){
29200       if( azArg[i][0]=='-' ){
29201         const char *z = azArg[i]+1;
29202         if( z[0]=='-' ) z++;
29203         if( cli_strcmp(z,"preserve-rowids")==0 ){
29204 #ifdef SQLITE_OMIT_VIRTUALTABLE
29205           eputz("The --preserve-rowids option is not compatible"
29206                 " with SQLITE_OMIT_VIRTUALTABLE\n");
29207           rc = 1;
29208           sqlite3_free(zLike);
29209           goto meta_command_exit;
29210 #else
29211           ShellSetFlag(p, SHFLG_PreserveRowid);
29212 #endif
29213         }else
29214         if( cli_strcmp(z,"newlines")==0 ){
29215           ShellSetFlag(p, SHFLG_Newlines);
29216         }else
29217         if( cli_strcmp(z,"data-only")==0 ){
29218           ShellSetFlag(p, SHFLG_DumpDataOnly);
29219         }else
29220         if( cli_strcmp(z,"nosys")==0 ){
29221           ShellSetFlag(p, SHFLG_DumpNoSys);
29222         }else
29223         {
29224           sqlite3_fprintf(stderr,
29225                "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
29226           rc = 1;
29227           sqlite3_free(zLike);
29228           goto meta_command_exit;
29229         }
29230       }else{
29231         /* azArg[i] contains a LIKE pattern. This ".dump" request should
29232         ** only dump data for tables for which either the table name matches
29233         ** the LIKE pattern, or the table appears to be a shadow table of
29234         ** a virtual table for which the name matches the LIKE pattern.
29235         */
29236         char *zExpr = sqlite3_mprintf(
29237             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
29238             "  SELECT 1 FROM sqlite_schema WHERE "
29239             "    name LIKE %Q ESCAPE '\\' AND"
29240             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
29241             "    substr(o.name, 1, length(name)+1) == (name||'_')"
29242             ")", azArg[i], azArg[i]
29243         );
29244 
29245         if( zLike ){
29246           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
29247         }else{
29248           zLike = zExpr;
29249         }
29250       }
29251     }
29252 
29253     open_db(p, 0);
29254 
29255     outputDumpWarning(p, zLike);
29256     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
29257       /* When playing back a "dump", the content might appear in an order
29258       ** which causes immediate foreign key constraints to be violated.
29259       ** So disable foreign-key constraint enforcement to prevent problems. */
29260       sqlite3_fputs("PRAGMA foreign_keys=OFF;\n", p->out);
29261       sqlite3_fputs("BEGIN TRANSACTION;\n", p->out);
29262     }
29263     p->writableSchema = 0;
29264     p->showHeader = 0;
29265     /* Set writable_schema=ON since doing so forces SQLite to initialize
29266     ** as much of the schema as it can even if the sqlite_schema table is
29267     ** corrupt. */
29268     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
29269     p->nErr = 0;
29270     if( zLike==0 ) zLike = sqlite3_mprintf("true");
29271     zSql = sqlite3_mprintf(
29272       "SELECT name, type, sql FROM sqlite_schema AS o "
29273       "WHERE (%s) AND type=='table'"
29274       "  AND sql NOT NULL"
29275       " ORDER BY tbl_name='sqlite_sequence', rowid",
29276       zLike
29277     );
29278     run_schema_dump_query(p,zSql);
29279     sqlite3_free(zSql);
29280     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
29281       zSql = sqlite3_mprintf(
29282         "SELECT sql FROM sqlite_schema AS o "
29283         "WHERE (%s) AND sql NOT NULL"
29284         "  AND type IN ('index','trigger','view') "
29285         "ORDER BY type COLLATE NOCASE DESC",
29286         zLike
29287       );
29288       run_table_dump_query(p, zSql);
29289       sqlite3_free(zSql);
29290     }
29291     sqlite3_free(zLike);
29292     if( p->writableSchema ){
29293       sqlite3_fputs("PRAGMA writable_schema=OFF;\n", p->out);
29294       p->writableSchema = 0;
29295     }
29296     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
29297     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
29298     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
29299       sqlite3_fputs(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n", p->out);
29300     }
29301     p->showHeader = savedShowHeader;
29302     p->shellFlgs = savedShellFlags;
29303   }else
29304 
29305   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
29306     if( nArg==2 ){
29307       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
29308     }else{
29309       eputz("Usage: .echo on|off\n");
29310       rc = 1;
29311     }
29312   }else
29313 
29314   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbtotxt", n)==0 ){
29315     rc = shell_dbtotxt_command(p, nArg, azArg);
29316   }else
29317 
29318   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
29319     if( nArg==2 ){
29320       p->autoEQPtest = 0;
29321       if( p->autoEQPtrace ){
29322         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
29323         p->autoEQPtrace = 0;
29324       }
29325       if( cli_strcmp(azArg[1],"full")==0 ){
29326         p->autoEQP = AUTOEQP_full;
29327       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
29328         p->autoEQP = AUTOEQP_trigger;
29329 #ifdef SQLITE_DEBUG
29330       }else if( cli_strcmp(azArg[1],"test")==0 ){
29331         p->autoEQP = AUTOEQP_on;
29332         p->autoEQPtest = 1;
29333       }else if( cli_strcmp(azArg[1],"trace")==0 ){
29334         p->autoEQP = AUTOEQP_full;
29335         p->autoEQPtrace = 1;
29336         open_db(p, 0);
29337         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
29338         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
29339 #endif
29340       }else{
29341         p->autoEQP = (u8)booleanValue(azArg[1]);
29342       }
29343     }else{
29344       eputz("Usage: .eqp off|on|trace|trigger|full\n");
29345       rc = 1;
29346     }
29347   }else
29348 
29349 #ifndef SQLITE_SHELL_FIDDLE
29350   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
29351     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
29352     rc = 2;
29353   }else
29354 #endif
29355 
29356   /* The ".explain" command is automatic now.  It is largely pointless.  It
29357   ** retained purely for backwards compatibility */
29358   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
29359     int val = 1;
29360     if( nArg>=2 ){
29361       if( cli_strcmp(azArg[1],"auto")==0 ){
29362         val = 99;
29363       }else{
29364         val =  booleanValue(azArg[1]);
29365       }
29366     }
29367     if( val==1 && p->mode!=MODE_Explain ){
29368       p->normalMode = p->mode;
29369       p->mode = MODE_Explain;
29370       p->autoExplain = 0;
29371     }else if( val==0 ){
29372       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
29373       p->autoExplain = 0;
29374     }else if( val==99 ){
29375       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
29376       p->autoExplain = 1;
29377     }
29378   }else
29379 
29380 #ifndef SQLITE_OMIT_VIRTUALTABLE
29381   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
29382     if( p->bSafeMode ){
29383       sqlite3_fprintf(stderr,
29384             "Cannot run experimental commands such as \"%s\" in safe mode\n",
29385             azArg[0]);
29386       rc = 1;
29387     }else{
29388       open_db(p, 0);
29389       expertDotCommand(p, azArg, nArg);
29390     }
29391   }else
29392 #endif
29393 
29394   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
29395     static const struct {
29396        const char *zCtrlName;   /* Name of a test-control option */
29397        int ctrlCode;            /* Integer code for that option */
29398        const char *zUsage;      /* Usage notes */
29399     } aCtrl[] = {
29400       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
29401       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
29402       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
29403       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
29404       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
29405    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
29406       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
29407       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
29408       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
29409       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
29410    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
29411     };
29412     int filectrl = -1;
29413     int iCtrl = -1;
29414     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
29415     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
29416     int n2, i;
29417     const char *zCmd = 0;
29418     const char *zSchema = 0;
29419 
29420     open_db(p, 0);
29421     zCmd = nArg>=2 ? azArg[1] : "help";
29422 
29423     if( zCmd[0]=='-'
29424      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
29425      && nArg>=4
29426     ){
29427       zSchema = azArg[2];
29428       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
29429       nArg -= 2;
29430       zCmd = azArg[1];
29431     }
29432 
29433     /* The argument can optionally begin with "-" or "--" */
29434     if( zCmd[0]=='-' && zCmd[1] ){
29435       zCmd++;
29436       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
29437     }
29438 
29439     /* --help lists all file-controls */
29440     if( cli_strcmp(zCmd,"help")==0 ){
29441       sqlite3_fputs("Available file-controls:\n", p->out);
29442       for(i=0; i<ArraySize(aCtrl); i++){
29443         sqlite3_fprintf(p->out,
29444                "  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
29445       }
29446       rc = 1;
29447       goto meta_command_exit;
29448     }
29449 
29450     /* convert filectrl text option to value. allow any unique prefix
29451     ** of the option name, or a numerical value. */
29452     n2 = strlen30(zCmd);
29453     for(i=0; i<ArraySize(aCtrl); i++){
29454       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
29455         if( filectrl<0 ){
29456           filectrl = aCtrl[i].ctrlCode;
29457           iCtrl = i;
29458         }else{
29459           sqlite3_fprintf(stderr,"Error: ambiguous file-control: \"%s\"\n"
29460                 "Use \".filectrl --help\" for help\n", zCmd);
29461           rc = 1;
29462           goto meta_command_exit;
29463         }
29464       }
29465     }
29466     if( filectrl<0 ){
29467       sqlite3_fprintf(stderr,"Error: unknown file-control: %s\n"
29468             "Use \".filectrl --help\" for help\n", zCmd);
29469     }else{
29470       switch(filectrl){
29471         case SQLITE_FCNTL_SIZE_LIMIT: {
29472           if( nArg!=2 && nArg!=3 ) break;
29473           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
29474           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
29475           isOk = 1;
29476           break;
29477         }
29478         case SQLITE_FCNTL_LOCK_TIMEOUT:
29479         case SQLITE_FCNTL_CHUNK_SIZE: {
29480           int x;
29481           if( nArg!=3 ) break;
29482           x = (int)integerValue(azArg[2]);
29483           sqlite3_file_control(p->db, zSchema, filectrl, &x);
29484           isOk = 2;
29485           break;
29486         }
29487         case SQLITE_FCNTL_PERSIST_WAL:
29488         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
29489           int x;
29490           if( nArg!=2 && nArg!=3 ) break;
29491           x = nArg==3 ? booleanValue(azArg[2]) : -1;
29492           sqlite3_file_control(p->db, zSchema, filectrl, &x);
29493           iRes = x;
29494           isOk = 1;
29495           break;
29496         }
29497         case SQLITE_FCNTL_DATA_VERSION:
29498         case SQLITE_FCNTL_HAS_MOVED: {
29499           int x;
29500           if( nArg!=2 ) break;
29501           sqlite3_file_control(p->db, zSchema, filectrl, &x);
29502           iRes = x;
29503           isOk = 1;
29504           break;
29505         }
29506         case SQLITE_FCNTL_TEMPFILENAME: {
29507           char *z = 0;
29508           if( nArg!=2 ) break;
29509           sqlite3_file_control(p->db, zSchema, filectrl, &z);
29510           if( z ){
29511             sqlite3_fprintf(p->out, "%s\n", z);
29512             sqlite3_free(z);
29513           }
29514           isOk = 2;
29515           break;
29516         }
29517         case SQLITE_FCNTL_RESERVE_BYTES: {
29518           int x;
29519           if( nArg>=3 ){
29520             x = atoi(azArg[2]);
29521             sqlite3_file_control(p->db, zSchema, filectrl, &x);
29522           }
29523           x = -1;
29524           sqlite3_file_control(p->db, zSchema, filectrl, &x);
29525           sqlite3_fprintf(p->out, "%d\n", x);
29526           isOk = 2;
29527           break;
29528         }
29529       }
29530     }
29531     if( isOk==0 && iCtrl>=0 ){
29532       sqlite3_fprintf(p->out, "Usage: .filectrl %s %s\n",
29533                       zCmd, aCtrl[iCtrl].zUsage);
29534       rc = 1;
29535     }else if( isOk==1 ){
29536       char zBuf[100];
29537       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
29538       sqlite3_fprintf(p->out, "%s\n", zBuf);
29539     }
29540   }else
29541 
29542   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
29543     ShellState data;
29544     int doStats = 0;
29545     memcpy(&data, p, sizeof(data));
29546     data.showHeader = 0;
29547     data.cMode = data.mode = MODE_Semi;
29548     if( nArg==2 && optionMatch(azArg[1], "indent") ){
29549       data.cMode = data.mode = MODE_Pretty;
29550       nArg = 1;
29551     }
29552     if( nArg!=1 ){
29553       eputz("Usage: .fullschema ?--indent?\n");
29554       rc = 1;
29555       goto meta_command_exit;
29556     }
29557     open_db(p, 0);
29558     rc = sqlite3_exec(p->db,
29559        "SELECT sql FROM"
29560        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
29561        "     FROM sqlite_schema UNION ALL"
29562        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
29563        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
29564        "ORDER BY x",
29565        callback, &data, 0
29566     );
29567     if( rc==SQLITE_OK ){
29568       sqlite3_stmt *pStmt;
29569       rc = sqlite3_prepare_v2(p->db,
29570                "SELECT rowid FROM sqlite_schema"
29571                " WHERE name GLOB 'sqlite_stat[134]'",
29572                -1, &pStmt, 0);
29573       if( rc==SQLITE_OK ){
29574         doStats = sqlite3_step(pStmt)==SQLITE_ROW;
29575         sqlite3_finalize(pStmt);
29576       }
29577     }
29578     if( doStats==0 ){
29579       sqlite3_fputs("/* No STAT tables available */\n", p->out);
29580     }else{
29581       sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out);
29582       data.cMode = data.mode = MODE_Insert;
29583       data.zDestTable = "sqlite_stat1";
29584       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
29585       data.zDestTable = "sqlite_stat4";
29586       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
29587       sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out);
29588     }
29589   }else
29590 
29591   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
29592     if( nArg==2 ){
29593       p->showHeader = booleanValue(azArg[1]);
29594       p->shellFlgs |= SHFLG_HeaderSet;
29595     }else{
29596       eputz("Usage: .headers on|off\n");
29597       rc = 1;
29598     }
29599   }else
29600 
29601   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
29602     if( nArg>=2 ){
29603       n = showHelp(p->out, azArg[1]);
29604       if( n==0 ){
29605         sqlite3_fprintf(p->out, "Nothing matches '%s'\n", azArg[1]);
29606       }
29607     }else{
29608       showHelp(p->out, 0);
29609     }
29610   }else
29611 
29612 #ifndef SQLITE_SHELL_FIDDLE
29613   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
29614     char *zTable = 0;           /* Insert data into this table */
29615     char *zSchema = 0;          /* Schema of zTable */
29616     char *zFile = 0;            /* Name of file to extra content from */
29617     sqlite3_stmt *pStmt = NULL; /* A statement */
29618     int nCol;                   /* Number of columns in the table */
29619     i64 nByte;                  /* Number of bytes in an SQL string */
29620     int i, j;                   /* Loop counters */
29621     int needCommit;             /* True to COMMIT or ROLLBACK at end */
29622     int nSep;                   /* Number of bytes in p->colSeparator[] */
29623     char *zSql = 0;             /* An SQL statement */
29624     ImportCtx sCtx;             /* Reader context */
29625     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
29626     int eVerbose = 0;           /* Larger for more console output */
29627     int nSkip = 0;              /* Initial lines to skip */
29628     int useOutputMode = 1;      /* Use output mode to determine separators */
29629     char *zCreate = 0;          /* CREATE TABLE statement text */
29630 
29631     failIfSafeMode(p, "cannot run .import in safe mode");
29632     memset(&sCtx, 0, sizeof(sCtx));
29633     if( p->mode==MODE_Ascii ){
29634       xRead = ascii_read_one_field;
29635     }else{
29636       xRead = csv_read_one_field;
29637     }
29638     rc = 1;
29639     for(i=1; i<nArg; i++){
29640       char *z = azArg[i];
29641       if( z[0]=='-' && z[1]=='-' ) z++;
29642       if( z[0]!='-' ){
29643         if( zFile==0 ){
29644           zFile = z;
29645         }else if( zTable==0 ){
29646           zTable = z;
29647         }else{
29648           sqlite3_fprintf(p->out, "ERROR: extra argument: \"%s\". Usage:\n",z);
29649           showHelp(p->out, "import");
29650           goto meta_command_exit;
29651         }
29652       }else if( cli_strcmp(z,"-v")==0 ){
29653         eVerbose++;
29654       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
29655         zSchema = azArg[++i];
29656       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
29657         nSkip = integerValue(azArg[++i]);
29658       }else if( cli_strcmp(z,"-ascii")==0 ){
29659         sCtx.cColSep = SEP_Unit[0];
29660         sCtx.cRowSep = SEP_Record[0];
29661         xRead = ascii_read_one_field;
29662         useOutputMode = 0;
29663       }else if( cli_strcmp(z,"-csv")==0 ){
29664         sCtx.cColSep = ',';
29665         sCtx.cRowSep = '\n';
29666         xRead = csv_read_one_field;
29667         useOutputMode = 0;
29668       }else{
29669         sqlite3_fprintf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
29670         showHelp(p->out, "import");
29671         goto meta_command_exit;
29672       }
29673     }
29674     if( zTable==0 ){
29675       sqlite3_fprintf(p->out, "ERROR: missing %s argument. Usage:\n",
29676             zFile==0 ? "FILE" : "TABLE");
29677       showHelp(p->out, "import");
29678       goto meta_command_exit;
29679     }
29680     seenInterrupt = 0;
29681     open_db(p, 0);
29682     if( useOutputMode ){
29683       /* If neither the --csv or --ascii options are specified, then set
29684       ** the column and row separator characters from the output mode. */
29685       nSep = strlen30(p->colSeparator);
29686       if( nSep==0 ){
29687         eputz("Error: non-null column separator required for import\n");
29688         goto meta_command_exit;
29689       }
29690       if( nSep>1 ){
29691         eputz("Error: multi-character column separators not allowed"
29692               " for import\n");
29693         goto meta_command_exit;
29694       }
29695       nSep = strlen30(p->rowSeparator);
29696       if( nSep==0 ){
29697         eputz("Error: non-null row separator required for import\n");
29698         goto meta_command_exit;
29699       }
29700       if( nSep==2 && p->mode==MODE_Csv
29701        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
29702       ){
29703         /* When importing CSV (only), if the row separator is set to the
29704         ** default output row separator, change it to the default input
29705         ** row separator.  This avoids having to maintain different input
29706         ** and output row separators. */
29707         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
29708         nSep = strlen30(p->rowSeparator);
29709       }
29710       if( nSep>1 ){
29711         eputz("Error: multi-character row separators not allowed"
29712               " for import\n");
29713         goto meta_command_exit;
29714       }
29715       sCtx.cColSep = (u8)p->colSeparator[0];
29716       sCtx.cRowSep = (u8)p->rowSeparator[0];
29717     }
29718     sCtx.zFile = zFile;
29719     sCtx.nLine = 1;
29720     if( sCtx.zFile[0]=='|' ){
29721 #ifdef SQLITE_OMIT_POPEN
29722       eputz("Error: pipes are not supported in this OS\n");
29723       goto meta_command_exit;
29724 #else
29725       sCtx.in = sqlite3_popen(sCtx.zFile+1, "r");
29726       sCtx.zFile = "<pipe>";
29727       sCtx.xCloser = pclose;
29728 #endif
29729     }else{
29730       sCtx.in = sqlite3_fopen(sCtx.zFile, "rb");
29731       sCtx.xCloser = fclose;
29732     }
29733     if( sCtx.in==0 ){
29734       sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", zFile);
29735       goto meta_command_exit;
29736     }
29737     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
29738       char zSep[2];
29739       zSep[1] = 0;
29740       zSep[0] = sCtx.cColSep;
29741       sqlite3_fputs("Column separator ", p->out);
29742       output_c_string(p->out, zSep);
29743       sqlite3_fputs(", row separator ", p->out);
29744       zSep[0] = sCtx.cRowSep;
29745       output_c_string(p->out, zSep);
29746       sqlite3_fputs("\n", p->out);
29747     }
29748     sCtx.z = sqlite3_malloc64(120);
29749     if( sCtx.z==0 ){
29750       import_cleanup(&sCtx);
29751       shell_out_of_memory();
29752     }
29753     /* Below, resources must be freed before exit. */
29754     while( (nSkip--)>0 ){
29755       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
29756     }
29757     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
29758     if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0)
29759      && 0==db_int(p->db, "SELECT count(*) FROM \"%w\".sqlite_schema"
29760                          " WHERE name=%Q AND type='view'",
29761                          zSchema ? zSchema : "main", zTable)
29762     ){
29763       /* Table does not exist.  Create it. */
29764       sqlite3 *dbCols = 0;
29765       char *zRenames = 0;
29766       char *zColDefs;
29767       zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"",
29768                     zSchema ? zSchema : "main", zTable);
29769       while( xRead(&sCtx) ){
29770         zAutoColumn(sCtx.z, &dbCols, 0);
29771         if( sCtx.cTerm!=sCtx.cColSep ) break;
29772       }
29773       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
29774       if( zRenames!=0 ){
29775         sqlite3_fprintf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
29776               "Columns renamed during .import %s due to duplicates:\n"
29777               "%s\n", sCtx.zFile, zRenames);
29778         sqlite3_free(zRenames);
29779       }
29780       assert(dbCols==0);
29781       if( zColDefs==0 ){
29782         sqlite3_fprintf(stderr,"%s: empty file\n", sCtx.zFile);
29783         import_cleanup(&sCtx);
29784         rc = 1;
29785         sqlite3_free(zCreate);
29786         goto meta_command_exit;
29787       }
29788       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
29789       if( zCreate==0 ){
29790         import_cleanup(&sCtx);
29791         shell_out_of_memory();
29792       }
29793       if( eVerbose>=1 ){
29794         sqlite3_fprintf(p->out, "%s\n", zCreate);
29795       }
29796       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
29797       if( rc ){
29798         sqlite3_fprintf(stderr,
29799              "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
29800       }
29801       sqlite3_free(zCreate);
29802       zCreate = 0;
29803       if( rc ){
29804         import_cleanup(&sCtx);
29805         rc = 1;
29806         goto meta_command_exit;
29807       }
29808     }
29809     zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
29810                            zTable, zSchema);
29811     if( zSql==0 ){
29812       import_cleanup(&sCtx);
29813       shell_out_of_memory();
29814     }
29815     rc =  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
29816     sqlite3_free(zSql);
29817     zSql = 0;
29818     if( rc ){
29819       if (pStmt) sqlite3_finalize(pStmt);
29820       shellDatabaseError(p->db);
29821       import_cleanup(&sCtx);
29822       rc = 1;
29823       goto meta_command_exit;
29824     }
29825     if( sqlite3_step(pStmt)==SQLITE_ROW ){
29826       nCol = sqlite3_column_int(pStmt, 0);
29827     }else{
29828       nCol = 0;
29829     }
29830     sqlite3_finalize(pStmt);
29831     pStmt = 0;
29832     if( nCol==0 ) return 0; /* no columns, no error */
29833 
29834     nByte = 64                 /* space for "INSERT INTO", "VALUES(", ")\0" */
29835           + (zSchema ? strlen(zSchema)*2 + 2: 0)  /* Quoted schema name */
29836           + strlen(zTable)*2 + 2                  /* Quoted table name */
29837           + nCol*2;            /* Space for ",?" for each column */
29838     zSql = sqlite3_malloc64( nByte );
29839     if( zSql==0 ){
29840       import_cleanup(&sCtx);
29841       shell_out_of_memory();
29842     }
29843     if( zSchema ){
29844       sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?",
29845                        zSchema, zTable);
29846     }else{
29847       sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
29848     }
29849     j = strlen30(zSql);
29850     for(i=1; i<nCol; i++){
29851       zSql[j++] = ',';
29852       zSql[j++] = '?';
29853     }
29854     zSql[j++] = ')';
29855     zSql[j] = 0;
29856     assert( j<nByte );
29857     if( eVerbose>=2 ){
29858       sqlite3_fprintf(p->out, "Insert using: %s\n", zSql);
29859     }
29860     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
29861     sqlite3_free(zSql);
29862     zSql = 0;
29863     if( rc ){
29864       shellDatabaseError(p->db);
29865       if (pStmt) sqlite3_finalize(pStmt);
29866       import_cleanup(&sCtx);
29867       rc = 1;
29868       goto meta_command_exit;
29869     }
29870     needCommit = sqlite3_get_autocommit(p->db);
29871     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
29872     do{
29873       int startLine = sCtx.nLine;
29874       for(i=0; i<nCol; i++){
29875         char *z = xRead(&sCtx);
29876         /*
29877         ** Did we reach end-of-file before finding any columns?
29878         ** If so, stop instead of NULL filling the remaining columns.
29879         */
29880         if( z==0 && i==0 ) break;
29881         /*
29882         ** Did we reach end-of-file OR end-of-line before finding any
29883         ** columns in ASCII mode?  If so, stop instead of NULL filling
29884         ** the remaining columns.
29885         */
29886         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
29887         /*
29888         ** For CSV mode, per RFC 4180, accept EOF in lieu of final
29889         ** record terminator but only for last field of multi-field row.
29890         ** (If there are too few fields, it's not valid CSV anyway.)
29891         */
29892         if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
29893           z = "";
29894         }
29895         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
29896         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
29897           sqlite3_fprintf(stderr,"%s:%d: expected %d columns but found %d"
29898                 " - filling the rest with NULL\n",
29899                 sCtx.zFile, startLine, nCol, i+1);
29900           i += 2;
29901           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
29902         }
29903       }
29904       if( sCtx.cTerm==sCtx.cColSep ){
29905         do{
29906           xRead(&sCtx);
29907           i++;
29908         }while( sCtx.cTerm==sCtx.cColSep );
29909         sqlite3_fprintf(stderr,
29910               "%s:%d: expected %d columns but found %d - extras ignored\n",
29911               sCtx.zFile, startLine, nCol, i);
29912       }
29913       if( i>=nCol ){
29914         sqlite3_step(pStmt);
29915         rc = sqlite3_reset(pStmt);
29916         if( rc!=SQLITE_OK ){
29917           sqlite3_fprintf(stderr,"%s:%d: INSERT failed: %s\n",
29918                 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
29919           sCtx.nErr++;
29920         }else{
29921           sCtx.nRow++;
29922         }
29923       }
29924     }while( sCtx.cTerm!=EOF );
29925 
29926     import_cleanup(&sCtx);
29927     sqlite3_finalize(pStmt);
29928     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
29929     if( eVerbose>0 ){
29930       sqlite3_fprintf(p->out,
29931             "Added %d rows with %d errors using %d lines of input\n",
29932             sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
29933     }
29934   }else
29935 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
29936 
29937 #ifndef SQLITE_UNTESTABLE
29938   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
29939     char *zSql;
29940     char *zCollist = 0;
29941     sqlite3_stmt *pStmt;
29942     int tnum = 0;
29943     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
29944     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
29945     int i;
29946     if( !ShellHasFlag(p,SHFLG_TestingMode) ){
29947       sqlite3_fprintf(stderr,".%s unavailable without --unsafe-testing\n",
29948             "imposter");
29949       rc = 1;
29950       goto meta_command_exit;
29951     }
29952     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
29953       eputz("Usage: .imposter INDEX IMPOSTER\n"
29954             "       .imposter off\n");
29955       /* Also allowed, but not documented:
29956       **
29957       **    .imposter TABLE IMPOSTER
29958       **
29959       ** where TABLE is a WITHOUT ROWID table.  In that case, the
29960       ** imposter is another WITHOUT ROWID table with the columns in
29961       ** storage order. */
29962       rc = 1;
29963       goto meta_command_exit;
29964     }
29965     open_db(p, 0);
29966     if( nArg==2 ){
29967       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
29968       goto meta_command_exit;
29969     }
29970     zSql = sqlite3_mprintf(
29971       "SELECT rootpage, 0 FROM sqlite_schema"
29972       " WHERE name='%q' AND type='index'"
29973       "UNION ALL "
29974       "SELECT rootpage, 1 FROM sqlite_schema"
29975       " WHERE name='%q' AND type='table'"
29976       "   AND sql LIKE '%%without%%rowid%%'",
29977       azArg[1], azArg[1]
29978     );
29979     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
29980     sqlite3_free(zSql);
29981     if( sqlite3_step(pStmt)==SQLITE_ROW ){
29982       tnum = sqlite3_column_int(pStmt, 0);
29983       isWO = sqlite3_column_int(pStmt, 1);
29984     }
29985     sqlite3_finalize(pStmt);
29986     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
29987     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
29988     sqlite3_free(zSql);
29989     i = 0;
29990     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
29991       char zLabel[20];
29992       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
29993       i++;
29994       if( zCol==0 ){
29995         if( sqlite3_column_int(pStmt,1)==-1 ){
29996           zCol = "_ROWID_";
29997         }else{
29998           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
29999           zCol = zLabel;
30000         }
30001       }
30002       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
30003         lenPK = (int)strlen(zCollist);
30004       }
30005       if( zCollist==0 ){
30006         zCollist = sqlite3_mprintf("\"%w\"", zCol);
30007       }else{
30008         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
30009       }
30010     }
30011     sqlite3_finalize(pStmt);
30012     if( i==0 || tnum==0 ){
30013       sqlite3_fprintf(stderr,"no such index: \"%s\"\n", azArg[1]);
30014       rc = 1;
30015       sqlite3_free(zCollist);
30016       goto meta_command_exit;
30017     }
30018     if( lenPK==0 ) lenPK = 100000;
30019     zSql = sqlite3_mprintf(
30020           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
30021           azArg[2], zCollist, lenPK, zCollist);
30022     sqlite3_free(zCollist);
30023     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
30024     if( rc==SQLITE_OK ){
30025       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
30026       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
30027       if( rc ){
30028         sqlite3_fprintf(stderr,
30029               "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
30030       }else{
30031         sqlite3_fprintf(stdout, "%s;\n", zSql);
30032         sqlite3_fprintf(stdout,
30033               "WARNING: writing to an imposter table will corrupt"
30034               " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
30035       }
30036     }else{
30037       sqlite3_fprintf(stderr,"SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
30038       rc = 1;
30039     }
30040     sqlite3_free(zSql);
30041   }else
30042 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
30043 
30044   if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
30045     i64 iArg = 0;
30046     if( nArg==2 ){
30047       iArg = integerValue(azArg[1]);
30048       if( iArg==0 ) iArg = -1;
30049     }
30050     if( (nArg!=1 && nArg!=2) || iArg<0 ){
30051       sqlite3_fprintf(stderr,"%s","Usage: .intck STEPS_PER_UNLOCK\n");
30052       rc = 1;
30053       goto meta_command_exit;
30054     }
30055     open_db(p, 0);
30056     rc = intckDatabaseCmd(p, iArg);
30057   }else
30058 
30059 #ifdef SQLITE_ENABLE_IOTRACE
30060   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
30061     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
30062     if( iotrace && iotrace!=stdout ) fclose(iotrace);
30063     iotrace = 0;
30064     if( nArg<2 ){
30065       sqlite3IoTrace = 0;
30066     }else if( cli_strcmp(azArg[1], "-")==0 ){
30067       sqlite3IoTrace = iotracePrintf;
30068       iotrace = stdout;
30069     }else{
30070       iotrace = sqlite3_fopen(azArg[1], "w");
30071       if( iotrace==0 ){
30072         sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
30073         sqlite3IoTrace = 0;
30074         rc = 1;
30075       }else{
30076         sqlite3IoTrace = iotracePrintf;
30077       }
30078     }
30079   }else
30080 #endif
30081 
30082   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
30083     static const struct {
30084        const char *zLimitName;   /* Name of a limit */
30085        int limitCode;            /* Integer code for that limit */
30086     } aLimit[] = {
30087       { "length",                SQLITE_LIMIT_LENGTH                    },
30088       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
30089       { "column",                SQLITE_LIMIT_COLUMN                    },
30090       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
30091       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
30092       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
30093       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
30094       { "attached",              SQLITE_LIMIT_ATTACHED                  },
30095       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
30096       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
30097       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
30098       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
30099     };
30100     int i, n2;
30101     open_db(p, 0);
30102     if( nArg==1 ){
30103       for(i=0; i<ArraySize(aLimit); i++){
30104         sqlite3_fprintf(stdout, "%20s %d\n", aLimit[i].zLimitName,
30105               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
30106       }
30107     }else if( nArg>3 ){
30108       eputz("Usage: .limit NAME ?NEW-VALUE?\n");
30109       rc = 1;
30110       goto meta_command_exit;
30111     }else{
30112       int iLimit = -1;
30113       n2 = strlen30(azArg[1]);
30114       for(i=0; i<ArraySize(aLimit); i++){
30115         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
30116           if( iLimit<0 ){
30117             iLimit = i;
30118           }else{
30119             sqlite3_fprintf(stderr,"ambiguous limit: \"%s\"\n", azArg[1]);
30120             rc = 1;
30121             goto meta_command_exit;
30122           }
30123         }
30124       }
30125       if( iLimit<0 ){
30126         sqlite3_fprintf(stderr,"unknown limit: \"%s\"\n"
30127               "enter \".limits\" with no arguments for a list.\n",
30128               azArg[1]);
30129         rc = 1;
30130         goto meta_command_exit;
30131       }
30132       if( nArg==3 ){
30133         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
30134                       (int)integerValue(azArg[2]));
30135       }
30136       sqlite3_fprintf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
30137             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
30138     }
30139   }else
30140 
30141   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
30142     open_db(p, 0);
30143     lintDotCommand(p, azArg, nArg);
30144   }else
30145 
30146 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
30147   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
30148     const char *zFile, *zProc;
30149     char *zErrMsg = 0;
30150     failIfSafeMode(p, "cannot run .load in safe mode");
30151     if( nArg<2 || azArg[1][0]==0 ){
30152       /* Must have a non-empty FILE. (Will not load self.) */
30153       eputz("Usage: .load FILE ?ENTRYPOINT?\n");
30154       rc = 1;
30155       goto meta_command_exit;
30156     }
30157     zFile = azArg[1];
30158     zProc = nArg>=3 ? azArg[2] : 0;
30159     open_db(p, 0);
30160     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
30161     if( rc!=SQLITE_OK ){
30162       shellEmitError(zErrMsg);
30163       sqlite3_free(zErrMsg);
30164       rc = 1;
30165     }
30166   }else
30167 #endif
30168 
30169   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
30170     if( nArg!=2 ){
30171       eputz("Usage: .log FILENAME\n");
30172       rc = 1;
30173     }else{
30174       const char *zFile = azArg[1];
30175       if( p->bSafeMode
30176        && cli_strcmp(zFile,"on")!=0
30177        && cli_strcmp(zFile,"off")!=0
30178       ){
30179         sputz(stdout, "cannot set .log to anything other"
30180               " than \"on\" or \"off\"\n");
30181         zFile = "off";
30182       }
30183       output_file_close(p->pLog);
30184       if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
30185       p->pLog = output_file_open(zFile);
30186     }
30187   }else
30188 
30189   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
30190     const char *zMode = 0;
30191     const char *zTabname = 0;
30192     int i, n2;
30193     int chng = 0;       /* 0x01:  change to cmopts.  0x02:  Any other change */
30194     ColModeOpts cmOpts = ColModeOpts_default;
30195     for(i=1; i<nArg; i++){
30196       const char *z = azArg[i];
30197       if( optionMatch(z,"wrap") && i+1<nArg ){
30198         cmOpts.iWrap = integerValue(azArg[++i]);
30199         chng |= 1;
30200       }else if( optionMatch(z,"ww") ){
30201         cmOpts.bWordWrap = 1;
30202         chng |= 1;
30203       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
30204         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
30205         chng |= 1;
30206       }else if( optionMatch(z,"quote") ){
30207         cmOpts.bQuote = 1;
30208         chng |= 1;
30209       }else if( optionMatch(z,"noquote") ){
30210         cmOpts.bQuote = 0;
30211         chng |= 1;
30212       }else if( optionMatch(z,"escape") && i+1<nArg ){
30213         /* See similar code at tag-20250224-1 */
30214         const char *zEsc = azArg[++i];
30215         int k;
30216         for(k=0; k<ArraySize(shell_EscModeNames); k++){
30217           if( sqlite3_stricmp(zEsc,shell_EscModeNames[k])==0 ){
30218             p->eEscMode = k;
30219             chng |= 2;
30220             break;
30221           }
30222         }
30223         if( k>=ArraySize(shell_EscModeNames) ){
30224           sqlite3_fprintf(stderr, "unknown control character escape mode \"%s\""
30225                                   " - choices:", zEsc);
30226           for(k=0; k<ArraySize(shell_EscModeNames); k++){
30227             sqlite3_fprintf(stderr, " %s", shell_EscModeNames[k]);
30228           }
30229           sqlite3_fprintf(stderr, "\n");
30230           rc = 1;
30231           goto meta_command_exit;
30232         }
30233       }else if( zMode==0 ){
30234         zMode = z;
30235         /* Apply defaults for qbox pseudo-mode.  If that
30236          * overwrites already-set values, user was informed of this.
30237          */
30238         chng |= 1;
30239         if( cli_strcmp(z, "qbox")==0 ){
30240           ColModeOpts cmo = ColModeOpts_default_qbox;
30241           zMode = "box";
30242           cmOpts = cmo;
30243         }
30244       }else if( zTabname==0 ){
30245         zTabname = z;
30246       }else if( z[0]=='-' ){
30247         sqlite3_fprintf(stderr,"unknown option: %s\n", z);
30248         eputz("options:\n"
30249               "  --escape MODE\n"
30250               "  --noquote\n"
30251               "  --quote\n"
30252               "  --wordwrap on/off\n"
30253               "  --wrap N\n"
30254               "  --ww\n");
30255         rc = 1;
30256         goto meta_command_exit;
30257       }else{
30258         sqlite3_fprintf(stderr,"extra argument: \"%s\"\n", z);
30259         rc = 1;
30260         goto meta_command_exit;
30261       }
30262     }
30263     if( !chng ){
30264       if( p->mode==MODE_Column
30265        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
30266       ){
30267         sqlite3_fprintf(p->out,
30268               "current output mode: %s --wrap %d --wordwrap %s "
30269               "--%squote --escape %s\n",
30270               modeDescr[p->mode], p->cmOpts.iWrap,
30271               p->cmOpts.bWordWrap ? "on" : "off",
30272               p->cmOpts.bQuote ? "" : "no",
30273               shell_EscModeNames[p->eEscMode]
30274         );
30275       }else{
30276         sqlite3_fprintf(p->out,
30277               "current output mode: %s --escape %s\n",
30278               modeDescr[p->mode],
30279               shell_EscModeNames[p->eEscMode]
30280         );
30281       }
30282     }
30283     if( zMode==0 ){
30284       zMode = modeDescr[p->mode];
30285       if( (chng&1)==0 ) cmOpts = p->cmOpts;
30286     }
30287     n2 = strlen30(zMode);
30288     if( cli_strncmp(zMode,"lines",n2)==0 ){
30289       p->mode = MODE_Line;
30290       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
30291     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
30292       p->mode = MODE_Column;
30293       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
30294         p->showHeader = 1;
30295       }
30296       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
30297       p->cmOpts = cmOpts;
30298     }else if( cli_strncmp(zMode,"list",n2)==0 ){
30299       p->mode = MODE_List;
30300       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
30301       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
30302     }else if( cli_strncmp(zMode,"html",n2)==0 ){
30303       p->mode = MODE_Html;
30304     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
30305       p->mode = MODE_Tcl;
30306       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
30307       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
30308     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
30309       p->mode = MODE_Csv;
30310       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
30311       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
30312     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
30313       p->mode = MODE_List;
30314       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
30315     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
30316       p->mode = MODE_Insert;
30317       set_table_name(p, zTabname ? zTabname : "table");
30318       if( p->eEscMode==SHELL_ESC_OFF ){
30319         ShellSetFlag(p, SHFLG_Newlines);
30320       }else{
30321         ShellClearFlag(p, SHFLG_Newlines);
30322       }
30323     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
30324       p->mode = MODE_Quote;
30325       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
30326       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
30327     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
30328       p->mode = MODE_Ascii;
30329       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
30330       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
30331     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
30332       p->mode = MODE_Markdown;
30333       p->cmOpts = cmOpts;
30334     }else if( cli_strncmp(zMode,"table",n2)==0 ){
30335       p->mode = MODE_Table;
30336       p->cmOpts = cmOpts;
30337     }else if( cli_strncmp(zMode,"box",n2)==0 ){
30338       p->mode = MODE_Box;
30339       p->cmOpts = cmOpts;
30340     }else if( cli_strncmp(zMode,"count",n2)==0 ){
30341       p->mode = MODE_Count;
30342     }else if( cli_strncmp(zMode,"off",n2)==0 ){
30343       p->mode = MODE_Off;
30344     }else if( cli_strncmp(zMode,"json",n2)==0 ){
30345       p->mode = MODE_Json;
30346     }else{
30347       eputz("Error: mode should be one of: "
30348             "ascii box column csv html insert json line list markdown "
30349             "qbox quote table tabs tcl\n");
30350       rc = 1;
30351     }
30352     p->cMode = p->mode;
30353   }else
30354 
30355 #ifndef SQLITE_SHELL_FIDDLE
30356   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
30357     if( nArg!=2 ){
30358       eputz("Usage: .nonce NONCE\n");
30359       rc = 1;
30360     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
30361       sqlite3_fprintf(stderr,"line %d: incorrect nonce: \"%s\"\n",
30362             p->lineno, azArg[1]);
30363       exit(1);
30364     }else{
30365       p->bSafeMode = 0;
30366       return 0;  /* Return immediately to bypass the safe mode reset
30367                  ** at the end of this procedure */
30368     }
30369   }else
30370 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
30371 
30372   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
30373     if( nArg==2 ){
30374       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
30375                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
30376     }else{
30377       eputz("Usage: .nullvalue STRING\n");
30378       rc = 1;
30379     }
30380   }else
30381 
30382   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
30383     const char *zFN = 0;     /* Pointer to constant filename */
30384     char *zNewFilename = 0;  /* Name of the database file to open */
30385     int iName = 1;           /* Index in azArg[] of the filename */
30386     int newFlag = 0;         /* True to delete file before opening */
30387     int openMode = SHELL_OPEN_UNSPEC;
30388 
30389     /* Check for command-line arguments */
30390     for(iName=1; iName<nArg; iName++){
30391       const char *z = azArg[iName];
30392 #ifndef SQLITE_SHELL_FIDDLE
30393       if( optionMatch(z,"new") ){
30394         newFlag = 1;
30395 #ifdef SQLITE_HAVE_ZLIB
30396       }else if( optionMatch(z, "zip") ){
30397         openMode = SHELL_OPEN_ZIPFILE;
30398 #endif
30399       }else if( optionMatch(z, "append") ){
30400         openMode = SHELL_OPEN_APPENDVFS;
30401       }else if( optionMatch(z, "readonly") ){
30402         openMode = SHELL_OPEN_READONLY;
30403       }else if( optionMatch(z, "nofollow") ){
30404         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
30405 #ifndef SQLITE_OMIT_DESERIALIZE
30406       }else if( optionMatch(z, "deserialize") ){
30407         openMode = SHELL_OPEN_DESERIALIZE;
30408       }else if( optionMatch(z, "hexdb") ){
30409         openMode = SHELL_OPEN_HEXDB;
30410       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
30411         p->szMax = integerValue(azArg[++iName]);
30412 #endif /* SQLITE_OMIT_DESERIALIZE */
30413       }else
30414 #endif /* !SQLITE_SHELL_FIDDLE */
30415       if( z[0]=='-' ){
30416         sqlite3_fprintf(stderr,"unknown option: %s\n", z);
30417         rc = 1;
30418         goto meta_command_exit;
30419       }else if( zFN ){
30420         sqlite3_fprintf(stderr,"extra argument: \"%s\"\n", z);
30421         rc = 1;
30422         goto meta_command_exit;
30423       }else{
30424         zFN = z;
30425       }
30426     }
30427 
30428     /* Close the existing database */
30429     session_close_all(p, -1);
30430     close_db(p->db);
30431     p->db = 0;
30432     p->pAuxDb->zDbFilename = 0;
30433     sqlite3_free(p->pAuxDb->zFreeOnClose);
30434     p->pAuxDb->zFreeOnClose = 0;
30435     p->openMode = openMode;
30436     p->openFlags = 0;
30437     p->szMax = 0;
30438 
30439     /* If a filename is specified, try to open it first */
30440     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
30441       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
30442 #ifndef SQLITE_SHELL_FIDDLE
30443       if( p->bSafeMode
30444        && p->openMode!=SHELL_OPEN_HEXDB
30445        && zFN
30446        && cli_strcmp(zFN,":memory:")!=0
30447       ){
30448         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
30449       }
30450 #else
30451       /* WASM mode has its own sandboxed pseudo-filesystem. */
30452 #endif
30453       if( zFN ){
30454         zNewFilename = sqlite3_mprintf("%s", zFN);
30455         shell_check_oom(zNewFilename);
30456       }else{
30457         zNewFilename = 0;
30458       }
30459       p->pAuxDb->zDbFilename = zNewFilename;
30460       open_db(p, OPEN_DB_KEEPALIVE);
30461       if( p->db==0 ){
30462         sqlite3_fprintf(stderr,"Error: cannot open '%s'\n", zNewFilename);
30463         sqlite3_free(zNewFilename);
30464       }else{
30465         p->pAuxDb->zFreeOnClose = zNewFilename;
30466       }
30467     }
30468     if( p->db==0 ){
30469       /* As a fall-back open a TEMP database */
30470       p->pAuxDb->zDbFilename = 0;
30471       open_db(p, 0);
30472     }
30473   }else
30474 
30475 #ifndef SQLITE_SHELL_FIDDLE
30476   if( (c=='o'
30477         && (cli_strncmp(azArg[0], "output", n)==0
30478             || cli_strncmp(azArg[0], "once", n)==0))
30479    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
30480    || (c=='w' && n==3 && cli_strcmp(azArg[0],"www")==0)
30481   ){
30482     char *zFile = 0;
30483     int i;
30484     int eMode = 0;          /* 0: .outout/.once, 'x'=.excel, 'w'=.www */
30485     int bOnce = 0;          /* 0: .output, 1: .once, 2: .excel/.www */
30486     int bPlain = 0;         /* --plain option */
30487     static const char *zBomUtf8 = "\357\273\277";
30488     const char *zBom = 0;
30489 
30490     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
30491     if( c=='e' ){
30492       eMode = 'x';
30493       bOnce = 2;
30494     }else if( c=='w' ){
30495       eMode = 'w';
30496       bOnce = 2;
30497     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
30498       bOnce = 1;
30499     }
30500     for(i=1; i<nArg; i++){
30501       char *z = azArg[i];
30502       if( z[0]=='-' ){
30503         if( z[1]=='-' ) z++;
30504         if( cli_strcmp(z,"-bom")==0 ){
30505           zBom = zBomUtf8;
30506         }else if( cli_strcmp(z,"-plain")==0 ){
30507           bPlain = 1;
30508         }else if( c=='o' && cli_strcmp(z,"-x")==0 ){
30509           eMode = 'x';  /* spreadsheet */
30510         }else if( c=='o' && cli_strcmp(z,"-e")==0 ){
30511           eMode = 'e';  /* text editor */
30512         }else if( c=='o' && cli_strcmp(z,"-w")==0 ){
30513           eMode = 'w';  /* Web browser */
30514         }else{
30515           sqlite3_fprintf(p->out,
30516                           "ERROR: unknown option: \"%s\". Usage:\n", azArg[i]);
30517           showHelp(p->out, azArg[0]);
30518           rc = 1;
30519           goto meta_command_exit;
30520         }
30521       }else if( zFile==0 && eMode==0 ){
30522         if( cli_strcmp(z, "off")==0 ){
30523 #ifdef _WIN32
30524           zFile = sqlite3_mprintf("nul");
30525 #else
30526           zFile = sqlite3_mprintf("/dev/null");
30527 #endif
30528         }else{
30529           zFile = sqlite3_mprintf("%s", z);
30530         }
30531         if( zFile && zFile[0]=='|' ){
30532           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
30533           break;
30534         }
30535       }else{
30536         sqlite3_fprintf(p->out,
30537             "ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
30538         showHelp(p->out, azArg[0]);
30539         rc = 1;
30540         sqlite3_free(zFile);
30541         goto meta_command_exit;
30542       }
30543     }
30544     if( zFile==0 ){
30545       zFile = sqlite3_mprintf("stdout");
30546     }
30547     shell_check_oom(zFile);
30548     if( bOnce ){
30549       p->outCount = 2;
30550     }else{
30551       p->outCount = 0;
30552     }
30553     output_reset(p);
30554 #ifndef SQLITE_NOHAVE_SYSTEM
30555     if( eMode=='e' || eMode=='x' || eMode=='w' ){
30556       p->doXdgOpen = 1;
30557       outputModePush(p);
30558       if( eMode=='x' ){
30559         /* spreadsheet mode.  Output as CSV. */
30560         newTempFile(p, "csv");
30561         ShellClearFlag(p, SHFLG_Echo);
30562         p->mode = MODE_Csv;
30563         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
30564         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
30565 #ifdef _WIN32
30566         zBom = zBomUtf8;  /* Always include the BOM on Windows, as Excel does
30567                           ** not work without it. */
30568 #endif
30569       }else if( eMode=='w' ){
30570         /* web-browser mode. */
30571         newTempFile(p, "html");
30572         if( !bPlain ) p->mode = MODE_Www;
30573       }else{
30574         /* text editor mode */
30575         newTempFile(p, "txt");
30576       }
30577       sqlite3_free(zFile);
30578       zFile = sqlite3_mprintf("%s", p->zTempFile);
30579     }
30580 #endif /* SQLITE_NOHAVE_SYSTEM */
30581     shell_check_oom(zFile);
30582     if( zFile[0]=='|' ){
30583 #ifdef SQLITE_OMIT_POPEN
30584       eputz("Error: pipes are not supported in this OS\n");
30585       rc = 1;
30586       output_redir(p, stdout);
30587 #else
30588       FILE *pfPipe = sqlite3_popen(zFile + 1, "w");
30589       if( pfPipe==0 ){
30590         assert( stderr!=NULL );
30591         sqlite3_fprintf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
30592         rc = 1;
30593       }else{
30594         output_redir(p, pfPipe);
30595         if( zBom ) sqlite3_fputs(zBom, pfPipe);
30596         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
30597       }
30598 #endif
30599     }else{
30600       FILE *pfFile = output_file_open(zFile);
30601       if( pfFile==0 ){
30602         if( cli_strcmp(zFile,"off")!=0 ){
30603          assert( stderr!=NULL );
30604          sqlite3_fprintf(stderr,"Error: cannot write to \"%s\"\n", zFile);
30605         }
30606         rc = 1;
30607       } else {
30608         output_redir(p, pfFile);
30609         if( zBom ) sqlite3_fputs(zBom, pfFile);
30610         if( bPlain && eMode=='w' ){
30611           sqlite3_fputs(
30612             "<!DOCTYPE html>\n<BODY>\n<PLAINTEXT>\n",
30613             pfFile
30614           );
30615         }
30616         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
30617       }
30618     }
30619     sqlite3_free(zFile);
30620   }else
30621 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
30622 
30623   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
30624     open_db(p,0);
30625     if( nArg<=1 ) goto parameter_syntax_error;
30626 
30627     /* .parameter clear
30628     ** Clear all bind parameters by dropping the TEMP table that holds them.
30629     */
30630     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
30631       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
30632                    0, 0, 0);
30633     }else
30634 
30635     /* .parameter list
30636     ** List all bind parameters.
30637     */
30638     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
30639       sqlite3_stmt *pStmt = 0;
30640       int rx;
30641       int len = 0;
30642       rx = sqlite3_prepare_v2(p->db,
30643              "SELECT max(length(key)) "
30644              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
30645       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
30646         len = sqlite3_column_int(pStmt, 0);
30647         if( len>40 ) len = 40;
30648       }
30649       sqlite3_finalize(pStmt);
30650       pStmt = 0;
30651       if( len ){
30652         rx = sqlite3_prepare_v2(p->db,
30653              "SELECT key, quote(value) "
30654              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
30655         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
30656           sqlite3_fprintf(p->out,
30657                 "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
30658                 sqlite3_column_text(pStmt,1));
30659         }
30660         sqlite3_finalize(pStmt);
30661       }
30662     }else
30663 
30664     /* .parameter init
30665     ** Make sure the TEMP table used to hold bind parameters exists.
30666     ** Create it if necessary.
30667     */
30668     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
30669       bind_table_init(p);
30670     }else
30671 
30672     /* .parameter set NAME VALUE
30673     ** Set or reset a bind parameter.  NAME should be the full parameter
30674     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
30675     ** VALUE can be in either SQL literal notation, or if not it will be
30676     ** understood to be a text string.
30677     */
30678     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
30679       int rx;
30680       char *zSql;
30681       sqlite3_stmt *pStmt;
30682       const char *zKey = azArg[2];
30683       const char *zValue = azArg[3];
30684       bind_table_init(p);
30685       zSql = sqlite3_mprintf(
30686                   "REPLACE INTO temp.sqlite_parameters(key,value)"
30687                   "VALUES(%Q,%s);", zKey, zValue);
30688       shell_check_oom(zSql);
30689       pStmt = 0;
30690       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
30691       sqlite3_free(zSql);
30692       if( rx!=SQLITE_OK ){
30693         sqlite3_finalize(pStmt);
30694         pStmt = 0;
30695         zSql = sqlite3_mprintf(
30696                    "REPLACE INTO temp.sqlite_parameters(key,value)"
30697                    "VALUES(%Q,%Q);", zKey, zValue);
30698         shell_check_oom(zSql);
30699         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
30700         sqlite3_free(zSql);
30701         if( rx!=SQLITE_OK ){
30702           sqlite3_fprintf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
30703           sqlite3_finalize(pStmt);
30704           pStmt = 0;
30705           rc = 1;
30706         }
30707       }
30708       bind_prepared_stmt(p, pStmt);
30709       sqlite3_step(pStmt);
30710       sqlite3_finalize(pStmt);
30711     }else
30712 
30713     /* .parameter unset NAME
30714     ** Remove the NAME binding from the parameter binding table, if it
30715     ** exists.
30716     */
30717     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
30718       char *zSql = sqlite3_mprintf(
30719           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
30720       shell_check_oom(zSql);
30721       sqlite3_exec(p->db, zSql, 0, 0, 0);
30722       sqlite3_free(zSql);
30723     }else
30724     /* If no command name matches, show a syntax error */
30725     parameter_syntax_error:
30726     showHelp(p->out, "parameter");
30727   }else
30728 
30729   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
30730     int i;
30731     for(i=1; i<nArg; i++){
30732       if( i>1 ) sqlite3_fputs(" ", p->out);
30733       sqlite3_fputs(azArg[i], p->out);
30734     }
30735     sqlite3_fputs("\n", p->out);
30736   }else
30737 
30738 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
30739   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
30740     int i;
30741     int nn = 0;
30742     p->flgProgress = 0;
30743     p->mxProgress = 0;
30744     p->nProgress = 0;
30745     for(i=1; i<nArg; i++){
30746       const char *z = azArg[i];
30747       if( z[0]=='-' ){
30748         z++;
30749         if( z[0]=='-' ) z++;
30750         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
30751           p->flgProgress |= SHELL_PROGRESS_QUIET;
30752           continue;
30753         }
30754         if( cli_strcmp(z,"reset")==0 ){
30755           p->flgProgress |= SHELL_PROGRESS_RESET;
30756           continue;
30757         }
30758         if( cli_strcmp(z,"once")==0 ){
30759           p->flgProgress |= SHELL_PROGRESS_ONCE;
30760           continue;
30761         }
30762         if( cli_strcmp(z,"limit")==0 ){
30763           if( i+1>=nArg ){
30764             eputz("Error: missing argument on --limit\n");
30765             rc = 1;
30766             goto meta_command_exit;
30767           }else{
30768             p->mxProgress = (int)integerValue(azArg[++i]);
30769           }
30770           continue;
30771         }
30772         sqlite3_fprintf(stderr,"Error: unknown option: \"%s\"\n", azArg[i]);
30773         rc = 1;
30774         goto meta_command_exit;
30775       }else{
30776         nn = (int)integerValue(z);
30777       }
30778     }
30779     open_db(p, 0);
30780     sqlite3_progress_handler(p->db, nn, progress_handler, p);
30781   }else
30782 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
30783 
30784   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
30785     if( nArg >= 2) {
30786       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
30787     }
30788     if( nArg >= 3) {
30789       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
30790     }
30791   }else
30792 
30793 #ifndef SQLITE_SHELL_FIDDLE
30794   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
30795     rc = 2;
30796   }else
30797 #endif
30798 
30799 #ifndef SQLITE_SHELL_FIDDLE
30800   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
30801     FILE *inSaved = p->in;
30802     int savedLineno = p->lineno;
30803     failIfSafeMode(p, "cannot run .read in safe mode");
30804     if( nArg!=2 ){
30805       eputz("Usage: .read FILE\n");
30806       rc = 1;
30807       goto meta_command_exit;
30808     }
30809     if( azArg[1][0]=='|' ){
30810 #ifdef SQLITE_OMIT_POPEN
30811       eputz("Error: pipes are not supported in this OS\n");
30812       rc = 1;
30813 #else
30814       p->in = sqlite3_popen(azArg[1]+1, "r");
30815       if( p->in==0 ){
30816         sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
30817         rc = 1;
30818       }else{
30819         rc = process_input(p);
30820         pclose(p->in);
30821       }
30822 #endif
30823     }else if( (p->in = openChrSource(azArg[1]))==0 ){
30824       sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
30825       rc = 1;
30826     }else{
30827       rc = process_input(p);
30828       fclose(p->in);
30829     }
30830     p->in = inSaved;
30831     p->lineno = savedLineno;
30832   }else
30833 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
30834 
30835 #ifndef SQLITE_SHELL_FIDDLE
30836   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
30837     const char *zSrcFile;
30838     const char *zDb;
30839     sqlite3 *pSrc;
30840     sqlite3_backup *pBackup;
30841     int nTimeout = 0;
30842 
30843     failIfSafeMode(p, "cannot run .restore in safe mode");
30844     if( nArg==2 ){
30845       zSrcFile = azArg[1];
30846       zDb = "main";
30847     }else if( nArg==3 ){
30848       zSrcFile = azArg[2];
30849       zDb = azArg[1];
30850     }else{
30851       eputz("Usage: .restore ?DB? FILE\n");
30852       rc = 1;
30853       goto meta_command_exit;
30854     }
30855     rc = sqlite3_open(zSrcFile, &pSrc);
30856     if( rc!=SQLITE_OK ){
30857       sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", zSrcFile);
30858       close_db(pSrc);
30859       return 1;
30860     }
30861     open_db(p, 0);
30862     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
30863     if( pBackup==0 ){
30864       shellDatabaseError(p->db);
30865       close_db(pSrc);
30866       return 1;
30867     }
30868     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
30869           || rc==SQLITE_BUSY  ){
30870       if( rc==SQLITE_BUSY ){
30871         if( nTimeout++ >= 3 ) break;
30872         sqlite3_sleep(100);
30873       }
30874     }
30875     sqlite3_backup_finish(pBackup);
30876     if( rc==SQLITE_DONE ){
30877       rc = 0;
30878     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
30879       eputz("Error: source database is busy\n");
30880       rc = 1;
30881     }else{
30882       shellDatabaseError(p->db);
30883       rc = 1;
30884     }
30885     close_db(pSrc);
30886   }else
30887 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
30888 
30889   if( c=='s' &&
30890      (cli_strncmp(azArg[0], "scanstats",  n)==0 ||
30891       cli_strncmp(azArg[0], "scanstatus", n)==0)
30892   ){
30893     if( nArg==2 ){
30894       if( cli_strcmp(azArg[1], "vm")==0 ){
30895         p->scanstatsOn = 3;
30896       }else
30897       if( cli_strcmp(azArg[1], "est")==0 ){
30898         p->scanstatsOn = 2;
30899       }else{
30900         p->scanstatsOn = (u8)booleanValue(azArg[1]);
30901       }
30902       open_db(p, 0);
30903       sqlite3_db_config(
30904           p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
30905       );
30906 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
30907       eputz("Warning: .scanstats not available in this build.\n");
30908 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
30909       if( p->scanstatsOn==3 ){
30910         eputz("Warning: \".scanstats vm\" not available in this build.\n");
30911       }
30912 #endif
30913     }else{
30914       eputz("Usage: .scanstats on|off|est\n");
30915       rc = 1;
30916     }
30917   }else
30918 
30919   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
30920     ShellText sSelect;
30921     ShellState data;
30922     char *zErrMsg = 0;
30923     const char *zDiv = "(";
30924     const char *zName = 0;
30925     int iSchema = 0;
30926     int bDebug = 0;
30927     int bNoSystemTabs = 0;
30928     int ii;
30929 
30930     open_db(p, 0);
30931     memcpy(&data, p, sizeof(data));
30932     data.showHeader = 0;
30933     data.cMode = data.mode = MODE_Semi;
30934     initText(&sSelect);
30935     for(ii=1; ii<nArg; ii++){
30936       if( optionMatch(azArg[ii],"indent") ){
30937         data.cMode = data.mode = MODE_Pretty;
30938       }else if( optionMatch(azArg[ii],"debug") ){
30939         bDebug = 1;
30940       }else if( optionMatch(azArg[ii],"nosys") ){
30941         bNoSystemTabs = 1;
30942       }else if( azArg[ii][0]=='-' ){
30943         sqlite3_fprintf(stderr,"Unknown option: \"%s\"\n", azArg[ii]);
30944         rc = 1;
30945         goto meta_command_exit;
30946       }else if( zName==0 ){
30947         zName = azArg[ii];
30948       }else{
30949         eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
30950         rc = 1;
30951         goto meta_command_exit;
30952       }
30953     }
30954     if( zName!=0 ){
30955       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
30956                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
30957                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
30958                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
30959       if( isSchema ){
30960         char *new_argv[2], *new_colv[2];
30961         new_argv[0] = sqlite3_mprintf(
30962                       "CREATE TABLE %s (\n"
30963                       "  type text,\n"
30964                       "  name text,\n"
30965                       "  tbl_name text,\n"
30966                       "  rootpage integer,\n"
30967                       "  sql text\n"
30968                       ")", zName);
30969         shell_check_oom(new_argv[0]);
30970         new_argv[1] = 0;
30971         new_colv[0] = "sql";
30972         new_colv[1] = 0;
30973         callback(&data, 1, new_argv, new_colv);
30974         sqlite3_free(new_argv[0]);
30975       }
30976     }
30977     if( zDiv ){
30978       sqlite3_stmt *pStmt = 0;
30979       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
30980                               -1, &pStmt, 0);
30981       if( rc ){
30982         shellDatabaseError(p->db);
30983         sqlite3_finalize(pStmt);
30984         rc = 1;
30985         goto meta_command_exit;
30986       }
30987       appendText(&sSelect, "SELECT sql FROM", 0);
30988       iSchema = 0;
30989       while( sqlite3_step(pStmt)==SQLITE_ROW ){
30990         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
30991         char zScNum[30];
30992         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
30993         appendText(&sSelect, zDiv, 0);
30994         zDiv = " UNION ALL ";
30995         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
30996         if( sqlite3_stricmp(zDb, "main")!=0 ){
30997           appendText(&sSelect, zDb, '\'');
30998         }else{
30999           appendText(&sSelect, "NULL", 0);
31000         }
31001         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
31002         appendText(&sSelect, zScNum, 0);
31003         appendText(&sSelect, " AS snum, ", 0);
31004         appendText(&sSelect, zDb, '\'');
31005         appendText(&sSelect, " AS sname FROM ", 0);
31006         appendText(&sSelect, zDb, quoteChar(zDb));
31007         appendText(&sSelect, ".sqlite_schema", 0);
31008       }
31009       sqlite3_finalize(pStmt);
31010 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
31011       if( zName ){
31012         appendText(&sSelect,
31013            " UNION ALL SELECT shell_module_schema(name),"
31014            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
31015         0);
31016       }
31017 #endif
31018       appendText(&sSelect, ") WHERE ", 0);
31019       if( zName ){
31020         char *zQarg = sqlite3_mprintf("%Q", zName);
31021         int bGlob;
31022         shell_check_oom(zQarg);
31023         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
31024                 strchr(zName, '[') != 0;
31025         if( strchr(zName, '.') ){
31026           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
31027         }else{
31028           appendText(&sSelect, "lower(tbl_name)", 0);
31029         }
31030         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
31031         appendText(&sSelect, zQarg, 0);
31032         if( !bGlob ){
31033           appendText(&sSelect, " ESCAPE '\\' ", 0);
31034         }
31035         appendText(&sSelect, " AND ", 0);
31036         sqlite3_free(zQarg);
31037       }
31038       if( bNoSystemTabs ){
31039         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
31040       }
31041       appendText(&sSelect, "sql IS NOT NULL"
31042                            " ORDER BY snum, rowid", 0);
31043       if( bDebug ){
31044         sqlite3_fprintf(p->out, "SQL: %s;\n", sSelect.z);
31045       }else{
31046         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
31047       }
31048       freeText(&sSelect);
31049     }
31050     if( zErrMsg ){
31051       shellEmitError(zErrMsg);
31052       sqlite3_free(zErrMsg);
31053       rc = 1;
31054     }else if( rc != SQLITE_OK ){
31055       eputz("Error: querying schema information\n");
31056       rc = 1;
31057     }else{
31058       rc = 0;
31059     }
31060   }else
31061 
31062   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
31063    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
31064   ){
31065     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
31066     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
31067   }else
31068 
31069 #if defined(SQLITE_ENABLE_SESSION)
31070   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
31071     struct AuxDb *pAuxDb = p->pAuxDb;
31072     OpenSession *pSession = &pAuxDb->aSession[0];
31073     char **azCmd = &azArg[1];
31074     int iSes = 0;
31075     int nCmd = nArg - 1;
31076     int i;
31077     if( nArg<=1 ) goto session_syntax_error;
31078     open_db(p, 0);
31079     if( nArg>=3 ){
31080       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
31081         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
31082       }
31083       if( iSes<pAuxDb->nSession ){
31084         pSession = &pAuxDb->aSession[iSes];
31085         azCmd++;
31086         nCmd--;
31087       }else{
31088         pSession = &pAuxDb->aSession[0];
31089         iSes = 0;
31090       }
31091     }
31092 
31093     /* .session attach TABLE
31094     ** Invoke the sqlite3session_attach() interface to attach a particular
31095     ** table so that it is never filtered.
31096     */
31097     if( cli_strcmp(azCmd[0],"attach")==0 ){
31098       if( nCmd!=2 ) goto session_syntax_error;
31099       if( pSession->p==0 ){
31100         session_not_open:
31101         eputz("ERROR: No sessions are open\n");
31102       }else{
31103         rc = sqlite3session_attach(pSession->p, azCmd[1]);
31104         if( rc ){
31105           sqlite3_fprintf(stderr,
31106                "ERROR: sqlite3session_attach() returns %d\n",rc);
31107           rc = 0;
31108         }
31109       }
31110     }else
31111 
31112     /* .session changeset FILE
31113     ** .session patchset FILE
31114     ** Write a changeset or patchset into a file.  The file is overwritten.
31115     */
31116     if( cli_strcmp(azCmd[0],"changeset")==0
31117      || cli_strcmp(azCmd[0],"patchset")==0
31118     ){
31119       FILE *out = 0;
31120       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
31121       if( nCmd!=2 ) goto session_syntax_error;
31122       if( pSession->p==0 ) goto session_not_open;
31123       out = sqlite3_fopen(azCmd[1], "wb");
31124       if( out==0 ){
31125         sqlite3_fprintf(stderr,"ERROR: cannot open \"%s\" for writing\n",
31126               azCmd[1]);
31127       }else{
31128         int szChng;
31129         void *pChng;
31130         if( azCmd[0][0]=='c' ){
31131           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
31132         }else{
31133           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
31134         }
31135         if( rc ){
31136           sqlite3_fprintf(stdout, "Error: error code %d\n", rc);
31137           rc = 0;
31138         }
31139         if( pChng
31140           && fwrite(pChng, szChng, 1, out)!=1 ){
31141           sqlite3_fprintf(stderr,
31142               "ERROR: Failed to write entire %d-byte output\n", szChng);
31143         }
31144         sqlite3_free(pChng);
31145         fclose(out);
31146       }
31147     }else
31148 
31149     /* .session close
31150     ** Close the identified session
31151     */
31152     if( cli_strcmp(azCmd[0], "close")==0 ){
31153       if( nCmd!=1 ) goto session_syntax_error;
31154       if( pAuxDb->nSession ){
31155         session_close(pSession);
31156         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
31157       }
31158     }else
31159 
31160     /* .session enable ?BOOLEAN?
31161     ** Query or set the enable flag
31162     */
31163     if( cli_strcmp(azCmd[0], "enable")==0 ){
31164       int ii;
31165       if( nCmd>2 ) goto session_syntax_error;
31166       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
31167       if( pAuxDb->nSession ){
31168         ii = sqlite3session_enable(pSession->p, ii);
31169         sqlite3_fprintf(p->out,
31170             "session %s enable flag = %d\n", pSession->zName, ii);
31171       }
31172     }else
31173 
31174     /* .session filter GLOB ....
31175     ** Set a list of GLOB patterns of table names to be excluded.
31176     */
31177     if( cli_strcmp(azCmd[0], "filter")==0 ){
31178       int ii, nByte;
31179       if( nCmd<2 ) goto session_syntax_error;
31180       if( pAuxDb->nSession ){
31181         for(ii=0; ii<pSession->nFilter; ii++){
31182           sqlite3_free(pSession->azFilter[ii]);
31183         }
31184         sqlite3_free(pSession->azFilter);
31185         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
31186         pSession->azFilter = sqlite3_malloc( nByte );
31187         shell_check_oom( pSession->azFilter );
31188         for(ii=1; ii<nCmd; ii++){
31189           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
31190           shell_check_oom(x);
31191         }
31192         pSession->nFilter = ii-1;
31193       }
31194     }else
31195 
31196     /* .session indirect ?BOOLEAN?
31197     ** Query or set the indirect flag
31198     */
31199     if( cli_strcmp(azCmd[0], "indirect")==0 ){
31200       int ii;
31201       if( nCmd>2 ) goto session_syntax_error;
31202       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
31203       if( pAuxDb->nSession ){
31204         ii = sqlite3session_indirect(pSession->p, ii);
31205         sqlite3_fprintf(p->out,
31206             "session %s indirect flag = %d\n", pSession->zName, ii);
31207       }
31208     }else
31209 
31210     /* .session isempty
31211     ** Determine if the session is empty
31212     */
31213     if( cli_strcmp(azCmd[0], "isempty")==0 ){
31214       int ii;
31215       if( nCmd!=1 ) goto session_syntax_error;
31216       if( pAuxDb->nSession ){
31217         ii = sqlite3session_isempty(pSession->p);
31218         sqlite3_fprintf(p->out,
31219              "session %s isempty flag = %d\n", pSession->zName, ii);
31220       }
31221     }else
31222 
31223     /* .session list
31224     ** List all currently open sessions
31225     */
31226     if( cli_strcmp(azCmd[0],"list")==0 ){
31227       for(i=0; i<pAuxDb->nSession; i++){
31228         sqlite3_fprintf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
31229       }
31230     }else
31231 
31232     /* .session open DB NAME
31233     ** Open a new session called NAME on the attached database DB.
31234     ** DB is normally "main".
31235     */
31236     if( cli_strcmp(azCmd[0],"open")==0 ){
31237       char *zName;
31238       if( nCmd!=3 ) goto session_syntax_error;
31239       zName = azCmd[2];
31240       if( zName[0]==0 ) goto session_syntax_error;
31241       for(i=0; i<pAuxDb->nSession; i++){
31242         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
31243           sqlite3_fprintf(stderr,"Session \"%s\" already exists\n", zName);
31244           goto meta_command_exit;
31245         }
31246       }
31247       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
31248         sqlite3_fprintf(stderr,
31249            "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
31250         goto meta_command_exit;
31251       }
31252       pSession = &pAuxDb->aSession[pAuxDb->nSession];
31253       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
31254       if( rc ){
31255         sqlite3_fprintf(stderr,"Cannot open session: error code=%d\n", rc);
31256         rc = 0;
31257         goto meta_command_exit;
31258       }
31259       pSession->nFilter = 0;
31260       sqlite3session_table_filter(pSession->p, session_filter, pSession);
31261       pAuxDb->nSession++;
31262       pSession->zName = sqlite3_mprintf("%s", zName);
31263       shell_check_oom(pSession->zName);
31264     }else
31265     /* If no command name matches, show a syntax error */
31266     session_syntax_error:
31267     showHelp(p->out, "session");
31268   }else
31269 #endif
31270 
31271 #ifdef SQLITE_DEBUG
31272   /* Undocumented commands for internal testing.  Subject to change
31273   ** without notice. */
31274   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
31275     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
31276       int i, v;
31277       for(i=1; i<nArg; i++){
31278         v = booleanValue(azArg[i]);
31279         sqlite3_fprintf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
31280       }
31281     }
31282     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
31283       int i; sqlite3_int64 v;
31284       for(i=1; i<nArg; i++){
31285         char zBuf[200];
31286         v = integerValue(azArg[i]);
31287         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
31288         sqlite3_fputs(zBuf, p->out);
31289       }
31290     }
31291   }else
31292 #endif
31293 
31294   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
31295     int bIsInit = 0;         /* True to initialize the SELFTEST table */
31296     int bVerbose = 0;        /* Verbose output */
31297     int bSelftestExists;     /* True if SELFTEST already exists */
31298     int i, k;                /* Loop counters */
31299     int nTest = 0;           /* Number of tests runs */
31300     int nErr = 0;            /* Number of errors seen */
31301     ShellText str;           /* Answer for a query */
31302     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
31303 
31304     open_db(p,0);
31305     for(i=1; i<nArg; i++){
31306       const char *z = azArg[i];
31307       if( z[0]=='-' && z[1]=='-' ) z++;
31308       if( cli_strcmp(z,"-init")==0 ){
31309         bIsInit = 1;
31310       }else
31311       if( cli_strcmp(z,"-v")==0 ){
31312         bVerbose++;
31313       }else
31314       {
31315         sqlite3_fprintf(stderr,
31316               "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
31317         sqlite3_fputs("Should be one of: --init -v\n", stderr);
31318         rc = 1;
31319         goto meta_command_exit;
31320       }
31321     }
31322     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
31323            != SQLITE_OK ){
31324       bSelftestExists = 0;
31325     }else{
31326       bSelftestExists = 1;
31327     }
31328     if( bIsInit ){
31329       createSelftestTable(p);
31330       bSelftestExists = 1;
31331     }
31332     initText(&str);
31333     appendText(&str, "x", 0);
31334     for(k=bSelftestExists; k>=0; k--){
31335       if( k==1 ){
31336         rc = sqlite3_prepare_v2(p->db,
31337             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
31338             -1, &pStmt, 0);
31339       }else{
31340         rc = sqlite3_prepare_v2(p->db,
31341           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
31342           "      (1,'run','PRAGMA integrity_check','ok')",
31343           -1, &pStmt, 0);
31344       }
31345       if( rc ){
31346         eputz("Error querying the selftest table\n");
31347         rc = 1;
31348         sqlite3_finalize(pStmt);
31349         goto meta_command_exit;
31350       }
31351       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
31352         int tno = sqlite3_column_int(pStmt, 0);
31353         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
31354         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
31355         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
31356 
31357         if( zOp==0 ) continue;
31358         if( zSql==0 ) continue;
31359         if( zAns==0 ) continue;
31360         k = 0;
31361         if( bVerbose>0 ){
31362           sqlite3_fprintf(stdout, "%d: %s %s\n", tno, zOp, zSql);
31363         }
31364         if( cli_strcmp(zOp,"memo")==0 ){
31365           sqlite3_fprintf(p->out, "%s\n", zSql);
31366         }else
31367         if( cli_strcmp(zOp,"run")==0 ){
31368           char *zErrMsg = 0;
31369           str.n = 0;
31370           str.z[0] = 0;
31371           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
31372           nTest++;
31373           if( bVerbose ){
31374             sqlite3_fprintf(p->out, "Result: %s\n", str.z);
31375           }
31376           if( rc || zErrMsg ){
31377             nErr++;
31378             rc = 1;
31379             sqlite3_fprintf(p->out, "%d: error-code-%d: %s\n", tno, rc,zErrMsg);
31380             sqlite3_free(zErrMsg);
31381           }else if( cli_strcmp(zAns,str.z)!=0 ){
31382             nErr++;
31383             rc = 1;
31384             sqlite3_fprintf(p->out, "%d: Expected: [%s]\n", tno, zAns);
31385             sqlite3_fprintf(p->out, "%d:      Got: [%s]\n", tno, str.z);
31386           }
31387         }
31388         else{
31389           sqlite3_fprintf(stderr,
31390                 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
31391           rc = 1;
31392           break;
31393         }
31394       } /* End loop over rows of content from SELFTEST */
31395       sqlite3_finalize(pStmt);
31396     } /* End loop over k */
31397     freeText(&str);
31398     sqlite3_fprintf(p->out, "%d errors out of %d tests\n", nErr, nTest);
31399   }else
31400 
31401   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
31402     if( nArg<2 || nArg>3 ){
31403       eputz("Usage: .separator COL ?ROW?\n");
31404       rc = 1;
31405     }
31406     if( nArg>=2 ){
31407       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
31408                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
31409     }
31410     if( nArg>=3 ){
31411       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
31412                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
31413     }
31414   }else
31415 
31416   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
31417     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
31418     int i;                   /* Loop counter */
31419     int bSchema = 0;         /* Also hash the schema */
31420     int bSeparate = 0;       /* Hash each table separately */
31421     int iSize = 224;         /* Hash algorithm to use */
31422     int bDebug = 0;          /* Only show the query that would have run */
31423     sqlite3_stmt *pStmt;     /* For querying tables names */
31424     char *zSql;              /* SQL to be run */
31425     char *zSep;              /* Separator */
31426     ShellText sSql;          /* Complete SQL for the query to run the hash */
31427     ShellText sQuery;        /* Set of queries used to read all content */
31428     open_db(p, 0);
31429     for(i=1; i<nArg; i++){
31430       const char *z = azArg[i];
31431       if( z[0]=='-' ){
31432         z++;
31433         if( z[0]=='-' ) z++;
31434         if( cli_strcmp(z,"schema")==0 ){
31435           bSchema = 1;
31436         }else
31437         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
31438          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
31439         ){
31440           iSize = atoi(&z[5]);
31441         }else
31442         if( cli_strcmp(z,"debug")==0 ){
31443           bDebug = 1;
31444         }else
31445         {
31446           sqlite3_fprintf(stderr,
31447                   "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
31448           showHelp(p->out, azArg[0]);
31449           rc = 1;
31450           goto meta_command_exit;
31451         }
31452       }else if( zLike ){
31453         eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
31454         rc = 1;
31455         goto meta_command_exit;
31456       }else{
31457         zLike = z;
31458         bSeparate = 1;
31459         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
31460       }
31461     }
31462     if( bSchema ){
31463       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
31464              " WHERE type='table' AND coalesce(rootpage,0)>1"
31465              " UNION ALL SELECT 'sqlite_schema'"
31466              " ORDER BY 1 collate nocase";
31467     }else{
31468       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
31469              " WHERE type='table' AND coalesce(rootpage,0)>1"
31470              " AND name NOT LIKE 'sqlite_%'"
31471              " ORDER BY 1 collate nocase";
31472     }
31473     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
31474     initText(&sQuery);
31475     initText(&sSql);
31476     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
31477     zSep = "VALUES(";
31478     while( SQLITE_ROW==sqlite3_step(pStmt) ){
31479       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
31480       if( zTab==0 ) continue;
31481       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
31482       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
31483         appendText(&sQuery,"SELECT * FROM ", 0);
31484         appendText(&sQuery,zTab,'"');
31485         appendText(&sQuery," NOT INDEXED;", 0);
31486       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
31487         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
31488                            " ORDER BY name;", 0);
31489       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
31490         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
31491                            " ORDER BY name;", 0);
31492       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
31493         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
31494                            " ORDER BY tbl,idx;", 0);
31495       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
31496         appendText(&sQuery, "SELECT * FROM ", 0);
31497         appendText(&sQuery, zTab, 0);
31498         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
31499       }
31500       appendText(&sSql, zSep, 0);
31501       appendText(&sSql, sQuery.z, '\'');
31502       sQuery.n = 0;
31503       appendText(&sSql, ",", 0);
31504       appendText(&sSql, zTab, '\'');
31505       zSep = "),(";
31506     }
31507     sqlite3_finalize(pStmt);
31508     if( bSeparate ){
31509       zSql = sqlite3_mprintf(
31510           "%s))"
31511           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
31512           "   FROM [sha3sum$query]",
31513           sSql.z, iSize);
31514     }else{
31515       zSql = sqlite3_mprintf(
31516           "%s))"
31517           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
31518           "   FROM [sha3sum$query]",
31519           sSql.z, iSize);
31520     }
31521     shell_check_oom(zSql);
31522     freeText(&sQuery);
31523     freeText(&sSql);
31524     if( bDebug ){
31525       sqlite3_fprintf(p->out, "%s\n", zSql);
31526     }else{
31527       shell_exec(p, zSql, 0);
31528     }
31529 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
31530     {
31531       int lrc;
31532       char *zRevText = /* Query for reversible to-blob-to-text check */
31533         "SELECT lower(name) as tname FROM sqlite_schema\n"
31534         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
31535         "AND name NOT LIKE 'sqlite_%%'%s\n"
31536         "ORDER BY 1 collate nocase";
31537       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
31538       zRevText = sqlite3_mprintf(
31539           /* lower-case query is first run, producing upper-case query. */
31540           "with tabcols as materialized(\n"
31541           "select tname, cname\n"
31542           "from ("
31543           " select printf('\"%%w\"',ss.tname) as tname,"
31544           " printf('\"%%w\"',ti.name) as cname\n"
31545           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
31546           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
31547           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
31548           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
31549           "FROM '||tname||' WHERE '\n"
31550           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
31551           "|| ' AND typeof('||cname||')=''text'' ',\n"
31552           "' OR ') as query, tname from tabcols group by tname)"
31553           , zRevText);
31554       shell_check_oom(zRevText);
31555       if( bDebug ) sqlite3_fprintf(p->out, "%s\n", zRevText);
31556       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
31557       if( lrc!=SQLITE_OK ){
31558         /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
31559         ** user does cruel and unnatural things like ".limit expr_depth 0". */
31560         rc = 1;
31561       }else{
31562         if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
31563         lrc = SQLITE_ROW==sqlite3_step(pStmt);
31564         if( lrc ){
31565           const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
31566           sqlite3_stmt *pCheckStmt;
31567           lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
31568           if( bDebug ) sqlite3_fprintf(p->out, "%s\n", zGenQuery);
31569           if( lrc!=SQLITE_OK ){
31570             rc = 1;
31571           }else{
31572             if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
31573               double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
31574               if( countIrreversible>0 ){
31575                 int sz = (int)(countIrreversible + 0.5);
31576                 sqlite3_fprintf(stderr,
31577                       "Digest includes %d invalidly encoded text field%s.\n",
31578                       sz, (sz>1)? "s": "");
31579               }
31580             }
31581             sqlite3_finalize(pCheckStmt);
31582           }
31583           sqlite3_finalize(pStmt);
31584         }
31585       }
31586       if( rc ) eputz(".sha3sum failed.\n");
31587       sqlite3_free(zRevText);
31588     }
31589 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
31590     sqlite3_free(zSql);
31591   }else
31592 
31593 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
31594   if( c=='s'
31595    && (cli_strncmp(azArg[0], "shell", n)==0
31596        || cli_strncmp(azArg[0],"system",n)==0)
31597   ){
31598     char *zCmd;
31599     int i, x;
31600     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
31601     if( nArg<2 ){
31602       eputz("Usage: .system COMMAND\n");
31603       rc = 1;
31604       goto meta_command_exit;
31605     }
31606     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
31607     for(i=2; i<nArg && zCmd!=0; i++){
31608       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
31609                              zCmd, azArg[i]);
31610     }
31611     /*consoleRestore();*/
31612     x = zCmd!=0 ? system(zCmd) : 1;
31613     /*consoleRenewSetup();*/
31614     sqlite3_free(zCmd);
31615     if( x ) sqlite3_fprintf(stderr,"System command returns %d\n", x);
31616   }else
31617 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
31618 
31619   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
31620     static const char *azBool[] = { "off", "on", "trigger", "full"};
31621     const char *zOut;
31622     int i;
31623     if( nArg!=1 ){
31624       eputz("Usage: .show\n");
31625       rc = 1;
31626       goto meta_command_exit;
31627     }
31628     sqlite3_fprintf(p->out, "%12.12s: %s\n","echo",
31629           azBool[ShellHasFlag(p, SHFLG_Echo)]);
31630     sqlite3_fprintf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
31631     sqlite3_fprintf(p->out, "%12.12s: %s\n","explain",
31632           p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
31633     sqlite3_fprintf(p->out, "%12.12s: %s\n","headers",
31634           azBool[p->showHeader!=0]);
31635     if( p->mode==MODE_Column
31636      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
31637     ){
31638       sqlite3_fprintf(p->out,
31639             "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
31640             modeDescr[p->mode], p->cmOpts.iWrap,
31641             p->cmOpts.bWordWrap ? "on" : "off",
31642             p->cmOpts.bQuote ? "" : "no");
31643     }else{
31644       sqlite3_fprintf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
31645     }
31646     sqlite3_fprintf(p->out, "%12.12s: ", "nullvalue");
31647     output_c_string(p->out, p->nullValue);
31648     sqlite3_fputs("\n", p->out);
31649     sqlite3_fprintf(p->out, "%12.12s: %s\n","output",
31650           strlen30(p->outfile) ? p->outfile : "stdout");
31651     sqlite3_fprintf(p->out, "%12.12s: ", "colseparator");
31652     output_c_string(p->out, p->colSeparator);
31653     sqlite3_fputs("\n", p->out);
31654     sqlite3_fprintf(p->out, "%12.12s: ", "rowseparator");
31655     output_c_string(p->out, p->rowSeparator);
31656     sqlite3_fputs("\n", p->out);
31657     switch( p->statsOn ){
31658       case 0:  zOut = "off";     break;
31659       default: zOut = "on";      break;
31660       case 2:  zOut = "stmt";    break;
31661       case 3:  zOut = "vmstep";  break;
31662     }
31663     sqlite3_fprintf(p->out, "%12.12s: %s\n","stats", zOut);
31664     sqlite3_fprintf(p->out, "%12.12s: ", "width");
31665     for (i=0;i<p->nWidth;i++) {
31666       sqlite3_fprintf(p->out, "%d ", p->colWidth[i]);
31667     }
31668     sqlite3_fputs("\n", p->out);
31669     sqlite3_fprintf(p->out, "%12.12s: %s\n", "filename",
31670           p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
31671   }else
31672 
31673   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
31674     if( nArg==2 ){
31675       if( cli_strcmp(azArg[1],"stmt")==0 ){
31676         p->statsOn = 2;
31677       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
31678         p->statsOn = 3;
31679       }else{
31680         p->statsOn = (u8)booleanValue(azArg[1]);
31681       }
31682     }else if( nArg==1 ){
31683       display_stats(p->db, p, 0);
31684     }else{
31685       eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
31686       rc = 1;
31687     }
31688   }else
31689 
31690   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
31691    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
31692                  || cli_strncmp(azArg[0], "indexes", n)==0) )
31693   ){
31694     sqlite3_stmt *pStmt;
31695     char **azResult;
31696     int nRow, nAlloc;
31697     int ii;
31698     ShellText s;
31699     initText(&s);
31700     open_db(p, 0);
31701     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
31702     if( rc ){
31703       sqlite3_finalize(pStmt);
31704       return shellDatabaseError(p->db);
31705     }
31706 
31707     if( nArg>2 && c=='i' ){
31708       /* It is an historical accident that the .indexes command shows an error
31709       ** when called with the wrong number of arguments whereas the .tables
31710       ** command does not. */
31711       eputz("Usage: .indexes ?LIKE-PATTERN?\n");
31712       rc = 1;
31713       sqlite3_finalize(pStmt);
31714       goto meta_command_exit;
31715     }
31716     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
31717       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
31718       if( zDbName==0 ) continue;
31719       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
31720       if( sqlite3_stricmp(zDbName, "main")==0 ){
31721         appendText(&s, "SELECT name FROM ", 0);
31722       }else{
31723         appendText(&s, "SELECT ", 0);
31724         appendText(&s, zDbName, '\'');
31725         appendText(&s, "||'.'||name FROM ", 0);
31726       }
31727       appendText(&s, zDbName, '"');
31728       appendText(&s, ".sqlite_schema ", 0);
31729       if( c=='t' ){
31730         appendText(&s," WHERE type IN ('table','view')"
31731                       "   AND name NOT LIKE 'sqlite_%'"
31732                       "   AND name LIKE ?1", 0);
31733       }else{
31734         appendText(&s," WHERE type='index'"
31735                       "   AND tbl_name LIKE ?1", 0);
31736       }
31737     }
31738     rc = sqlite3_finalize(pStmt);
31739     if( rc==SQLITE_OK ){
31740       appendText(&s, " ORDER BY 1", 0);
31741       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
31742     }
31743     freeText(&s);
31744     if( rc ) return shellDatabaseError(p->db);
31745 
31746     /* Run the SQL statement prepared by the above block. Store the results
31747     ** as an array of nul-terminated strings in azResult[].  */
31748     nRow = nAlloc = 0;
31749     azResult = 0;
31750     if( nArg>1 ){
31751       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
31752     }else{
31753       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
31754     }
31755     while( sqlite3_step(pStmt)==SQLITE_ROW ){
31756       if( nRow>=nAlloc ){
31757         char **azNew;
31758         int n2 = nAlloc*2 + 10;
31759         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
31760         shell_check_oom(azNew);
31761         nAlloc = n2;
31762         azResult = azNew;
31763       }
31764       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
31765       shell_check_oom(azResult[nRow]);
31766       nRow++;
31767     }
31768     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
31769       rc = shellDatabaseError(p->db);
31770     }
31771 
31772     /* Pretty-print the contents of array azResult[] to the output */
31773     if( rc==0 && nRow>0 ){
31774       int len, maxlen = 0;
31775       int i, j;
31776       int nPrintCol, nPrintRow;
31777       for(i=0; i<nRow; i++){
31778         len = strlen30(azResult[i]);
31779         if( len>maxlen ) maxlen = len;
31780       }
31781       nPrintCol = 80/(maxlen+2);
31782       if( nPrintCol<1 ) nPrintCol = 1;
31783       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
31784       for(i=0; i<nPrintRow; i++){
31785         for(j=i; j<nRow; j+=nPrintRow){
31786           char *zSp = j<nPrintRow ? "" : "  ";
31787           sqlite3_fprintf(p->out,
31788                "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
31789         }
31790         sqlite3_fputs("\n", p->out);
31791       }
31792     }
31793 
31794     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
31795     sqlite3_free(azResult);
31796   }else
31797 
31798 #ifndef SQLITE_SHELL_FIDDLE
31799   /* Begin redirecting output to the file "testcase-out.txt" */
31800   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
31801     output_reset(p);
31802     p->out = output_file_open("testcase-out.txt");
31803     if( p->out==0 ){
31804       eputz("Error: cannot open 'testcase-out.txt'\n");
31805     }
31806     if( nArg>=2 ){
31807       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
31808     }else{
31809       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
31810     }
31811   }else
31812 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
31813 
31814 #ifndef SQLITE_UNTESTABLE
31815   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
31816     static const struct {
31817        const char *zCtrlName;   /* Name of a test-control option */
31818        int ctrlCode;            /* Integer code for that option */
31819        int unSafe;              /* Not valid unless --unsafe-testing */
31820        const char *zUsage;      /* Usage notes */
31821     } aCtrl[] = {
31822     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
31823     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
31824   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
31825   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
31826     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
31827     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
31828     {"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..."       },
31829     {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
31830     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
31831     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
31832     {"json_selfcheck",     SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN"      },
31833     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
31834     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
31835     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK ..."},
31836 #ifdef YYCOVERAGE
31837     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
31838 #endif
31839     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,1, "OFFSET  "       },
31840     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
31841     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
31842     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
31843     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
31844     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
31845     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
31846     };
31847     int testctrl = -1;
31848     int iCtrl = -1;
31849     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
31850     int isOk = 0;
31851     int i, n2;
31852     const char *zCmd = 0;
31853 
31854     open_db(p, 0);
31855     zCmd = nArg>=2 ? azArg[1] : "help";
31856 
31857     /* The argument can optionally begin with "-" or "--" */
31858     if( zCmd[0]=='-' && zCmd[1] ){
31859       zCmd++;
31860       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
31861     }
31862 
31863     /* --help lists all test-controls */
31864     if( cli_strcmp(zCmd,"help")==0 ){
31865       sqlite3_fputs("Available test-controls:\n", p->out);
31866       for(i=0; i<ArraySize(aCtrl); i++){
31867         if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
31868         sqlite3_fprintf(p->out, "  .testctrl %s %s\n",
31869               aCtrl[i].zCtrlName, aCtrl[i].zUsage);
31870       }
31871       rc = 1;
31872       goto meta_command_exit;
31873     }
31874 
31875     /* convert testctrl text option to value. allow any unique prefix
31876     ** of the option name, or a numerical value. */
31877     n2 = strlen30(zCmd);
31878     for(i=0; i<ArraySize(aCtrl); i++){
31879       if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
31880       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
31881         if( testctrl<0 ){
31882           testctrl = aCtrl[i].ctrlCode;
31883           iCtrl = i;
31884         }else{
31885           sqlite3_fprintf(stderr,"Error: ambiguous test-control: \"%s\"\n"
31886                 "Use \".testctrl --help\" for help\n", zCmd);
31887           rc = 1;
31888           goto meta_command_exit;
31889         }
31890       }
31891     }
31892     if( testctrl<0 ){
31893       sqlite3_fprintf(stderr,"Error: unknown test-control: %s\n"
31894             "Use \".testctrl --help\" for help\n", zCmd);
31895     }else{
31896       switch(testctrl){
31897 
31898         /* Special processing for .testctrl opt MASK ...
31899         ** Each MASK argument can be one of:
31900         **
31901         **      +LABEL       Enable the named optimization
31902         **
31903         **      -LABEL       Disable the named optimization
31904         **
31905         **      INTEGER      Mask of optimizations to disable
31906         */
31907         case SQLITE_TESTCTRL_OPTIMIZATIONS: {
31908           static const struct {
31909              unsigned int mask;    /* Mask for this optimization */
31910              unsigned int bDsply;  /* Display this on output */
31911              const char *zLabel;   /* Name of optimization */
31912           } aLabel[] = {
31913             { 0x00000001, 1, "QueryFlattener" },
31914             { 0x00000001, 0, "Flatten" },
31915             { 0x00000002, 1, "WindowFunc" },
31916             { 0x00000004, 1, "GroupByOrder" },
31917             { 0x00000008, 1, "FactorOutConst" },
31918             { 0x00000010, 1, "DistinctOpt" },
31919             { 0x00000020, 1, "CoverIdxScan" },
31920             { 0x00000040, 1, "OrderByIdxJoin" },
31921             { 0x00000080, 1, "Transitive" },
31922             { 0x00000100, 1, "OmitNoopJoin" },
31923             { 0x00000200, 1, "CountOfView" },
31924             { 0x00000400, 1, "CurosrHints" },
31925             { 0x00000800, 1, "Stat4" },
31926             { 0x00001000, 1, "PushDown" },
31927             { 0x00002000, 1, "SimplifyJoin" },
31928             { 0x00004000, 1, "SkipScan" },
31929             { 0x00008000, 1, "PropagateConst" },
31930             { 0x00010000, 1, "MinMaxOpt" },
31931             { 0x00020000, 1, "SeekScan" },
31932             { 0x00040000, 1, "OmitOrderBy" },
31933             { 0x00080000, 1, "BloomFilter" },
31934             { 0x00100000, 1, "BloomPulldown" },
31935             { 0x00200000, 1, "BalancedMerge" },
31936             { 0x00400000, 1, "ReleaseReg" },
31937             { 0x00800000, 1, "FlttnUnionAll" },
31938             { 0x01000000, 1, "IndexedEXpr" },
31939             { 0x02000000, 1, "Coroutines" },
31940             { 0x04000000, 1, "NullUnusedCols" },
31941             { 0x08000000, 1, "OnePass" },
31942             { 0x10000000, 1, "OrderBySubq" },
31943             { 0x20000000, 1, "StarQuery" },
31944             { 0xffffffff, 0, "All" },
31945           };
31946           unsigned int curOpt;
31947           unsigned int newOpt;
31948           unsigned int m;
31949           int ii;
31950           int nOff;
31951           sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt);
31952           newOpt = curOpt;
31953           for(ii=2; ii<nArg; ii++){
31954             const char *z = azArg[ii];
31955             int useLabel = 0;
31956             const char *zLabel = 0;
31957             if( (z[0]=='+'|| z[0]=='-') && !IsDigit(z[1]) ){
31958               useLabel = z[0];
31959               zLabel = &z[1];
31960             }else if( !IsDigit(z[0]) && z[0]!=0 && !IsDigit(z[1]) ){
31961               useLabel = '+';
31962               zLabel = z;
31963             }else{
31964               newOpt = (unsigned int)strtol(z,0,0);
31965             }
31966             if( useLabel ){
31967               int jj;
31968               for(jj=0; jj<ArraySize(aLabel); jj++){
31969                 if( sqlite3_stricmp(zLabel, aLabel[jj].zLabel)==0 ) break;
31970               }
31971               if( jj>=ArraySize(aLabel) ){
31972                 sqlite3_fprintf(stderr,
31973                     "Error: no such optimization: \"%s\"\n", zLabel);
31974                 sqlite3_fputs("Should be one of:", stderr);
31975                 for(jj=0; jj<ArraySize(aLabel); jj++){
31976                   sqlite3_fprintf(stderr," %s", aLabel[jj].zLabel);
31977                 }
31978                 sqlite3_fputs("\n", stderr);
31979                 rc = 1;
31980                 goto meta_command_exit;
31981               }
31982               if( useLabel=='+' ){
31983                 newOpt &= ~aLabel[jj].mask;
31984               }else{
31985                 newOpt |= aLabel[jj].mask;
31986               }
31987             }
31988           }
31989           if( curOpt!=newOpt ){
31990             sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt);
31991           }
31992           for(ii=nOff=0, m=1; ii<32; ii++, m <<= 1){
31993             if( m & newOpt ) nOff++;
31994           }
31995           if( nOff<12 ){
31996             sqlite3_fputs("+All", p->out);
31997             for(ii=0; ii<ArraySize(aLabel); ii++){
31998               if( !aLabel[ii].bDsply  ) continue;
31999               if( (newOpt & aLabel[ii].mask)!=0 ){
32000                 sqlite3_fprintf(p->out, " -%s", aLabel[ii].zLabel);
32001               }
32002             }
32003           }else{
32004             sqlite3_fputs("-All", p->out);
32005             for(ii=0; ii<ArraySize(aLabel); ii++){
32006               if( !aLabel[ii].bDsply  ) continue;
32007               if( (newOpt & aLabel[ii].mask)==0 ){
32008                 sqlite3_fprintf(p->out, " +%s", aLabel[ii].zLabel);
32009               }
32010             }
32011           }
32012           sqlite3_fputs("\n", p->out);
32013           rc2 = isOk = 3;
32014           break;
32015         }
32016 
32017         /* sqlite3_test_control(int, db, int) */
32018         case SQLITE_TESTCTRL_FK_NO_ACTION:
32019           if( nArg==3 ){
32020             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
32021             rc2 = sqlite3_test_control(testctrl, p->db, opt);
32022             isOk = 3;
32023           }
32024           break;
32025 
32026         /* sqlite3_test_control(int) */
32027         case SQLITE_TESTCTRL_PRNG_SAVE:
32028         case SQLITE_TESTCTRL_PRNG_RESTORE:
32029         case SQLITE_TESTCTRL_BYTEORDER:
32030           if( nArg==2 ){
32031             rc2 = sqlite3_test_control(testctrl);
32032             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
32033           }
32034           break;
32035 
32036         /* sqlite3_test_control(int, uint) */
32037         case SQLITE_TESTCTRL_PENDING_BYTE:
32038           if( nArg==3 ){
32039             unsigned int opt = (unsigned int)integerValue(azArg[2]);
32040             rc2 = sqlite3_test_control(testctrl, opt);
32041             isOk = 3;
32042           }
32043           break;
32044 
32045         /* sqlite3_test_control(int, int, sqlite3*) */
32046         case SQLITE_TESTCTRL_PRNG_SEED:
32047           if( nArg==3 || nArg==4 ){
32048             int ii = (int)integerValue(azArg[2]);
32049             sqlite3 *db;
32050             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
32051               sqlite3_randomness(sizeof(ii),&ii);
32052               sqlite3_fprintf(stdout, "-- random seed: %d\n", ii);
32053             }
32054             if( nArg==3 ){
32055               db = 0;
32056             }else{
32057               db = p->db;
32058               /* Make sure the schema has been loaded */
32059               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
32060             }
32061             rc2 = sqlite3_test_control(testctrl, ii, db);
32062             isOk = 3;
32063           }
32064           break;
32065 
32066         /* sqlite3_test_control(int, int) */
32067         case SQLITE_TESTCTRL_ASSERT:
32068         case SQLITE_TESTCTRL_ALWAYS:
32069           if( nArg==3 ){
32070             int opt = booleanValue(azArg[2]);
32071             rc2 = sqlite3_test_control(testctrl, opt);
32072             isOk = 1;
32073           }
32074           break;
32075 
32076         /* sqlite3_test_control(int, int) */
32077         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
32078         case SQLITE_TESTCTRL_NEVER_CORRUPT:
32079           if( nArg==3 ){
32080             int opt = booleanValue(azArg[2]);
32081             rc2 = sqlite3_test_control(testctrl, opt);
32082             isOk = 3;
32083           }
32084           break;
32085 
32086         /* sqlite3_test_control(sqlite3*) */
32087         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
32088           rc2 = sqlite3_test_control(testctrl, p->db);
32089           isOk = 3;
32090           break;
32091 
32092         case SQLITE_TESTCTRL_IMPOSTER:
32093           if( nArg==5 ){
32094             rc2 = sqlite3_test_control(testctrl, p->db,
32095                           azArg[2],
32096                           integerValue(azArg[3]),
32097                           integerValue(azArg[4]));
32098             isOk = 3;
32099           }
32100           break;
32101 
32102         case SQLITE_TESTCTRL_SEEK_COUNT: {
32103           u64 x = 0;
32104           rc2 = sqlite3_test_control(testctrl, p->db, &x);
32105           sqlite3_fprintf(p->out, "%llu\n", x);
32106           isOk = 3;
32107           break;
32108         }
32109 
32110 #ifdef YYCOVERAGE
32111         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
32112           if( nArg==2 ){
32113             sqlite3_test_control(testctrl, p->out);
32114             isOk = 3;
32115           }
32116           break;
32117         }
32118 #endif
32119 #ifdef SQLITE_DEBUG
32120         case SQLITE_TESTCTRL_TUNE: {
32121           if( nArg==4 ){
32122             int id = (int)integerValue(azArg[2]);
32123             int val = (int)integerValue(azArg[3]);
32124             sqlite3_test_control(testctrl, id, &val);
32125             isOk = 3;
32126           }else if( nArg==3 ){
32127             int id = (int)integerValue(azArg[2]);
32128             sqlite3_test_control(testctrl, -id, &rc2);
32129             isOk = 1;
32130           }else if( nArg==2 ){
32131             int id = 1;
32132             while(1){
32133               int val = 0;
32134               rc2 = sqlite3_test_control(testctrl, -id, &val);
32135               if( rc2!=SQLITE_OK ) break;
32136               if( id>1 ) sqlite3_fputs("  ", p->out);
32137               sqlite3_fprintf(p->out, "%d: %d", id, val);
32138               id++;
32139             }
32140             if( id>1 ) sqlite3_fputs("\n", p->out);
32141             isOk = 3;
32142           }
32143           break;
32144         }
32145 #endif
32146         case SQLITE_TESTCTRL_SORTER_MMAP:
32147           if( nArg==3 ){
32148             int opt = (unsigned int)integerValue(azArg[2]);
32149             rc2 = sqlite3_test_control(testctrl, p->db, opt);
32150             isOk = 3;
32151           }
32152           break;
32153         case SQLITE_TESTCTRL_JSON_SELFCHECK:
32154           if( nArg==2 ){
32155             rc2 = -1;
32156             isOk = 1;
32157           }else{
32158             rc2 = booleanValue(azArg[2]);
32159             isOk = 3;
32160           }
32161           sqlite3_test_control(testctrl, &rc2);
32162           break;
32163         case SQLITE_TESTCTRL_FAULT_INSTALL: {
32164           int kk;
32165           int bShowHelp = nArg<=2;
32166           isOk = 3;
32167           for(kk=2; kk<nArg; kk++){
32168             const char *z = azArg[kk];
32169             if( z[0]=='-' && z[1]=='-' ) z++;
32170             if( cli_strcmp(z,"off")==0 ){
32171               sqlite3_test_control(testctrl, 0);
32172             }else if( cli_strcmp(z,"on")==0 ){
32173               faultsim_state.iCnt = faultsim_state.nSkip;
32174               if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;
32175               faultsim_state.nHit = 0;
32176               sqlite3_test_control(testctrl, faultsim_callback);
32177             }else if( cli_strcmp(z,"reset")==0 ){
32178               faultsim_state.iCnt = faultsim_state.nSkip;
32179               faultsim_state.nHit = 0;
32180               sqlite3_test_control(testctrl, faultsim_callback);
32181             }else if( cli_strcmp(z,"status")==0 ){
32182               sqlite3_fprintf(p->out, "faultsim.iId:       %d\n",
32183                               faultsim_state.iId);
32184               sqlite3_fprintf(p->out, "faultsim.iErr:      %d\n",
32185                               faultsim_state.iErr);
32186               sqlite3_fprintf(p->out, "faultsim.iCnt:      %d\n",
32187                               faultsim_state.iCnt);
32188               sqlite3_fprintf(p->out, "faultsim.nHit:      %d\n",
32189                               faultsim_state.nHit);
32190               sqlite3_fprintf(p->out, "faultsim.iInterval: %d\n",
32191                               faultsim_state.iInterval);
32192               sqlite3_fprintf(p->out, "faultsim.eVerbose:  %d\n",
32193                               faultsim_state.eVerbose);
32194               sqlite3_fprintf(p->out, "faultsim.nRepeat:   %d\n",
32195                               faultsim_state.nRepeat);
32196               sqlite3_fprintf(p->out, "faultsim.nSkip:     %d\n",
32197                               faultsim_state.nSkip);
32198             }else if( cli_strcmp(z,"-v")==0 ){
32199               if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
32200             }else if( cli_strcmp(z,"-q")==0 ){
32201               if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
32202             }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
32203               faultsim_state.iId = atoi(azArg[++kk]);
32204             }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
32205               faultsim_state.iErr = atoi(azArg[++kk]);
32206             }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
32207               faultsim_state.iInterval = atoi(azArg[++kk]);
32208             }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){
32209               faultsim_state.nRepeat = atoi(azArg[++kk]);
32210            }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){
32211               faultsim_state.nSkip = atoi(azArg[++kk]);
32212             }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
32213               bShowHelp = 1;
32214             }else{
32215               sqlite3_fprintf(stderr,
32216                   "Unrecognized fault_install argument: \"%s\"\n",
32217                   azArg[kk]);
32218               rc = 1;
32219               bShowHelp = 1;
32220               break;
32221             }
32222           }
32223           if( bShowHelp ){
32224             sqlite3_fputs(
32225                "Usage: .testctrl fault_install ARGS\n"
32226                "Possible arguments:\n"
32227                "   off               Disable faultsim\n"
32228                "   on                Activate faultsim\n"
32229                "   reset             Reset the trigger counter\n"
32230                "   status            Show current status\n"
32231                "   -v                Increase verbosity\n"
32232                "   -q                Decrease verbosity\n"
32233                "   --errcode N       When triggered, return N as error code\n"
32234                "   --id ID           Trigger only for the ID specified\n"
32235                "   --interval N      Trigger only after every N-th call\n"
32236                "   --repeat N        Turn off after N hits.  0 means never\n"
32237                "   --skip N          Skip the first N encounters\n"
32238                ,p->out
32239             );
32240           }
32241           break;
32242         }
32243       }
32244     }
32245     if( isOk==0 && iCtrl>=0 ){
32246       sqlite3_fprintf(p->out,
32247           "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
32248       rc = 1;
32249     }else if( isOk==1 ){
32250       sqlite3_fprintf(p->out, "%d\n", rc2);
32251     }else if( isOk==2 ){
32252       sqlite3_fprintf(p->out, "0x%08x\n", rc2);
32253     }
32254   }else
32255 #endif /* !defined(SQLITE_UNTESTABLE) */
32256 
32257   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
32258     open_db(p, 0);
32259     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
32260   }else
32261 
32262   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
32263     if( nArg==2 ){
32264       enableTimer = booleanValue(azArg[1]);
32265       if( enableTimer && !HAS_TIMER ){
32266         eputz("Error: timer not available on this system.\n");
32267         enableTimer = 0;
32268       }
32269     }else{
32270       eputz("Usage: .timer on|off\n");
32271       rc = 1;
32272     }
32273   }else
32274 
32275 #ifndef SQLITE_OMIT_TRACE
32276   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
32277     int mType = 0;
32278     int jj;
32279     open_db(p, 0);
32280     for(jj=1; jj<nArg; jj++){
32281       const char *z = azArg[jj];
32282       if( z[0]=='-' ){
32283         if( optionMatch(z, "expanded") ){
32284           p->eTraceType = SHELL_TRACE_EXPANDED;
32285         }
32286 #ifdef SQLITE_ENABLE_NORMALIZE
32287         else if( optionMatch(z, "normalized") ){
32288           p->eTraceType = SHELL_TRACE_NORMALIZED;
32289         }
32290 #endif
32291         else if( optionMatch(z, "plain") ){
32292           p->eTraceType = SHELL_TRACE_PLAIN;
32293         }
32294         else if( optionMatch(z, "profile") ){
32295           mType |= SQLITE_TRACE_PROFILE;
32296         }
32297         else if( optionMatch(z, "row") ){
32298           mType |= SQLITE_TRACE_ROW;
32299         }
32300         else if( optionMatch(z, "stmt") ){
32301           mType |= SQLITE_TRACE_STMT;
32302         }
32303         else if( optionMatch(z, "close") ){
32304           mType |= SQLITE_TRACE_CLOSE;
32305         }
32306         else {
32307           sqlite3_fprintf(stderr,"Unknown option \"%s\" on \".trace\"\n", z);
32308           rc = 1;
32309           goto meta_command_exit;
32310         }
32311       }else{
32312         output_file_close(p->traceOut);
32313         p->traceOut = output_file_open(z);
32314       }
32315     }
32316     if( p->traceOut==0 ){
32317       sqlite3_trace_v2(p->db, 0, 0, 0);
32318     }else{
32319       if( mType==0 ) mType = SQLITE_TRACE_STMT;
32320       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
32321     }
32322   }else
32323 #endif /* !defined(SQLITE_OMIT_TRACE) */
32324 
32325 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
32326   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
32327     int ii;
32328     int lenOpt;
32329     char *zOpt;
32330     if( nArg<2 ){
32331       eputz("Usage: .unmodule [--allexcept] NAME ...\n");
32332       rc = 1;
32333       goto meta_command_exit;
32334     }
32335     open_db(p, 0);
32336     zOpt = azArg[1];
32337     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
32338     lenOpt = (int)strlen(zOpt);
32339     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
32340       assert( azArg[nArg]==0 );
32341       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
32342     }else{
32343       for(ii=1; ii<nArg; ii++){
32344         sqlite3_create_module(p->db, azArg[ii], 0, 0);
32345       }
32346     }
32347   }else
32348 #endif
32349 
32350   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
32351     char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
32352     sqlite3_fprintf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
32353           sqlite3_libversion(), sqlite3_sourceid());
32354 #if SQLITE_HAVE_ZLIB
32355     sqlite3_fprintf(p->out, "zlib version %s\n", zlibVersion());
32356 #endif
32357 #define CTIMEOPT_VAL_(opt) #opt
32358 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
32359 #if defined(__clang__) && defined(__clang_major__)
32360     sqlite3_fprintf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
32361           CTIMEOPT_VAL(__clang_minor__) "."
32362           CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
32363 #elif defined(_MSC_VER)
32364     sqlite3_fprintf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
32365 #elif defined(__GNUC__) && defined(__VERSION__)
32366     sqlite3_fprintf(p->out, "gcc-" __VERSION__ " (%s)\n", zPtrSz);
32367 #endif
32368   }else
32369 
32370   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
32371     const char *zDbName = nArg==2 ? azArg[1] : "main";
32372     sqlite3_vfs *pVfs = 0;
32373     if( p->db ){
32374       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
32375       if( pVfs ){
32376         sqlite3_fprintf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
32377         sqlite3_fprintf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
32378         sqlite3_fprintf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
32379         sqlite3_fprintf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
32380       }
32381     }
32382   }else
32383 
32384   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
32385     sqlite3_vfs *pVfs;
32386     sqlite3_vfs *pCurrent = 0;
32387     if( p->db ){
32388       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
32389     }
32390     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
32391       sqlite3_fprintf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
32392             pVfs==pCurrent ? "  <--- CURRENT" : "");
32393       sqlite3_fprintf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
32394       sqlite3_fprintf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
32395       sqlite3_fprintf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
32396       if( pVfs->pNext ){
32397         sqlite3_fputs("-----------------------------------\n", p->out);
32398       }
32399     }
32400   }else
32401 
32402   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
32403     const char *zDbName = nArg==2 ? azArg[1] : "main";
32404     char *zVfsName = 0;
32405     if( p->db ){
32406       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
32407       if( zVfsName ){
32408         sqlite3_fprintf(p->out, "%s\n", zVfsName);
32409         sqlite3_free(zVfsName);
32410       }
32411     }
32412   }else
32413 
32414   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
32415     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
32416     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
32417   }else
32418 
32419   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
32420     int j;
32421     assert( nArg<=ArraySize(azArg) );
32422     p->nWidth = nArg-1;
32423     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
32424     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
32425     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
32426     for(j=1; j<nArg; j++){
32427       p->colWidth[j-1] = (int)integerValue(azArg[j]);
32428     }
32429   }else
32430 
32431   {
32432     sqlite3_fprintf(stderr,"Error: unknown command or invalid arguments: "
32433           " \"%s\". Enter \".help\" for help\n", azArg[0]);
32434     rc = 1;
32435   }
32436 
32437 meta_command_exit:
32438   if( p->outCount ){
32439     p->outCount--;
32440     if( p->outCount==0 ) output_reset(p);
32441   }
32442   p->bSafeMode = p->bSafeModePersist;
32443   return rc;
32444 }
32445 
32446 /* Line scan result and intermediate states (supporting scan resumption)
32447 */
32448 #ifndef CHAR_BIT
32449 # define CHAR_BIT 8
32450 #endif
32451 typedef enum {
32452   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
32453   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
32454   QSS_Start = 0
32455 } QuickScanState;
32456 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
32457 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
32458 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
32459 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
32460 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
32461 
32462 /*
32463 ** Scan line for classification to guide shell's handling.
32464 ** The scan is resumable for subsequent lines when prior
32465 ** return values are passed as the 2nd argument.
32466 */
quickscan(char * zLine,QuickScanState qss,SCAN_TRACKER_REFTYPE pst)32467 static QuickScanState quickscan(char *zLine, QuickScanState qss,
32468                                 SCAN_TRACKER_REFTYPE pst){
32469   char cin;
32470   char cWait = (char)qss; /* intentional narrowing loss */
32471   if( cWait==0 ){
32472   PlainScan:
32473     while( (cin = *zLine++)!=0 ){
32474       if( IsSpace(cin) )
32475         continue;
32476       switch (cin){
32477       case '-':
32478         if( *zLine!='-' )
32479           break;
32480         while((cin = *++zLine)!=0 )
32481           if( cin=='\n')
32482             goto PlainScan;
32483         return qss;
32484       case ';':
32485         qss |= QSS_EndingSemi;
32486         continue;
32487       case '/':
32488         if( *zLine=='*' ){
32489           ++zLine;
32490           cWait = '*';
32491           CONTINUE_PROMPT_AWAITS(pst, "/*");
32492           qss = QSS_SETV(qss, cWait);
32493           goto TermScan;
32494         }
32495         break;
32496       case '[':
32497         cin = ']';
32498         deliberate_fall_through; /* FALLTHRU */
32499       case '`': case '\'': case '"':
32500         cWait = cin;
32501         qss = QSS_HasDark | cWait;
32502         CONTINUE_PROMPT_AWAITC(pst, cin);
32503         goto TermScan;
32504       case '(':
32505         CONTINUE_PAREN_INCR(pst, 1);
32506         break;
32507       case ')':
32508         CONTINUE_PAREN_INCR(pst, -1);
32509         break;
32510       default:
32511         break;
32512       }
32513       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
32514     }
32515   }else{
32516   TermScan:
32517     while( (cin = *zLine++)!=0 ){
32518       if( cin==cWait ){
32519         switch( cWait ){
32520         case '*':
32521           if( *zLine != '/' )
32522             continue;
32523           ++zLine;
32524           CONTINUE_PROMPT_AWAITC(pst, 0);
32525           qss = QSS_SETV(qss, 0);
32526           goto PlainScan;
32527         case '`': case '\'': case '"':
32528           if(*zLine==cWait){
32529             /* Swallow doubled end-delimiter.*/
32530             ++zLine;
32531             continue;
32532           }
32533           deliberate_fall_through; /* FALLTHRU */
32534         case ']':
32535           CONTINUE_PROMPT_AWAITC(pst, 0);
32536           qss = QSS_SETV(qss, 0);
32537           goto PlainScan;
32538         default: assert(0);
32539         }
32540       }
32541     }
32542   }
32543   return qss;
32544 }
32545 
32546 /*
32547 ** Return TRUE if the line typed in is an SQL command terminator other
32548 ** than a semi-colon.  The SQL Server style "go" command is understood
32549 ** as is the Oracle "/".
32550 */
line_is_command_terminator(char * zLine)32551 static int line_is_command_terminator(char *zLine){
32552   while( IsSpace(zLine[0]) ){ zLine++; };
32553   if( zLine[0]=='/' )
32554     zLine += 1; /* Oracle */
32555   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
32556     zLine += 2; /* SQL Server */
32557   else
32558     return 0;
32559   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
32560 }
32561 
32562 /*
32563 ** The CLI needs a working sqlite3_complete() to work properly.  So error
32564 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
32565 */
32566 #ifdef SQLITE_OMIT_COMPLETE
32567 # error the CLI application is incompatible with SQLITE_OMIT_COMPLETE.
32568 #endif
32569 
32570 /*
32571 ** Return true if zSql is a complete SQL statement.  Return false if it
32572 ** ends in the middle of a string literal or C-style comment.
32573 */
line_is_complete(char * zSql,int nSql)32574 static int line_is_complete(char *zSql, int nSql){
32575   int rc;
32576   if( zSql==0 ) return 1;
32577   zSql[nSql] = ';';
32578   zSql[nSql+1] = 0;
32579   rc = sqlite3_complete(zSql);
32580   zSql[nSql] = 0;
32581   return rc;
32582 }
32583 
32584 /*
32585 ** This function is called after processing each line of SQL in the
32586 ** runOneSqlLine() function. Its purpose is to detect scenarios where
32587 ** defensive mode should be automatically turned off. Specifically, when
32588 **
32589 **   1. The first line of input is "PRAGMA foreign_keys=OFF;",
32590 **   2. The second line of input is "BEGIN TRANSACTION;",
32591 **   3. The database is empty, and
32592 **   4. The shell is not running in --safe mode.
32593 **
32594 ** The implementation uses the ShellState.eRestoreState to maintain state:
32595 **
32596 **    0: Have not seen any SQL.
32597 **    1: Have seen "PRAGMA foreign_keys=OFF;".
32598 **    2-6: Currently running .dump transaction. If the "2" bit is set,
32599 **         disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
32600 **    7: Nothing left to do. This function becomes a no-op.
32601 */
doAutoDetectRestore(ShellState * p,const char * zSql)32602 static int doAutoDetectRestore(ShellState *p, const char *zSql){
32603   int rc = SQLITE_OK;
32604 
32605   if( p->eRestoreState<7 ){
32606     switch( p->eRestoreState ){
32607       case 0: {
32608         const char *zExpect = "PRAGMA foreign_keys=OFF;";
32609         assert( strlen(zExpect)==24 );
32610         if( p->bSafeMode==0
32611          && strlen(zSql)>=24
32612          && memcmp(zSql, zExpect, 25)==0
32613         ){
32614           p->eRestoreState = 1;
32615         }else{
32616           p->eRestoreState = 7;
32617         }
32618         break;
32619       };
32620 
32621       case 1: {
32622         int bIsDump = 0;
32623         const char *zExpect = "BEGIN TRANSACTION;";
32624         assert( strlen(zExpect)==18 );
32625         if( memcmp(zSql, zExpect, 19)==0 ){
32626           /* Now check if the database is empty. */
32627           const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
32628           sqlite3_stmt *pStmt = 0;
32629 
32630           bIsDump = 1;
32631           shellPrepare(p->db, &rc, zQuery, &pStmt);
32632           if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
32633             bIsDump = 0;
32634           }
32635           shellFinalize(&rc, pStmt);
32636         }
32637         if( bIsDump && rc==SQLITE_OK ){
32638           int bDefense = 0;
32639           int bDqsDdl = 0;
32640           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
32641           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
32642           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
32643           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
32644           p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
32645         }else{
32646           p->eRestoreState = 7;
32647         }
32648         break;
32649       }
32650 
32651       default: {
32652         if( sqlite3_get_autocommit(p->db) ){
32653           if( (p->eRestoreState & 2) ){
32654             sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
32655           }
32656           if( (p->eRestoreState & 4) ){
32657             sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
32658           }
32659           p->eRestoreState = 7;
32660         }
32661         break;
32662       }
32663     }
32664   }
32665 
32666   return rc;
32667 }
32668 
32669 /*
32670 ** Run a single line of SQL.  Return the number of errors.
32671 */
runOneSqlLine(ShellState * p,char * zSql,FILE * in,int startline)32672 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
32673   int rc;
32674   char *zErrMsg = 0;
32675 
32676   open_db(p, 0);
32677   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
32678   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
32679   BEGIN_TIMER;
32680   rc = shell_exec(p, zSql, &zErrMsg);
32681   END_TIMER(p->out);
32682   if( rc || zErrMsg ){
32683     char zPrefix[100];
32684     const char *zErrorTail;
32685     const char *zErrorType;
32686     if( zErrMsg==0 ){
32687       zErrorType = "Error";
32688       zErrorTail = sqlite3_errmsg(p->db);
32689     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
32690       zErrorType = "Parse error";
32691       zErrorTail = &zErrMsg[12];
32692     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
32693       zErrorType = "Runtime error";
32694       zErrorTail = &zErrMsg[10];
32695     }else{
32696       zErrorType = "Error";
32697       zErrorTail = zErrMsg;
32698     }
32699     if( in!=0 || !stdin_is_interactive ){
32700       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
32701                        "%s near line %d:", zErrorType, startline);
32702     }else{
32703       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
32704     }
32705     sqlite3_fprintf(stderr,"%s %s\n", zPrefix, zErrorTail);
32706     sqlite3_free(zErrMsg);
32707     zErrMsg = 0;
32708     return 1;
32709   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
32710     char zLineBuf[2000];
32711     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
32712             "changes: %lld   total_changes: %lld",
32713             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
32714     sqlite3_fprintf(p->out, "%s\n", zLineBuf);
32715   }
32716 
32717   if( doAutoDetectRestore(p, zSql) ) return 1;
32718   return 0;
32719 }
32720 
echo_group_input(ShellState * p,const char * zDo)32721 static void echo_group_input(ShellState *p, const char *zDo){
32722   if( ShellHasFlag(p, SHFLG_Echo) ){
32723     sqlite3_fprintf(p->out, "%s\n", zDo);
32724     fflush(p->out);
32725   }
32726 }
32727 
32728 #ifdef SQLITE_SHELL_FIDDLE
32729 /*
32730 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
32731 ** impl because we need the global shellState and cannot access it from that
32732 ** function without moving lots of code around (creating a larger/messier diff).
32733 */
one_input_line(FILE * in,char * zPrior,int isContinuation)32734 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
32735   /* Parse the next line from shellState.wasm.zInput. */
32736   const char *zBegin = shellState.wasm.zPos;
32737   const char *z = zBegin;
32738   char *zLine = 0;
32739   i64 nZ = 0;
32740 
32741   UNUSED_PARAMETER(in);
32742   UNUSED_PARAMETER(isContinuation);
32743   if(!z || !*z){
32744     return 0;
32745   }
32746   while(*z && IsSpace(*z)) ++z;
32747   zBegin = z;
32748   for(; *z && '\n'!=*z; ++nZ, ++z){}
32749   if(nZ>0 && '\r'==zBegin[nZ-1]){
32750     --nZ;
32751   }
32752   shellState.wasm.zPos = z;
32753   zLine = realloc(zPrior, nZ+1);
32754   shell_check_oom(zLine);
32755   memcpy(zLine, zBegin, nZ);
32756   zLine[nZ] = 0;
32757   return zLine;
32758 }
32759 #endif /* SQLITE_SHELL_FIDDLE */
32760 
32761 /*
32762 ** Read input from *in and process it.  If *in==0 then input
32763 ** is interactive - the user is typing it it.  Otherwise, input
32764 ** is coming from a file or device.  A prompt is issued and history
32765 ** is saved only if input is interactive.  An interrupt signal will
32766 ** cause this routine to exit immediately, unless input is interactive.
32767 **
32768 ** Return the number of errors.
32769 */
process_input(ShellState * p)32770 static int process_input(ShellState *p){
32771   char *zLine = 0;          /* A single input line */
32772   char *zSql = 0;           /* Accumulated SQL text */
32773   i64 nLine;                /* Length of current line */
32774   i64 nSql = 0;             /* Bytes of zSql[] used */
32775   i64 nAlloc = 0;           /* Allocated zSql[] space */
32776   int rc;                   /* Error code */
32777   int errCnt = 0;           /* Number of errors seen */
32778   i64 startline = 0;        /* Line number for start of current input */
32779   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
32780 
32781   if( p->inputNesting==MAX_INPUT_NESTING ){
32782     /* This will be more informative in a later version. */
32783     sqlite3_fprintf(stderr,"Input nesting limit (%d) reached at line %d."
32784           " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
32785     return 1;
32786   }
32787   ++p->inputNesting;
32788   p->lineno = 0;
32789   CONTINUE_PROMPT_RESET;
32790   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
32791     fflush(p->out);
32792     zLine = one_input_line(p->in, zLine, nSql>0);
32793     if( zLine==0 ){
32794       /* End of input */
32795       if( p->in==0 && stdin_is_interactive ) sqlite3_fputs("\n", p->out);
32796       break;
32797     }
32798     if( seenInterrupt ){
32799       if( p->in!=0 ) break;
32800       seenInterrupt = 0;
32801     }
32802     p->lineno++;
32803     if( QSS_INPLAIN(qss)
32804         && line_is_command_terminator(zLine)
32805         && line_is_complete(zSql, nSql) ){
32806       memcpy(zLine,";",2);
32807     }
32808     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
32809     if( QSS_PLAINWHITE(qss) && nSql==0 ){
32810       /* Just swallow single-line whitespace */
32811       echo_group_input(p, zLine);
32812       qss = QSS_Start;
32813       continue;
32814     }
32815     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
32816       CONTINUE_PROMPT_RESET;
32817       echo_group_input(p, zLine);
32818       if( zLine[0]=='.' ){
32819         rc = do_meta_command(zLine, p);
32820         if( rc==2 ){ /* exit requested */
32821           break;
32822         }else if( rc ){
32823           errCnt++;
32824         }
32825       }
32826       qss = QSS_Start;
32827       continue;
32828     }
32829     /* No single-line dispositions remain; accumulate line(s). */
32830     nLine = strlen(zLine);
32831     if( nSql+nLine+2>=nAlloc ){
32832       /* Grow buffer by half-again increments when big. */
32833       nAlloc = nSql+(nSql>>1)+nLine+100;
32834       zSql = realloc(zSql, nAlloc);
32835       shell_check_oom(zSql);
32836     }
32837     if( nSql==0 ){
32838       i64 i;
32839       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
32840       assert( nAlloc>0 && zSql!=0 );
32841       memcpy(zSql, zLine+i, nLine+1-i);
32842       startline = p->lineno;
32843       nSql = nLine-i;
32844     }else{
32845       zSql[nSql++] = '\n';
32846       memcpy(zSql+nSql, zLine, nLine+1);
32847       nSql += nLine;
32848     }
32849     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
32850       echo_group_input(p, zSql);
32851       errCnt += runOneSqlLine(p, zSql, p->in, startline);
32852       CONTINUE_PROMPT_RESET;
32853       nSql = 0;
32854       if( p->outCount ){
32855         output_reset(p);
32856         p->outCount = 0;
32857       }else{
32858         clearTempFile(p);
32859       }
32860       p->bSafeMode = p->bSafeModePersist;
32861       qss = QSS_Start;
32862     }else if( nSql && QSS_PLAINWHITE(qss) ){
32863       echo_group_input(p, zSql);
32864       nSql = 0;
32865       qss = QSS_Start;
32866     }
32867   }
32868   if( nSql ){
32869     /* This may be incomplete. Let the SQL parser deal with that. */
32870     echo_group_input(p, zSql);
32871     errCnt += runOneSqlLine(p, zSql, p->in, startline);
32872     CONTINUE_PROMPT_RESET;
32873   }
32874   free(zSql);
32875   free(zLine);
32876   --p->inputNesting;
32877   return errCnt>0;
32878 }
32879 
32880 /*
32881 ** Return a pathname which is the user's home directory.  A
32882 ** 0 return indicates an error of some kind.
32883 */
find_home_dir(int clearFlag)32884 static char *find_home_dir(int clearFlag){
32885   static char *home_dir = NULL;
32886   if( clearFlag ){
32887     free(home_dir);
32888     home_dir = 0;
32889     return 0;
32890   }
32891   if( home_dir ) return home_dir;
32892 
32893 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
32894      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
32895   {
32896     struct passwd *pwent;
32897     uid_t uid = getuid();
32898     if( (pwent=getpwuid(uid)) != NULL) {
32899       home_dir = pwent->pw_dir;
32900     }
32901   }
32902 #endif
32903 
32904 #if defined(_WIN32_WCE)
32905   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
32906    */
32907   home_dir = "/";
32908 #else
32909 
32910 #if defined(_WIN32) || defined(WIN32)
32911   if (!home_dir) {
32912     home_dir = getenv("USERPROFILE");
32913   }
32914 #endif
32915 
32916   if (!home_dir) {
32917     home_dir = getenv("HOME");
32918   }
32919 
32920 #if defined(_WIN32) || defined(WIN32)
32921   if (!home_dir) {
32922     char *zDrive, *zPath;
32923     int n;
32924     zDrive = getenv("HOMEDRIVE");
32925     zPath = getenv("HOMEPATH");
32926     if( zDrive && zPath ){
32927       n = strlen30(zDrive) + strlen30(zPath) + 1;
32928       home_dir = malloc( n );
32929       if( home_dir==0 ) return 0;
32930       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
32931       return home_dir;
32932     }
32933     home_dir = "c:\\";
32934   }
32935 #endif
32936 
32937 #endif /* !_WIN32_WCE */
32938 
32939   if( home_dir ){
32940     i64 n = strlen(home_dir) + 1;
32941     char *z = malloc( n );
32942     if( z ) memcpy(z, home_dir, n);
32943     home_dir = z;
32944   }
32945 
32946   return home_dir;
32947 }
32948 
32949 /*
32950 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
32951 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
32952 ** the path to it.  If there is no $(XDG_CONFIG_HOME) then
32953 ** look for $(HOME)/.config/sqlite3/sqliterc and if found
32954 ** return that.  If none of these are found, return 0.
32955 **
32956 ** The string returned is obtained from sqlite3_malloc() and
32957 ** should be freed by the caller.
32958 */
find_xdg_config(void)32959 static char *find_xdg_config(void){
32960 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
32961      || defined(__RTP__) || defined(_WRS_KERNEL)
32962   return 0;
32963 #else
32964   char *zConfig = 0;
32965   const char *zXdgHome;
32966 
32967   zXdgHome = getenv("XDG_CONFIG_HOME");
32968   if( zXdgHome==0 ){
32969     const char *zHome = getenv("HOME");
32970     if( zHome==0 ) return 0;
32971     zConfig = sqlite3_mprintf("%s/.config/sqlite3/sqliterc", zHome);
32972   }else{
32973     zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
32974   }
32975   shell_check_oom(zConfig);
32976   if( access(zConfig,0)!=0 ){
32977     sqlite3_free(zConfig);
32978     zConfig = 0;
32979   }
32980   return zConfig;
32981 #endif
32982 }
32983 
32984 /*
32985 ** Read input from the file given by sqliterc_override.  Or if that
32986 ** parameter is NULL, take input from the first of find_xdg_config()
32987 ** or ~/.sqliterc which is found.
32988 **
32989 ** Returns the number of errors.
32990 */
process_sqliterc(ShellState * p,const char * sqliterc_override)32991 static void process_sqliterc(
32992   ShellState *p,                  /* Configuration data */
32993   const char *sqliterc_override   /* Name of config file. NULL to use default */
32994 ){
32995   char *home_dir = NULL;
32996   const char *sqliterc = sqliterc_override;
32997   char *zBuf = 0;
32998   FILE *inSaved = p->in;
32999   int savedLineno = p->lineno;
33000 
33001   if( sqliterc == NULL ){
33002     sqliterc = zBuf = find_xdg_config();
33003   }
33004   if( sqliterc == NULL ){
33005     home_dir = find_home_dir(0);
33006     if( home_dir==0 ){
33007       eputz("-- warning: cannot find home directory;"
33008             " cannot read ~/.sqliterc\n");
33009       return;
33010     }
33011     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
33012     shell_check_oom(zBuf);
33013     sqliterc = zBuf;
33014   }
33015   p->in = sqlite3_fopen(sqliterc,"rb");
33016   if( p->in ){
33017     if( stdin_is_interactive ){
33018       sqlite3_fprintf(stderr,"-- Loading resources from %s\n", sqliterc);
33019     }
33020     if( process_input(p) && bail_on_error ) exit(1);
33021     fclose(p->in);
33022   }else if( sqliterc_override!=0 ){
33023     sqlite3_fprintf(stderr,"cannot open: \"%s\"\n", sqliterc);
33024     if( bail_on_error ) exit(1);
33025   }
33026   p->in = inSaved;
33027   p->lineno = savedLineno;
33028   sqlite3_free(zBuf);
33029 }
33030 
33031 /*
33032 ** Show available command line options
33033 */
33034 static const char zOptions[] =
33035   "   --                   treat no subsequent arguments as options\n"
33036 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
33037   "   -A ARGS...           run \".archive ARGS\" and exit\n"
33038 #endif
33039   "   -append              append the database to the end of the file\n"
33040   "   -ascii               set output mode to 'ascii'\n"
33041   "   -bail                stop after hitting an error\n"
33042   "   -batch               force batch I/O\n"
33043   "   -box                 set output mode to 'box'\n"
33044   "   -column              set output mode to 'column'\n"
33045   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
33046   "   -csv                 set output mode to 'csv'\n"
33047 #if !defined(SQLITE_OMIT_DESERIALIZE)
33048   "   -deserialize         open the database using sqlite3_deserialize()\n"
33049 #endif
33050   "   -echo                print inputs before execution\n"
33051   "   -escape T            ctrl-char escape; T is one of: symbol, ascii, off\n"
33052   "   -init FILENAME       read/process named file\n"
33053   "   -[no]header          turn headers on or off\n"
33054 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
33055   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
33056 #endif
33057   "   -help                show this message\n"
33058   "   -html                set output mode to HTML\n"
33059   "   -interactive         force interactive I/O\n"
33060   "   -json                set output mode to 'json'\n"
33061   "   -line                set output mode to 'line'\n"
33062   "   -list                set output mode to 'list'\n"
33063   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
33064   "   -markdown            set output mode to 'markdown'\n"
33065 #if !defined(SQLITE_OMIT_DESERIALIZE)
33066   "   -maxsize N           maximum size for a --deserialize database\n"
33067 #endif
33068   "   -memtrace            trace all memory allocations and deallocations\n"
33069   "   -mmap N              default mmap size set to N\n"
33070 #ifdef SQLITE_ENABLE_MULTIPLEX
33071   "   -multiplex           enable the multiplexor VFS\n"
33072 #endif
33073   "   -newline SEP         set output row separator. Default: '\\n'\n"
33074   "   -nofollow            refuse to open symbolic links to database files\n"
33075   "   -nonce STRING        set the safe-mode escape nonce\n"
33076   "   -no-rowid-in-view    Disable rowid-in-view using sqlite3_config()\n"
33077   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
33078   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
33079   "   -pcachetrace         trace all page cache operations\n"
33080   "   -quote               set output mode to 'quote'\n"
33081   "   -readonly            open the database read-only\n"
33082   "   -safe                enable safe-mode\n"
33083   "   -separator SEP       set output column separator. Default: '|'\n"
33084 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
33085   "   -sorterref SIZE      sorter references threshold size\n"
33086 #endif
33087   "   -stats               print memory stats before each finalize\n"
33088   "   -table               set output mode to 'table'\n"
33089   "   -tabs                set output mode to 'tabs'\n"
33090   "   -unsafe-testing      allow unsafe commands and modes for testing\n"
33091   "   -version             show SQLite version\n"
33092   "   -vfs NAME            use NAME as the default VFS\n"
33093   "   -vfstrace            enable tracing of all VFS calls\n"
33094 #ifdef SQLITE_HAVE_ZLIB
33095   "   -zip                 open the file as a ZIP Archive\n"
33096 #endif
33097 ;
usage(int showDetail)33098 static void usage(int showDetail){
33099   sqlite3_fprintf(stderr,"Usage: %s [OPTIONS] [FILENAME [SQL...]]\n"
33100        "FILENAME is the name of an SQLite database. A new database is created\n"
33101        "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
33102   if( showDetail ){
33103     sqlite3_fprintf(stderr,"OPTIONS include:\n%s", zOptions);
33104   }else{
33105     eputz("Use the -help option for additional information\n");
33106   }
33107   exit(0);
33108 }
33109 
33110 /*
33111 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
33112 ** error message if it is initialized.
33113 */
verify_uninitialized(void)33114 static void verify_uninitialized(void){
33115   if( sqlite3_config(-1)==SQLITE_MISUSE ){
33116     sputz(stdout, "WARNING: attempt to configure SQLite after"
33117           " initialization.\n");
33118   }
33119 }
33120 
33121 /*
33122 ** Initialize the state information in data
33123 */
main_init(ShellState * data)33124 static void main_init(ShellState *data) {
33125   memset(data, 0, sizeof(*data));
33126   data->normalMode = data->cMode = data->mode = MODE_List;
33127   data->autoExplain = 1;
33128 #ifdef _WIN32
33129   data->crlfMode = 1;
33130 #endif
33131   data->pAuxDb = &data->aAuxDb[0];
33132   memcpy(data->colSeparator,SEP_Column, 2);
33133   memcpy(data->rowSeparator,SEP_Row, 2);
33134   data->showHeader = 0;
33135   data->shellFlgs = SHFLG_Lookaside;
33136   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
33137 #if !defined(SQLITE_SHELL_FIDDLE)
33138   verify_uninitialized();
33139 #endif
33140   sqlite3_config(SQLITE_CONFIG_URI, 1);
33141   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
33142   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
33143   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
33144 }
33145 
33146 /*
33147 ** Output text to the console in a font that attracts extra attention.
33148 */
33149 #if defined(_WIN32) || defined(WIN32)
printBold(const char * zText)33150 static void printBold(const char *zText){
33151 #if !SQLITE_OS_WINRT
33152   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
33153   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
33154   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
33155   SetConsoleTextAttribute(out,
33156          FOREGROUND_RED|FOREGROUND_INTENSITY
33157   );
33158 #endif
33159   sputz(stdout, zText);
33160 #if !SQLITE_OS_WINRT
33161   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
33162 #endif
33163 }
33164 #else
printBold(const char * zText)33165 static void printBold(const char *zText){
33166   sqlite3_fprintf(stdout, "\033[1m%s\033[0m", zText);
33167 }
33168 #endif
33169 
33170 /*
33171 ** Get the argument to an --option.  Throw an error and die if no argument
33172 ** is available.
33173 */
cmdline_option_value(int argc,char ** argv,int i)33174 static char *cmdline_option_value(int argc, char **argv, int i){
33175   if( i==argc ){
33176     sqlite3_fprintf(stderr,
33177             "%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
33178     exit(1);
33179   }
33180   return argv[i];
33181 }
33182 
sayAbnormalExit(void)33183 static void sayAbnormalExit(void){
33184   if( seenInterrupt ) eputz("Program interrupted.\n");
33185 }
33186 
33187 /* Routine to output from vfstrace
33188 */
vfstraceOut(const char * z,void * pArg)33189 static int vfstraceOut(const char *z, void *pArg){
33190   ShellState *p = (ShellState*)pArg;
33191   sqlite3_fputs(z, p->out);
33192   fflush(p->out);
33193   return 1;
33194 }
33195 
33196 #ifndef SQLITE_SHELL_IS_UTF8
33197 #  if (defined(_WIN32) || defined(WIN32)) \
33198    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
33199 #    define SQLITE_SHELL_IS_UTF8          (0)
33200 #  else
33201 #    define SQLITE_SHELL_IS_UTF8          (1)
33202 #  endif
33203 #endif
33204 
33205 #ifdef SQLITE_SHELL_FIDDLE
33206 #  define main fiddle_main
33207 #endif
33208 
33209 #if SQLITE_SHELL_IS_UTF8
main(int argc,char ** argv)33210 int SQLITE_CDECL main(int argc, char **argv){
33211 #else
33212 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
33213   char **argv;
33214 #endif
33215 #ifdef SQLITE_DEBUG
33216   sqlite3_int64 mem_main_enter = 0;
33217 #endif
33218   char *zErrMsg = 0;
33219 #ifdef SQLITE_SHELL_FIDDLE
33220 #  define data shellState
33221 #else
33222   ShellState data;
33223 #endif
33224   const char *zInitFile = 0;
33225   int i;
33226   int rc = 0;
33227   int warnInmemoryDb = 0;
33228   int readStdin = 1;
33229   int nCmd = 0;
33230   int nOptsEnd = argc;
33231   int bEnableVfstrace = 0;
33232   char **azCmd = 0;
33233   const char *zVfs = 0;           /* Value of -vfs command-line option */
33234 #if !SQLITE_SHELL_IS_UTF8
33235   char **argvToFree = 0;
33236   int argcToFree = 0;
33237 #endif
33238   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
33239 
33240 #ifdef SQLITE_SHELL_FIDDLE
33241   stdin_is_interactive = 0;
33242   stdout_is_console = 1;
33243   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
33244 #else
33245   stdin_is_interactive = isatty(0);
33246   stdout_is_console = isatty(1);
33247 #endif
33248   atexit(sayAbnormalExit);
33249 #ifdef SQLITE_DEBUG
33250   mem_main_enter = sqlite3_memory_used();
33251 #endif
33252 #if !defined(_WIN32_WCE)
33253   if( getenv("SQLITE_DEBUG_BREAK") ){
33254     if( isatty(0) && isatty(2) ){
33255       char zLine[100];
33256       sqlite3_fprintf(stderr,
33257             "attach debugger to process %d and press ENTER to continue...",
33258             GETPID());
33259       if( sqlite3_fgets(zLine, sizeof(zLine), stdin)!=0
33260        && cli_strcmp(zLine,"stop")==0
33261       ){
33262         exit(1);
33263       }
33264     }else{
33265 #if defined(_WIN32) || defined(WIN32)
33266 #if SQLITE_OS_WINRT
33267       __debugbreak();
33268 #else
33269       DebugBreak();
33270 #endif
33271 #elif defined(SIGTRAP)
33272       raise(SIGTRAP);
33273 #endif
33274     }
33275   }
33276 #endif
33277   /* Register a valid signal handler early, before much else is done. */
33278 #ifdef SIGINT
33279   signal(SIGINT, interrupt_handler);
33280 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
33281   if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
33282     eputz("No ^C handler.\n");
33283   }
33284 #endif
33285 
33286 #if USE_SYSTEM_SQLITE+0!=1
33287   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
33288     sqlite3_fprintf(stderr,
33289           "SQLite header and source version mismatch\n%s\n%s\n",
33290           sqlite3_sourceid(), SQLITE_SOURCE_ID);
33291     exit(1);
33292   }
33293 #endif
33294   main_init(&data);
33295 
33296   /* On Windows, we must translate command-line arguments into UTF-8.
33297   ** The SQLite memory allocator subsystem has to be enabled in order to
33298   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
33299   ** subsequent sqlite3_config() calls will work.  So copy all results into
33300   ** memory that does not come from the SQLite memory allocator.
33301   */
33302 #if !SQLITE_SHELL_IS_UTF8
33303   sqlite3_initialize();
33304   argvToFree = malloc(sizeof(argv[0])*argc*2);
33305   shell_check_oom(argvToFree);
33306   argcToFree = argc;
33307   argv = argvToFree + argc;
33308   for(i=0; i<argc; i++){
33309     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
33310     i64 n;
33311     shell_check_oom(z);
33312     n = strlen(z);
33313     argv[i] = malloc( n+1 );
33314     shell_check_oom(argv[i]);
33315     memcpy(argv[i], z, n+1);
33316     argvToFree[i] = argv[i];
33317     sqlite3_free(z);
33318   }
33319   sqlite3_shutdown();
33320 #endif
33321 
33322   assert( argc>=1 && argv && argv[0] );
33323   Argv0 = argv[0];
33324 
33325 #ifdef SQLITE_SHELL_DBNAME_PROC
33326   {
33327     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
33328     ** of a C-function that will provide the name of the database file.  Use
33329     ** this compile-time option to embed this shell program in larger
33330     ** applications. */
33331     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
33332     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
33333     warnInmemoryDb = 0;
33334   }
33335 #endif
33336 
33337   /* Do an initial pass through the command-line argument to locate
33338   ** the name of the database file, the name of the initialization file,
33339   ** the size of the alternative malloc heap, options affecting commands
33340   ** or SQL run from the command line, and the first command to execute.
33341   */
33342 #ifndef SQLITE_SHELL_FIDDLE
33343   verify_uninitialized();
33344 #endif
33345   for(i=1; i<argc; i++){
33346     char *z;
33347     z = argv[i];
33348     if( z[0]!='-' || i>nOptsEnd ){
33349       if( data.aAuxDb->zDbFilename==0 ){
33350         data.aAuxDb->zDbFilename = z;
33351       }else{
33352         /* Excess arguments are interpreted as SQL (or dot-commands) and
33353         ** mean that nothing is read from stdin */
33354         readStdin = 0;
33355         nCmd++;
33356         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
33357         shell_check_oom(azCmd);
33358         azCmd[nCmd-1] = z;
33359       }
33360       continue;
33361     }
33362     if( z[1]=='-' ) z++;
33363     if( cli_strcmp(z, "-")==0 ){
33364       nOptsEnd = i;
33365       continue;
33366     }else if( cli_strcmp(z,"-separator")==0
33367      || cli_strcmp(z,"-nullvalue")==0
33368      || cli_strcmp(z,"-newline")==0
33369      || cli_strcmp(z,"-cmd")==0
33370     ){
33371       (void)cmdline_option_value(argc, argv, ++i);
33372     }else if( cli_strcmp(z,"-init")==0 ){
33373       zInitFile = cmdline_option_value(argc, argv, ++i);
33374     }else if( cli_strcmp(z,"-interactive")==0 ){
33375     }else if( cli_strcmp(z,"-batch")==0 ){
33376       /* Need to check for batch mode here to so we can avoid printing
33377       ** informational messages (like from process_sqliterc) before
33378       ** we do the actual processing of arguments later in a second pass.
33379       */
33380       stdin_is_interactive = 0;
33381     }else if( cli_strcmp(z,"-utf8")==0 ){
33382     }else if( cli_strcmp(z,"-no-utf8")==0 ){
33383     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
33384       int val = 0;
33385       sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
33386       assert( val==0 );
33387     }else if( cli_strcmp(z,"-heap")==0 ){
33388 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
33389       const char *zSize;
33390       sqlite3_int64 szHeap;
33391 
33392       zSize = cmdline_option_value(argc, argv, ++i);
33393       szHeap = integerValue(zSize);
33394       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
33395       verify_uninitialized();
33396       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
33397 #else
33398       (void)cmdline_option_value(argc, argv, ++i);
33399 #endif
33400     }else if( cli_strcmp(z,"-pagecache")==0 ){
33401       sqlite3_int64 n, sz;
33402       sz = integerValue(cmdline_option_value(argc,argv,++i));
33403       if( sz>70000 ) sz = 70000;
33404       if( sz<0 ) sz = 0;
33405       n = integerValue(cmdline_option_value(argc,argv,++i));
33406       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
33407         n = 0xffffffffffffLL/sz;
33408       }
33409       verify_uninitialized();
33410       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
33411                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
33412       data.shellFlgs |= SHFLG_Pagecache;
33413     }else if( cli_strcmp(z,"-lookaside")==0 ){
33414       int n, sz;
33415       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
33416       if( sz<0 ) sz = 0;
33417       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
33418       if( n<0 ) n = 0;
33419       verify_uninitialized();
33420       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
33421       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
33422     }else if( cli_strcmp(z,"-threadsafe")==0 ){
33423       int n;
33424       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
33425       verify_uninitialized();
33426       switch( n ){
33427          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
33428          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
33429          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
33430       }
33431     }else if( cli_strcmp(z,"-vfstrace")==0 ){
33432       bEnableVfstrace = 1;
33433 #ifdef SQLITE_ENABLE_MULTIPLEX
33434     }else if( cli_strcmp(z,"-multiplex")==0 ){
33435       extern int sqlite3_multiplex_initialize(const char*,int);
33436       sqlite3_multiplex_initialize(0, 1);
33437 #endif
33438     }else if( cli_strcmp(z,"-mmap")==0 ){
33439       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
33440       verify_uninitialized();
33441       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
33442 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
33443     }else if( cli_strcmp(z,"-sorterref")==0 ){
33444       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
33445       verify_uninitialized();
33446       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
33447 #endif
33448     }else if( cli_strcmp(z,"-vfs")==0 ){
33449       zVfs = cmdline_option_value(argc, argv, ++i);
33450 #ifdef SQLITE_HAVE_ZLIB
33451     }else if( cli_strcmp(z,"-zip")==0 ){
33452       data.openMode = SHELL_OPEN_ZIPFILE;
33453 #endif
33454     }else if( cli_strcmp(z,"-append")==0 ){
33455       data.openMode = SHELL_OPEN_APPENDVFS;
33456 #ifndef SQLITE_OMIT_DESERIALIZE
33457     }else if( cli_strcmp(z,"-deserialize")==0 ){
33458       data.openMode = SHELL_OPEN_DESERIALIZE;
33459     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
33460       data.szMax = integerValue(argv[++i]);
33461 #endif
33462     }else if( cli_strcmp(z,"-readonly")==0 ){
33463       data.openMode = SHELL_OPEN_READONLY;
33464     }else if( cli_strcmp(z,"-nofollow")==0 ){
33465       data.openFlags = SQLITE_OPEN_NOFOLLOW;
33466 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
33467     }else if( cli_strncmp(z, "-A",2)==0 ){
33468       /* All remaining command-line arguments are passed to the ".archive"
33469       ** command, so ignore them */
33470       break;
33471 #endif
33472     }else if( cli_strcmp(z, "-memtrace")==0 ){
33473       sqlite3MemTraceActivate(stderr);
33474     }else if( cli_strcmp(z, "-pcachetrace")==0 ){
33475       sqlite3PcacheTraceActivate(stderr);
33476     }else if( cli_strcmp(z,"-bail")==0 ){
33477       bail_on_error = 1;
33478     }else if( cli_strcmp(z,"-nonce")==0 ){
33479       free(data.zNonce);
33480       data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
33481     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
33482       ShellSetFlag(&data,SHFLG_TestingMode);
33483     }else if( cli_strcmp(z,"-safe")==0 ){
33484       /* no-op - catch this on the second pass */
33485     }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
33486       /* skip over the argument */
33487       i++;
33488     }
33489   }
33490 #ifndef SQLITE_SHELL_FIDDLE
33491   if( !bEnableVfstrace ) verify_uninitialized();
33492 #endif
33493 
33494 
33495 #ifdef SQLITE_SHELL_INIT_PROC
33496   {
33497     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
33498     ** of a C-function that will perform initialization actions on SQLite that
33499     ** occur just before or after sqlite3_initialize(). Use this compile-time
33500     ** option to embed this shell program in larger applications. */
33501     extern void SQLITE_SHELL_INIT_PROC(void);
33502     SQLITE_SHELL_INIT_PROC();
33503   }
33504 #else
33505   /* All the sqlite3_config() calls have now been made. So it is safe
33506   ** to call sqlite3_initialize() and process any command line -vfs option. */
33507   sqlite3_initialize();
33508 #endif
33509 
33510   if( zVfs ){
33511     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
33512     if( pVfs ){
33513       sqlite3_vfs_register(pVfs, 1);
33514     }else{
33515       sqlite3_fprintf(stderr,"no such VFS: \"%s\"\n", zVfs);
33516       exit(1);
33517     }
33518   }
33519 
33520   if( data.pAuxDb->zDbFilename==0 ){
33521 #ifndef SQLITE_OMIT_MEMORYDB
33522     data.pAuxDb->zDbFilename = ":memory:";
33523     warnInmemoryDb = argc==1;
33524 #else
33525     sqlite3_fprintf(stderr,
33526                     "%s: Error: no database filename specified\n", Argv0);
33527     return 1;
33528 #endif
33529   }
33530   data.out = stdout;
33531   if( bEnableVfstrace ){
33532     vfstrace_register("trace",0,vfstraceOut, &data, 1);
33533   }
33534 #ifndef SQLITE_SHELL_FIDDLE
33535   sqlite3_appendvfs_init(0,0,0);
33536 #endif
33537 
33538   /* Go ahead and open the database file if it already exists.  If the
33539   ** file does not exist, delay opening it.  This prevents empty database
33540   ** files from being created if a user mistypes the database name argument
33541   ** to the sqlite command-line tool.
33542   */
33543   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
33544     open_db(&data, 0);
33545   }
33546 
33547   /* Process the initialization file if there is one.  If no -init option
33548   ** is given on the command line, look for a file named ~/.sqliterc and
33549   ** try to process it.
33550   */
33551   process_sqliterc(&data,zInitFile);
33552 
33553   /* Make a second pass through the command-line argument and set
33554   ** options.  This second pass is delayed until after the initialization
33555   ** file is processed so that the command-line arguments will override
33556   ** settings in the initialization file.
33557   */
33558   for(i=1; i<argc; i++){
33559     char *z = argv[i];
33560     if( z[0]!='-' || i>=nOptsEnd ) continue;
33561     if( z[1]=='-' ){ z++; }
33562     if( cli_strcmp(z,"-init")==0 ){
33563       i++;
33564     }else if( cli_strcmp(z,"-html")==0 ){
33565       data.mode = MODE_Html;
33566     }else if( cli_strcmp(z,"-list")==0 ){
33567       data.mode = MODE_List;
33568     }else if( cli_strcmp(z,"-quote")==0 ){
33569       data.mode = MODE_Quote;
33570       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
33571       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
33572     }else if( cli_strcmp(z,"-line")==0 ){
33573       data.mode = MODE_Line;
33574     }else if( cli_strcmp(z,"-column")==0 ){
33575       data.mode = MODE_Column;
33576     }else if( cli_strcmp(z,"-json")==0 ){
33577       data.mode = MODE_Json;
33578     }else if( cli_strcmp(z,"-markdown")==0 ){
33579       data.mode = MODE_Markdown;
33580     }else if( cli_strcmp(z,"-table")==0 ){
33581       data.mode = MODE_Table;
33582     }else if( cli_strcmp(z,"-box")==0 ){
33583       data.mode = MODE_Box;
33584     }else if( cli_strcmp(z,"-csv")==0 ){
33585       data.mode = MODE_Csv;
33586       memcpy(data.colSeparator,",",2);
33587     }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
33588       /* See similar code at tag-20250224-1 */
33589       const char *zEsc = argv[++i];
33590       int k;
33591       for(k=0; k<ArraySize(shell_EscModeNames); k++){
33592         if( sqlite3_stricmp(zEsc,shell_EscModeNames[k])==0 ){
33593           data.eEscMode = k;
33594           break;
33595         }
33596       }
33597       if( k>=ArraySize(shell_EscModeNames) ){
33598         sqlite3_fprintf(stderr, "unknown control character escape mode \"%s\""
33599                                 " - choices:", zEsc);
33600         for(k=0; k<ArraySize(shell_EscModeNames); k++){
33601           sqlite3_fprintf(stderr, " %s", shell_EscModeNames[k]);
33602         }
33603         sqlite3_fprintf(stderr, "\n");
33604         exit(1);
33605       }
33606 #ifdef SQLITE_HAVE_ZLIB
33607     }else if( cli_strcmp(z,"-zip")==0 ){
33608       data.openMode = SHELL_OPEN_ZIPFILE;
33609 #endif
33610     }else if( cli_strcmp(z,"-append")==0 ){
33611       data.openMode = SHELL_OPEN_APPENDVFS;
33612 #ifndef SQLITE_OMIT_DESERIALIZE
33613     }else if( cli_strcmp(z,"-deserialize")==0 ){
33614       data.openMode = SHELL_OPEN_DESERIALIZE;
33615     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
33616       data.szMax = integerValue(argv[++i]);
33617 #endif
33618     }else if( cli_strcmp(z,"-readonly")==0 ){
33619       data.openMode = SHELL_OPEN_READONLY;
33620     }else if( cli_strcmp(z,"-nofollow")==0 ){
33621       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
33622     }else if( cli_strcmp(z,"-ascii")==0 ){
33623       data.mode = MODE_Ascii;
33624       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
33625       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
33626     }else if( cli_strcmp(z,"-tabs")==0 ){
33627       data.mode = MODE_List;
33628       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
33629       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
33630     }else if( cli_strcmp(z,"-separator")==0 ){
33631       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
33632                        "%s",cmdline_option_value(argc,argv,++i));
33633     }else if( cli_strcmp(z,"-newline")==0 ){
33634       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
33635                        "%s",cmdline_option_value(argc,argv,++i));
33636     }else if( cli_strcmp(z,"-nullvalue")==0 ){
33637       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
33638                        "%s",cmdline_option_value(argc,argv,++i));
33639     }else if( cli_strcmp(z,"-header")==0 ){
33640       data.showHeader = 1;
33641       ShellSetFlag(&data, SHFLG_HeaderSet);
33642      }else if( cli_strcmp(z,"-noheader")==0 ){
33643       data.showHeader = 0;
33644       ShellSetFlag(&data, SHFLG_HeaderSet);
33645     }else if( cli_strcmp(z,"-echo")==0 ){
33646       ShellSetFlag(&data, SHFLG_Echo);
33647     }else if( cli_strcmp(z,"-eqp")==0 ){
33648       data.autoEQP = AUTOEQP_on;
33649     }else if( cli_strcmp(z,"-eqpfull")==0 ){
33650       data.autoEQP = AUTOEQP_full;
33651     }else if( cli_strcmp(z,"-stats")==0 ){
33652       data.statsOn = 1;
33653     }else if( cli_strcmp(z,"-scanstats")==0 ){
33654       data.scanstatsOn = 1;
33655     }else if( cli_strcmp(z,"-backslash")==0 ){
33656       /* Undocumented command-line option: -backslash
33657       ** Causes C-style backslash escapes to be evaluated in SQL statements
33658       ** prior to sending the SQL into SQLite.  Useful for injecting
33659       ** crazy bytes in the middle of SQL statements for testing and debugging.
33660       */
33661       ShellSetFlag(&data, SHFLG_Backslash);
33662     }else if( cli_strcmp(z,"-bail")==0 ){
33663       /* No-op.  The bail_on_error flag should already be set. */
33664     }else if( cli_strcmp(z,"-version")==0 ){
33665       sqlite3_fprintf(stdout, "%s %s (%d-bit)\n",
33666             sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
33667       return 0;
33668     }else if( cli_strcmp(z,"-interactive")==0 ){
33669       /* Need to check for interactive override here to so that it can
33670       ** affect console setup (for Windows only) and testing thereof.
33671       */
33672       stdin_is_interactive = 1;
33673     }else if( cli_strcmp(z,"-batch")==0 ){
33674       /* already handled */
33675     }else if( cli_strcmp(z,"-utf8")==0 ){
33676       /* already handled */
33677     }else if( cli_strcmp(z,"-no-utf8")==0 ){
33678       /* already handled */
33679     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
33680       /* already handled */
33681     }else if( cli_strcmp(z,"-heap")==0 ){
33682       i++;
33683     }else if( cli_strcmp(z,"-pagecache")==0 ){
33684       i+=2;
33685     }else if( cli_strcmp(z,"-lookaside")==0 ){
33686       i+=2;
33687     }else if( cli_strcmp(z,"-threadsafe")==0 ){
33688       i+=2;
33689     }else if( cli_strcmp(z,"-nonce")==0 ){
33690       i += 2;
33691     }else if( cli_strcmp(z,"-mmap")==0 ){
33692       i++;
33693     }else if( cli_strcmp(z,"-memtrace")==0 ){
33694       i++;
33695     }else if( cli_strcmp(z,"-pcachetrace")==0 ){
33696       i++;
33697 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
33698     }else if( cli_strcmp(z,"-sorterref")==0 ){
33699       i++;
33700 #endif
33701     }else if( cli_strcmp(z,"-vfs")==0 ){
33702       i++;
33703     }else if( cli_strcmp(z,"-vfstrace")==0 ){
33704       i++;
33705 #ifdef SQLITE_ENABLE_MULTIPLEX
33706     }else if( cli_strcmp(z,"-multiplex")==0 ){
33707       i++;
33708 #endif
33709     }else if( cli_strcmp(z,"-help")==0 ){
33710       usage(1);
33711     }else if( cli_strcmp(z,"-cmd")==0 ){
33712       /* Run commands that follow -cmd first and separately from commands
33713       ** that simply appear on the command-line.  This seems goofy.  It would
33714       ** be better if all commands ran in the order that they appear.  But
33715       ** we retain the goofy behavior for historical compatibility. */
33716       if( i==argc-1 ) break;
33717       z = cmdline_option_value(argc,argv,++i);
33718       if( z[0]=='.' ){
33719         rc = do_meta_command(z, &data);
33720         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
33721       }else{
33722         open_db(&data, 0);
33723         rc = shell_exec(&data, z, &zErrMsg);
33724         if( zErrMsg!=0 ){
33725           shellEmitError(zErrMsg);
33726           if( bail_on_error ) return rc!=0 ? rc : 1;
33727         }else if( rc!=0 ){
33728           sqlite3_fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z);
33729           if( bail_on_error ) return rc;
33730         }
33731       }
33732 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
33733     }else if( cli_strncmp(z, "-A", 2)==0 ){
33734       if( nCmd>0 ){
33735         sqlite3_fprintf(stderr,"Error: cannot mix regular SQL or dot-commands"
33736               " with \"%s\"\n", z);
33737         return 1;
33738       }
33739       open_db(&data, OPEN_DB_ZIPFILE);
33740       if( z[2] ){
33741         argv[i] = &z[2];
33742         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
33743       }else{
33744         arDotCommand(&data, 1, argv+i, argc-i);
33745       }
33746       readStdin = 0;
33747       break;
33748 #endif
33749     }else if( cli_strcmp(z,"-safe")==0 ){
33750       data.bSafeMode = data.bSafeModePersist = 1;
33751     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
33752       /* Acted upon in first pass. */
33753     }else{
33754       sqlite3_fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
33755       eputz("Use -help for a list of options.\n");
33756       return 1;
33757     }
33758     data.cMode = data.mode;
33759   }
33760 
33761   if( !readStdin ){
33762     /* Run all arguments that do not begin with '-' as if they were separate
33763     ** command-line inputs, except for the argToSkip argument which contains
33764     ** the database filename.
33765     */
33766     for(i=0; i<nCmd; i++){
33767       echo_group_input(&data, azCmd[i]);
33768       if( azCmd[i][0]=='.' ){
33769         rc = do_meta_command(azCmd[i], &data);
33770         if( rc ){
33771           if( rc==2 ) rc = 0;
33772           goto shell_main_exit;
33773         }
33774       }else{
33775         open_db(&data, 0);
33776         rc = shell_exec(&data, azCmd[i], &zErrMsg);
33777         if( zErrMsg || rc ){
33778           if( zErrMsg!=0 ){
33779             shellEmitError(zErrMsg);
33780           }else{
33781             sqlite3_fprintf(stderr,
33782                             "Error: unable to process SQL: %s\n", azCmd[i]);
33783           }
33784           sqlite3_free(zErrMsg);
33785           if( rc==0 ) rc = 1;
33786           goto shell_main_exit;
33787         }
33788       }
33789     }
33790   }else{
33791     /* Run commands received from standard input
33792     */
33793     if( stdin_is_interactive ){
33794       char *zHome;
33795       char *zHistory;
33796       int nHistory;
33797       sqlite3_fprintf(stdout,
33798             "SQLite version %s %.19s\n" /*extra-version-info*/
33799             "Enter \".help\" for usage hints.\n",
33800             sqlite3_libversion(), sqlite3_sourceid());
33801       if( warnInmemoryDb ){
33802         sputz(stdout, "Connected to a ");
33803         printBold("transient in-memory database");
33804         sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
33805               " persistent database.\n");
33806       }
33807       zHistory = getenv("SQLITE_HISTORY");
33808       if( zHistory ){
33809         zHistory = strdup(zHistory);
33810       }else if( (zHome = find_home_dir(0))!=0 ){
33811         nHistory = strlen30(zHome) + 20;
33812         if( (zHistory = malloc(nHistory))!=0 ){
33813           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
33814         }
33815       }
33816       if( zHistory ){ shell_read_history(zHistory); }
33817 #if (HAVE_READLINE || HAVE_EDITLINE) && !defined(SQLITE_OMIT_READLINE_COMPLETION)
33818       rl_attempted_completion_function = readline_completion;
33819 #elif HAVE_LINENOISE==1
33820       linenoiseSetCompletionCallback(linenoise_completion);
33821 #elif HAVE_LINENOISE==2
33822       linenoiseSetCompletionCallback(linenoise_completion, NULL);
33823 #endif
33824       data.in = 0;
33825       rc = process_input(&data);
33826       if( zHistory ){
33827         shell_stifle_history(2000);
33828         shell_write_history(zHistory);
33829         free(zHistory);
33830       }
33831     }else{
33832       data.in = stdin;
33833       rc = process_input(&data);
33834     }
33835   }
33836 #ifndef SQLITE_SHELL_FIDDLE
33837   /* In WASM mode we have to leave the db state in place so that
33838   ** client code can "push" SQL into it after this call returns. */
33839 #ifndef SQLITE_OMIT_VIRTUALTABLE
33840   if( data.expert.pExpert ){
33841     expertFinish(&data, 1, 0);
33842   }
33843 #endif
33844  shell_main_exit:
33845   free(azCmd);
33846   set_table_name(&data, 0);
33847   if( data.db ){
33848     session_close_all(&data, -1);
33849     close_db(data.db);
33850   }
33851   for(i=0; i<ArraySize(data.aAuxDb); i++){
33852     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
33853     if( data.aAuxDb[i].db ){
33854       session_close_all(&data, i);
33855       close_db(data.aAuxDb[i].db);
33856     }
33857   }
33858   find_home_dir(1);
33859   output_reset(&data);
33860   data.doXdgOpen = 0;
33861   clearTempFile(&data);
33862 #if !SQLITE_SHELL_IS_UTF8
33863   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
33864   free(argvToFree);
33865 #endif
33866   free(data.colWidth);
33867   free(data.zNonce);
33868   /* Clear the global data structure so that valgrind will detect memory
33869   ** leaks */
33870   memset(&data, 0, sizeof(data));
33871   if( bEnableVfstrace ){
33872     vfstrace_unregister("trace");
33873   }
33874 #ifdef SQLITE_DEBUG
33875   if( sqlite3_memory_used()>mem_main_enter ){
33876     sqlite3_fprintf(stderr,"Memory leaked: %u bytes\n",
33877           (unsigned int)(sqlite3_memory_used()-mem_main_enter));
33878   }
33879 #endif
33880 #else /* SQLITE_SHELL_FIDDLE... */
33881   shell_main_exit:
33882 #endif
33883   return rc;
33884 }
33885 
33886 
33887 #ifdef SQLITE_SHELL_FIDDLE
33888 /* Only for emcc experimentation purposes. */
33889 int fiddle_experiment(int a,int b){
33890   return a + b;
33891 }
33892 
33893 /*
33894 ** Returns a pointer to the current DB handle.
33895 */
33896 sqlite3 * fiddle_db_handle(){
33897   return globalDb;
33898 }
33899 
33900 /*
33901 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
33902 ** "main" is assumed. Returns 0 if no db with the given name is
33903 ** open.
33904 */
33905 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
33906   sqlite3_vfs * pVfs = 0;
33907   if(globalDb){
33908     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
33909                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
33910   }
33911   return pVfs;
33912 }
33913 
33914 /* Only for emcc experimentation purposes. */
33915 sqlite3 * fiddle_db_arg(sqlite3 *arg){
33916     sqlite3_fprintf(stdout, "fiddle_db_arg(%p)\n", (const void*)arg);
33917     return arg;
33918 }
33919 
33920 /*
33921 ** Intended to be called via a SharedWorker() while a separate
33922 ** SharedWorker() (which manages the wasm module) is performing work
33923 ** which should be interrupted. Unfortunately, SharedWorker is not
33924 ** portable enough to make real use of.
33925 */
33926 void fiddle_interrupt(void){
33927   if( globalDb ) sqlite3_interrupt(globalDb);
33928 }
33929 
33930 /*
33931 ** Returns the filename of the given db name, assuming "main" if
33932 ** zDbName is NULL. Returns NULL if globalDb is not opened.
33933 */
33934 const char * fiddle_db_filename(const char * zDbName){
33935     return globalDb
33936       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
33937       : NULL;
33938 }
33939 
33940 /*
33941 ** Completely wipes out the contents of the currently-opened database
33942 ** but leaves its storage intact for reuse. If any transactions are
33943 ** active, they are forcibly rolled back.
33944 */
33945 void fiddle_reset_db(void){
33946   if( globalDb ){
33947     int rc;
33948     while( sqlite3_txn_state(globalDb,0)>0 ){
33949       /*
33950       ** Resolve problem reported in
33951       ** https://sqlite.org/forum/forumpost/0b41a25d65
33952       */
33953       sqlite3_fputs("Rolling back in-progress transaction.\n", stdout);
33954       sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
33955     }
33956     rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
33957     if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
33958     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
33959   }
33960 }
33961 
33962 /*
33963 ** Uses the current database's VFS xRead to stream the db file's
33964 ** contents out to the given callback. The callback gets a single
33965 ** chunk of size n (its 2nd argument) on each call and must return 0
33966 ** on success, non-0 on error. This function returns 0 on success,
33967 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
33968 ** code from the callback. Note that this is not thread-friendly: it
33969 ** expects that it will be the only thread reading the db file and
33970 ** takes no measures to ensure that is the case.
33971 */
33972 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
33973   sqlite3_int64 nSize = 0;
33974   sqlite3_int64 nPos = 0;
33975   sqlite3_file * pFile = 0;
33976   unsigned char buf[1024 * 8];
33977   int nBuf = (int)sizeof(buf);
33978   int rc = shellState.db
33979     ? sqlite3_file_control(shellState.db, "main",
33980                            SQLITE_FCNTL_FILE_POINTER, &pFile)
33981     : SQLITE_NOTFOUND;
33982   if( rc ) return rc;
33983   rc = pFile->pMethods->xFileSize(pFile, &nSize);
33984   if( rc ) return rc;
33985   if(nSize % nBuf){
33986     /* DB size is not an even multiple of the buffer size. Reduce
33987     ** buffer size so that we do not unduly inflate the db size when
33988     ** exporting. */
33989     if(0 == nSize % 4096) nBuf = 4096;
33990     else if(0 == nSize % 2048) nBuf = 2048;
33991     else if(0 == nSize % 1024) nBuf = 1024;
33992     else nBuf = 512;
33993   }
33994   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
33995     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
33996     if(SQLITE_IOERR_SHORT_READ == rc){
33997       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
33998     }
33999     if( 0==rc ) rc = xCallback(buf, nBuf);
34000   }
34001   return rc;
34002 }
34003 
34004 /*
34005 ** Trivial exportable function for emscripten. It processes zSql as if
34006 ** it were input to the sqlite3 shell and redirects all output to the
34007 ** wasm binding. fiddle_main() must have been called before this
34008 ** is called, or results are undefined.
34009 */
34010 void fiddle_exec(const char * zSql){
34011   if(zSql && *zSql){
34012     if('.'==*zSql) puts(zSql);
34013     shellState.wasm.zInput = zSql;
34014     shellState.wasm.zPos = zSql;
34015     process_input(&shellState);
34016     shellState.wasm.zInput = shellState.wasm.zPos = 0;
34017   }
34018 }
34019 #endif /* SQLITE_SHELL_FIDDLE */
34020