xref: /aosp_15_r20/external/sqlite/dist/sqlite-autoconf-3440300/orig/shell.c (revision a3141fd39888aecc864dfb08485df64ff6c387f9)
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37 typedef unsigned int u32;
38 typedef unsigned short int u16;
39 
40 /*
41 ** Optionally #include a user-defined header, whereby compilation options
42 ** may be set prior to where they take effect, but after platform setup.
43 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
44 ** file. Note that this macro has a like effect on sqlite3.c compilation.
45 */
46 # define SHELL_STRINGIFY_(f) #f
47 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
48 #ifdef SQLITE_CUSTOM_INCLUDE
49 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
50 #endif
51 
52 /*
53 ** Determine if we are dealing with WinRT, which provides only a subset of
54 ** the full Win32 API.
55 */
56 #if !defined(SQLITE_OS_WINRT)
57 # define SQLITE_OS_WINRT 0
58 #endif
59 
60 /*
61 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
62 ** somewhat for use as a WASM module in a web browser. This flag
63 ** should only be used when building the "fiddle" web application, as
64 ** the browser-mode build has much different user input requirements
65 ** and this build mode rewires the user input subsystem to account for
66 ** that.
67 */
68 
69 /*
70 ** Warning pragmas copied from msvc.h in the core.
71 */
72 #if defined(_MSC_VER)
73 #pragma warning(disable : 4054)
74 #pragma warning(disable : 4055)
75 #pragma warning(disable : 4100)
76 #pragma warning(disable : 4127)
77 #pragma warning(disable : 4130)
78 #pragma warning(disable : 4152)
79 #pragma warning(disable : 4189)
80 #pragma warning(disable : 4206)
81 #pragma warning(disable : 4210)
82 #pragma warning(disable : 4232)
83 #pragma warning(disable : 4244)
84 #pragma warning(disable : 4305)
85 #pragma warning(disable : 4306)
86 #pragma warning(disable : 4702)
87 #pragma warning(disable : 4706)
88 #endif /* defined(_MSC_VER) */
89 
90 /*
91 ** No support for loadable extensions in VxWorks.
92 */
93 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
94 # define SQLITE_OMIT_LOAD_EXTENSION 1
95 #endif
96 
97 /*
98 ** Enable large-file support for fopen() and friends on unix.
99 */
100 #ifndef SQLITE_DISABLE_LFS
101 # define _LARGE_FILE       1
102 # ifndef _FILE_OFFSET_BITS
103 #   define _FILE_OFFSET_BITS 64
104 # endif
105 # define _LARGEFILE_SOURCE 1
106 #endif
107 
108 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
109 /*
110 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
111 ** to expose strdup().
112 */
113 # define _POSIX_SOURCE
114 #endif
115 
116 #include <stdlib.h>
117 #include <string.h>
118 #include <stdio.h>
119 #include <assert.h>
120 #include <math.h>
121 #include "sqlite3.h"
122 typedef sqlite3_int64 i64;
123 typedef sqlite3_uint64 u64;
124 typedef unsigned char u8;
125 #if SQLITE_USER_AUTHENTICATION
126 # include "sqlite3userauth.h"
127 #endif
128 #include <ctype.h>
129 #include <stdarg.h>
130 
131 #if !defined(_WIN32) && !defined(WIN32)
132 # include <signal.h>
133 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
134 #  include <pwd.h>
135 # endif
136 #endif
137 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
138 # include <unistd.h>
139 # include <dirent.h>
140 # define GETPID getpid
141 # if defined(__MINGW32__)
142 #  define DIRENT dirent
143 #  ifndef S_ISLNK
144 #   define S_ISLNK(mode) (0)
145 #  endif
146 # endif
147 #else
148 # define GETPID (int)GetCurrentProcessId
149 #endif
150 #include <sys/types.h>
151 #include <sys/stat.h>
152 
153 #if HAVE_READLINE
154 # include <readline/readline.h>
155 # include <readline/history.h>
156 #endif
157 
158 #if HAVE_EDITLINE
159 # include <editline/readline.h>
160 #endif
161 
162 #if HAVE_EDITLINE || HAVE_READLINE
163 
164 # define shell_add_history(X) add_history(X)
165 # define shell_read_history(X) read_history(X)
166 # define shell_write_history(X) write_history(X)
167 # define shell_stifle_history(X) stifle_history(X)
168 # define shell_readline(X) readline(X)
169 
170 #elif HAVE_LINENOISE
171 
172 # include "linenoise.h"
173 # define shell_add_history(X) linenoiseHistoryAdd(X)
174 # define shell_read_history(X) linenoiseHistoryLoad(X)
175 # define shell_write_history(X) linenoiseHistorySave(X)
176 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
177 # define shell_readline(X) linenoise(X)
178 
179 #else
180 
181 # define shell_read_history(X)
182 # define shell_write_history(X)
183 # define shell_stifle_history(X)
184 
185 # define SHELL_USE_LOCAL_GETLINE 1
186 #endif
187 
188 #ifndef deliberate_fall_through
189 /* Quiet some compilers about some of our intentional code. */
190 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
191 #  define deliberate_fall_through __attribute__((fallthrough));
192 # else
193 #  define deliberate_fall_through
194 # endif
195 #endif
196 
197 #if defined(_WIN32) || defined(WIN32)
198 # if SQLITE_OS_WINRT
199 #  define SQLITE_OMIT_POPEN 1
200 # else
201 #  include <io.h>
202 #  include <fcntl.h>
203 #  define isatty(h) _isatty(h)
204 #  ifndef access
205 #   define access(f,m) _access((f),(m))
206 #  endif
207 #  ifndef unlink
208 #   define unlink _unlink
209 #  endif
210 #  ifndef strdup
211 #   define strdup _strdup
212 #  endif
213 #  undef popen
214 #  define popen _popen
215 #  undef pclose
216 #  define pclose _pclose
217 # endif
218 #else
219  /* Make sure isatty() has a prototype. */
220  extern int isatty(int);
221 
222 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
223   /* popen and pclose are not C89 functions and so are
224   ** sometimes omitted from the <stdio.h> header */
225    extern FILE *popen(const char*,const char*);
226    extern int pclose(FILE*);
227 # else
228 #  define SQLITE_OMIT_POPEN 1
229 # endif
230 #endif
231 
232 #if defined(_WIN32_WCE)
233 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
234  * thus we always assume that we have a console. That can be
235  * overridden with the -batch command line option.
236  */
237 #define isatty(x) 1
238 #endif
239 
240 /* ctype macros that work with signed characters */
241 #define IsSpace(X)  isspace((unsigned char)X)
242 #define IsDigit(X)  isdigit((unsigned char)X)
243 #define ToLower(X)  (char)tolower((unsigned char)X)
244 
245 #if defined(_WIN32) || defined(WIN32)
246 #if SQLITE_OS_WINRT
247 #include <intrin.h>
248 #endif
249 #undef WIN32_LEAN_AND_MEAN
250 #define WIN32_LEAN_AND_MEAN
251 #include <windows.h>
252 
253 /* string conversion routines only needed on Win32 */
254 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
255 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
256 #endif
257 
258 /* Use console I/O package as a direct INCLUDE. */
259 #define SQLITE_INTERNAL_LINKAGE static
260 
261 #ifdef SQLITE_SHELL_FIDDLE
262 /* Deselect most features from the console I/O package for Fiddle. */
263 # define SQLITE_CIO_NO_REDIRECT
264 # define SQLITE_CIO_NO_CLASSIFY
265 # define SQLITE_CIO_NO_TRANSLATE
266 # define SQLITE_CIO_NO_SETMODE
267 #endif
268 /************************* Begin ../ext/consio/console_io.h ******************/
269 /*
270 ** 2023 November 1
271 **
272 ** The author disclaims copyright to this source code.  In place of
273 ** a legal notice, here is a blessing:
274 **
275 **    May you do good and not evil.
276 **    May you find forgiveness for yourself and forgive others.
277 **    May you share freely, never taking more than you give.
278 **
279 ********************************************************************************
280 ** This file exposes various interfaces used for console and other I/O
281 ** by the SQLite project command-line tools. These interfaces are used
282 ** at either source conglomeration time, compilation time, or run time.
283 ** This source provides for either inclusion into conglomerated,
284 ** "single-source" forms or separate compilation then linking.
285 **
286 ** Platform dependencies are "hidden" here by various stratagems so
287 ** that, provided certain conditions are met, the programs using this
288 ** source or object code compiled from it need no explicit conditional
289 ** compilation in their source for their console and stream I/O.
290 **
291 ** The symbols and functionality exposed here are not a public API.
292 ** This code may change in tandem with other project code as needed.
293 **
294 ** When this .h file and its companion .c are directly incorporated into
295 ** a source conglomeration (such as shell.c), the preprocessor symbol
296 ** CIO_WIN_WC_XLATE is defined as 0 or 1, reflecting whether console I/O
297 ** translation for Windows is effected for the build.
298 */
299 
300 #ifndef SQLITE_INTERNAL_LINKAGE
301 # define SQLITE_INTERNAL_LINKAGE extern /* external to translation unit */
302 # include <stdio.h>
303 #else
304 # define SHELL_NO_SYSINC /* Better yet, modify mkshellc.tcl for this. */
305 #endif
306 
307 #ifndef SQLITE3_H
308 /* # include "sqlite3.h" */
309 #endif
310 
311 #ifndef SQLITE_CIO_NO_CLASSIFY
312 
313 /* Define enum for use with following function. */
314 typedef enum StreamsAreConsole {
315   SAC_NoConsole = 0,
316   SAC_InConsole = 1, SAC_OutConsole = 2, SAC_ErrConsole = 4,
317   SAC_AnyConsole = 0x7
318 } StreamsAreConsole;
319 
320 /*
321 ** Classify the three standard I/O streams according to whether
322 ** they are connected to a console attached to the process.
323 **
324 ** Returns the bit-wise OR of SAC_{In,Out,Err}Console values,
325 ** or SAC_NoConsole if none of the streams reaches a console.
326 **
327 ** This function should be called before any I/O is done with
328 ** the given streams. As a side-effect, the given inputs are
329 ** recorded so that later I/O operations on them may be done
330 ** differently than the C library FILE* I/O would be done,
331 ** iff the stream is used for the I/O functions that follow,
332 ** and to support the ones that use an implicit stream.
333 **
334 ** On some platforms, stream or console mode alteration (aka
335 ** "Setup") may be made which is undone by consoleRestore().
336 */
337 SQLITE_INTERNAL_LINKAGE StreamsAreConsole
338 consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr );
339 /* A usual call for convenience: */
340 #define SQLITE_STD_CONSOLE_INIT() consoleClassifySetup(stdin,stdout,stderr)
341 
342 /*
343 ** After an initial call to consoleClassifySetup(...), renew
344 ** the same setup it effected. (A call not after is an error.)
345 ** This will restore state altered by consoleRestore();
346 **
347 ** Applications which run an inferior (child) process which
348 ** inherits the same I/O streams may call this function after
349 ** such a process exits to guard against console mode changes.
350 */
351 SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void);
352 
353 /*
354 ** Undo any side-effects left by consoleClassifySetup(...).
355 **
356 ** This should be called after consoleClassifySetup() and
357 ** before the process terminates normally. It is suitable
358 ** for use with the atexit() C library procedure. After
359 ** this call, no console I/O should be done until one of
360 ** console{Classify or Renew}Setup(...) is called again.
361 **
362 ** Applications which run an inferior (child) process that
363 ** inherits the same I/O streams might call this procedure
364 ** before so that said process will have a console setup
365 ** however users have configured it or come to expect.
366 */
367 SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void );
368 
369 #else /* defined(SQLITE_CIO_NO_CLASSIFY) */
370 # define consoleClassifySetup(i,o,e)
371 # define consoleRenewSetup()
372 # define consoleRestore()
373 #endif /* defined(SQLITE_CIO_NO_CLASSIFY) */
374 
375 #ifndef SQLITE_CIO_NO_REDIRECT
376 /*
377 ** Set stream to be used for the functions below which write
378 ** to "the designated X stream", where X is Output or Error.
379 ** Returns the previous value.
380 **
381 ** Alternatively, pass the special value, invalidFileStream,
382 ** to get the designated stream value without setting it.
383 **
384 ** Before the designated streams are set, they default to
385 ** those passed to consoleClassifySetup(...), and before
386 ** that is called they default to stdout and stderr.
387 **
388 ** It is error to close a stream so designated, then, without
389 ** designating another, use the corresponding {o,e}Emit(...).
390 */
391 SQLITE_INTERNAL_LINKAGE FILE *invalidFileStream;
392 SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf);
393 # ifdef CONSIO_SET_ERROR_STREAM
394 SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf);
395 # endif
396 #else
397 # define setOutputStream(pf)
398 # define setErrorStream(pf)
399 #endif /* !defined(SQLITE_CIO_NO_REDIRECT) */
400 
401 #ifndef SQLITE_CIO_NO_TRANSLATE
402 /*
403 ** Emit output like fprintf(). If the output is going to the
404 ** console and translation from UTF-8 is necessary, perform
405 ** the needed translation. Otherwise, write formatted output
406 ** to the provided stream almost as-is, possibly with newline
407 ** translation as specified by set{Binary,Text}Mode().
408 */
409 SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...);
410 /* Like fPrintfUtf8 except stream is always the designated output. */
411 SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...);
412 /* Like fPrintfUtf8 except stream is always the designated error. */
413 SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...);
414 
415 /*
416 ** Emit output like fputs(). If the output is going to the
417 ** console and translation from UTF-8 is necessary, perform
418 ** the needed translation. Otherwise, write given text to the
419 ** provided stream almost as-is, possibly with newline
420 ** translation as specified by set{Binary,Text}Mode().
421 */
422 SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO);
423 /* Like fPutsUtf8 except stream is always the designated output. */
424 SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z);
425 /* Like fPutsUtf8 except stream is always the designated error. */
426 SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z);
427 
428 /*
429 ** Emit output like fPutsUtf8(), except that the length of the
430 ** accepted char or character sequence is limited by nAccept.
431 **
432 ** Returns the number of accepted char values.
433 */
434 #ifdef CONSIO_SPUTB
435 SQLITE_INTERNAL_LINKAGE int
436 fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
437 #endif
438 /* Like fPutbUtf8 except stream is always the designated output. */
439 SQLITE_INTERNAL_LINKAGE int
440 oPutbUtf8(const char *cBuf, int nAccept);
441 /* Like fPutbUtf8 except stream is always the designated error. */
442 #ifdef CONSIO_EPUTB
443 SQLITE_INTERNAL_LINKAGE int
444 ePutbUtf8(const char *cBuf, int nAccept);
445 #endif
446 
447 /*
448 ** Collect input like fgets(...) with special provisions for input
449 ** from the console on platforms that require same. Defers to the
450 ** C library fgets() when input is not from the console. Newline
451 ** translation may be done as set by set{Binary,Text}Mode(). As a
452 ** convenience, pfIn==NULL is treated as stdin.
453 */
454 SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn);
455 /* Like fGetsUtf8 except stream is always the designated input. */
456 /* SQLITE_INTERNAL_LINKAGE char* iGetsUtf8(char *cBuf, int ncMax); */
457 
458 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
459 
460 #ifndef SQLITE_CIO_NO_SETMODE
461 /*
462 ** Set given stream for binary mode, where newline translation is
463 ** not done, or for text mode where, for some platforms, newlines
464 ** are translated to the platform's conventional char sequence.
465 ** If bFlush true, flush the stream.
466 **
467 ** An additional side-effect is that if the stream is one passed
468 ** to consoleClassifySetup() as an output, it is flushed first.
469 **
470 ** Note that binary/text mode has no effect on console I/O
471 ** translation. On all platforms, newline to the console starts
472 ** a new line and CR,LF chars from the console become a newline.
473 */
474 SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *, short bFlush);
475 SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *, short bFlush);
476 #endif
477 
478 #ifdef SQLITE_CIO_PROMPTED_IN
479 typedef struct Prompts {
480   int numPrompts;
481   const char **azPrompts;
482 } Prompts;
483 
484 /*
485 ** Macros for use of a line editor.
486 **
487 ** The following macros define operations involving use of a
488 ** line-editing library or simple console interaction.
489 ** A "T" argument is a text (char *) buffer or filename.
490 ** A "N" argument is an integer.
491 **
492 ** SHELL_ADD_HISTORY(T) // Record text as line(s) of history.
493 ** SHELL_READ_HISTORY(T) // Read history from file named by T.
494 ** SHELL_WRITE_HISTORY(T) // Write history to file named by T.
495 ** SHELL_STIFLE_HISTORY(N) // Limit history to N entries.
496 **
497 ** A console program which does interactive console input is
498 ** expected to call:
499 ** SHELL_READ_HISTORY(T) before collecting such input;
500 ** SHELL_ADD_HISTORY(T) as record-worthy input is taken;
501 ** SHELL_STIFLE_HISTORY(N) after console input ceases; then
502 ** SHELL_WRITE_HISTORY(T) before the program exits.
503 */
504 
505 /*
506 ** Retrieve a single line of input text from an input stream.
507 **
508 ** If pfIn is the input stream passed to consoleClassifySetup(),
509 ** and azPrompt is not NULL, then a prompt is issued before the
510 ** line is collected, as selected by the isContinuation flag.
511 ** Array azPrompt[{0,1}] holds the {main,continuation} prompt.
512 **
513 ** If zBufPrior is not NULL then it is a buffer from a prior
514 ** call to this routine that can be reused, or will be freed.
515 **
516 ** The result is stored in space obtained from malloc() and
517 ** must either be freed by the caller or else passed back to
518 ** this function as zBufPrior for reuse.
519 **
520 ** This function may call upon services of a line-editing
521 ** library to interactively collect line edited input.
522 */
523 SQLITE_INTERNAL_LINKAGE char *
524 shellGetLine(FILE *pfIn, char *zBufPrior, int nLen,
525              short isContinuation, Prompts azPrompt);
526 #endif /* defined(SQLITE_CIO_PROMPTED_IN) */
527 /*
528 ** TBD: Define an interface for application(s) to generate
529 ** completion candidates for use by the line-editor.
530 **
531 ** This may be premature; the CLI is the only application
532 ** that does this. Yet, getting line-editing melded into
533 ** console I/O is desirable because a line-editing library
534 ** may have to establish console operating mode, possibly
535 ** in a way that interferes with the above functionality.
536 */
537 
538 #if !(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))
539 /* Skip over as much z[] input char sequence as is valid UTF-8,
540 ** limited per nAccept char's or whole characters and containing
541 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
542 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
543 ** Limit: nAccept>=0 => char count, nAccept<0 => character
544  */
545 SQLITE_INTERNAL_LINKAGE const char*
546 zSkipValidUtf8(const char *z, int nAccept, long ccm);
547 
548 #endif
549 
550 /************************* End ../ext/consio/console_io.h ********************/
551 /************************* Begin ../ext/consio/console_io.c ******************/
552 /*
553 ** 2023 November 4
554 **
555 ** The author disclaims copyright to this source code.  In place of
556 ** a legal notice, here is a blessing:
557 **
558 **    May you do good and not evil.
559 **    May you find forgiveness for yourself and forgive others.
560 **    May you share freely, never taking more than you give.
561 **
562 ********************************************************************************
563 ** This file implements various interfaces used for console and stream I/O
564 ** by the SQLite project command-line tools, as explained in console_io.h .
565 ** Functions prefixed by "SQLITE_INTERNAL_LINKAGE" behave as described there.
566 */
567 
568 #ifndef SQLITE_CDECL
569 # define SQLITE_CDECL
570 #endif
571 
572 #ifndef SHELL_NO_SYSINC
573 # include <stdarg.h>
574 # include <string.h>
575 # include <stdlib.h>
576 # include <limits.h>
577 # include <assert.h>
578 # include "console_io.h"
579 /* # include "sqlite3.h" */
580 #endif
581 
582 #ifndef SQLITE_CIO_NO_TRANSLATE
583 # if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
584 #  ifndef SHELL_NO_SYSINC
585 #   include <io.h>
586 #   include <fcntl.h>
587 #   undef WIN32_LEAN_AND_MEAN
588 #   define WIN32_LEAN_AND_MEAN
589 #   include <windows.h>
590 #  endif
591 #  define CIO_WIN_WC_XLATE 1 /* Use WCHAR Windows APIs for console I/O */
592 # else
593 #  ifndef SHELL_NO_SYSINC
594 #   include <unistd.h>
595 #  endif
596 #  define CIO_WIN_WC_XLATE 0 /* Use plain C library stream I/O at console */
597 # endif
598 #else
599 # define CIO_WIN_WC_XLATE 0 /* Not exposing translation routines at all */
600 #endif
601 
602 #if CIO_WIN_WC_XLATE
603 /* Character used to represent a known-incomplete UTF-8 char group (�) */
604 static WCHAR cBadGroup = 0xfffd;
605 #endif
606 
607 #if CIO_WIN_WC_XLATE
handleOfFile(FILE * pf)608 static HANDLE handleOfFile(FILE *pf){
609   int fileDesc = _fileno(pf);
610   union { intptr_t osfh; HANDLE fh; } fid = {
611     (fileDesc>=0)? _get_osfhandle(fileDesc) : (intptr_t)INVALID_HANDLE_VALUE
612   };
613   return fid.fh;
614 }
615 #endif
616 
617 #ifndef SQLITE_CIO_NO_TRANSLATE
618 typedef struct PerStreamTags {
619 # if CIO_WIN_WC_XLATE
620   HANDLE hx;
621   DWORD consMode;
622   char acIncomplete[4];
623 # else
624   short reachesConsole;
625 # endif
626   FILE *pf;
627 } PerStreamTags;
628 
629 /* Define NULL-like value for things which can validly be 0. */
630 # define SHELL_INVALID_FILE_PTR ((FILE *)~0)
631 # if CIO_WIN_WC_XLATE
632 #  define SHELL_INVALID_CONS_MODE 0xFFFF0000
633 # endif
634 
635 # if CIO_WIN_WC_XLATE
636 #  define PST_INITIALIZER { INVALID_HANDLE_VALUE, SHELL_INVALID_CONS_MODE, \
637       {0,0,0,0}, SHELL_INVALID_FILE_PTR }
638 # else
639 #  define PST_INITIALIZER { 0, SHELL_INVALID_FILE_PTR }
640 # endif
641 
642 /* Quickly say whether a known output is going to the console. */
643 # if CIO_WIN_WC_XLATE
pstReachesConsole(PerStreamTags * ppst)644 static short pstReachesConsole(PerStreamTags *ppst){
645   return (ppst->hx != INVALID_HANDLE_VALUE);
646 }
647 # else
648 #  define pstReachesConsole(ppst) 0
649 # endif
650 
651 # if CIO_WIN_WC_XLATE
restoreConsoleArb(PerStreamTags * ppst)652 static void restoreConsoleArb(PerStreamTags *ppst){
653   if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode);
654 }
655 # else
656 #  define restoreConsoleArb(ppst)
657 # endif
658 
659 /* Say whether FILE* appears to be a console, collect associated info. */
streamOfConsole(FILE * pf,PerStreamTags * ppst)660 static short streamOfConsole(FILE *pf, /* out */ PerStreamTags *ppst){
661 # if CIO_WIN_WC_XLATE
662   short rv = 0;
663   DWORD dwCM = SHELL_INVALID_CONS_MODE;
664   HANDLE fh = handleOfFile(pf);
665   ppst->pf = pf;
666   if( INVALID_HANDLE_VALUE != fh ){
667     rv = (GetFileType(fh) == FILE_TYPE_CHAR && GetConsoleMode(fh,&dwCM));
668   }
669   ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE;
670   ppst->consMode = dwCM;
671   return rv;
672 # else
673   ppst->pf = pf;
674   ppst->reachesConsole = ( (short)isatty(fileno(pf)) );
675   return ppst->reachesConsole;
676 # endif
677 }
678 
679 # if CIO_WIN_WC_XLATE
680 /* Define console modes for use with the Windows Console API. */
681 #  define SHELL_CONI_MODE \
682   (ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE | ENABLE_LINE_INPUT | 0x80 \
683   | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS | ENABLE_PROCESSED_INPUT)
684 #  define SHELL_CONO_MODE (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT \
685   | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
686 # endif
687 
688 typedef struct ConsoleInfo {
689   PerStreamTags pstSetup[3];
690   PerStreamTags pstDesignated[3];
691   StreamsAreConsole sacSetup;
692 } ConsoleInfo;
693 
isValidStreamInfo(PerStreamTags * ppst)694 static short isValidStreamInfo(PerStreamTags *ppst){
695   return (ppst->pf != SHELL_INVALID_FILE_PTR);
696 }
697 
698 static ConsoleInfo consoleInfo = {
699   { /* pstSetup */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
700   { /* pstDesignated[] */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
701   SAC_NoConsole /* sacSetup */
702 };
703 
704 SQLITE_INTERNAL_LINKAGE FILE* invalidFileStream = (FILE *)~0;
705 
706 # if CIO_WIN_WC_XLATE
maybeSetupAsConsole(PerStreamTags * ppst,short odir)707 static void maybeSetupAsConsole(PerStreamTags *ppst, short odir){
708   if( pstReachesConsole(ppst) ){
709     DWORD cm = odir? SHELL_CONO_MODE : SHELL_CONI_MODE;
710     SetConsoleMode(ppst->hx, cm);
711   }
712 }
713 # else
714 #  define maybeSetupAsConsole(ppst,odir)
715 # endif
716 
consoleRenewSetup(void)717 SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void){
718 # if CIO_WIN_WC_XLATE
719   int ix = 0;
720   while( ix < 6 ){
721     PerStreamTags *ppst = (ix<3)?
722       &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3];
723     maybeSetupAsConsole(ppst, (ix % 3)>0);
724     ++ix;
725   }
726 # endif
727 }
728 
729 SQLITE_INTERNAL_LINKAGE StreamsAreConsole
consoleClassifySetup(FILE * pfIn,FILE * pfOut,FILE * pfErr)730 consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr ){
731   StreamsAreConsole rv = SAC_NoConsole;
732   FILE* apf[3] = { pfIn, pfOut, pfErr };
733   int ix;
734   for( ix = 2; ix >= 0; --ix ){
735     PerStreamTags *ppst = &consoleInfo.pstSetup[ix];
736     if( streamOfConsole(apf[ix], ppst) ){
737       rv |= (SAC_InConsole<<ix);
738     }
739     consoleInfo.pstDesignated[ix] = *ppst;
740     if( ix > 0 ) fflush(apf[ix]);
741   }
742   consoleInfo.sacSetup = rv;
743   consoleRenewSetup();
744   return rv;
745 }
746 
consoleRestore(void)747 SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void ){
748 # if CIO_WIN_WC_XLATE
749   static ConsoleInfo *pci = &consoleInfo;
750   if( pci->sacSetup ){
751     int ix;
752     for( ix=0; ix<3; ++ix ){
753       if( pci->sacSetup & (SAC_InConsole<<ix) ){
754         PerStreamTags *ppst = &pci->pstSetup[ix];
755         SetConsoleMode(ppst->hx, ppst->consMode);
756       }
757     }
758   }
759 # endif
760 }
761 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
762 
763 #ifdef SQLITE_CIO_INPUT_REDIR
764 /* Say whether given FILE* is among those known, via either
765 ** consoleClassifySetup() or set{Output,Error}Stream, as
766 ** readable, and return an associated PerStreamTags pointer
767 ** if so. Otherwise, return 0.
768 */
isKnownReadable(FILE * pf)769 static PerStreamTags * isKnownReadable(FILE *pf){
770   static PerStreamTags *apst[] = {
771     &consoleInfo.pstDesignated[0], &consoleInfo.pstSetup[0], 0
772   };
773   int ix = 0;
774   do {
775     if( apst[ix]->pf == pf ) break;
776   } while( apst[++ix] != 0 );
777   return apst[ix];
778 }
779 #endif
780 
781 #ifndef SQLITE_CIO_NO_TRANSLATE
782 /* Say whether given FILE* is among those known, via either
783 ** consoleClassifySetup() or set{Output,Error}Stream, as
784 ** writable, and return an associated PerStreamTags pointer
785 ** if so. Otherwise, return 0.
786 */
isKnownWritable(FILE * pf)787 static PerStreamTags * isKnownWritable(FILE *pf){
788   static PerStreamTags *apst[] = {
789     &consoleInfo.pstDesignated[1], &consoleInfo.pstDesignated[2],
790     &consoleInfo.pstSetup[1], &consoleInfo.pstSetup[2], 0
791   };
792   int ix = 0;
793   do {
794     if( apst[ix]->pf == pf ) break;
795   } while( apst[++ix] != 0 );
796   return apst[ix];
797 }
798 
designateEmitStream(FILE * pf,unsigned chix)799 static FILE *designateEmitStream(FILE *pf, unsigned chix){
800   FILE *rv = consoleInfo.pstDesignated[chix].pf;
801   if( pf == invalidFileStream ) return rv;
802   else{
803     /* Setting a possibly new output stream. */
804     PerStreamTags *ppst = isKnownWritable(pf);
805     if( ppst != 0 ){
806       PerStreamTags pst = *ppst;
807       consoleInfo.pstDesignated[chix] = pst;
808     }else streamOfConsole(pf, &consoleInfo.pstDesignated[chix]);
809   }
810   return rv;
811 }
812 
setOutputStream(FILE * pf)813 SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf){
814   return designateEmitStream(pf, 1);
815 }
816 # ifdef CONSIO_SET_ERROR_STREAM
setErrorStream(FILE * pf)817 SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf){
818   return designateEmitStream(pf, 2);
819 }
820 # endif
821 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
822 
823 #ifndef SQLITE_CIO_NO_SETMODE
824 # if CIO_WIN_WC_XLATE
setModeFlushQ(FILE * pf,short bFlush,int mode)825 static void setModeFlushQ(FILE *pf, short bFlush, int mode){
826   if( bFlush ) fflush(pf);
827   _setmode(_fileno(pf), mode);
828 }
829 # else
830 #  define setModeFlushQ(f, b, m) if(b) fflush(f)
831 # endif
832 
setBinaryMode(FILE * pf,short bFlush)833 SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *pf, short bFlush){
834   setModeFlushQ(pf, bFlush, _O_BINARY);
835 }
setTextMode(FILE * pf,short bFlush)836 SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *pf, short bFlush){
837   setModeFlushQ(pf, bFlush, _O_TEXT);
838 }
839 # undef setModeFlushQ
840 
841 #else /* defined(SQLITE_CIO_NO_SETMODE) */
842 # define setBinaryMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
843 # define setTextMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
844 #endif /* defined(SQLITE_CIO_NO_SETMODE) */
845 
846 #ifndef SQLITE_CIO_NO_TRANSLATE
847 # if CIO_WIN_WC_XLATE
848 /* Write buffer cBuf as output to stream known to reach console,
849 ** limited to ncTake char's. Return ncTake on success, else 0. */
conZstrEmit(PerStreamTags * ppst,const char * z,int ncTake)850 static int conZstrEmit(PerStreamTags *ppst, const char *z, int ncTake){
851   int rv = 0;
852   if( z!=NULL ){
853     int nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, 0,0);
854     if( nwc > 0 ){
855       WCHAR *zw = sqlite3_malloc64(nwc*sizeof(WCHAR));
856       if( zw!=NULL ){
857         nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, zw,nwc);
858         if( nwc > 0 ){
859           /* Translation from UTF-8 to UTF-16, then WCHARs out. */
860           if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){
861             rv = ncTake;
862           }
863         }
864         sqlite3_free(zw);
865       }
866     }
867   }
868   return rv;
869 }
870 
871 /* For {f,o,e}PrintfUtf8() when stream is known to reach console. */
conioVmPrintf(PerStreamTags * ppst,const char * zFormat,va_list ap)872 static int conioVmPrintf(PerStreamTags *ppst, const char *zFormat, va_list ap){
873   char *z = sqlite3_vmprintf(zFormat, ap);
874   if( z ){
875     int rv = conZstrEmit(ppst, z, (int)strlen(z));
876     sqlite3_free(z);
877     return rv;
878   }else return 0;
879 }
880 # endif /* CIO_WIN_WC_XLATE */
881 
882 # ifdef CONSIO_GET_EMIT_STREAM
getDesignatedEmitStream(FILE * pf,unsigned chix,PerStreamTags * ppst)883 static PerStreamTags * getDesignatedEmitStream(FILE *pf, unsigned chix,
884                                                PerStreamTags *ppst){
885   PerStreamTags *rv = isKnownWritable(pf);
886   short isValid = (rv!=0)? isValidStreamInfo(rv) : 0;
887   if( rv != 0 && isValid ) return rv;
888   streamOfConsole(pf, ppst);
889   return ppst;
890 }
891 # endif
892 
893 /* Get stream info, either for designated output or error stream when
894 ** chix equals 1 or 2, or for an arbitrary stream when chix == 0.
895 ** In either case, ppst references a caller-owned PerStreamTags
896 ** struct which may be filled in if none of the known writable
897 ** streams is being held by consoleInfo. The ppf parameter is a
898 ** byref output when chix!=0 and a byref input when chix==0.
899  */
900 static PerStreamTags *
getEmitStreamInfo(unsigned chix,PerStreamTags * ppst,FILE ** ppf)901 getEmitStreamInfo(unsigned chix, PerStreamTags *ppst,
902                   /* in/out */ FILE **ppf){
903   PerStreamTags *ppstTry;
904   FILE *pfEmit;
905   if( chix > 0 ){
906     ppstTry = &consoleInfo.pstDesignated[chix];
907     if( !isValidStreamInfo(ppstTry) ){
908       ppstTry = &consoleInfo.pstSetup[chix];
909       pfEmit = ppst->pf;
910     }else pfEmit = ppstTry->pf;
911     if( !isValidStreamInfo(ppstTry) ){
912       pfEmit = (chix > 1)? stderr : stdout;
913       ppstTry = ppst;
914       streamOfConsole(pfEmit, ppstTry);
915     }
916     *ppf = pfEmit;
917   }else{
918     ppstTry = isKnownWritable(*ppf);
919     if( ppstTry != 0 ) return ppstTry;
920     streamOfConsole(*ppf, ppst);
921     return ppst;
922   }
923   return ppstTry;
924 }
925 
oPrintfUtf8(const char * zFormat,...)926 SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...){
927   va_list ap;
928   int rv;
929   FILE *pfOut;
930   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
931 # if CIO_WIN_WC_XLATE
932   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
933 # else
934   getEmitStreamInfo(1, &pst, &pfOut);
935 # endif
936   assert(zFormat!=0);
937   va_start(ap, zFormat);
938 # if CIO_WIN_WC_XLATE
939   if( pstReachesConsole(ppst) ){
940     rv = conioVmPrintf(ppst, zFormat, ap);
941   }else{
942 # endif
943     rv = vfprintf(pfOut, zFormat, ap);
944 # if CIO_WIN_WC_XLATE
945   }
946 # endif
947   va_end(ap);
948   return rv;
949 }
950 
ePrintfUtf8(const char * zFormat,...)951 SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...){
952   va_list ap;
953   int rv;
954   FILE *pfErr;
955   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
956 # if CIO_WIN_WC_XLATE
957   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
958 # else
959   getEmitStreamInfo(2, &pst, &pfErr);
960 # endif
961   assert(zFormat!=0);
962   va_start(ap, zFormat);
963 # if CIO_WIN_WC_XLATE
964   if( pstReachesConsole(ppst) ){
965     rv = conioVmPrintf(ppst, zFormat, ap);
966   }else{
967 # endif
968     rv = vfprintf(pfErr, zFormat, ap);
969 # if CIO_WIN_WC_XLATE
970   }
971 # endif
972   va_end(ap);
973   return rv;
974 }
975 
fPrintfUtf8(FILE * pfO,const char * zFormat,...)976 SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...){
977   va_list ap;
978   int rv;
979   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
980 # if CIO_WIN_WC_XLATE
981   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
982 # else
983   getEmitStreamInfo(0, &pst, &pfO);
984 # endif
985   assert(zFormat!=0);
986   va_start(ap, zFormat);
987 # if CIO_WIN_WC_XLATE
988   if( pstReachesConsole(ppst) ){
989     maybeSetupAsConsole(ppst, 1);
990     rv = conioVmPrintf(ppst, zFormat, ap);
991     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
992   }else{
993 # endif
994     rv = vfprintf(pfO, zFormat, ap);
995 # if CIO_WIN_WC_XLATE
996   }
997 # endif
998   va_end(ap);
999   return rv;
1000 }
1001 
fPutsUtf8(const char * z,FILE * pfO)1002 SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO){
1003   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1004 # if CIO_WIN_WC_XLATE
1005   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1006 # else
1007   getEmitStreamInfo(0, &pst, &pfO);
1008 # endif
1009   assert(z!=0);
1010 # if CIO_WIN_WC_XLATE
1011   if( pstReachesConsole(ppst) ){
1012     int rv;
1013     maybeSetupAsConsole(ppst, 1);
1014     rv = conZstrEmit(ppst, z, (int)strlen(z));
1015     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1016     return rv;
1017   }else {
1018 # endif
1019     return (fputs(z, pfO)<0)? 0 : (int)strlen(z);
1020 # if CIO_WIN_WC_XLATE
1021   }
1022 # endif
1023 }
1024 
ePutsUtf8(const char * z)1025 SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z){
1026   FILE *pfErr;
1027   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1028 # if CIO_WIN_WC_XLATE
1029   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1030 # else
1031   getEmitStreamInfo(2, &pst, &pfErr);
1032 # endif
1033   assert(z!=0);
1034 # if CIO_WIN_WC_XLATE
1035   if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1036   else {
1037 # endif
1038     return (fputs(z, pfErr)<0)? 0 : (int)strlen(z);
1039 # if CIO_WIN_WC_XLATE
1040   }
1041 # endif
1042 }
1043 
oPutsUtf8(const char * z)1044 SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z){
1045   FILE *pfOut;
1046   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1047 # if CIO_WIN_WC_XLATE
1048   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1049 # else
1050   getEmitStreamInfo(1, &pst, &pfOut);
1051 # endif
1052   assert(z!=0);
1053 # if CIO_WIN_WC_XLATE
1054   if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1055   else {
1056 # endif
1057     return (fputs(z, pfOut)<0)? 0 : (int)strlen(z);
1058 # if CIO_WIN_WC_XLATE
1059   }
1060 # endif
1061 }
1062 
1063 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1064 
1065 #if !(defined(SQLITE_CIO_NO_UTF8SCAN) && defined(SQLITE_CIO_NO_TRANSLATE))
1066 /* Skip over as much z[] input char sequence as is valid UTF-8,
1067 ** limited per nAccept char's or whole characters and containing
1068 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
1069 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
1070 ** Limit: nAccept>=0 => char count, nAccept<0 => character
1071  */
1072 SQLITE_INTERNAL_LINKAGE const char*
zSkipValidUtf8(const char * z,int nAccept,long ccm)1073 zSkipValidUtf8(const char *z, int nAccept, long ccm){
1074   int ng = (nAccept<0)? -nAccept : 0;
1075   const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
1076   assert(z!=0);
1077   while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
1078     char c = *z;
1079     if( (c & 0x80) == 0 ){
1080       if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
1081       ++z; /* ASCII */
1082     }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
1083     else{
1084       const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
1085       do{
1086         if( pcLimit && zt >= pcLimit ) return z;
1087         else{
1088           char ct = *zt++;
1089           if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
1090             /* Trailing bytes are too few, too many, or invalid. */
1091             return z;
1092           }
1093         }
1094       } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
1095       z = zt;
1096     }
1097   }
1098   return z;
1099 }
1100 #endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
1101 
1102 #ifndef SQLITE_CIO_NO_TRANSLATE
1103 
1104 #ifdef CONSIO_SPUTB
1105 SQLITE_INTERNAL_LINKAGE int
fPutbUtf8(FILE * pfO,const char * cBuf,int nAccept)1106 fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
1107   assert(pfO!=0);
1108 # if CIO_WIN_WC_XLATE
1109   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1110   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1111   if( pstReachesConsole(ppst) ){
1112     int rv;
1113     maybeSetupAsConsole(ppst, 1);
1114     rv = conZstrEmit(ppst, cBuf, nAccept);
1115     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1116     return rv;
1117   }else {
1118 # endif
1119     return (int)fwrite(cBuf, 1, nAccept, pfO);
1120 # if CIO_WIN_WC_XLATE
1121   }
1122 # endif
1123 }
1124 #endif /* defined(CONSIO_SPUTB) */
1125 
1126 SQLITE_INTERNAL_LINKAGE int
oPutbUtf8(const char * cBuf,int nAccept)1127 oPutbUtf8(const char *cBuf, int nAccept){
1128   FILE *pfOut;
1129   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1130 # if CIO_WIN_WC_XLATE
1131   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1132 # else
1133   getEmitStreamInfo(1, &pst, &pfOut);
1134 # endif
1135 # if CIO_WIN_WC_XLATE
1136   if( pstReachesConsole(ppst) ){
1137     return conZstrEmit(ppst, cBuf, nAccept);
1138   }else {
1139 # endif
1140     return (int)fwrite(cBuf, 1, nAccept, pfOut);
1141 # if CIO_WIN_WC_XLATE
1142   }
1143 # endif
1144 }
1145 
1146 # ifdef CONSIO_EPUTB
1147 SQLITE_INTERNAL_LINKAGE int
ePutbUtf8(const char * cBuf,int nAccept)1148 ePutbUtf8(const char *cBuf, int nAccept){
1149   FILE *pfErr;
1150   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1151   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1152 #  if CIO_WIN_WC_XLATE
1153   if( pstReachesConsole(ppst) ){
1154     return conZstrEmit(ppst, cBuf, nAccept);
1155   }else {
1156 #  endif
1157     return (int)fwrite(cBuf, 1, nAccept, pfErr);
1158 #  if CIO_WIN_WC_XLATE
1159   }
1160 #  endif
1161 }
1162 # endif /* defined(CONSIO_EPUTB) */
1163 
fGetsUtf8(char * cBuf,int ncMax,FILE * pfIn)1164 SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn){
1165   if( pfIn==0 ) pfIn = stdin;
1166 # if CIO_WIN_WC_XLATE
1167   if( pfIn == consoleInfo.pstSetup[0].pf
1168       && (consoleInfo.sacSetup & SAC_InConsole)!=0 ){
1169 #  if CIO_WIN_WC_XLATE==1
1170 #   define SHELL_GULP 150 /* Count of WCHARS to be gulped at a time */
1171     WCHAR wcBuf[SHELL_GULP+1];
1172     int lend = 0, noc = 0;
1173     if( ncMax > 0 ) cBuf[0] = 0;
1174     while( noc < ncMax-8-1 && !lend ){
1175       /* There is room for at least 2 more characters and a 0-terminator. */
1176       int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4;
1177 #   undef SHELL_GULP
1178       DWORD nbr = 0;
1179       BOOL bRC = ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf, na, &nbr, 0);
1180       if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){
1181         /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */
1182         DWORD nbrx;
1183         bRC &= ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf+nbr, 1, &nbrx, 0);
1184         if( bRC ) nbr += nbrx;
1185       }
1186       if( !bRC || (noc==0 && nbr==0) ) return 0;
1187       if( nbr > 0 ){
1188         int nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,0,0,0,0);
1189         if( nmb != 0 && noc+nmb <= ncMax ){
1190           int iseg = noc;
1191           nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,cBuf+noc,nmb,0,0);
1192           noc += nmb;
1193           /* Fixup line-ends as coded by Windows for CR (or "Enter".)
1194           ** This is done without regard for any setMode{Text,Binary}()
1195           ** call that might have been done on the interactive input.
1196           */
1197           if( noc > 0 ){
1198             if( cBuf[noc-1]=='\n' ){
1199               lend = 1;
1200               if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n';
1201             }
1202           }
1203           /* Check for ^Z (anywhere in line) too, to act as EOF. */
1204           while( iseg < noc ){
1205             if( cBuf[iseg]=='\x1a' ){
1206               noc = iseg; /* Chop ^Z and anything following. */
1207               lend = 1; /* Counts as end of line too. */
1208               break;
1209             }
1210             ++iseg;
1211           }
1212         }else break; /* Drop apparent garbage in. (Could assert.) */
1213       }else break;
1214     }
1215     /* If got nothing, (after ^Z chop), must be at end-of-file. */
1216     if( noc > 0 ){
1217       cBuf[noc] = 0;
1218       return cBuf;
1219     }else return 0;
1220 #  endif
1221   }else{
1222 # endif
1223     return fgets(cBuf, ncMax, pfIn);
1224 # if CIO_WIN_WC_XLATE
1225   }
1226 # endif
1227 }
1228 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1229 
1230 #undef SHELL_INVALID_FILE_PTR
1231 
1232 /************************* End ../ext/consio/console_io.c ********************/
1233 
1234 #ifndef SQLITE_SHELL_FIDDLE
1235 /* From here onward, fgets() is redirected to the console_io library. */
1236 # define fgets(b,n,f) fGetsUtf8(b,n,f)
1237 /*
1238  * Define macros for emitting output text in various ways:
1239  *  sputz(s, z)      => emit 0-terminated string z to given stream s
1240  *  sputf(s, f, ...) => emit varargs per format f to given stream s
1241  *  oputz(z)         => emit 0-terminated string z to default stream
1242  *  oputf(f, ...)    => emit varargs per format f to default stream
1243  *  eputz(z)         => emit 0-terminated string z to error stream
1244  *  eputf(f, ...)    => emit varargs per format f to error stream
1245  *  oputb(b, n)      => emit char buffer b[0..n-1] to default stream
1246  *
1247  * Note that the default stream is whatever has been last set via:
1248  *   setOutputStream(FILE *pf)
1249  * This is normally the stream that CLI normal output goes to.
1250  * For the stand-alone CLI, it is stdout with no .output redirect.
1251  */
1252 # define sputz(s,z) fPutsUtf8(z,s)
1253 # define sputf fPrintfUtf8
1254 # define oputz(z) oPutsUtf8(z)
1255 # define oputf oPrintfUtf8
1256 # define eputz(z) ePutsUtf8(z)
1257 # define eputf ePrintfUtf8
1258 # define oputb(buf,na) oPutbUtf8(buf,na)
1259 #else
1260 /* For Fiddle, all console handling and emit redirection is omitted. */
1261 # define sputz(fp,z) fputs(z,fp)
1262 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
1263 # define oputz(z) fputs(z,stdout)
1264 # define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
1265 # define eputz(z) fputs(z,stderr)
1266 # define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
1267 # define oputb(buf,na) fwrite(buf,1,na,stdout)
1268 #endif
1269 
1270 /* True if the timer is enabled */
1271 static int enableTimer = 0;
1272 
1273 /* A version of strcmp() that works with NULL values */
cli_strcmp(const char * a,const char * b)1274 static int cli_strcmp(const char *a, const char *b){
1275   if( a==0 ) a = "";
1276   if( b==0 ) b = "";
1277   return strcmp(a,b);
1278 }
cli_strncmp(const char * a,const char * b,size_t n)1279 static int cli_strncmp(const char *a, const char *b, size_t n){
1280   if( a==0 ) a = "";
1281   if( b==0 ) b = "";
1282   return strncmp(a,b,n);
1283 }
1284 
1285 /* Return the current wall-clock time */
timeOfDay(void)1286 static sqlite3_int64 timeOfDay(void){
1287   static sqlite3_vfs *clockVfs = 0;
1288   sqlite3_int64 t;
1289   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
1290   if( clockVfs==0 ) return 0;  /* Never actually happens */
1291   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
1292     clockVfs->xCurrentTimeInt64(clockVfs, &t);
1293   }else{
1294     double r;
1295     clockVfs->xCurrentTime(clockVfs, &r);
1296     t = (sqlite3_int64)(r*86400000.0);
1297   }
1298   return t;
1299 }
1300 
1301 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
1302 #include <sys/time.h>
1303 #include <sys/resource.h>
1304 
1305 /* VxWorks does not support getrusage() as far as we can determine */
1306 #if defined(_WRS_KERNEL) || defined(__RTP__)
1307 struct rusage {
1308   struct timeval ru_utime; /* user CPU time used */
1309   struct timeval ru_stime; /* system CPU time used */
1310 };
1311 #define getrusage(A,B) memset(B,0,sizeof(*B))
1312 #endif
1313 
1314 /* Saved resource information for the beginning of an operation */
1315 static struct rusage sBegin;  /* CPU time at start */
1316 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
1317 
1318 /*
1319 ** Begin timing an operation
1320 */
beginTimer(void)1321 static void beginTimer(void){
1322   if( enableTimer ){
1323     getrusage(RUSAGE_SELF, &sBegin);
1324     iBegin = timeOfDay();
1325   }
1326 }
1327 
1328 /* Return the difference of two time_structs in seconds */
timeDiff(struct timeval * pStart,struct timeval * pEnd)1329 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
1330   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
1331          (double)(pEnd->tv_sec - pStart->tv_sec);
1332 }
1333 
1334 /*
1335 ** Print the timing results.
1336 */
endTimer(void)1337 static void endTimer(void){
1338   if( enableTimer ){
1339     sqlite3_int64 iEnd = timeOfDay();
1340     struct rusage sEnd;
1341     getrusage(RUSAGE_SELF, &sEnd);
1342     oputf("Run Time: real %.3f user %f sys %f\n",
1343           (iEnd - iBegin)*0.001,
1344           timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
1345           timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
1346   }
1347 }
1348 
1349 #define BEGIN_TIMER beginTimer()
1350 #define END_TIMER endTimer()
1351 #define HAS_TIMER 1
1352 
1353 #elif (defined(_WIN32) || defined(WIN32))
1354 
1355 /* Saved resource information for the beginning of an operation */
1356 static HANDLE hProcess;
1357 static FILETIME ftKernelBegin;
1358 static FILETIME ftUserBegin;
1359 static sqlite3_int64 ftWallBegin;
1360 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
1361                                     LPFILETIME, LPFILETIME);
1362 static GETPROCTIMES getProcessTimesAddr = NULL;
1363 
1364 /*
1365 ** Check to see if we have timer support.  Return 1 if necessary
1366 ** support found (or found previously).
1367 */
hasTimer(void)1368 static int hasTimer(void){
1369   if( getProcessTimesAddr ){
1370     return 1;
1371   } else {
1372 #if !SQLITE_OS_WINRT
1373     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
1374     ** versions. See if the version we are running on has it, and if it
1375     ** does, save off a pointer to it and the current process handle.
1376     */
1377     hProcess = GetCurrentProcess();
1378     if( hProcess ){
1379       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
1380       if( NULL != hinstLib ){
1381         getProcessTimesAddr =
1382             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
1383         if( NULL != getProcessTimesAddr ){
1384           return 1;
1385         }
1386         FreeLibrary(hinstLib);
1387       }
1388     }
1389 #endif
1390   }
1391   return 0;
1392 }
1393 
1394 /*
1395 ** Begin timing an operation
1396 */
beginTimer(void)1397 static void beginTimer(void){
1398   if( enableTimer && getProcessTimesAddr ){
1399     FILETIME ftCreation, ftExit;
1400     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
1401                         &ftKernelBegin,&ftUserBegin);
1402     ftWallBegin = timeOfDay();
1403   }
1404 }
1405 
1406 /* Return the difference of two FILETIME structs in seconds */
timeDiff(FILETIME * pStart,FILETIME * pEnd)1407 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
1408   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
1409   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
1410   return (double) ((i64End - i64Start) / 10000000.0);
1411 }
1412 
1413 /*
1414 ** Print the timing results.
1415 */
endTimer(void)1416 static void endTimer(void){
1417   if( enableTimer && getProcessTimesAddr){
1418     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
1419     sqlite3_int64 ftWallEnd = timeOfDay();
1420     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1421     oputf("Run Time: real %.3f user %f sys %f\n",
1422           (ftWallEnd - ftWallBegin)*0.001,
1423           timeDiff(&ftUserBegin, &ftUserEnd),
1424           timeDiff(&ftKernelBegin, &ftKernelEnd));
1425   }
1426 }
1427 
1428 #define BEGIN_TIMER beginTimer()
1429 #define END_TIMER endTimer()
1430 #define HAS_TIMER hasTimer()
1431 
1432 #else
1433 #define BEGIN_TIMER
1434 #define END_TIMER
1435 #define HAS_TIMER 0
1436 #endif
1437 
1438 /*
1439 ** Used to prevent warnings about unused parameters
1440 */
1441 #define UNUSED_PARAMETER(x) (void)(x)
1442 
1443 /*
1444 ** Number of elements in an array
1445 */
1446 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
1447 
1448 /*
1449 ** If the following flag is set, then command execution stops
1450 ** at an error if we are not interactive.
1451 */
1452 static int bail_on_error = 0;
1453 
1454 /*
1455 ** Treat stdin as an interactive input if the following variable
1456 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
1457 */
1458 static int stdin_is_interactive = 1;
1459 
1460 /*
1461 ** On Windows systems we need to know if standard output is a console
1462 ** in order to show that UTF-16 translation is done in the sign-on
1463 ** banner. The following variable is true if it is the console.
1464 */
1465 static int stdout_is_console = 1;
1466 
1467 /*
1468 ** The following is the open SQLite database.  We make a pointer
1469 ** to this database a static variable so that it can be accessed
1470 ** by the SIGINT handler to interrupt database processing.
1471 */
1472 static sqlite3 *globalDb = 0;
1473 
1474 /*
1475 ** True if an interrupt (Control-C) has been received.
1476 */
1477 static volatile int seenInterrupt = 0;
1478 
1479 /*
1480 ** This is the name of our program. It is set in main(), used
1481 ** in a number of other places, mostly for error messages.
1482 */
1483 static char *Argv0;
1484 
1485 /*
1486 ** Prompt strings. Initialized in main. Settable with
1487 **   .prompt main continue
1488 */
1489 #define PROMPT_LEN_MAX 20
1490 /* First line prompt.   default: "sqlite> " */
1491 static char mainPrompt[PROMPT_LEN_MAX];
1492 /* Continuation prompt. default: "   ...> " */
1493 static char continuePrompt[PROMPT_LEN_MAX];
1494 
1495 /* This is variant of the standard-library strncpy() routine with the
1496 ** one change that the destination string is always zero-terminated, even
1497 ** if there is no zero-terminator in the first n-1 characters of the source
1498 ** string.
1499 */
shell_strncpy(char * dest,const char * src,size_t n)1500 static char *shell_strncpy(char *dest, const char *src, size_t n){
1501   size_t i;
1502   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
1503   dest[i] = 0;
1504   return dest;
1505 }
1506 
1507 /*
1508 ** Optionally disable dynamic continuation prompt.
1509 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
1510 ** or open parentheses level if non-zero, or continuation prompt as set.
1511 ** This facility interacts with the scanner and process_input() where the
1512 ** below 5 macros are used.
1513 */
1514 #ifdef SQLITE_OMIT_DYNAPROMPT
1515 # define CONTINUATION_PROMPT continuePrompt
1516 # define CONTINUE_PROMPT_RESET
1517 # define CONTINUE_PROMPT_AWAITS(p,s)
1518 # define CONTINUE_PROMPT_AWAITC(p,c)
1519 # define CONTINUE_PAREN_INCR(p,n)
1520 # define CONTINUE_PROMPT_PSTATE 0
1521 typedef void *t_NoDynaPrompt;
1522 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
1523 #else
1524 # define CONTINUATION_PROMPT dynamicContinuePrompt()
1525 # define CONTINUE_PROMPT_RESET \
1526   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
1527 # define CONTINUE_PROMPT_AWAITS(p,s) \
1528   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
1529 # define CONTINUE_PROMPT_AWAITC(p,c) \
1530   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
1531 # define CONTINUE_PAREN_INCR(p,n) \
1532   if(p && stdin_is_interactive) (trackParenLevel(p,n))
1533 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
1534 typedef struct DynaPrompt *t_DynaPromptRef;
1535 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
1536 
1537 static struct DynaPrompt {
1538   char dynamicPrompt[PROMPT_LEN_MAX];
1539   char acAwait[2];
1540   int inParenLevel;
1541   char *zScannerAwaits;
1542 } dynPrompt = { {0}, {0}, 0, 0 };
1543 
1544 /* Record parenthesis nesting level change, or force level to 0. */
trackParenLevel(struct DynaPrompt * p,int ni)1545 static void trackParenLevel(struct DynaPrompt *p, int ni){
1546   p->inParenLevel += ni;
1547   if( ni==0 ) p->inParenLevel = 0;
1548   p->zScannerAwaits = 0;
1549 }
1550 
1551 /* Record that a lexeme is opened, or closed with args==0. */
setLexemeOpen(struct DynaPrompt * p,char * s,char c)1552 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
1553   if( s!=0 || c==0 ){
1554     p->zScannerAwaits = s;
1555     p->acAwait[0] = 0;
1556   }else{
1557     p->acAwait[0] = c;
1558     p->zScannerAwaits = p->acAwait;
1559   }
1560 }
1561 
1562 /* Upon demand, derive the continuation prompt to display. */
dynamicContinuePrompt(void)1563 static char *dynamicContinuePrompt(void){
1564   if( continuePrompt[0]==0
1565       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
1566     return continuePrompt;
1567   }else{
1568     if( dynPrompt.zScannerAwaits ){
1569       size_t ncp = strlen(continuePrompt);
1570       size_t ndp = strlen(dynPrompt.zScannerAwaits);
1571       if( ndp > ncp-3 ) return continuePrompt;
1572       strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
1573       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
1574       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1575               PROMPT_LEN_MAX-4);
1576     }else{
1577       if( dynPrompt.inParenLevel>9 ){
1578         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
1579       }else if( dynPrompt.inParenLevel<0 ){
1580         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
1581       }else{
1582         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
1583         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
1584       }
1585       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1586                     PROMPT_LEN_MAX-4);
1587     }
1588   }
1589   return dynPrompt.dynamicPrompt;
1590 }
1591 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
1592 
1593 /* Indicate out-of-memory and exit. */
shell_out_of_memory(void)1594 static void shell_out_of_memory(void){
1595   eputz("Error: out of memory\n");
1596   exit(1);
1597 }
1598 
1599 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
1600 ** out-of-memory error.
1601 */
shell_check_oom(const void * p)1602 static void shell_check_oom(const void *p){
1603   if( p==0 ) shell_out_of_memory();
1604 }
1605 
1606 /*
1607 ** Write I/O traces to the following stream.
1608 */
1609 #ifdef SQLITE_ENABLE_IOTRACE
1610 static FILE *iotrace = 0;
1611 #endif
1612 
1613 /*
1614 ** This routine works like printf in that its first argument is a
1615 ** format string and subsequent arguments are values to be substituted
1616 ** in place of % fields.  The result of formatting this string
1617 ** is written to iotrace.
1618 */
1619 #ifdef SQLITE_ENABLE_IOTRACE
iotracePrintf(const char * zFormat,...)1620 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
1621   va_list ap;
1622   char *z;
1623   if( iotrace==0 ) return;
1624   va_start(ap, zFormat);
1625   z = sqlite3_vmprintf(zFormat, ap);
1626   va_end(ap);
1627   sputf(iotrace, "%s", z);
1628   sqlite3_free(z);
1629 }
1630 #endif
1631 
1632 /*
1633 ** Output string zUtf to Out stream as w characters.  If w is negative,
1634 ** then right-justify the text.  W is the width in UTF-8 characters, not
1635 ** in bytes.  This is different from the %*.*s specification in printf
1636 ** since with %*.*s the width is measured in bytes, not characters.
1637 */
utf8_width_print(int w,const char * zUtf)1638 static void utf8_width_print(int w, const char *zUtf){
1639   int i;
1640   int n;
1641   int aw = w<0 ? -w : w;
1642   if( zUtf==0 ) zUtf = "";
1643   for(i=n=0; zUtf[i]; i++){
1644     if( (zUtf[i]&0xc0)!=0x80 ){
1645       n++;
1646       if( n==aw ){
1647         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
1648         break;
1649       }
1650     }
1651   }
1652   if( n>=aw ){
1653     oputf("%.*s", i, zUtf);
1654   }else if( w<0 ){
1655     oputf("%*s%s", aw-n, "", zUtf);
1656   }else{
1657     oputf("%s%*s", zUtf, aw-n, "");
1658   }
1659 }
1660 
1661 
1662 /*
1663 ** Determines if a string is a number of not.
1664 */
isNumber(const char * z,int * realnum)1665 static int isNumber(const char *z, int *realnum){
1666   if( *z=='-' || *z=='+' ) z++;
1667   if( !IsDigit(*z) ){
1668     return 0;
1669   }
1670   z++;
1671   if( realnum ) *realnum = 0;
1672   while( IsDigit(*z) ){ z++; }
1673   if( *z=='.' ){
1674     z++;
1675     if( !IsDigit(*z) ) return 0;
1676     while( IsDigit(*z) ){ z++; }
1677     if( realnum ) *realnum = 1;
1678   }
1679   if( *z=='e' || *z=='E' ){
1680     z++;
1681     if( *z=='+' || *z=='-' ) z++;
1682     if( !IsDigit(*z) ) return 0;
1683     while( IsDigit(*z) ){ z++; }
1684     if( realnum ) *realnum = 1;
1685   }
1686   return *z==0;
1687 }
1688 
1689 /*
1690 ** Compute a string length that is limited to what can be stored in
1691 ** lower 30 bits of a 32-bit signed integer.
1692 */
strlen30(const char * z)1693 static int strlen30(const char *z){
1694   const char *z2 = z;
1695   while( *z2 ){ z2++; }
1696   return 0x3fffffff & (int)(z2 - z);
1697 }
1698 
1699 /*
1700 ** Return the length of a string in characters.  Multibyte UTF8 characters
1701 ** count as a single character.
1702 */
strlenChar(const char * z)1703 static int strlenChar(const char *z){
1704   int n = 0;
1705   while( *z ){
1706     if( (0xc0&*(z++))!=0x80 ) n++;
1707   }
1708   return n;
1709 }
1710 
1711 /*
1712 ** Return open FILE * if zFile exists, can be opened for read
1713 ** and is an ordinary file or a character stream source.
1714 ** Otherwise return 0.
1715 */
openChrSource(const char * zFile)1716 static FILE * openChrSource(const char *zFile){
1717 #if defined(_WIN32) || defined(WIN32)
1718   struct _stat x = {0};
1719 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1720   /* On Windows, open first, then check the stream nature. This order
1721   ** is necessary because _stat() and sibs, when checking a named pipe,
1722   ** effectively break the pipe as its supplier sees it. */
1723   FILE *rv = fopen(zFile, "rb");
1724   if( rv==0 ) return 0;
1725   if( _fstat(_fileno(rv), &x) != 0
1726       || !STAT_CHR_SRC(x.st_mode)){
1727     fclose(rv);
1728     rv = 0;
1729   }
1730   return rv;
1731 #else
1732   struct stat x = {0};
1733   int rc = stat(zFile, &x);
1734 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
1735   if( rc!=0 ) return 0;
1736   if( STAT_CHR_SRC(x.st_mode) ){
1737     return fopen(zFile, "rb");
1738   }else{
1739     return 0;
1740   }
1741 #endif
1742 #undef STAT_CHR_SRC
1743 }
1744 
1745 /*
1746 ** This routine reads a line of text from FILE in, stores
1747 ** the text in memory obtained from malloc() and returns a pointer
1748 ** to the text.  NULL is returned at end of file, or if malloc()
1749 ** fails.
1750 **
1751 ** If zLine is not NULL then it is a malloced buffer returned from
1752 ** a previous call to this routine that may be reused.
1753 */
local_getline(char * zLine,FILE * in)1754 static char *local_getline(char *zLine, FILE *in){
1755   int nLine = zLine==0 ? 0 : 100;
1756   int n = 0;
1757 
1758   while( 1 ){
1759     if( n+100>nLine ){
1760       nLine = nLine*2 + 100;
1761       zLine = realloc(zLine, nLine);
1762       shell_check_oom(zLine);
1763     }
1764     if( fgets(&zLine[n], nLine - n, in)==0 ){
1765       if( n==0 ){
1766         free(zLine);
1767         return 0;
1768       }
1769       zLine[n] = 0;
1770       break;
1771     }
1772     while( zLine[n] ) n++;
1773     if( n>0 && zLine[n-1]=='\n' ){
1774       n--;
1775       if( n>0 && zLine[n-1]=='\r' ) n--;
1776       zLine[n] = 0;
1777       break;
1778     }
1779   }
1780   return zLine;
1781 }
1782 
1783 /*
1784 ** Retrieve a single line of input text.
1785 **
1786 ** If in==0 then read from standard input and prompt before each line.
1787 ** If isContinuation is true, then a continuation prompt is appropriate.
1788 ** If isContinuation is zero, then the main prompt should be used.
1789 **
1790 ** If zPrior is not NULL then it is a buffer from a prior call to this
1791 ** routine that can be reused.
1792 **
1793 ** The result is stored in space obtained from malloc() and must either
1794 ** be freed by the caller or else passed back into this routine via the
1795 ** zPrior argument for reuse.
1796 */
1797 #ifndef SQLITE_SHELL_FIDDLE
one_input_line(FILE * in,char * zPrior,int isContinuation)1798 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1799   char *zPrompt;
1800   char *zResult;
1801   if( in!=0 ){
1802     zResult = local_getline(zPrior, in);
1803   }else{
1804     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1805 #if SHELL_USE_LOCAL_GETLINE
1806     sputz(stdout, zPrompt);
1807     fflush(stdout);
1808     do{
1809       zResult = local_getline(zPrior, stdin);
1810       zPrior = 0;
1811       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1812       if( zResult==0 ) sqlite3_sleep(50);
1813     }while( zResult==0 && seenInterrupt>0 );
1814 #else
1815     free(zPrior);
1816     zResult = shell_readline(zPrompt);
1817     while( zResult==0 ){
1818       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1819       sqlite3_sleep(50);
1820       if( seenInterrupt==0 ) break;
1821       zResult = shell_readline("");
1822     }
1823     if( zResult && *zResult ) shell_add_history(zResult);
1824 #endif
1825   }
1826   return zResult;
1827 }
1828 #endif /* !SQLITE_SHELL_FIDDLE */
1829 
1830 /*
1831 ** Return the value of a hexadecimal digit.  Return -1 if the input
1832 ** is not a hex digit.
1833 */
hexDigitValue(char c)1834 static int hexDigitValue(char c){
1835   if( c>='0' && c<='9' ) return c - '0';
1836   if( c>='a' && c<='f' ) return c - 'a' + 10;
1837   if( c>='A' && c<='F' ) return c - 'A' + 10;
1838   return -1;
1839 }
1840 
1841 /*
1842 ** Interpret zArg as an integer value, possibly with suffixes.
1843 */
integerValue(const char * zArg)1844 static sqlite3_int64 integerValue(const char *zArg){
1845   sqlite3_int64 v = 0;
1846   static const struct { char *zSuffix; int iMult; } aMult[] = {
1847     { "KiB", 1024 },
1848     { "MiB", 1024*1024 },
1849     { "GiB", 1024*1024*1024 },
1850     { "KB",  1000 },
1851     { "MB",  1000000 },
1852     { "GB",  1000000000 },
1853     { "K",   1000 },
1854     { "M",   1000000 },
1855     { "G",   1000000000 },
1856   };
1857   int i;
1858   int isNeg = 0;
1859   if( zArg[0]=='-' ){
1860     isNeg = 1;
1861     zArg++;
1862   }else if( zArg[0]=='+' ){
1863     zArg++;
1864   }
1865   if( zArg[0]=='0' && zArg[1]=='x' ){
1866     int x;
1867     zArg += 2;
1868     while( (x = hexDigitValue(zArg[0]))>=0 ){
1869       v = (v<<4) + x;
1870       zArg++;
1871     }
1872   }else{
1873     while( IsDigit(zArg[0]) ){
1874       v = v*10 + zArg[0] - '0';
1875       zArg++;
1876     }
1877   }
1878   for(i=0; i<ArraySize(aMult); i++){
1879     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1880       v *= aMult[i].iMult;
1881       break;
1882     }
1883   }
1884   return isNeg? -v : v;
1885 }
1886 
1887 /*
1888 ** A variable length string to which one can append text.
1889 */
1890 typedef struct ShellText ShellText;
1891 struct ShellText {
1892   char *z;
1893   int n;
1894   int nAlloc;
1895 };
1896 
1897 /*
1898 ** Initialize and destroy a ShellText object
1899 */
initText(ShellText * p)1900 static void initText(ShellText *p){
1901   memset(p, 0, sizeof(*p));
1902 }
freeText(ShellText * p)1903 static void freeText(ShellText *p){
1904   free(p->z);
1905   initText(p);
1906 }
1907 
1908 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1909 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1910 ** added to zIn, and the result returned in memory obtained from malloc().
1911 ** zIn, if it was not NULL, is freed.
1912 **
1913 ** If the third argument, quote, is not '\0', then it is used as a
1914 ** quote character for zAppend.
1915 */
appendText(ShellText * p,const char * zAppend,char quote)1916 static void appendText(ShellText *p, const char *zAppend, char quote){
1917   i64 len;
1918   i64 i;
1919   i64 nAppend = strlen30(zAppend);
1920 
1921   len = nAppend+p->n+1;
1922   if( quote ){
1923     len += 2;
1924     for(i=0; i<nAppend; i++){
1925       if( zAppend[i]==quote ) len++;
1926     }
1927   }
1928 
1929   if( p->z==0 || p->n+len>=p->nAlloc ){
1930     p->nAlloc = p->nAlloc*2 + len + 20;
1931     p->z = realloc(p->z, p->nAlloc);
1932     shell_check_oom(p->z);
1933   }
1934 
1935   if( quote ){
1936     char *zCsr = p->z+p->n;
1937     *zCsr++ = quote;
1938     for(i=0; i<nAppend; i++){
1939       *zCsr++ = zAppend[i];
1940       if( zAppend[i]==quote ) *zCsr++ = quote;
1941     }
1942     *zCsr++ = quote;
1943     p->n = (int)(zCsr - p->z);
1944     *zCsr = '\0';
1945   }else{
1946     memcpy(p->z+p->n, zAppend, nAppend);
1947     p->n += nAppend;
1948     p->z[p->n] = '\0';
1949   }
1950 }
1951 
1952 /*
1953 ** Attempt to determine if identifier zName needs to be quoted, either
1954 ** because it contains non-alphanumeric characters, or because it is an
1955 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1956 ** that quoting is required.
1957 **
1958 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1959 */
quoteChar(const char * zName)1960 static char quoteChar(const char *zName){
1961   int i;
1962   if( zName==0 ) return '"';
1963   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1964   for(i=0; zName[i]; i++){
1965     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1966   }
1967   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1968 }
1969 
1970 /*
1971 ** Construct a fake object name and column list to describe the structure
1972 ** of the view, virtual table, or table valued function zSchema.zName.
1973 */
shellFakeSchema(sqlite3 * db,const char * zSchema,const char * zName)1974 static char *shellFakeSchema(
1975   sqlite3 *db,            /* The database connection containing the vtab */
1976   const char *zSchema,    /* Schema of the database holding the vtab */
1977   const char *zName       /* The name of the virtual table */
1978 ){
1979   sqlite3_stmt *pStmt = 0;
1980   char *zSql;
1981   ShellText s;
1982   char cQuote;
1983   char *zDiv = "(";
1984   int nRow = 0;
1985 
1986   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1987                          zSchema ? zSchema : "main", zName);
1988   shell_check_oom(zSql);
1989   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1990   sqlite3_free(zSql);
1991   initText(&s);
1992   if( zSchema ){
1993     cQuote = quoteChar(zSchema);
1994     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1995     appendText(&s, zSchema, cQuote);
1996     appendText(&s, ".", 0);
1997   }
1998   cQuote = quoteChar(zName);
1999   appendText(&s, zName, cQuote);
2000   while( sqlite3_step(pStmt)==SQLITE_ROW ){
2001     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
2002     nRow++;
2003     appendText(&s, zDiv, 0);
2004     zDiv = ",";
2005     if( zCol==0 ) zCol = "";
2006     cQuote = quoteChar(zCol);
2007     appendText(&s, zCol, cQuote);
2008   }
2009   appendText(&s, ")", 0);
2010   sqlite3_finalize(pStmt);
2011   if( nRow==0 ){
2012     freeText(&s);
2013     s.z = 0;
2014   }
2015   return s.z;
2016 }
2017 
2018 /*
2019 ** SQL function:  strtod(X)
2020 **
2021 ** Use the C-library strtod() function to convert string X into a double.
2022 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
2023 ** routines against the C-library.
2024 */
shellStrtod(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2025 static void shellStrtod(
2026   sqlite3_context *pCtx,
2027   int nVal,
2028   sqlite3_value **apVal
2029 ){
2030   char *z = (char*)sqlite3_value_text(apVal[0]);
2031   UNUSED_PARAMETER(nVal);
2032   if( z==0 ) return;
2033   sqlite3_result_double(pCtx, strtod(z,0));
2034 }
2035 
2036 /*
2037 ** SQL function:  dtostr(X)
2038 **
2039 ** Use the C-library printf() function to convert real value X into a string.
2040 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
2041 ** routines against the C-library.
2042 */
shellDtostr(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2043 static void shellDtostr(
2044   sqlite3_context *pCtx,
2045   int nVal,
2046   sqlite3_value **apVal
2047 ){
2048   double r = sqlite3_value_double(apVal[0]);
2049   int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
2050   char z[400];
2051   if( n<1 ) n = 1;
2052   if( n>350 ) n = 350;
2053   sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
2054   sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
2055 }
2056 
2057 
2058 /*
2059 ** SQL function:  shell_module_schema(X)
2060 **
2061 ** Return a fake schema for the table-valued function or eponymous virtual
2062 ** table X.
2063 */
shellModuleSchema(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2064 static void shellModuleSchema(
2065   sqlite3_context *pCtx,
2066   int nVal,
2067   sqlite3_value **apVal
2068 ){
2069   const char *zName;
2070   char *zFake;
2071   UNUSED_PARAMETER(nVal);
2072   zName = (const char*)sqlite3_value_text(apVal[0]);
2073   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
2074   if( zFake ){
2075     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
2076                         -1, sqlite3_free);
2077     free(zFake);
2078   }
2079 }
2080 
2081 /*
2082 ** SQL function:  shell_add_schema(S,X)
2083 **
2084 ** Add the schema name X to the CREATE statement in S and return the result.
2085 ** Examples:
2086 **
2087 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
2088 **
2089 ** Also works on
2090 **
2091 **    CREATE INDEX
2092 **    CREATE UNIQUE INDEX
2093 **    CREATE VIEW
2094 **    CREATE TRIGGER
2095 **    CREATE VIRTUAL TABLE
2096 **
2097 ** This UDF is used by the .schema command to insert the schema name of
2098 ** attached databases into the middle of the sqlite_schema.sql field.
2099 */
shellAddSchemaName(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2100 static void shellAddSchemaName(
2101   sqlite3_context *pCtx,
2102   int nVal,
2103   sqlite3_value **apVal
2104 ){
2105   static const char *aPrefix[] = {
2106      "TABLE",
2107      "INDEX",
2108      "UNIQUE INDEX",
2109      "VIEW",
2110      "TRIGGER",
2111      "VIRTUAL TABLE"
2112   };
2113   int i = 0;
2114   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
2115   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
2116   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
2117   sqlite3 *db = sqlite3_context_db_handle(pCtx);
2118   UNUSED_PARAMETER(nVal);
2119   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
2120     for(i=0; i<ArraySize(aPrefix); i++){
2121       int n = strlen30(aPrefix[i]);
2122       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
2123         char *z = 0;
2124         char *zFake = 0;
2125         if( zSchema ){
2126           char cQuote = quoteChar(zSchema);
2127           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
2128             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
2129           }else{
2130             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
2131           }
2132         }
2133         if( zName
2134          && aPrefix[i][0]=='V'
2135          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
2136         ){
2137           if( z==0 ){
2138             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
2139           }else{
2140             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
2141           }
2142           free(zFake);
2143         }
2144         if( z ){
2145           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
2146           return;
2147         }
2148       }
2149     }
2150   }
2151   sqlite3_result_value(pCtx, apVal[0]);
2152 }
2153 
2154 /*
2155 ** The source code for several run-time loadable extensions is inserted
2156 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
2157 ** code, we need to override some macros to make the included program code
2158 ** work here in the middle of this regular program.
2159 */
2160 #define SQLITE_EXTENSION_INIT1
2161 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
2162 
2163 #if defined(_WIN32) && defined(_MSC_VER)
2164 /************************* Begin test_windirent.h ******************/
2165 /*
2166 ** 2015 November 30
2167 **
2168 ** The author disclaims copyright to this source code.  In place of
2169 ** a legal notice, here is a blessing:
2170 **
2171 **    May you do good and not evil.
2172 **    May you find forgiveness for yourself and forgive others.
2173 **    May you share freely, never taking more than you give.
2174 **
2175 *************************************************************************
2176 ** This file contains declarations for most of the opendir() family of
2177 ** POSIX functions on Win32 using the MSVCRT.
2178 */
2179 
2180 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
2181 #define SQLITE_WINDIRENT_H
2182 
2183 /*
2184 ** We need several data types from the Windows SDK header.
2185 */
2186 
2187 #ifndef WIN32_LEAN_AND_MEAN
2188 #define WIN32_LEAN_AND_MEAN
2189 #endif
2190 
2191 #include "windows.h"
2192 
2193 /*
2194 ** We need several support functions from the SQLite core.
2195 */
2196 
2197 /* #include "sqlite3.h" */
2198 
2199 /*
2200 ** We need several things from the ANSI and MSVCRT headers.
2201 */
2202 
2203 #include <stdio.h>
2204 #include <stdlib.h>
2205 #include <errno.h>
2206 #include <io.h>
2207 #include <limits.h>
2208 #include <sys/types.h>
2209 #include <sys/stat.h>
2210 
2211 /*
2212 ** We may need several defines that should have been in "sys/stat.h".
2213 */
2214 
2215 #ifndef S_ISREG
2216 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
2217 #endif
2218 
2219 #ifndef S_ISDIR
2220 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
2221 #endif
2222 
2223 #ifndef S_ISLNK
2224 #define S_ISLNK(mode) (0)
2225 #endif
2226 
2227 /*
2228 ** We may need to provide the "mode_t" type.
2229 */
2230 
2231 #ifndef MODE_T_DEFINED
2232   #define MODE_T_DEFINED
2233   typedef unsigned short mode_t;
2234 #endif
2235 
2236 /*
2237 ** We may need to provide the "ino_t" type.
2238 */
2239 
2240 #ifndef INO_T_DEFINED
2241   #define INO_T_DEFINED
2242   typedef unsigned short ino_t;
2243 #endif
2244 
2245 /*
2246 ** We need to define "NAME_MAX" if it was not present in "limits.h".
2247 */
2248 
2249 #ifndef NAME_MAX
2250 #  ifdef FILENAME_MAX
2251 #    define NAME_MAX (FILENAME_MAX)
2252 #  else
2253 #    define NAME_MAX (260)
2254 #  endif
2255 #endif
2256 
2257 /*
2258 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
2259 */
2260 
2261 #ifndef NULL_INTPTR_T
2262 #  define NULL_INTPTR_T ((intptr_t)(0))
2263 #endif
2264 
2265 #ifndef BAD_INTPTR_T
2266 #  define BAD_INTPTR_T ((intptr_t)(-1))
2267 #endif
2268 
2269 /*
2270 ** We need to provide the necessary structures and related types.
2271 */
2272 
2273 #ifndef DIRENT_DEFINED
2274 #define DIRENT_DEFINED
2275 typedef struct DIRENT DIRENT;
2276 typedef DIRENT *LPDIRENT;
2277 struct DIRENT {
2278   ino_t d_ino;               /* Sequence number, do not use. */
2279   unsigned d_attributes;     /* Win32 file attributes. */
2280   char d_name[NAME_MAX + 1]; /* Name within the directory. */
2281 };
2282 #endif
2283 
2284 #ifndef DIR_DEFINED
2285 #define DIR_DEFINED
2286 typedef struct DIR DIR;
2287 typedef DIR *LPDIR;
2288 struct DIR {
2289   intptr_t d_handle; /* Value returned by "_findfirst". */
2290   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
2291   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
2292 };
2293 #endif
2294 
2295 /*
2296 ** Provide a macro, for use by the implementation, to determine if a
2297 ** particular directory entry should be skipped over when searching for
2298 ** the next directory entry that should be returned by the readdir() or
2299 ** readdir_r() functions.
2300 */
2301 
2302 #ifndef is_filtered
2303 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
2304 #endif
2305 
2306 /*
2307 ** Provide the function prototype for the POSIX compatible getenv()
2308 ** function.  This function is not thread-safe.
2309 */
2310 
2311 extern const char *windirent_getenv(const char *name);
2312 
2313 /*
2314 ** Finally, we can provide the function prototypes for the opendir(),
2315 ** readdir(), readdir_r(), and closedir() POSIX functions.
2316 */
2317 
2318 extern LPDIR opendir(const char *dirname);
2319 extern LPDIRENT readdir(LPDIR dirp);
2320 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
2321 extern INT closedir(LPDIR dirp);
2322 
2323 #endif /* defined(WIN32) && defined(_MSC_VER) */
2324 
2325 /************************* End test_windirent.h ********************/
2326 /************************* Begin test_windirent.c ******************/
2327 /*
2328 ** 2015 November 30
2329 **
2330 ** The author disclaims copyright to this source code.  In place of
2331 ** a legal notice, here is a blessing:
2332 **
2333 **    May you do good and not evil.
2334 **    May you find forgiveness for yourself and forgive others.
2335 **    May you share freely, never taking more than you give.
2336 **
2337 *************************************************************************
2338 ** This file contains code to implement most of the opendir() family of
2339 ** POSIX functions on Win32 using the MSVCRT.
2340 */
2341 
2342 #if defined(_WIN32) && defined(_MSC_VER)
2343 /* #include "test_windirent.h" */
2344 
2345 /*
2346 ** Implementation of the POSIX getenv() function using the Win32 API.
2347 ** This function is not thread-safe.
2348 */
windirent_getenv(const char * name)2349 const char *windirent_getenv(
2350   const char *name
2351 ){
2352   static char value[32768]; /* Maximum length, per MSDN */
2353   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
2354   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
2355 
2356   memset(value, 0, sizeof(value));
2357   dwRet = GetEnvironmentVariableA(name, value, dwSize);
2358   if( dwRet==0 || dwRet>dwSize ){
2359     /*
2360     ** The function call to GetEnvironmentVariableA() failed -OR-
2361     ** the buffer is not large enough.  Either way, return NULL.
2362     */
2363     return 0;
2364   }else{
2365     /*
2366     ** The function call to GetEnvironmentVariableA() succeeded
2367     ** -AND- the buffer contains the entire value.
2368     */
2369     return value;
2370   }
2371 }
2372 
2373 /*
2374 ** Implementation of the POSIX opendir() function using the MSVCRT.
2375 */
opendir(const char * dirname)2376 LPDIR opendir(
2377   const char *dirname
2378 ){
2379   struct _finddata_t data;
2380   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
2381   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
2382 
2383   if( dirp==NULL ) return NULL;
2384   memset(dirp, 0, sizeof(DIR));
2385 
2386   /* TODO: Remove this if Unix-style root paths are not used. */
2387   if( sqlite3_stricmp(dirname, "/")==0 ){
2388     dirname = windirent_getenv("SystemDrive");
2389   }
2390 
2391   memset(&data, 0, sizeof(struct _finddata_t));
2392   _snprintf(data.name, namesize, "%s\\*", dirname);
2393   dirp->d_handle = _findfirst(data.name, &data);
2394 
2395   if( dirp->d_handle==BAD_INTPTR_T ){
2396     closedir(dirp);
2397     return NULL;
2398   }
2399 
2400   /* TODO: Remove this block to allow hidden and/or system files. */
2401   if( is_filtered(data) ){
2402 next:
2403 
2404     memset(&data, 0, sizeof(struct _finddata_t));
2405     if( _findnext(dirp->d_handle, &data)==-1 ){
2406       closedir(dirp);
2407       return NULL;
2408     }
2409 
2410     /* TODO: Remove this block to allow hidden and/or system files. */
2411     if( is_filtered(data) ) goto next;
2412   }
2413 
2414   dirp->d_first.d_attributes = data.attrib;
2415   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
2416   dirp->d_first.d_name[NAME_MAX] = '\0';
2417 
2418   return dirp;
2419 }
2420 
2421 /*
2422 ** Implementation of the POSIX readdir() function using the MSVCRT.
2423 */
readdir(LPDIR dirp)2424 LPDIRENT readdir(
2425   LPDIR dirp
2426 ){
2427   struct _finddata_t data;
2428 
2429   if( dirp==NULL ) return NULL;
2430 
2431   if( dirp->d_first.d_ino==0 ){
2432     dirp->d_first.d_ino++;
2433     dirp->d_next.d_ino++;
2434 
2435     return &dirp->d_first;
2436   }
2437 
2438 next:
2439 
2440   memset(&data, 0, sizeof(struct _finddata_t));
2441   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
2442 
2443   /* TODO: Remove this block to allow hidden and/or system files. */
2444   if( is_filtered(data) ) goto next;
2445 
2446   dirp->d_next.d_ino++;
2447   dirp->d_next.d_attributes = data.attrib;
2448   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
2449   dirp->d_next.d_name[NAME_MAX] = '\0';
2450 
2451   return &dirp->d_next;
2452 }
2453 
2454 /*
2455 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
2456 */
readdir_r(LPDIR dirp,LPDIRENT entry,LPDIRENT * result)2457 INT readdir_r(
2458   LPDIR dirp,
2459   LPDIRENT entry,
2460   LPDIRENT *result
2461 ){
2462   struct _finddata_t data;
2463 
2464   if( dirp==NULL ) return EBADF;
2465 
2466   if( dirp->d_first.d_ino==0 ){
2467     dirp->d_first.d_ino++;
2468     dirp->d_next.d_ino++;
2469 
2470     entry->d_ino = dirp->d_first.d_ino;
2471     entry->d_attributes = dirp->d_first.d_attributes;
2472     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
2473     entry->d_name[NAME_MAX] = '\0';
2474 
2475     *result = entry;
2476     return 0;
2477   }
2478 
2479 next:
2480 
2481   memset(&data, 0, sizeof(struct _finddata_t));
2482   if( _findnext(dirp->d_handle, &data)==-1 ){
2483     *result = NULL;
2484     return ENOENT;
2485   }
2486 
2487   /* TODO: Remove this block to allow hidden and/or system files. */
2488   if( is_filtered(data) ) goto next;
2489 
2490   entry->d_ino = (ino_t)-1; /* not available */
2491   entry->d_attributes = data.attrib;
2492   strncpy(entry->d_name, data.name, NAME_MAX);
2493   entry->d_name[NAME_MAX] = '\0';
2494 
2495   *result = entry;
2496   return 0;
2497 }
2498 
2499 /*
2500 ** Implementation of the POSIX closedir() function using the MSVCRT.
2501 */
closedir(LPDIR dirp)2502 INT closedir(
2503   LPDIR dirp
2504 ){
2505   INT result = 0;
2506 
2507   if( dirp==NULL ) return EINVAL;
2508 
2509   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
2510     result = _findclose(dirp->d_handle);
2511   }
2512 
2513   sqlite3_free(dirp);
2514   return result;
2515 }
2516 
2517 #endif /* defined(WIN32) && defined(_MSC_VER) */
2518 
2519 /************************* End test_windirent.c ********************/
2520 #define dirent DIRENT
2521 #endif
2522 /************************* Begin ../ext/misc/memtrace.c ******************/
2523 /*
2524 ** 2019-01-21
2525 **
2526 ** The author disclaims copyright to this source code.  In place of
2527 ** a legal notice, here is a blessing:
2528 **
2529 **    May you do good and not evil.
2530 **    May you find forgiveness for yourself and forgive others.
2531 **    May you share freely, never taking more than you give.
2532 **
2533 *************************************************************************
2534 **
2535 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
2536 ** mechanism to add a tracing layer on top of SQLite.  If this extension
2537 ** is registered prior to sqlite3_initialize(), it will cause all memory
2538 ** allocation activities to be logged on standard output, or to some other
2539 ** FILE specified by the initializer.
2540 **
2541 ** This file needs to be compiled into the application that uses it.
2542 **
2543 ** This extension is used to implement the --memtrace option of the
2544 ** command-line shell.
2545 */
2546 #include <assert.h>
2547 #include <string.h>
2548 #include <stdio.h>
2549 
2550 /* The original memory allocation routines */
2551 static sqlite3_mem_methods memtraceBase;
2552 static FILE *memtraceOut;
2553 
2554 /* Methods that trace memory allocations */
memtraceMalloc(int n)2555 static void *memtraceMalloc(int n){
2556   if( memtraceOut ){
2557     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
2558             memtraceBase.xRoundup(n));
2559   }
2560   return memtraceBase.xMalloc(n);
2561 }
memtraceFree(void * p)2562 static void memtraceFree(void *p){
2563   if( p==0 ) return;
2564   if( memtraceOut ){
2565     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
2566   }
2567   memtraceBase.xFree(p);
2568 }
memtraceRealloc(void * p,int n)2569 static void *memtraceRealloc(void *p, int n){
2570   if( p==0 ) return memtraceMalloc(n);
2571   if( n==0 ){
2572     memtraceFree(p);
2573     return 0;
2574   }
2575   if( memtraceOut ){
2576     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
2577             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
2578   }
2579   return memtraceBase.xRealloc(p, n);
2580 }
memtraceSize(void * p)2581 static int memtraceSize(void *p){
2582   return memtraceBase.xSize(p);
2583 }
memtraceRoundup(int n)2584 static int memtraceRoundup(int n){
2585   return memtraceBase.xRoundup(n);
2586 }
memtraceInit(void * p)2587 static int memtraceInit(void *p){
2588   return memtraceBase.xInit(p);
2589 }
memtraceShutdown(void * p)2590 static void memtraceShutdown(void *p){
2591   memtraceBase.xShutdown(p);
2592 }
2593 
2594 /* The substitute memory allocator */
2595 static sqlite3_mem_methods ersaztMethods = {
2596   memtraceMalloc,
2597   memtraceFree,
2598   memtraceRealloc,
2599   memtraceSize,
2600   memtraceRoundup,
2601   memtraceInit,
2602   memtraceShutdown,
2603   0
2604 };
2605 
2606 /* Begin tracing memory allocations to out. */
sqlite3MemTraceActivate(FILE * out)2607 int sqlite3MemTraceActivate(FILE *out){
2608   int rc = SQLITE_OK;
2609   if( memtraceBase.xMalloc==0 ){
2610     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
2611     if( rc==SQLITE_OK ){
2612       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
2613     }
2614   }
2615   memtraceOut = out;
2616   return rc;
2617 }
2618 
2619 /* Deactivate memory tracing */
sqlite3MemTraceDeactivate(void)2620 int sqlite3MemTraceDeactivate(void){
2621   int rc = SQLITE_OK;
2622   if( memtraceBase.xMalloc!=0 ){
2623     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
2624     if( rc==SQLITE_OK ){
2625       memset(&memtraceBase, 0, sizeof(memtraceBase));
2626     }
2627   }
2628   memtraceOut = 0;
2629   return rc;
2630 }
2631 
2632 /************************* End ../ext/misc/memtrace.c ********************/
2633 /************************* Begin ../ext/misc/pcachetrace.c ******************/
2634 /*
2635 ** 2023-06-21
2636 **
2637 ** The author disclaims copyright to this source code.  In place of
2638 ** a legal notice, here is a blessing:
2639 **
2640 **    May you do good and not evil.
2641 **    May you find forgiveness for yourself and forgive others.
2642 **    May you share freely, never taking more than you give.
2643 **
2644 *************************************************************************
2645 **
2646 ** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
2647 ** mechanism to add a tracing layer on top of pluggable page cache of
2648 ** SQLite.  If this extension is registered prior to sqlite3_initialize(),
2649 ** it will cause all page cache activities to be logged on standard output,
2650 ** or to some other FILE specified by the initializer.
2651 **
2652 ** This file needs to be compiled into the application that uses it.
2653 **
2654 ** This extension is used to implement the --pcachetrace option of the
2655 ** command-line shell.
2656 */
2657 #include <assert.h>
2658 #include <string.h>
2659 #include <stdio.h>
2660 
2661 /* The original page cache routines */
2662 static sqlite3_pcache_methods2 pcacheBase;
2663 static FILE *pcachetraceOut;
2664 
2665 /* Methods that trace pcache activity */
pcachetraceInit(void * pArg)2666 static int pcachetraceInit(void *pArg){
2667   int nRes;
2668   if( pcachetraceOut ){
2669     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
2670   }
2671   nRes = pcacheBase.xInit(pArg);
2672   if( pcachetraceOut ){
2673     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
2674   }
2675   return nRes;
2676 }
pcachetraceShutdown(void * pArg)2677 static void pcachetraceShutdown(void *pArg){
2678   if( pcachetraceOut ){
2679     fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
2680   }
2681   pcacheBase.xShutdown(pArg);
2682 }
pcachetraceCreate(int szPage,int szExtra,int bPurge)2683 static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
2684   sqlite3_pcache *pRes;
2685   if( pcachetraceOut ){
2686     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
2687             szPage, szExtra, bPurge);
2688   }
2689   pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
2690   if( pcachetraceOut ){
2691     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
2692             szPage, szExtra, bPurge, pRes);
2693   }
2694   return pRes;
2695 }
pcachetraceCachesize(sqlite3_pcache * p,int nCachesize)2696 static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
2697   if( pcachetraceOut ){
2698     fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
2699   }
2700   pcacheBase.xCachesize(p, nCachesize);
2701 }
pcachetracePagecount(sqlite3_pcache * p)2702 static int pcachetracePagecount(sqlite3_pcache *p){
2703   int nRes;
2704   if( pcachetraceOut ){
2705     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
2706   }
2707   nRes = pcacheBase.xPagecount(p);
2708   if( pcachetraceOut ){
2709     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
2710   }
2711   return nRes;
2712 }
pcachetraceFetch(sqlite3_pcache * p,unsigned key,int crFg)2713 static sqlite3_pcache_page *pcachetraceFetch(
2714   sqlite3_pcache *p,
2715   unsigned key,
2716   int crFg
2717 ){
2718   sqlite3_pcache_page *pRes;
2719   if( pcachetraceOut ){
2720     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
2721   }
2722   pRes = pcacheBase.xFetch(p, key, crFg);
2723   if( pcachetraceOut ){
2724     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
2725             p, key, crFg, pRes);
2726   }
2727   return pRes;
2728 }
pcachetraceUnpin(sqlite3_pcache * p,sqlite3_pcache_page * pPg,int bDiscard)2729 static void pcachetraceUnpin(
2730   sqlite3_pcache *p,
2731   sqlite3_pcache_page *pPg,
2732   int bDiscard
2733 ){
2734   if( pcachetraceOut ){
2735     fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
2736             p, pPg, bDiscard);
2737   }
2738   pcacheBase.xUnpin(p, pPg, bDiscard);
2739 }
pcachetraceRekey(sqlite3_pcache * p,sqlite3_pcache_page * pPg,unsigned oldKey,unsigned newKey)2740 static void pcachetraceRekey(
2741   sqlite3_pcache *p,
2742   sqlite3_pcache_page *pPg,
2743   unsigned oldKey,
2744   unsigned newKey
2745 ){
2746   if( pcachetraceOut ){
2747     fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
2748         p, pPg, oldKey, newKey);
2749   }
2750   pcacheBase.xRekey(p, pPg, oldKey, newKey);
2751 }
pcachetraceTruncate(sqlite3_pcache * p,unsigned n)2752 static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
2753   if( pcachetraceOut ){
2754     fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
2755   }
2756   pcacheBase.xTruncate(p, n);
2757 }
pcachetraceDestroy(sqlite3_pcache * p)2758 static void pcachetraceDestroy(sqlite3_pcache *p){
2759   if( pcachetraceOut ){
2760     fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
2761   }
2762   pcacheBase.xDestroy(p);
2763 }
pcachetraceShrink(sqlite3_pcache * p)2764 static void pcachetraceShrink(sqlite3_pcache *p){
2765   if( pcachetraceOut ){
2766     fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
2767   }
2768   pcacheBase.xShrink(p);
2769 }
2770 
2771 /* The substitute pcache methods */
2772 static sqlite3_pcache_methods2 ersaztPcacheMethods = {
2773   0,
2774   0,
2775   pcachetraceInit,
2776   pcachetraceShutdown,
2777   pcachetraceCreate,
2778   pcachetraceCachesize,
2779   pcachetracePagecount,
2780   pcachetraceFetch,
2781   pcachetraceUnpin,
2782   pcachetraceRekey,
2783   pcachetraceTruncate,
2784   pcachetraceDestroy,
2785   pcachetraceShrink
2786 };
2787 
2788 /* Begin tracing memory allocations to out. */
sqlite3PcacheTraceActivate(FILE * out)2789 int sqlite3PcacheTraceActivate(FILE *out){
2790   int rc = SQLITE_OK;
2791   if( pcacheBase.xFetch==0 ){
2792     rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
2793     if( rc==SQLITE_OK ){
2794       rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
2795     }
2796   }
2797   pcachetraceOut = out;
2798   return rc;
2799 }
2800 
2801 /* Deactivate memory tracing */
sqlite3PcacheTraceDeactivate(void)2802 int sqlite3PcacheTraceDeactivate(void){
2803   int rc = SQLITE_OK;
2804   if( pcacheBase.xFetch!=0 ){
2805     rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
2806     if( rc==SQLITE_OK ){
2807       memset(&pcacheBase, 0, sizeof(pcacheBase));
2808     }
2809   }
2810   pcachetraceOut = 0;
2811   return rc;
2812 }
2813 
2814 /************************* End ../ext/misc/pcachetrace.c ********************/
2815 /************************* Begin ../ext/misc/shathree.c ******************/
2816 /*
2817 ** 2017-03-08
2818 **
2819 ** The author disclaims copyright to this source code.  In place of
2820 ** a legal notice, here is a blessing:
2821 **
2822 **    May you do good and not evil.
2823 **    May you find forgiveness for yourself and forgive others.
2824 **    May you share freely, never taking more than you give.
2825 **
2826 ******************************************************************************
2827 **
2828 ** This SQLite extension implements functions that compute SHA3 hashes
2829 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2830 ** Two SQL functions are implemented:
2831 **
2832 **     sha3(X,SIZE)
2833 **     sha3_query(Y,SIZE)
2834 **
2835 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
2836 ** X is NULL.
2837 **
2838 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
2839 ** and returns a hash of their results.
2840 **
2841 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
2842 ** is used.  If SIZE is included it must be one of the integers 224, 256,
2843 ** 384, or 512, to determine SHA3 hash variant that is computed.
2844 */
2845 /* #include "sqlite3ext.h" */
2846 SQLITE_EXTENSION_INIT1
2847 #include <assert.h>
2848 #include <string.h>
2849 #include <stdarg.h>
2850 
2851 #ifndef SQLITE_AMALGAMATION
2852 /* typedef sqlite3_uint64 u64; */
2853 #endif /* SQLITE_AMALGAMATION */
2854 
2855 /******************************************************************************
2856 ** The Hash Engine
2857 */
2858 /*
2859 ** Macros to determine whether the machine is big or little endian,
2860 ** and whether or not that determination is run-time or compile-time.
2861 **
2862 ** For best performance, an attempt is made to guess at the byte-order
2863 ** using C-preprocessor macros.  If that is unsuccessful, or if
2864 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2865 ** at run-time.
2866 */
2867 #ifndef SHA3_BYTEORDER
2868 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
2869      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
2870      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
2871      defined(__arm__)
2872 #   define SHA3_BYTEORDER    1234
2873 # elif defined(sparc)    || defined(__ppc__)
2874 #   define SHA3_BYTEORDER    4321
2875 # else
2876 #   define SHA3_BYTEORDER 0
2877 # endif
2878 #endif
2879 
2880 
2881 /*
2882 ** State structure for a SHA3 hash in progress
2883 */
2884 typedef struct SHA3Context SHA3Context;
2885 struct SHA3Context {
2886   union {
2887     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
2888     unsigned char x[1600];    /* ... or 1600 bytes */
2889   } u;
2890   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
2891   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
2892   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
2893 };
2894 
2895 /*
2896 ** A single step of the Keccak mixing function for a 1600-bit state
2897 */
KeccakF1600Step(SHA3Context * p)2898 static void KeccakF1600Step(SHA3Context *p){
2899   int i;
2900   u64 b0, b1, b2, b3, b4;
2901   u64 c0, c1, c2, c3, c4;
2902   u64 d0, d1, d2, d3, d4;
2903   static const u64 RC[] = {
2904     0x0000000000000001ULL,  0x0000000000008082ULL,
2905     0x800000000000808aULL,  0x8000000080008000ULL,
2906     0x000000000000808bULL,  0x0000000080000001ULL,
2907     0x8000000080008081ULL,  0x8000000000008009ULL,
2908     0x000000000000008aULL,  0x0000000000000088ULL,
2909     0x0000000080008009ULL,  0x000000008000000aULL,
2910     0x000000008000808bULL,  0x800000000000008bULL,
2911     0x8000000000008089ULL,  0x8000000000008003ULL,
2912     0x8000000000008002ULL,  0x8000000000000080ULL,
2913     0x000000000000800aULL,  0x800000008000000aULL,
2914     0x8000000080008081ULL,  0x8000000000008080ULL,
2915     0x0000000080000001ULL,  0x8000000080008008ULL
2916   };
2917 # define a00 (p->u.s[0])
2918 # define a01 (p->u.s[1])
2919 # define a02 (p->u.s[2])
2920 # define a03 (p->u.s[3])
2921 # define a04 (p->u.s[4])
2922 # define a10 (p->u.s[5])
2923 # define a11 (p->u.s[6])
2924 # define a12 (p->u.s[7])
2925 # define a13 (p->u.s[8])
2926 # define a14 (p->u.s[9])
2927 # define a20 (p->u.s[10])
2928 # define a21 (p->u.s[11])
2929 # define a22 (p->u.s[12])
2930 # define a23 (p->u.s[13])
2931 # define a24 (p->u.s[14])
2932 # define a30 (p->u.s[15])
2933 # define a31 (p->u.s[16])
2934 # define a32 (p->u.s[17])
2935 # define a33 (p->u.s[18])
2936 # define a34 (p->u.s[19])
2937 # define a40 (p->u.s[20])
2938 # define a41 (p->u.s[21])
2939 # define a42 (p->u.s[22])
2940 # define a43 (p->u.s[23])
2941 # define a44 (p->u.s[24])
2942 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
2943 
2944   for(i=0; i<24; i+=4){
2945     c0 = a00^a10^a20^a30^a40;
2946     c1 = a01^a11^a21^a31^a41;
2947     c2 = a02^a12^a22^a32^a42;
2948     c3 = a03^a13^a23^a33^a43;
2949     c4 = a04^a14^a24^a34^a44;
2950     d0 = c4^ROL64(c1, 1);
2951     d1 = c0^ROL64(c2, 1);
2952     d2 = c1^ROL64(c3, 1);
2953     d3 = c2^ROL64(c4, 1);
2954     d4 = c3^ROL64(c0, 1);
2955 
2956     b0 = (a00^d0);
2957     b1 = ROL64((a11^d1), 44);
2958     b2 = ROL64((a22^d2), 43);
2959     b3 = ROL64((a33^d3), 21);
2960     b4 = ROL64((a44^d4), 14);
2961     a00 =   b0 ^((~b1)&  b2 );
2962     a00 ^= RC[i];
2963     a11 =   b1 ^((~b2)&  b3 );
2964     a22 =   b2 ^((~b3)&  b4 );
2965     a33 =   b3 ^((~b4)&  b0 );
2966     a44 =   b4 ^((~b0)&  b1 );
2967 
2968     b2 = ROL64((a20^d0), 3);
2969     b3 = ROL64((a31^d1), 45);
2970     b4 = ROL64((a42^d2), 61);
2971     b0 = ROL64((a03^d3), 28);
2972     b1 = ROL64((a14^d4), 20);
2973     a20 =   b0 ^((~b1)&  b2 );
2974     a31 =   b1 ^((~b2)&  b3 );
2975     a42 =   b2 ^((~b3)&  b4 );
2976     a03 =   b3 ^((~b4)&  b0 );
2977     a14 =   b4 ^((~b0)&  b1 );
2978 
2979     b4 = ROL64((a40^d0), 18);
2980     b0 = ROL64((a01^d1), 1);
2981     b1 = ROL64((a12^d2), 6);
2982     b2 = ROL64((a23^d3), 25);
2983     b3 = ROL64((a34^d4), 8);
2984     a40 =   b0 ^((~b1)&  b2 );
2985     a01 =   b1 ^((~b2)&  b3 );
2986     a12 =   b2 ^((~b3)&  b4 );
2987     a23 =   b3 ^((~b4)&  b0 );
2988     a34 =   b4 ^((~b0)&  b1 );
2989 
2990     b1 = ROL64((a10^d0), 36);
2991     b2 = ROL64((a21^d1), 10);
2992     b3 = ROL64((a32^d2), 15);
2993     b4 = ROL64((a43^d3), 56);
2994     b0 = ROL64((a04^d4), 27);
2995     a10 =   b0 ^((~b1)&  b2 );
2996     a21 =   b1 ^((~b2)&  b3 );
2997     a32 =   b2 ^((~b3)&  b4 );
2998     a43 =   b3 ^((~b4)&  b0 );
2999     a04 =   b4 ^((~b0)&  b1 );
3000 
3001     b3 = ROL64((a30^d0), 41);
3002     b4 = ROL64((a41^d1), 2);
3003     b0 = ROL64((a02^d2), 62);
3004     b1 = ROL64((a13^d3), 55);
3005     b2 = ROL64((a24^d4), 39);
3006     a30 =   b0 ^((~b1)&  b2 );
3007     a41 =   b1 ^((~b2)&  b3 );
3008     a02 =   b2 ^((~b3)&  b4 );
3009     a13 =   b3 ^((~b4)&  b0 );
3010     a24 =   b4 ^((~b0)&  b1 );
3011 
3012     c0 = a00^a20^a40^a10^a30;
3013     c1 = a11^a31^a01^a21^a41;
3014     c2 = a22^a42^a12^a32^a02;
3015     c3 = a33^a03^a23^a43^a13;
3016     c4 = a44^a14^a34^a04^a24;
3017     d0 = c4^ROL64(c1, 1);
3018     d1 = c0^ROL64(c2, 1);
3019     d2 = c1^ROL64(c3, 1);
3020     d3 = c2^ROL64(c4, 1);
3021     d4 = c3^ROL64(c0, 1);
3022 
3023     b0 = (a00^d0);
3024     b1 = ROL64((a31^d1), 44);
3025     b2 = ROL64((a12^d2), 43);
3026     b3 = ROL64((a43^d3), 21);
3027     b4 = ROL64((a24^d4), 14);
3028     a00 =   b0 ^((~b1)&  b2 );
3029     a00 ^= RC[i+1];
3030     a31 =   b1 ^((~b2)&  b3 );
3031     a12 =   b2 ^((~b3)&  b4 );
3032     a43 =   b3 ^((~b4)&  b0 );
3033     a24 =   b4 ^((~b0)&  b1 );
3034 
3035     b2 = ROL64((a40^d0), 3);
3036     b3 = ROL64((a21^d1), 45);
3037     b4 = ROL64((a02^d2), 61);
3038     b0 = ROL64((a33^d3), 28);
3039     b1 = ROL64((a14^d4), 20);
3040     a40 =   b0 ^((~b1)&  b2 );
3041     a21 =   b1 ^((~b2)&  b3 );
3042     a02 =   b2 ^((~b3)&  b4 );
3043     a33 =   b3 ^((~b4)&  b0 );
3044     a14 =   b4 ^((~b0)&  b1 );
3045 
3046     b4 = ROL64((a30^d0), 18);
3047     b0 = ROL64((a11^d1), 1);
3048     b1 = ROL64((a42^d2), 6);
3049     b2 = ROL64((a23^d3), 25);
3050     b3 = ROL64((a04^d4), 8);
3051     a30 =   b0 ^((~b1)&  b2 );
3052     a11 =   b1 ^((~b2)&  b3 );
3053     a42 =   b2 ^((~b3)&  b4 );
3054     a23 =   b3 ^((~b4)&  b0 );
3055     a04 =   b4 ^((~b0)&  b1 );
3056 
3057     b1 = ROL64((a20^d0), 36);
3058     b2 = ROL64((a01^d1), 10);
3059     b3 = ROL64((a32^d2), 15);
3060     b4 = ROL64((a13^d3), 56);
3061     b0 = ROL64((a44^d4), 27);
3062     a20 =   b0 ^((~b1)&  b2 );
3063     a01 =   b1 ^((~b2)&  b3 );
3064     a32 =   b2 ^((~b3)&  b4 );
3065     a13 =   b3 ^((~b4)&  b0 );
3066     a44 =   b4 ^((~b0)&  b1 );
3067 
3068     b3 = ROL64((a10^d0), 41);
3069     b4 = ROL64((a41^d1), 2);
3070     b0 = ROL64((a22^d2), 62);
3071     b1 = ROL64((a03^d3), 55);
3072     b2 = ROL64((a34^d4), 39);
3073     a10 =   b0 ^((~b1)&  b2 );
3074     a41 =   b1 ^((~b2)&  b3 );
3075     a22 =   b2 ^((~b3)&  b4 );
3076     a03 =   b3 ^((~b4)&  b0 );
3077     a34 =   b4 ^((~b0)&  b1 );
3078 
3079     c0 = a00^a40^a30^a20^a10;
3080     c1 = a31^a21^a11^a01^a41;
3081     c2 = a12^a02^a42^a32^a22;
3082     c3 = a43^a33^a23^a13^a03;
3083     c4 = a24^a14^a04^a44^a34;
3084     d0 = c4^ROL64(c1, 1);
3085     d1 = c0^ROL64(c2, 1);
3086     d2 = c1^ROL64(c3, 1);
3087     d3 = c2^ROL64(c4, 1);
3088     d4 = c3^ROL64(c0, 1);
3089 
3090     b0 = (a00^d0);
3091     b1 = ROL64((a21^d1), 44);
3092     b2 = ROL64((a42^d2), 43);
3093     b3 = ROL64((a13^d3), 21);
3094     b4 = ROL64((a34^d4), 14);
3095     a00 =   b0 ^((~b1)&  b2 );
3096     a00 ^= RC[i+2];
3097     a21 =   b1 ^((~b2)&  b3 );
3098     a42 =   b2 ^((~b3)&  b4 );
3099     a13 =   b3 ^((~b4)&  b0 );
3100     a34 =   b4 ^((~b0)&  b1 );
3101 
3102     b2 = ROL64((a30^d0), 3);
3103     b3 = ROL64((a01^d1), 45);
3104     b4 = ROL64((a22^d2), 61);
3105     b0 = ROL64((a43^d3), 28);
3106     b1 = ROL64((a14^d4), 20);
3107     a30 =   b0 ^((~b1)&  b2 );
3108     a01 =   b1 ^((~b2)&  b3 );
3109     a22 =   b2 ^((~b3)&  b4 );
3110     a43 =   b3 ^((~b4)&  b0 );
3111     a14 =   b4 ^((~b0)&  b1 );
3112 
3113     b4 = ROL64((a10^d0), 18);
3114     b0 = ROL64((a31^d1), 1);
3115     b1 = ROL64((a02^d2), 6);
3116     b2 = ROL64((a23^d3), 25);
3117     b3 = ROL64((a44^d4), 8);
3118     a10 =   b0 ^((~b1)&  b2 );
3119     a31 =   b1 ^((~b2)&  b3 );
3120     a02 =   b2 ^((~b3)&  b4 );
3121     a23 =   b3 ^((~b4)&  b0 );
3122     a44 =   b4 ^((~b0)&  b1 );
3123 
3124     b1 = ROL64((a40^d0), 36);
3125     b2 = ROL64((a11^d1), 10);
3126     b3 = ROL64((a32^d2), 15);
3127     b4 = ROL64((a03^d3), 56);
3128     b0 = ROL64((a24^d4), 27);
3129     a40 =   b0 ^((~b1)&  b2 );
3130     a11 =   b1 ^((~b2)&  b3 );
3131     a32 =   b2 ^((~b3)&  b4 );
3132     a03 =   b3 ^((~b4)&  b0 );
3133     a24 =   b4 ^((~b0)&  b1 );
3134 
3135     b3 = ROL64((a20^d0), 41);
3136     b4 = ROL64((a41^d1), 2);
3137     b0 = ROL64((a12^d2), 62);
3138     b1 = ROL64((a33^d3), 55);
3139     b2 = ROL64((a04^d4), 39);
3140     a20 =   b0 ^((~b1)&  b2 );
3141     a41 =   b1 ^((~b2)&  b3 );
3142     a12 =   b2 ^((~b3)&  b4 );
3143     a33 =   b3 ^((~b4)&  b0 );
3144     a04 =   b4 ^((~b0)&  b1 );
3145 
3146     c0 = a00^a30^a10^a40^a20;
3147     c1 = a21^a01^a31^a11^a41;
3148     c2 = a42^a22^a02^a32^a12;
3149     c3 = a13^a43^a23^a03^a33;
3150     c4 = a34^a14^a44^a24^a04;
3151     d0 = c4^ROL64(c1, 1);
3152     d1 = c0^ROL64(c2, 1);
3153     d2 = c1^ROL64(c3, 1);
3154     d3 = c2^ROL64(c4, 1);
3155     d4 = c3^ROL64(c0, 1);
3156 
3157     b0 = (a00^d0);
3158     b1 = ROL64((a01^d1), 44);
3159     b2 = ROL64((a02^d2), 43);
3160     b3 = ROL64((a03^d3), 21);
3161     b4 = ROL64((a04^d4), 14);
3162     a00 =   b0 ^((~b1)&  b2 );
3163     a00 ^= RC[i+3];
3164     a01 =   b1 ^((~b2)&  b3 );
3165     a02 =   b2 ^((~b3)&  b4 );
3166     a03 =   b3 ^((~b4)&  b0 );
3167     a04 =   b4 ^((~b0)&  b1 );
3168 
3169     b2 = ROL64((a10^d0), 3);
3170     b3 = ROL64((a11^d1), 45);
3171     b4 = ROL64((a12^d2), 61);
3172     b0 = ROL64((a13^d3), 28);
3173     b1 = ROL64((a14^d4), 20);
3174     a10 =   b0 ^((~b1)&  b2 );
3175     a11 =   b1 ^((~b2)&  b3 );
3176     a12 =   b2 ^((~b3)&  b4 );
3177     a13 =   b3 ^((~b4)&  b0 );
3178     a14 =   b4 ^((~b0)&  b1 );
3179 
3180     b4 = ROL64((a20^d0), 18);
3181     b0 = ROL64((a21^d1), 1);
3182     b1 = ROL64((a22^d2), 6);
3183     b2 = ROL64((a23^d3), 25);
3184     b3 = ROL64((a24^d4), 8);
3185     a20 =   b0 ^((~b1)&  b2 );
3186     a21 =   b1 ^((~b2)&  b3 );
3187     a22 =   b2 ^((~b3)&  b4 );
3188     a23 =   b3 ^((~b4)&  b0 );
3189     a24 =   b4 ^((~b0)&  b1 );
3190 
3191     b1 = ROL64((a30^d0), 36);
3192     b2 = ROL64((a31^d1), 10);
3193     b3 = ROL64((a32^d2), 15);
3194     b4 = ROL64((a33^d3), 56);
3195     b0 = ROL64((a34^d4), 27);
3196     a30 =   b0 ^((~b1)&  b2 );
3197     a31 =   b1 ^((~b2)&  b3 );
3198     a32 =   b2 ^((~b3)&  b4 );
3199     a33 =   b3 ^((~b4)&  b0 );
3200     a34 =   b4 ^((~b0)&  b1 );
3201 
3202     b3 = ROL64((a40^d0), 41);
3203     b4 = ROL64((a41^d1), 2);
3204     b0 = ROL64((a42^d2), 62);
3205     b1 = ROL64((a43^d3), 55);
3206     b2 = ROL64((a44^d4), 39);
3207     a40 =   b0 ^((~b1)&  b2 );
3208     a41 =   b1 ^((~b2)&  b3 );
3209     a42 =   b2 ^((~b3)&  b4 );
3210     a43 =   b3 ^((~b4)&  b0 );
3211     a44 =   b4 ^((~b0)&  b1 );
3212   }
3213 }
3214 
3215 /*
3216 ** Initialize a new hash.  iSize determines the size of the hash
3217 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
3218 ** can be zero to use the default hash size of 256 bits.
3219 */
SHA3Init(SHA3Context * p,int iSize)3220 static void SHA3Init(SHA3Context *p, int iSize){
3221   memset(p, 0, sizeof(*p));
3222   if( iSize>=128 && iSize<=512 ){
3223     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
3224   }else{
3225     p->nRate = (1600 - 2*256)/8;
3226   }
3227 #if SHA3_BYTEORDER==1234
3228   /* Known to be little-endian at compile-time. No-op */
3229 #elif SHA3_BYTEORDER==4321
3230   p->ixMask = 7;  /* Big-endian */
3231 #else
3232   {
3233     static unsigned int one = 1;
3234     if( 1==*(unsigned char*)&one ){
3235       /* Little endian.  No byte swapping. */
3236       p->ixMask = 0;
3237     }else{
3238       /* Big endian.  Byte swap. */
3239       p->ixMask = 7;
3240     }
3241   }
3242 #endif
3243 }
3244 
3245 /*
3246 ** Make consecutive calls to the SHA3Update function to add new content
3247 ** to the hash
3248 */
SHA3Update(SHA3Context * p,const unsigned char * aData,unsigned int nData)3249 static void SHA3Update(
3250   SHA3Context *p,
3251   const unsigned char *aData,
3252   unsigned int nData
3253 ){
3254   unsigned int i = 0;
3255   if( aData==0 ) return;
3256 #if SHA3_BYTEORDER==1234
3257   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
3258     for(; i+7<nData; i+=8){
3259       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
3260       p->nLoaded += 8;
3261       if( p->nLoaded>=p->nRate ){
3262         KeccakF1600Step(p);
3263         p->nLoaded = 0;
3264       }
3265     }
3266   }
3267 #endif
3268   for(; i<nData; i++){
3269 #if SHA3_BYTEORDER==1234
3270     p->u.x[p->nLoaded] ^= aData[i];
3271 #elif SHA3_BYTEORDER==4321
3272     p->u.x[p->nLoaded^0x07] ^= aData[i];
3273 #else
3274     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
3275 #endif
3276     p->nLoaded++;
3277     if( p->nLoaded==p->nRate ){
3278       KeccakF1600Step(p);
3279       p->nLoaded = 0;
3280     }
3281   }
3282 }
3283 
3284 /*
3285 ** After all content has been added, invoke SHA3Final() to compute
3286 ** the final hash.  The function returns a pointer to the binary
3287 ** hash value.
3288 */
SHA3Final(SHA3Context * p)3289 static unsigned char *SHA3Final(SHA3Context *p){
3290   unsigned int i;
3291   if( p->nLoaded==p->nRate-1 ){
3292     const unsigned char c1 = 0x86;
3293     SHA3Update(p, &c1, 1);
3294   }else{
3295     const unsigned char c2 = 0x06;
3296     const unsigned char c3 = 0x80;
3297     SHA3Update(p, &c2, 1);
3298     p->nLoaded = p->nRate - 1;
3299     SHA3Update(p, &c3, 1);
3300   }
3301   for(i=0; i<p->nRate; i++){
3302     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
3303   }
3304   return &p->u.x[p->nRate];
3305 }
3306 /* End of the hashing logic
3307 *****************************************************************************/
3308 
3309 /*
3310 ** Implementation of the sha3(X,SIZE) function.
3311 **
3312 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
3313 ** size is 256.  If X is a BLOB, it is hashed as is.
3314 ** For all other non-NULL types of input, X is converted into a UTF-8 string
3315 ** and the string is hashed without the trailing 0x00 terminator.  The hash
3316 ** of a NULL value is NULL.
3317 */
sha3Func(sqlite3_context * context,int argc,sqlite3_value ** argv)3318 static void sha3Func(
3319   sqlite3_context *context,
3320   int argc,
3321   sqlite3_value **argv
3322 ){
3323   SHA3Context cx;
3324   int eType = sqlite3_value_type(argv[0]);
3325   int nByte = sqlite3_value_bytes(argv[0]);
3326   int iSize;
3327   if( argc==1 ){
3328     iSize = 256;
3329   }else{
3330     iSize = sqlite3_value_int(argv[1]);
3331     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3332       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3333                                     "384 512", -1);
3334       return;
3335     }
3336   }
3337   if( eType==SQLITE_NULL ) return;
3338   SHA3Init(&cx, iSize);
3339   if( eType==SQLITE_BLOB ){
3340     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
3341   }else{
3342     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
3343   }
3344   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3345 }
3346 
3347 /* Compute a string using sqlite3_vsnprintf() with a maximum length
3348 ** of 50 bytes and add it to the hash.
3349 */
sha3_step_vformat(SHA3Context * p,const char * zFormat,...)3350 static void sha3_step_vformat(
3351   SHA3Context *p,                 /* Add content to this context */
3352   const char *zFormat,
3353   ...
3354 ){
3355   va_list ap;
3356   int n;
3357   char zBuf[50];
3358   va_start(ap, zFormat);
3359   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
3360   va_end(ap);
3361   n = (int)strlen(zBuf);
3362   SHA3Update(p, (unsigned char*)zBuf, n);
3363 }
3364 
3365 /*
3366 ** Implementation of the sha3_query(SQL,SIZE) function.
3367 **
3368 ** This function compiles and runs the SQL statement(s) given in the
3369 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
3370 ** size is 256.
3371 **
3372 ** The format of the byte stream that is hashed is summarized as follows:
3373 **
3374 **       S<n>:<sql>
3375 **       R
3376 **       N
3377 **       I<int>
3378 **       F<ieee-float>
3379 **       B<size>:<bytes>
3380 **       T<size>:<text>
3381 **
3382 ** <sql> is the original SQL text for each statement run and <n> is
3383 ** the size of that text.  The SQL text is UTF-8.  A single R character
3384 ** occurs before the start of each row.  N means a NULL value.
3385 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
3386 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3387 ** B means blobs of <size> bytes.  T means text rendered as <size>
3388 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
3389 ** text integers.
3390 **
3391 ** For each SQL statement in the X input, there is one S segment.  Each
3392 ** S segment is followed by zero or more R segments, one for each row in the
3393 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
3394 ** one for each column in the result set.  Segments are concatentated directly
3395 ** with no delimiters of any kind.
3396 */
sha3QueryFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)3397 static void sha3QueryFunc(
3398   sqlite3_context *context,
3399   int argc,
3400   sqlite3_value **argv
3401 ){
3402   sqlite3 *db = sqlite3_context_db_handle(context);
3403   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
3404   sqlite3_stmt *pStmt = 0;
3405   int nCol;                   /* Number of columns in the result set */
3406   int i;                      /* Loop counter */
3407   int rc;
3408   int n;
3409   const char *z;
3410   SHA3Context cx;
3411   int iSize;
3412 
3413   if( argc==1 ){
3414     iSize = 256;
3415   }else{
3416     iSize = sqlite3_value_int(argv[1]);
3417     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3418       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3419                                     "384 512", -1);
3420       return;
3421     }
3422   }
3423   if( zSql==0 ) return;
3424   SHA3Init(&cx, iSize);
3425   while( zSql[0] ){
3426     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
3427     if( rc ){
3428       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
3429                                    zSql, sqlite3_errmsg(db));
3430       sqlite3_finalize(pStmt);
3431       sqlite3_result_error(context, zMsg, -1);
3432       sqlite3_free(zMsg);
3433       return;
3434     }
3435     if( !sqlite3_stmt_readonly(pStmt) ){
3436       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
3437       sqlite3_finalize(pStmt);
3438       sqlite3_result_error(context, zMsg, -1);
3439       sqlite3_free(zMsg);
3440       return;
3441     }
3442     nCol = sqlite3_column_count(pStmt);
3443     z = sqlite3_sql(pStmt);
3444     if( z ){
3445       n = (int)strlen(z);
3446       sha3_step_vformat(&cx,"S%d:",n);
3447       SHA3Update(&cx,(unsigned char*)z,n);
3448     }
3449 
3450     /* Compute a hash over the result of the query */
3451     while( SQLITE_ROW==sqlite3_step(pStmt) ){
3452       SHA3Update(&cx,(const unsigned char*)"R",1);
3453       for(i=0; i<nCol; i++){
3454         switch( sqlite3_column_type(pStmt,i) ){
3455           case SQLITE_NULL: {
3456             SHA3Update(&cx, (const unsigned char*)"N",1);
3457             break;
3458           }
3459           case SQLITE_INTEGER: {
3460             sqlite3_uint64 u;
3461             int j;
3462             unsigned char x[9];
3463             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
3464             memcpy(&u, &v, 8);
3465             for(j=8; j>=1; j--){
3466               x[j] = u & 0xff;
3467               u >>= 8;
3468             }
3469             x[0] = 'I';
3470             SHA3Update(&cx, x, 9);
3471             break;
3472           }
3473           case SQLITE_FLOAT: {
3474             sqlite3_uint64 u;
3475             int j;
3476             unsigned char x[9];
3477             double r = sqlite3_column_double(pStmt,i);
3478             memcpy(&u, &r, 8);
3479             for(j=8; j>=1; j--){
3480               x[j] = u & 0xff;
3481               u >>= 8;
3482             }
3483             x[0] = 'F';
3484             SHA3Update(&cx,x,9);
3485             break;
3486           }
3487           case SQLITE_TEXT: {
3488             int n2 = sqlite3_column_bytes(pStmt, i);
3489             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
3490             sha3_step_vformat(&cx,"T%d:",n2);
3491             SHA3Update(&cx, z2, n2);
3492             break;
3493           }
3494           case SQLITE_BLOB: {
3495             int n2 = sqlite3_column_bytes(pStmt, i);
3496             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
3497             sha3_step_vformat(&cx,"B%d:",n2);
3498             SHA3Update(&cx, z2, n2);
3499             break;
3500           }
3501         }
3502       }
3503     }
3504     sqlite3_finalize(pStmt);
3505   }
3506   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3507 }
3508 
3509 
3510 #ifdef _WIN32
3511 
3512 #endif
sqlite3_shathree_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3513 int sqlite3_shathree_init(
3514   sqlite3 *db,
3515   char **pzErrMsg,
3516   const sqlite3_api_routines *pApi
3517 ){
3518   int rc = SQLITE_OK;
3519   SQLITE_EXTENSION_INIT2(pApi);
3520   (void)pzErrMsg;  /* Unused parameter */
3521   rc = sqlite3_create_function(db, "sha3", 1,
3522                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3523                       0, sha3Func, 0, 0);
3524   if( rc==SQLITE_OK ){
3525     rc = sqlite3_create_function(db, "sha3", 2,
3526                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3527                       0, sha3Func, 0, 0);
3528   }
3529   if( rc==SQLITE_OK ){
3530     rc = sqlite3_create_function(db, "sha3_query", 1,
3531                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3532                       0, sha3QueryFunc, 0, 0);
3533   }
3534   if( rc==SQLITE_OK ){
3535     rc = sqlite3_create_function(db, "sha3_query", 2,
3536                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3537                       0, sha3QueryFunc, 0, 0);
3538   }
3539   return rc;
3540 }
3541 
3542 /************************* End ../ext/misc/shathree.c ********************/
3543 /************************* Begin ../ext/misc/uint.c ******************/
3544 /*
3545 ** 2020-04-14
3546 **
3547 ** The author disclaims copyright to this source code.  In place of
3548 ** a legal notice, here is a blessing:
3549 **
3550 **    May you do good and not evil.
3551 **    May you find forgiveness for yourself and forgive others.
3552 **    May you share freely, never taking more than you give.
3553 **
3554 ******************************************************************************
3555 **
3556 ** This SQLite extension implements the UINT collating sequence.
3557 **
3558 ** UINT works like BINARY for text, except that embedded strings
3559 ** of digits compare in numeric order.
3560 **
3561 **     *   Leading zeros are handled properly, in the sense that
3562 **         they do not mess of the maginitude comparison of embedded
3563 **         strings of digits.  "x00123y" is equal to "x123y".
3564 **
3565 **     *   Only unsigned integers are recognized.  Plus and minus
3566 **         signs are ignored.  Decimal points and exponential notation
3567 **         are ignored.
3568 **
3569 **     *   Embedded integers can be of arbitrary length.  Comparison
3570 **         is *not* limited integers that can be expressed as a
3571 **         64-bit machine integer.
3572 */
3573 /* #include "sqlite3ext.h" */
3574 SQLITE_EXTENSION_INIT1
3575 #include <assert.h>
3576 #include <string.h>
3577 #include <ctype.h>
3578 
3579 /*
3580 ** Compare text in lexicographic order, except strings of digits
3581 ** compare in numeric order.
3582 */
uintCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)3583 static int uintCollFunc(
3584   void *notUsed,
3585   int nKey1, const void *pKey1,
3586   int nKey2, const void *pKey2
3587 ){
3588   const unsigned char *zA = (const unsigned char*)pKey1;
3589   const unsigned char *zB = (const unsigned char*)pKey2;
3590   int i=0, j=0, x;
3591   (void)notUsed;
3592   while( i<nKey1 && j<nKey2 ){
3593     x = zA[i] - zB[j];
3594     if( isdigit(zA[i]) ){
3595       int k;
3596       if( !isdigit(zB[j]) ) return x;
3597       while( i<nKey1 && zA[i]=='0' ){ i++; }
3598       while( j<nKey2 && zB[j]=='0' ){ j++; }
3599       k = 0;
3600       while( i+k<nKey1 && isdigit(zA[i+k])
3601              && j+k<nKey2 && isdigit(zB[j+k]) ){
3602         k++;
3603       }
3604       if( i+k<nKey1 && isdigit(zA[i+k]) ){
3605         return +1;
3606       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
3607         return -1;
3608       }else{
3609         x = memcmp(zA+i, zB+j, k);
3610         if( x ) return x;
3611         i += k;
3612         j += k;
3613       }
3614     }else if( x ){
3615       return x;
3616     }else{
3617       i++;
3618       j++;
3619     }
3620   }
3621   return (nKey1 - i) - (nKey2 - j);
3622 }
3623 
3624 #ifdef _WIN32
3625 
3626 #endif
sqlite3_uint_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3627 int sqlite3_uint_init(
3628   sqlite3 *db,
3629   char **pzErrMsg,
3630   const sqlite3_api_routines *pApi
3631 ){
3632   SQLITE_EXTENSION_INIT2(pApi);
3633   (void)pzErrMsg;  /* Unused parameter */
3634   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
3635 }
3636 
3637 /************************* End ../ext/misc/uint.c ********************/
3638 /************************* Begin ../ext/misc/decimal.c ******************/
3639 /*
3640 ** 2020-06-22
3641 **
3642 ** The author disclaims copyright to this source code.  In place of
3643 ** a legal notice, here is a blessing:
3644 **
3645 **    May you do good and not evil.
3646 **    May you find forgiveness for yourself and forgive others.
3647 **    May you share freely, never taking more than you give.
3648 **
3649 ******************************************************************************
3650 **
3651 ** Routines to implement arbitrary-precision decimal math.
3652 **
3653 ** The focus here is on simplicity and correctness, not performance.
3654 */
3655 /* #include "sqlite3ext.h" */
3656 SQLITE_EXTENSION_INIT1
3657 #include <assert.h>
3658 #include <string.h>
3659 #include <ctype.h>
3660 #include <stdlib.h>
3661 
3662 /* Mark a function parameter as unused, to suppress nuisance compiler
3663 ** warnings. */
3664 #ifndef UNUSED_PARAMETER
3665 # define UNUSED_PARAMETER(X)  (void)(X)
3666 #endif
3667 
3668 
3669 /* A decimal object */
3670 typedef struct Decimal Decimal;
3671 struct Decimal {
3672   char sign;        /* 0 for positive, 1 for negative */
3673   char oom;         /* True if an OOM is encountered */
3674   char isNull;      /* True if holds a NULL rather than a number */
3675   char isInit;      /* True upon initialization */
3676   int nDigit;       /* Total number of digits */
3677   int nFrac;        /* Number of digits to the right of the decimal point */
3678   signed char *a;   /* Array of digits.  Most significant first. */
3679 };
3680 
3681 /*
3682 ** Release memory held by a Decimal, but do not free the object itself.
3683 */
decimal_clear(Decimal * p)3684 static void decimal_clear(Decimal *p){
3685   sqlite3_free(p->a);
3686 }
3687 
3688 /*
3689 ** Destroy a Decimal object
3690 */
decimal_free(Decimal * p)3691 static void decimal_free(Decimal *p){
3692   if( p ){
3693     decimal_clear(p);
3694     sqlite3_free(p);
3695   }
3696 }
3697 
3698 /*
3699 ** Allocate a new Decimal object initialized to the text in zIn[].
3700 ** Return NULL if any kind of error occurs.
3701 */
decimalNewFromText(const char * zIn,int n)3702 static Decimal *decimalNewFromText(const char *zIn, int n){
3703   Decimal *p = 0;
3704   int i;
3705   int iExp = 0;
3706 
3707   p = sqlite3_malloc( sizeof(*p) );
3708   if( p==0 ) goto new_from_text_failed;
3709   p->sign = 0;
3710   p->oom = 0;
3711   p->isInit = 1;
3712   p->isNull = 0;
3713   p->nDigit = 0;
3714   p->nFrac = 0;
3715   p->a = sqlite3_malloc64( n+1 );
3716   if( p->a==0 ) goto new_from_text_failed;
3717   for(i=0; isspace(zIn[i]); i++){}
3718   if( zIn[i]=='-' ){
3719     p->sign = 1;
3720     i++;
3721   }else if( zIn[i]=='+' ){
3722     i++;
3723   }
3724   while( i<n && zIn[i]=='0' ) i++;
3725   while( i<n ){
3726     char c = zIn[i];
3727     if( c>='0' && c<='9' ){
3728       p->a[p->nDigit++] = c - '0';
3729     }else if( c=='.' ){
3730       p->nFrac = p->nDigit + 1;
3731     }else if( c=='e' || c=='E' ){
3732       int j = i+1;
3733       int neg = 0;
3734       if( j>=n ) break;
3735       if( zIn[j]=='-' ){
3736         neg = 1;
3737         j++;
3738       }else if( zIn[j]=='+' ){
3739         j++;
3740       }
3741       while( j<n && iExp<1000000 ){
3742         if( zIn[j]>='0' && zIn[j]<='9' ){
3743           iExp = iExp*10 + zIn[j] - '0';
3744         }
3745         j++;
3746       }
3747       if( neg ) iExp = -iExp;
3748       break;
3749     }
3750     i++;
3751   }
3752   if( p->nFrac ){
3753     p->nFrac = p->nDigit - (p->nFrac - 1);
3754   }
3755   if( iExp>0 ){
3756     if( p->nFrac>0 ){
3757       if( iExp<=p->nFrac ){
3758         p->nFrac -= iExp;
3759         iExp = 0;
3760       }else{
3761         iExp -= p->nFrac;
3762         p->nFrac = 0;
3763       }
3764     }
3765     if( iExp>0 ){
3766       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3767       if( p->a==0 ) goto new_from_text_failed;
3768       memset(p->a+p->nDigit, 0, iExp);
3769       p->nDigit += iExp;
3770     }
3771   }else if( iExp<0 ){
3772     int nExtra;
3773     iExp = -iExp;
3774     nExtra = p->nDigit - p->nFrac - 1;
3775     if( nExtra ){
3776       if( nExtra>=iExp ){
3777         p->nFrac += iExp;
3778         iExp  = 0;
3779       }else{
3780         iExp -= nExtra;
3781         p->nFrac = p->nDigit - 1;
3782       }
3783     }
3784     if( iExp>0 ){
3785       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3786       if( p->a==0 ) goto new_from_text_failed;
3787       memmove(p->a+iExp, p->a, p->nDigit);
3788       memset(p->a, 0, iExp);
3789       p->nDigit += iExp;
3790       p->nFrac += iExp;
3791     }
3792   }
3793   return p;
3794 
3795 new_from_text_failed:
3796   if( p ){
3797     if( p->a ) sqlite3_free(p->a);
3798     sqlite3_free(p);
3799   }
3800   return 0;
3801 }
3802 
3803 /* Forward reference */
3804 static Decimal *decimalFromDouble(double);
3805 
3806 /*
3807 ** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
3808 ** to the new object, or NULL if there is an error.  If the pCtx argument
3809 ** is not NULL, then errors are reported on it as well.
3810 **
3811 ** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3812 ** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
3813 ** 8 bytes, the resulting double value is expanded into its decimal equivalent.
3814 ** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3815 ** then NULL is returned.
3816 */
decimal_new(sqlite3_context * pCtx,sqlite3_value * pIn,int bTextOnly)3817 static Decimal *decimal_new(
3818   sqlite3_context *pCtx,       /* Report error here, if not null */
3819   sqlite3_value *pIn,          /* Construct the decimal object from this */
3820   int bTextOnly                /* Always interpret pIn as text if true */
3821 ){
3822   Decimal *p = 0;
3823   int eType = sqlite3_value_type(pIn);
3824   if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
3825     eType = SQLITE_TEXT;
3826   }
3827   switch( eType ){
3828     case SQLITE_TEXT:
3829     case SQLITE_INTEGER: {
3830       const char *zIn = (const char*)sqlite3_value_text(pIn);
3831       int n = sqlite3_value_bytes(pIn);
3832       p = decimalNewFromText(zIn, n);
3833       if( p==0 ) goto new_failed;
3834       break;
3835     }
3836 
3837     case SQLITE_FLOAT: {
3838       p = decimalFromDouble(sqlite3_value_double(pIn));
3839       break;
3840     }
3841 
3842     case SQLITE_BLOB: {
3843       const unsigned char *x;
3844       unsigned int i;
3845       sqlite3_uint64 v = 0;
3846       double r;
3847 
3848       if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
3849       x = sqlite3_value_blob(pIn);
3850       for(i=0; i<sizeof(r); i++){
3851         v = (v<<8) | x[i];
3852       }
3853       memcpy(&r, &v, sizeof(r));
3854       p = decimalFromDouble(r);
3855       break;
3856     }
3857 
3858     case SQLITE_NULL: {
3859       break;
3860     }
3861   }
3862   return p;
3863 
3864 new_failed:
3865   if( pCtx ) sqlite3_result_error_nomem(pCtx);
3866   sqlite3_free(p);
3867   return 0;
3868 }
3869 
3870 /*
3871 ** Make the given Decimal the result.
3872 */
decimal_result(sqlite3_context * pCtx,Decimal * p)3873 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
3874   char *z;
3875   int i, j;
3876   int n;
3877   if( p==0 || p->oom ){
3878     sqlite3_result_error_nomem(pCtx);
3879     return;
3880   }
3881   if( p->isNull ){
3882     sqlite3_result_null(pCtx);
3883     return;
3884   }
3885   z = sqlite3_malloc( p->nDigit+4 );
3886   if( z==0 ){
3887     sqlite3_result_error_nomem(pCtx);
3888     return;
3889   }
3890   i = 0;
3891   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
3892     p->sign = 0;
3893   }
3894   if( p->sign ){
3895     z[0] = '-';
3896     i = 1;
3897   }
3898   n = p->nDigit - p->nFrac;
3899   if( n<=0 ){
3900     z[i++] = '0';
3901   }
3902   j = 0;
3903   while( n>1 && p->a[j]==0 ){
3904     j++;
3905     n--;
3906   }
3907   while( n>0  ){
3908     z[i++] = p->a[j] + '0';
3909     j++;
3910     n--;
3911   }
3912   if( p->nFrac ){
3913     z[i++] = '.';
3914     do{
3915       z[i++] = p->a[j] + '0';
3916       j++;
3917     }while( j<p->nDigit );
3918   }
3919   z[i] = 0;
3920   sqlite3_result_text(pCtx, z, i, sqlite3_free);
3921 }
3922 
3923 /*
3924 ** Make the given Decimal the result in an format similar to  '%+#e'.
3925 ** In other words, show exponential notation with leading and trailing
3926 ** zeros omitted.
3927 */
decimal_result_sci(sqlite3_context * pCtx,Decimal * p)3928 static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){
3929   char *z;       /* The output buffer */
3930   int i;         /* Loop counter */
3931   int nZero;     /* Number of leading zeros */
3932   int nDigit;    /* Number of digits not counting trailing zeros */
3933   int nFrac;     /* Digits to the right of the decimal point */
3934   int exp;       /* Exponent value */
3935   signed char zero;     /* Zero value */
3936   signed char *a;       /* Array of digits */
3937 
3938   if( p==0 || p->oom ){
3939     sqlite3_result_error_nomem(pCtx);
3940     return;
3941   }
3942   if( p->isNull ){
3943     sqlite3_result_null(pCtx);
3944     return;
3945   }
3946   for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){}
3947   for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
3948   nFrac = p->nFrac + (nDigit - p->nDigit);
3949   nDigit -= nZero;
3950   z = sqlite3_malloc( nDigit+20 );
3951   if( z==0 ){
3952     sqlite3_result_error_nomem(pCtx);
3953     return;
3954   }
3955   if( nDigit==0 ){
3956     zero = 0;
3957     a = &zero;
3958     nDigit = 1;
3959     nFrac = 0;
3960   }else{
3961     a = &p->a[nZero];
3962   }
3963   if( p->sign && nDigit>0 ){
3964     z[0] = '-';
3965   }else{
3966     z[0] = '+';
3967   }
3968   z[1] = a[0]+'0';
3969   z[2] = '.';
3970   if( nDigit==1 ){
3971     z[3] = '0';
3972     i = 4;
3973   }else{
3974     for(i=1; i<nDigit; i++){
3975       z[2+i] = a[i]+'0';
3976     }
3977     i = nDigit+2;
3978   }
3979   exp = nDigit - nFrac - 1;
3980   sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
3981   sqlite3_result_text(pCtx, z, -1, sqlite3_free);
3982 }
3983 
3984 /*
3985 ** Compare to Decimal objects.  Return negative, 0, or positive if the
3986 ** first object is less than, equal to, or greater than the second.
3987 **
3988 ** Preconditions for this routine:
3989 **
3990 **    pA!=0
3991 **    pA->isNull==0
3992 **    pB!=0
3993 **    pB->isNull==0
3994 */
decimal_cmp(const Decimal * pA,const Decimal * pB)3995 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
3996   int nASig, nBSig, rc, n;
3997   if( pA->sign!=pB->sign ){
3998     return pA->sign ? -1 : +1;
3999   }
4000   if( pA->sign ){
4001     const Decimal *pTemp = pA;
4002     pA = pB;
4003     pB = pTemp;
4004   }
4005   nASig = pA->nDigit - pA->nFrac;
4006   nBSig = pB->nDigit - pB->nFrac;
4007   if( nASig!=nBSig ){
4008     return nASig - nBSig;
4009   }
4010   n = pA->nDigit;
4011   if( n>pB->nDigit ) n = pB->nDigit;
4012   rc = memcmp(pA->a, pB->a, n);
4013   if( rc==0 ){
4014     rc = pA->nDigit - pB->nDigit;
4015   }
4016   return rc;
4017 }
4018 
4019 /*
4020 ** SQL Function:   decimal_cmp(X, Y)
4021 **
4022 ** Return negative, zero, or positive if X is less then, equal to, or
4023 ** greater than Y.
4024 */
decimalCmpFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4025 static void decimalCmpFunc(
4026   sqlite3_context *context,
4027   int argc,
4028   sqlite3_value **argv
4029 ){
4030   Decimal *pA = 0, *pB = 0;
4031   int rc;
4032 
4033   UNUSED_PARAMETER(argc);
4034   pA = decimal_new(context, argv[0], 1);
4035   if( pA==0 || pA->isNull ) goto cmp_done;
4036   pB = decimal_new(context, argv[1], 1);
4037   if( pB==0 || pB->isNull ) goto cmp_done;
4038   rc = decimal_cmp(pA, pB);
4039   if( rc<0 ) rc = -1;
4040   else if( rc>0 ) rc = +1;
4041   sqlite3_result_int(context, rc);
4042 cmp_done:
4043   decimal_free(pA);
4044   decimal_free(pB);
4045 }
4046 
4047 /*
4048 ** Expand the Decimal so that it has a least nDigit digits and nFrac
4049 ** digits to the right of the decimal point.
4050 */
decimal_expand(Decimal * p,int nDigit,int nFrac)4051 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4052   int nAddSig;
4053   int nAddFrac;
4054   if( p==0 ) return;
4055   nAddFrac = nFrac - p->nFrac;
4056   nAddSig = (nDigit - p->nDigit) - nAddFrac;
4057   if( nAddFrac==0 && nAddSig==0 ) return;
4058   p->a = sqlite3_realloc64(p->a, nDigit+1);
4059   if( p->a==0 ){
4060     p->oom = 1;
4061     return;
4062   }
4063   if( nAddSig ){
4064     memmove(p->a+nAddSig, p->a, p->nDigit);
4065     memset(p->a, 0, nAddSig);
4066     p->nDigit += nAddSig;
4067   }
4068   if( nAddFrac ){
4069     memset(p->a+p->nDigit, 0, nAddFrac);
4070     p->nDigit += nAddFrac;
4071     p->nFrac += nAddFrac;
4072   }
4073 }
4074 
4075 /*
4076 ** Add the value pB into pA.   A := A + B.
4077 **
4078 ** Both pA and pB might become denormalized by this routine.
4079 */
decimal_add(Decimal * pA,Decimal * pB)4080 static void decimal_add(Decimal *pA, Decimal *pB){
4081   int nSig, nFrac, nDigit;
4082   int i, rc;
4083   if( pA==0 ){
4084     return;
4085   }
4086   if( pA->oom || pB==0 || pB->oom ){
4087     pA->oom = 1;
4088     return;
4089   }
4090   if( pA->isNull || pB->isNull ){
4091     pA->isNull = 1;
4092     return;
4093   }
4094   nSig = pA->nDigit - pA->nFrac;
4095   if( nSig && pA->a[0]==0 ) nSig--;
4096   if( nSig<pB->nDigit-pB->nFrac ){
4097     nSig = pB->nDigit - pB->nFrac;
4098   }
4099   nFrac = pA->nFrac;
4100   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4101   nDigit = nSig + nFrac + 1;
4102   decimal_expand(pA, nDigit, nFrac);
4103   decimal_expand(pB, nDigit, nFrac);
4104   if( pA->oom || pB->oom ){
4105     pA->oom = 1;
4106   }else{
4107     if( pA->sign==pB->sign ){
4108       int carry = 0;
4109       for(i=nDigit-1; i>=0; i--){
4110         int x = pA->a[i] + pB->a[i] + carry;
4111         if( x>=10 ){
4112           carry = 1;
4113           pA->a[i] = x - 10;
4114         }else{
4115           carry = 0;
4116           pA->a[i] = x;
4117         }
4118       }
4119     }else{
4120       signed char *aA, *aB;
4121       int borrow = 0;
4122       rc = memcmp(pA->a, pB->a, nDigit);
4123       if( rc<0 ){
4124         aA = pB->a;
4125         aB = pA->a;
4126         pA->sign = !pA->sign;
4127       }else{
4128         aA = pA->a;
4129         aB = pB->a;
4130       }
4131       for(i=nDigit-1; i>=0; i--){
4132         int x = aA[i] - aB[i] - borrow;
4133         if( x<0 ){
4134           pA->a[i] = x+10;
4135           borrow = 1;
4136         }else{
4137           pA->a[i] = x;
4138           borrow = 0;
4139         }
4140       }
4141     }
4142   }
4143 }
4144 
4145 /*
4146 ** Multiply A by B.   A := A * B
4147 **
4148 ** All significant digits after the decimal point are retained.
4149 ** Trailing zeros after the decimal point are omitted as long as
4150 ** the number of digits after the decimal point is no less than
4151 ** either the number of digits in either input.
4152 */
decimalMul(Decimal * pA,Decimal * pB)4153 static void decimalMul(Decimal *pA, Decimal *pB){
4154   signed char *acc = 0;
4155   int i, j, k;
4156   int minFrac;
4157 
4158   if( pA==0 || pA->oom || pA->isNull
4159    || pB==0 || pB->oom || pB->isNull
4160   ){
4161     goto mul_end;
4162   }
4163   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
4164   if( acc==0 ){
4165     pA->oom = 1;
4166     goto mul_end;
4167   }
4168   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
4169   minFrac = pA->nFrac;
4170   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
4171   for(i=pA->nDigit-1; i>=0; i--){
4172     signed char f = pA->a[i];
4173     int carry = 0, x;
4174     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
4175       x = acc[k] + f*pB->a[j] + carry;
4176       acc[k] = x%10;
4177       carry = x/10;
4178     }
4179     x = acc[k] + carry;
4180     acc[k] = x%10;
4181     acc[k-1] += x/10;
4182   }
4183   sqlite3_free(pA->a);
4184   pA->a = acc;
4185   acc = 0;
4186   pA->nDigit += pB->nDigit + 2;
4187   pA->nFrac += pB->nFrac;
4188   pA->sign ^= pB->sign;
4189   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
4190     pA->nFrac--;
4191     pA->nDigit--;
4192   }
4193 
4194 mul_end:
4195   sqlite3_free(acc);
4196 }
4197 
4198 /*
4199 ** Create a new Decimal object that contains an integer power of 2.
4200 */
decimalPow2(int N)4201 static Decimal *decimalPow2(int N){
4202   Decimal *pA = 0;      /* The result to be returned */
4203   Decimal *pX = 0;      /* Multiplier */
4204   if( N<-20000 || N>20000 ) goto pow2_fault;
4205   pA = decimalNewFromText("1.0", 3);
4206   if( pA==0 || pA->oom ) goto pow2_fault;
4207   if( N==0 ) return pA;
4208   if( N>0 ){
4209     pX = decimalNewFromText("2.0", 3);
4210   }else{
4211     N = -N;
4212     pX = decimalNewFromText("0.5", 3);
4213   }
4214   if( pX==0 || pX->oom ) goto pow2_fault;
4215   while( 1 /* Exit by break */ ){
4216     if( N & 1 ){
4217       decimalMul(pA, pX);
4218       if( pA->oom ) goto pow2_fault;
4219     }
4220     N >>= 1;
4221     if( N==0 ) break;
4222     decimalMul(pX, pX);
4223   }
4224   decimal_free(pX);
4225   return pA;
4226 
4227 pow2_fault:
4228   decimal_free(pA);
4229   decimal_free(pX);
4230   return 0;
4231 }
4232 
4233 /*
4234 ** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
4235 */
decimalFromDouble(double r)4236 static Decimal *decimalFromDouble(double r){
4237   sqlite3_int64 m, a;
4238   int e;
4239   int isNeg;
4240   Decimal *pA;
4241   Decimal *pX;
4242   char zNum[100];
4243   if( r<0.0 ){
4244     isNeg = 1;
4245     r = -r;
4246   }else{
4247     isNeg = 0;
4248   }
4249   memcpy(&a,&r,sizeof(a));
4250   if( a==0 ){
4251     e = 0;
4252     m = 0;
4253   }else{
4254     e = a>>52;
4255     m = a & ((((sqlite3_int64)1)<<52)-1);
4256     if( e==0 ){
4257       m <<= 1;
4258     }else{
4259       m |= ((sqlite3_int64)1)<<52;
4260     }
4261     while( e<1075 && m>0 && (m&1)==0 ){
4262       m >>= 1;
4263       e++;
4264     }
4265     if( isNeg ) m = -m;
4266     e = e - 1075;
4267     if( e>971 ){
4268       return 0;  /* A NaN or an Infinity */
4269     }
4270   }
4271 
4272   /* At this point m is the integer significand and e is the exponent */
4273   sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
4274   pA = decimalNewFromText(zNum, (int)strlen(zNum));
4275   pX = decimalPow2(e);
4276   decimalMul(pA, pX);
4277   decimal_free(pX);
4278   return pA;
4279 }
4280 
4281 /*
4282 ** SQL Function:   decimal(X)
4283 ** OR:             decimal_exp(X)
4284 **
4285 ** Convert input X into decimal and then back into text.
4286 **
4287 ** If X is originally a float, then a full decimal expansion of that floating
4288 ** point value is done.  Or if X is an 8-byte blob, it is interpreted
4289 ** as a float and similarly expanded.
4290 **
4291 ** The decimal_exp(X) function returns the result in exponential notation.
4292 ** decimal(X) returns a complete decimal, without the e+NNN at the end.
4293 */
decimalFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4294 static void decimalFunc(
4295   sqlite3_context *context,
4296   int argc,
4297   sqlite3_value **argv
4298 ){
4299   Decimal *p =  decimal_new(context, argv[0], 0);
4300   UNUSED_PARAMETER(argc);
4301   if( p ){
4302     if( sqlite3_user_data(context)!=0 ){
4303       decimal_result_sci(context, p);
4304     }else{
4305       decimal_result(context, p);
4306     }
4307     decimal_free(p);
4308   }
4309 }
4310 
4311 /*
4312 ** Compare text in decimal order.
4313 */
decimalCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)4314 static int decimalCollFunc(
4315   void *notUsed,
4316   int nKey1, const void *pKey1,
4317   int nKey2, const void *pKey2
4318 ){
4319   const unsigned char *zA = (const unsigned char*)pKey1;
4320   const unsigned char *zB = (const unsigned char*)pKey2;
4321   Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
4322   Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
4323   int rc;
4324   UNUSED_PARAMETER(notUsed);
4325   if( pA==0 || pB==0 ){
4326     rc = 0;
4327   }else{
4328     rc = decimal_cmp(pA, pB);
4329   }
4330   decimal_free(pA);
4331   decimal_free(pB);
4332   return rc;
4333 }
4334 
4335 
4336 /*
4337 ** SQL Function:   decimal_add(X, Y)
4338 **                 decimal_sub(X, Y)
4339 **
4340 ** Return the sum or difference of X and Y.
4341 */
decimalAddFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4342 static void decimalAddFunc(
4343   sqlite3_context *context,
4344   int argc,
4345   sqlite3_value **argv
4346 ){
4347   Decimal *pA = decimal_new(context, argv[0], 1);
4348   Decimal *pB = decimal_new(context, argv[1], 1);
4349   UNUSED_PARAMETER(argc);
4350   decimal_add(pA, pB);
4351   decimal_result(context, pA);
4352   decimal_free(pA);
4353   decimal_free(pB);
4354 }
decimalSubFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4355 static void decimalSubFunc(
4356   sqlite3_context *context,
4357   int argc,
4358   sqlite3_value **argv
4359 ){
4360   Decimal *pA = decimal_new(context, argv[0], 1);
4361   Decimal *pB = decimal_new(context, argv[1], 1);
4362   UNUSED_PARAMETER(argc);
4363   if( pB ){
4364     pB->sign = !pB->sign;
4365     decimal_add(pA, pB);
4366     decimal_result(context, pA);
4367   }
4368   decimal_free(pA);
4369   decimal_free(pB);
4370 }
4371 
4372 /* Aggregate funcion:   decimal_sum(X)
4373 **
4374 ** Works like sum() except that it uses decimal arithmetic for unlimited
4375 ** precision.
4376 */
decimalSumStep(sqlite3_context * context,int argc,sqlite3_value ** argv)4377 static void decimalSumStep(
4378   sqlite3_context *context,
4379   int argc,
4380   sqlite3_value **argv
4381 ){
4382   Decimal *p;
4383   Decimal *pArg;
4384   UNUSED_PARAMETER(argc);
4385   p = sqlite3_aggregate_context(context, sizeof(*p));
4386   if( p==0 ) return;
4387   if( !p->isInit ){
4388     p->isInit = 1;
4389     p->a = sqlite3_malloc(2);
4390     if( p->a==0 ){
4391       p->oom = 1;
4392     }else{
4393       p->a[0] = 0;
4394     }
4395     p->nDigit = 1;
4396     p->nFrac = 0;
4397   }
4398   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4399   pArg = decimal_new(context, argv[0], 1);
4400   decimal_add(p, pArg);
4401   decimal_free(pArg);
4402 }
decimalSumInverse(sqlite3_context * context,int argc,sqlite3_value ** argv)4403 static void decimalSumInverse(
4404   sqlite3_context *context,
4405   int argc,
4406   sqlite3_value **argv
4407 ){
4408   Decimal *p;
4409   Decimal *pArg;
4410   UNUSED_PARAMETER(argc);
4411   p = sqlite3_aggregate_context(context, sizeof(*p));
4412   if( p==0 ) return;
4413   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4414   pArg = decimal_new(context, argv[0], 1);
4415   if( pArg ) pArg->sign = !pArg->sign;
4416   decimal_add(p, pArg);
4417   decimal_free(pArg);
4418 }
decimalSumValue(sqlite3_context * context)4419 static void decimalSumValue(sqlite3_context *context){
4420   Decimal *p = sqlite3_aggregate_context(context, 0);
4421   if( p==0 ) return;
4422   decimal_result(context, p);
4423 }
decimalSumFinalize(sqlite3_context * context)4424 static void decimalSumFinalize(sqlite3_context *context){
4425   Decimal *p = sqlite3_aggregate_context(context, 0);
4426   if( p==0 ) return;
4427   decimal_result(context, p);
4428   decimal_clear(p);
4429 }
4430 
4431 /*
4432 ** SQL Function:   decimal_mul(X, Y)
4433 **
4434 ** Return the product of X and Y.
4435 */
decimalMulFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4436 static void decimalMulFunc(
4437   sqlite3_context *context,
4438   int argc,
4439   sqlite3_value **argv
4440 ){
4441   Decimal *pA = decimal_new(context, argv[0], 1);
4442   Decimal *pB = decimal_new(context, argv[1], 1);
4443   UNUSED_PARAMETER(argc);
4444   if( pA==0 || pA->oom || pA->isNull
4445    || pB==0 || pB->oom || pB->isNull
4446   ){
4447     goto mul_end;
4448   }
4449   decimalMul(pA, pB);
4450   if( pA->oom ){
4451     goto mul_end;
4452   }
4453   decimal_result(context, pA);
4454 
4455 mul_end:
4456   decimal_free(pA);
4457   decimal_free(pB);
4458 }
4459 
4460 /*
4461 ** SQL Function:   decimal_pow2(N)
4462 **
4463 ** Return the N-th power of 2.  N must be an integer.
4464 */
decimalPow2Func(sqlite3_context * context,int argc,sqlite3_value ** argv)4465 static void decimalPow2Func(
4466   sqlite3_context *context,
4467   int argc,
4468   sqlite3_value **argv
4469 ){
4470   UNUSED_PARAMETER(argc);
4471   if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
4472     Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
4473     decimal_result_sci(context, pA);
4474     decimal_free(pA);
4475   }
4476 }
4477 
4478 #ifdef _WIN32
4479 
4480 #endif
sqlite3_decimal_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)4481 int sqlite3_decimal_init(
4482   sqlite3 *db,
4483   char **pzErrMsg,
4484   const sqlite3_api_routines *pApi
4485 ){
4486   int rc = SQLITE_OK;
4487   static const struct {
4488     const char *zFuncName;
4489     int nArg;
4490     int iArg;
4491     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4492   } aFunc[] = {
4493     { "decimal",       1, 0,  decimalFunc        },
4494     { "decimal_exp",   1, 1,  decimalFunc        },
4495     { "decimal_cmp",   2, 0,  decimalCmpFunc     },
4496     { "decimal_add",   2, 0,  decimalAddFunc     },
4497     { "decimal_sub",   2, 0,  decimalSubFunc     },
4498     { "decimal_mul",   2, 0,  decimalMulFunc     },
4499     { "decimal_pow2",  1, 0,  decimalPow2Func    },
4500   };
4501   unsigned int i;
4502   (void)pzErrMsg;  /* Unused parameter */
4503 
4504   SQLITE_EXTENSION_INIT2(pApi);
4505 
4506   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
4507     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
4508                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4509                    aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
4510   }
4511   if( rc==SQLITE_OK ){
4512     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
4513                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
4514                    decimalSumStep, decimalSumFinalize,
4515                    decimalSumValue, decimalSumInverse, 0);
4516   }
4517   if( rc==SQLITE_OK ){
4518     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
4519                                   0, decimalCollFunc);
4520   }
4521   return rc;
4522 }
4523 
4524 /************************* End ../ext/misc/decimal.c ********************/
4525 #undef sqlite3_base_init
4526 #define sqlite3_base_init sqlite3_base64_init
4527 /************************* Begin ../ext/misc/base64.c ******************/
4528 /*
4529 ** 2022-11-18
4530 **
4531 ** The author disclaims copyright to this source code.  In place of
4532 ** a legal notice, here is a blessing:
4533 **
4534 **    May you do good and not evil.
4535 **    May you find forgiveness for yourself and forgive others.
4536 **    May you share freely, never taking more than you give.
4537 **
4538 *************************************************************************
4539 **
4540 ** This is a SQLite extension for converting in either direction
4541 ** between a (binary) blob and base64 text. Base64 can transit a
4542 ** sane USASCII channel unmolested. It also plays nicely in CSV or
4543 ** written as TCL brace-enclosed literals or SQL string literals,
4544 ** and can be used unmodified in XML-like documents.
4545 **
4546 ** This is an independent implementation of conversions specified in
4547 ** RFC 4648, done on the above date by the author (Larry Brasfield)
4548 ** who thereby has the right to put this into the public domain.
4549 **
4550 ** The conversions meet RFC 4648 requirements, provided that this
4551 ** C source specifies that line-feeds are included in the encoded
4552 ** data to limit visible line lengths to 72 characters and to
4553 ** terminate any encoded blob having non-zero length.
4554 **
4555 ** Length limitations are not imposed except that the runtime
4556 ** SQLite string or blob length limits are respected. Otherwise,
4557 ** any length binary sequence can be represented and recovered.
4558 ** Generated base64 sequences, with their line-feeds included,
4559 ** can be concatenated; the result converted back to binary will
4560 ** be the concatenation of the represented binary sequences.
4561 **
4562 ** This SQLite3 extension creates a function, base64(x), which
4563 ** either: converts text x containing base64 to a returned blob;
4564 ** or converts a blob x to returned text containing base64. An
4565 ** error will be thrown for other input argument types.
4566 **
4567 ** This code relies on UTF-8 encoding only with respect to the
4568 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
4569 ** It will fail miserably if somehow made to try to convert EBCDIC.
4570 ** Because it is table-driven, it could be enhanced to handle that,
4571 ** but the world and SQLite have moved on from that anachronism.
4572 **
4573 ** To build the extension:
4574 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4575 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
4576 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
4577 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
4578 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
4579 */
4580 
4581 #include <assert.h>
4582 
4583 /* #include "sqlite3ext.h" */
4584 
4585 #ifndef deliberate_fall_through
4586 /* Quiet some compilers about some of our intentional code. */
4587 # if GCC_VERSION>=7000000
4588 #  define deliberate_fall_through __attribute__((fallthrough));
4589 # else
4590 #  define deliberate_fall_through
4591 # endif
4592 #endif
4593 
4594 SQLITE_EXTENSION_INIT1;
4595 
4596 #define PC 0x80 /* pad character */
4597 #define WS 0x81 /* whitespace */
4598 #define ND 0x82 /* Not above or digit-value */
4599 #define PAD_CHAR '='
4600 
4601 #ifndef U8_TYPEDEF
4602 /* typedef unsigned char u8; */
4603 #define U8_TYPEDEF
4604 #endif
4605 
4606 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
4607 static const u8 b64DigitValues[128] = {
4608   /*                             HT LF VT  FF CR       */
4609     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
4610   /*                                                US */
4611     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
4612   /*sp                                  +            / */
4613     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
4614   /* 0  1            5            9            =       */
4615     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
4616   /*    A                                            O */
4617     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
4618   /* P                               Z                 */
4619     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
4620   /*    a                                            o */
4621     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
4622   /* p                               z                 */
4623     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
4624 };
4625 
4626 static const char b64Numerals[64+1]
4627 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4628 
4629 #define BX_DV_PROTO(c) \
4630   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
4631 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
4632 #define IS_BX_WS(bdp) ((bdp)==WS)
4633 #define IS_BX_PAD(bdp) ((bdp)==PC)
4634 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
4635 /* Width of base64 lines. Should be an integer multiple of 4. */
4636 #define B64_DARK_MAX 72
4637 
4638 /* Encode a byte buffer into base64 text with linefeeds appended to limit
4639 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
4640 */
toBase64(u8 * pIn,int nbIn,char * pOut)4641 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
4642   int nCol = 0;
4643   while( nbIn >= 3 ){
4644     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
4645     pOut[0] = BX_NUMERAL(pIn[0]>>2);
4646     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
4647     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
4648     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
4649     pOut += 4;
4650     nbIn -= 3;
4651     pIn += 3;
4652     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
4653       *pOut++ = '\n';
4654       nCol = 0;
4655     }
4656   }
4657   if( nbIn > 0 ){
4658     signed char nco = nbIn+1;
4659     int nbe;
4660     unsigned long qv = *pIn++;
4661     for( nbe=1; nbe<3; ++nbe ){
4662       qv <<= 8;
4663       if( nbe<nbIn ) qv |= *pIn++;
4664     }
4665     for( nbe=3; nbe>=0; --nbe ){
4666       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
4667       qv >>= 6;
4668       pOut[nbe] = ce;
4669     }
4670     pOut += 4;
4671     *pOut++ = '\n';
4672   }
4673   *pOut = 0;
4674   return pOut;
4675 }
4676 
4677 /* Skip over text which is not base64 numeral(s). */
skipNonB64(char * s,int nc)4678 static char * skipNonB64( char *s, int nc ){
4679   char c;
4680   while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
4681   return s;
4682 }
4683 
4684 /* Decode base64 text into a byte buffer. */
fromBase64(char * pIn,int ncIn,u8 * pOut)4685 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
4686   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
4687   while( ncIn>0 && *pIn!=PAD_CHAR ){
4688     static signed char nboi[] = { 0, 0, 1, 2, 3 };
4689     char *pUse = skipNonB64(pIn, ncIn);
4690     unsigned long qv = 0L;
4691     int nti, nbo, nac;
4692     ncIn -= (pUse - pIn);
4693     pIn = pUse;
4694     nti = (ncIn>4)? 4 : ncIn;
4695     ncIn -= nti;
4696     nbo = nboi[nti];
4697     if( nbo==0 ) break;
4698     for( nac=0; nac<4; ++nac ){
4699       char c = (nac<nti)? *pIn++ : b64Numerals[0];
4700       u8 bdp = BX_DV_PROTO(c);
4701       switch( bdp ){
4702       case ND:
4703         /*  Treat dark non-digits as pad, but they terminate decode too. */
4704         ncIn = 0;
4705         deliberate_fall_through;
4706       case WS:
4707         /* Treat whitespace as pad and terminate this group.*/
4708         nti = nac;
4709         deliberate_fall_through;
4710       case PC:
4711         bdp = 0;
4712         --nbo;
4713         deliberate_fall_through;
4714       default: /* bdp is the digit value. */
4715         qv = qv<<6 | bdp;
4716         break;
4717       }
4718     }
4719     switch( nbo ){
4720     case 3:
4721       pOut[2] = (qv) & 0xff;
4722     case 2:
4723       pOut[1] = (qv>>8) & 0xff;
4724     case 1:
4725       pOut[0] = (qv>>16) & 0xff;
4726     }
4727     pOut += nbo;
4728   }
4729   return pOut;
4730 }
4731 
4732 /* This function does the work for the SQLite base64(x) UDF. */
base64(sqlite3_context * context,int na,sqlite3_value * av[])4733 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
4734   int nb, nc, nv = sqlite3_value_bytes(av[0]);
4735   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
4736                             SQLITE_LIMIT_LENGTH, -1);
4737   char *cBuf;
4738   u8 *bBuf;
4739   assert(na==1);
4740   switch( sqlite3_value_type(av[0]) ){
4741   case SQLITE_BLOB:
4742     nb = nv;
4743     nc = 4*(nv+2/3); /* quads needed */
4744     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
4745     if( nvMax < nc ){
4746       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
4747       return;
4748     }
4749     bBuf = (u8*)sqlite3_value_blob(av[0]);
4750     if( !bBuf ){
4751       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4752         goto memFail;
4753       }
4754       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
4755       break;
4756     }
4757     cBuf = sqlite3_malloc(nc);
4758     if( !cBuf ) goto memFail;
4759     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
4760     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
4761     break;
4762   case SQLITE_TEXT:
4763     nc = nv;
4764     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
4765     if( nvMax < nb ){
4766       sqlite3_result_error(context, "blob from base64 may be too big", -1);
4767       return;
4768     }else if( nb<1 ){
4769       nb = 1;
4770     }
4771     cBuf = (char *)sqlite3_value_text(av[0]);
4772     if( !cBuf ){
4773       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4774         goto memFail;
4775       }
4776       sqlite3_result_zeroblob(context, 0);
4777       break;
4778     }
4779     bBuf = sqlite3_malloc(nb);
4780     if( !bBuf ) goto memFail;
4781     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
4782     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
4783     break;
4784   default:
4785     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
4786     return;
4787   }
4788   return;
4789  memFail:
4790   sqlite3_result_error(context, "base64 OOM", -1);
4791 }
4792 
4793 /*
4794 ** Establish linkage to running SQLite library.
4795 */
4796 #ifndef SQLITE_SHELL_EXTFUNCS
4797 #ifdef _WIN32
4798 
4799 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)4800 int sqlite3_base_init
4801 #else
4802 static int sqlite3_base64_init
4803 #endif
4804 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
4805   SQLITE_EXTENSION_INIT2(pApi);
4806   (void)pzErr;
4807   return sqlite3_create_function
4808     (db, "base64", 1,
4809      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
4810      0, base64, 0, 0);
4811 }
4812 
4813 /*
4814 ** Define some macros to allow this extension to be built into the shell
4815 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
4816 ** allows shell.c, as distributed, to have this extension built in.
4817 */
4818 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
4819 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
4820 
4821 /************************* End ../ext/misc/base64.c ********************/
4822 #undef sqlite3_base_init
4823 #define sqlite3_base_init sqlite3_base85_init
4824 #define OMIT_BASE85_CHECKER
4825 /************************* Begin ../ext/misc/base85.c ******************/
4826 /*
4827 ** 2022-11-16
4828 **
4829 ** The author disclaims copyright to this source code.  In place of
4830 ** a legal notice, here is a blessing:
4831 **
4832 **    May you do good and not evil.
4833 **    May you find forgiveness for yourself and forgive others.
4834 **    May you share freely, never taking more than you give.
4835 **
4836 *************************************************************************
4837 **
4838 ** This is a utility for converting binary to base85 or vice-versa.
4839 ** It can be built as a standalone program or an SQLite3 extension.
4840 **
4841 ** Much like base64 representations, base85 can be sent through a
4842 ** sane USASCII channel unmolested. It also plays nicely in CSV or
4843 ** written as TCL brace-enclosed literals or SQL string literals.
4844 ** It is not suited for unmodified use in XML-like documents.
4845 **
4846 ** The encoding used resembles Ascii85, but was devised by the author
4847 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
4848 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
4849 ** Further, this is an independent implementation of a base85 system.
4850 ** Hence, the author has rightfully put this into the public domain.
4851 **
4852 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
4853 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
4854 ** in code order representing digit values 0 to 84 (base 10.)
4855 **
4856 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4857 ** are represented as 5-digit base85 numbers with MS to LS digit
4858 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
4859 ** still big-endian but 8-24 bit values. (Using big-endian yields
4860 ** the simplest transition to byte groups smaller than 4 bytes.
4861 ** These byte groups can also be considered base-256 numbers.)
4862 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
4863 ** No pad characters are used; Encoded base85 numeral sequence
4864 ** (aka "group") length maps 1-to-1 to the decoded binary length.
4865 **
4866 ** Any character not in the base85 numeral set delimits groups.
4867 ** When base85 is streamed or stored in containers of indefinite
4868 ** size, newline is used to separate it into sub-sequences of no
4869 ** more than 80 digits so that fgets() can be used to read it.
4870 **
4871 ** Length limitations are not imposed except that the runtime
4872 ** SQLite string or blob length limits are respected. Otherwise,
4873 ** any length binary sequence can be represented and recovered.
4874 ** Base85 sequences can be concatenated by separating them with
4875 ** a non-base85 character; the conversion to binary will then
4876 ** be the concatenation of the represented binary sequences.
4877 
4878 ** The standalone program either converts base85 on stdin to create
4879 ** a binary file or converts a binary file to base85 on stdout.
4880 ** Read or make it blurt its help for invocation details.
4881 **
4882 ** The SQLite3 extension creates a function, base85(x), which will
4883 ** either convert text base85 to a blob or a blob to text base85
4884 ** and return the result (or throw an error for other types.)
4885 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
4886 ** function, is_base85(t), which returns 1 iff the text t contains
4887 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
4888 **
4889 ** To build the extension:
4890 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4891 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4892 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4893 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4894 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4895 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4896 **
4897 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
4898 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4899 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4900 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4901 */
4902 
4903 #include <stdio.h>
4904 #include <memory.h>
4905 #include <string.h>
4906 #include <assert.h>
4907 #ifndef OMIT_BASE85_CHECKER
4908 # include <ctype.h>
4909 #endif
4910 
4911 #ifndef BASE85_STANDALONE
4912 
4913 /* # include "sqlite3ext.h" */
4914 
4915 SQLITE_EXTENSION_INIT1;
4916 
4917 #else
4918 
4919 # ifdef _WIN32
4920 #  include <io.h>
4921 #  include <fcntl.h>
4922 # else
4923 #  define setmode(fd,m)
4924 # endif
4925 
4926 static char *zHelp =
4927   "Usage: base85 <dirFlag> <binFile>\n"
4928   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4929   "   content to be converted to/from base85 on stdout/stdin.\n"
4930   " <binFile> names a binary file to be rendered or created.\n"
4931   "   Or, the name '-' refers to the stdin or stdout stream.\n"
4932   ;
4933 
sayHelp()4934 static void sayHelp(){
4935   printf("%s", zHelp);
4936 }
4937 #endif
4938 
4939 #ifndef U8_TYPEDEF
4940 /* typedef unsigned char u8; */
4941 #define U8_TYPEDEF
4942 #endif
4943 
4944 /* Classify c according to interval within USASCII set w.r.t. base85
4945  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
4946  */
4947 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
4948 
4949 /* Provide digitValue to b85Numeral offset as a function of above class. */
4950 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4951 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
4952 
4953 /* Say whether c is a base85 numeral. */
4954 #define IS_B85( c ) (B85_CLASS(c) & 1)
4955 
4956 #if 0 /* Not used, */
4957 static u8 base85DigitValue( char c ){
4958   u8 dv = (u8)(c - '#');
4959   if( dv>87 ) return 0xff;
4960   return (dv > 3)? dv-3 : dv;
4961 }
4962 #endif
4963 
4964 /* Width of base64 lines. Should be an integer multiple of 5. */
4965 #define B85_DARK_MAX 80
4966 
4967 
skipNonB85(char * s,int nc)4968 static char * skipNonB85( char *s, int nc ){
4969   char c;
4970   while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
4971   return s;
4972 }
4973 
4974 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
4975  * Do not use the macro form with argument expression having a side-effect.*/
4976 #if 0
4977 static char base85Numeral( u8 b ){
4978   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
4979 }
4980 #else
4981 # define base85Numeral( dn )\
4982   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
4983 #endif
4984 
putcs(char * pc,char * s)4985 static char *putcs(char *pc, char *s){
4986   char c;
4987   while( (c = *s++)!=0 ) *pc++ = c;
4988   return pc;
4989 }
4990 
4991 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
4992 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
4993 ** or to terminate the last group (to aid concatenation.)
4994 */
toBase85(u8 * pIn,int nbIn,char * pOut,char * pSep)4995 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
4996   int nCol = 0;
4997   while( nbIn >= 4 ){
4998     int nco = 5;
4999     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
5000                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
5001     while( nco > 0 ){
5002       unsigned nqv = (unsigned)(qbv/85UL);
5003       unsigned char dv = qbv - 85UL*nqv;
5004       qbv = nqv;
5005       pOut[--nco] = base85Numeral(dv);
5006     }
5007     nbIn -= 4;
5008     pIn += 4;
5009     pOut += 5;
5010     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
5011       pOut = putcs(pOut, pSep);
5012       nCol = 0;
5013     }
5014   }
5015   if( nbIn > 0 ){
5016     int nco = nbIn + 1;
5017     unsigned long qv = *pIn++;
5018     int nbe = 1;
5019     while( nbe++ < nbIn ){
5020       qv = (qv<<8) | *pIn++;
5021     }
5022     nCol += nco;
5023     while( nco > 0 ){
5024       u8 dv = (u8)(qv % 85);
5025       qv /= 85;
5026       pOut[--nco] = base85Numeral(dv);
5027     }
5028     pOut += (nbIn+1);
5029   }
5030   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
5031   *pOut = 0;
5032   return pOut;
5033 }
5034 
5035 /* Decode base85 text into a byte buffer. */
fromBase85(char * pIn,int ncIn,u8 * pOut)5036 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
5037   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
5038   while( ncIn>0 ){
5039     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
5040     char *pUse = skipNonB85(pIn, ncIn);
5041     unsigned long qv = 0L;
5042     int nti, nbo;
5043     ncIn -= (pUse - pIn);
5044     pIn = pUse;
5045     nti = (ncIn>5)? 5 : ncIn;
5046     nbo = nboi[nti];
5047     if( nbo==0 ) break;
5048     while( nti>0 ){
5049       char c = *pIn++;
5050       u8 cdo = B85_DNOS(c);
5051       --ncIn;
5052       if( cdo==0 ) break;
5053       qv = 85 * qv + (c - cdo);
5054       --nti;
5055     }
5056     nbo -= nti; /* Adjust for early (non-digit) end of group. */
5057     switch( nbo ){
5058     case 4:
5059       *pOut++ = (qv >> 24)&0xff;
5060     case 3:
5061       *pOut++ = (qv >> 16)&0xff;
5062     case 2:
5063       *pOut++ = (qv >> 8)&0xff;
5064     case 1:
5065       *pOut++ = qv&0xff;
5066     case 0:
5067       break;
5068     }
5069   }
5070   return pOut;
5071 }
5072 
5073 #ifndef OMIT_BASE85_CHECKER
5074 /* Say whether input char sequence is all (base85 and/or whitespace).*/
allBase85(char * p,int len)5075 static int allBase85( char *p, int len ){
5076   char c;
5077   while( len-- > 0 && (c = *p++) != 0 ){
5078     if( !IS_B85(c) && !isspace(c) ) return 0;
5079   }
5080   return 1;
5081 }
5082 #endif
5083 
5084 #ifndef BASE85_STANDALONE
5085 
5086 # ifndef OMIT_BASE85_CHECKER
5087 /* This function does the work for the SQLite is_base85(t) UDF. */
is_base85(sqlite3_context * context,int na,sqlite3_value * av[])5088 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5089   assert(na==1);
5090   switch( sqlite3_value_type(av[0]) ){
5091   case SQLITE_TEXT:
5092     {
5093       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
5094                           sqlite3_value_bytes(av[0]) );
5095       sqlite3_result_int(context, rv);
5096     }
5097     break;
5098   case SQLITE_NULL:
5099     sqlite3_result_null(context);
5100     break;
5101   default:
5102     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
5103     return;
5104   }
5105 }
5106 # endif
5107 
5108 /* This function does the work for the SQLite base85(x) UDF. */
base85(sqlite3_context * context,int na,sqlite3_value * av[])5109 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5110   int nb, nc, nv = sqlite3_value_bytes(av[0]);
5111   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
5112                             SQLITE_LIMIT_LENGTH, -1);
5113   char *cBuf;
5114   u8 *bBuf;
5115   assert(na==1);
5116   switch( sqlite3_value_type(av[0]) ){
5117   case SQLITE_BLOB:
5118     nb = nv;
5119     /*    ulongs    tail   newlines  tailenc+nul*/
5120     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
5121     if( nvMax < nc ){
5122       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
5123       return;
5124     }
5125     bBuf = (u8*)sqlite3_value_blob(av[0]);
5126     if( !bBuf ){
5127       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5128         goto memFail;
5129       }
5130       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
5131       break;
5132     }
5133     cBuf = sqlite3_malloc(nc);
5134     if( !cBuf ) goto memFail;
5135     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
5136     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
5137     break;
5138   case SQLITE_TEXT:
5139     nc = nv;
5140     nb = 4*(nv/5) + nv%5; /* may overestimate */
5141     if( nvMax < nb ){
5142       sqlite3_result_error(context, "blob from base85 may be too big", -1);
5143       return;
5144     }else if( nb<1 ){
5145       nb = 1;
5146     }
5147     cBuf = (char *)sqlite3_value_text(av[0]);
5148     if( !cBuf ){
5149       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5150         goto memFail;
5151       }
5152       sqlite3_result_zeroblob(context, 0);
5153       break;
5154     }
5155     bBuf = sqlite3_malloc(nb);
5156     if( !bBuf ) goto memFail;
5157     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
5158     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
5159     break;
5160   default:
5161     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
5162     return;
5163   }
5164   return;
5165  memFail:
5166   sqlite3_result_error(context, "base85 OOM", -1);
5167 }
5168 
5169 /*
5170 ** Establish linkage to running SQLite library.
5171 */
5172 #ifndef SQLITE_SHELL_EXTFUNCS
5173 #ifdef _WIN32
5174 
5175 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)5176 int sqlite3_base_init
5177 #else
5178 static int sqlite3_base85_init
5179 #endif
5180 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
5181   SQLITE_EXTENSION_INIT2(pApi);
5182   (void)pzErr;
5183 # ifndef OMIT_BASE85_CHECKER
5184   {
5185     int rc = sqlite3_create_function
5186       (db, "is_base85", 1,
5187        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
5188        0, is_base85, 0, 0);
5189     if( rc!=SQLITE_OK ) return rc;
5190   }
5191 # endif
5192   return sqlite3_create_function
5193     (db, "base85", 1,
5194      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
5195      0, base85, 0, 0);
5196 }
5197 
5198 /*
5199 ** Define some macros to allow this extension to be built into the shell
5200 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
5201 ** allows shell.c, as distributed, to have this extension built in.
5202 */
5203 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
5204 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
5205 
5206 #else /* standalone program */
5207 
main(int na,char * av[])5208 int main(int na, char *av[]){
5209   int cin;
5210   int rc = 0;
5211   u8 bBuf[4*(B85_DARK_MAX/5)];
5212   char cBuf[5*(sizeof(bBuf)/4)+2];
5213   size_t nio;
5214 # ifndef OMIT_BASE85_CHECKER
5215   int b85Clean = 1;
5216 # endif
5217   char rw;
5218   FILE *fb = 0, *foc = 0;
5219   char fmode[3] = "xb";
5220   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
5221     sayHelp();
5222     return 0;
5223   }
5224   fmode[0] = rw;
5225   if( av[2][0]=='-' && av[2][1]==0 ){
5226     switch( rw ){
5227     case 'r':
5228       fb = stdin;
5229       setmode(fileno(stdin), O_BINARY);
5230       break;
5231     case 'w':
5232       fb = stdout;
5233       setmode(fileno(stdout), O_BINARY);
5234       break;
5235     }
5236   }else{
5237     fb = fopen(av[2], fmode);
5238     foc = fb;
5239   }
5240   if( !fb ){
5241     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
5242     rc = 1;
5243   }else{
5244     switch( rw ){
5245     case 'r':
5246       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
5247         toBase85( bBuf, (int)nio, cBuf, 0 );
5248         fprintf(stdout, "%s\n", cBuf);
5249       }
5250       break;
5251     case 'w':
5252       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
5253         int nc = strlen(cBuf);
5254         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
5255         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
5256 # ifndef OMIT_BASE85_CHECKER
5257         b85Clean &= allBase85( cBuf, nc );
5258 # endif
5259       }
5260       break;
5261     default:
5262       sayHelp();
5263       rc = 1;
5264     }
5265     if( foc ) fclose(foc);
5266   }
5267 # ifndef OMIT_BASE85_CHECKER
5268   if( !b85Clean ){
5269     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
5270   }
5271 # endif
5272   return rc;
5273 }
5274 
5275 #endif
5276 
5277 /************************* End ../ext/misc/base85.c ********************/
5278 /************************* Begin ../ext/misc/ieee754.c ******************/
5279 /*
5280 ** 2013-04-17
5281 **
5282 ** The author disclaims copyright to this source code.  In place of
5283 ** a legal notice, here is a blessing:
5284 **
5285 **    May you do good and not evil.
5286 **    May you find forgiveness for yourself and forgive others.
5287 **    May you share freely, never taking more than you give.
5288 **
5289 ******************************************************************************
5290 **
5291 ** This SQLite extension implements functions for the exact display
5292 ** and input of IEEE754 Binary64 floating-point numbers.
5293 **
5294 **   ieee754(X)
5295 **   ieee754(Y,Z)
5296 **
5297 ** In the first form, the value X should be a floating-point number.
5298 ** The function will return a string of the form 'ieee754(Y,Z)' where
5299 ** Y and Z are integers such that X==Y*pow(2,Z).
5300 **
5301 ** In the second form, Y and Z are integers which are the mantissa and
5302 ** base-2 exponent of a new floating point number.  The function returns
5303 ** a floating-point value equal to Y*pow(2,Z).
5304 **
5305 ** Examples:
5306 **
5307 **     ieee754(2.0)             ->     'ieee754(2,0)'
5308 **     ieee754(45.25)           ->     'ieee754(181,-2)'
5309 **     ieee754(2, 0)            ->     2.0
5310 **     ieee754(181, -2)         ->     45.25
5311 **
5312 ** Two additional functions break apart the one-argument ieee754()
5313 ** result into separate integer values:
5314 **
5315 **     ieee754_mantissa(45.25)  ->     181
5316 **     ieee754_exponent(45.25)  ->     -2
5317 **
5318 ** These functions convert binary64 numbers into blobs and back again.
5319 **
5320 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5321 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5322 **
5323 ** In all single-argument functions, if the argument is an 8-byte blob
5324 ** then that blob is interpreted as a big-endian binary64 value.
5325 **
5326 **
5327 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5328 ** -----------------------------------------------
5329 **
5330 ** This extension in combination with the separate 'decimal' extension
5331 ** can be used to compute the exact decimal representation of binary64
5332 ** values.  To begin, first compute a table of exponent values:
5333 **
5334 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5335 **    WITH RECURSIVE c(x,v) AS (
5336 **      VALUES(0,'1')
5337 **      UNION ALL
5338 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5339 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5340 **    WITH RECURSIVE c(x,v) AS (
5341 **      VALUES(-1,'0.5')
5342 **      UNION ALL
5343 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5344 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5345 **
5346 ** Then, to compute the exact decimal representation of a floating
5347 ** point value (the value 47.49 is used in the example) do:
5348 **
5349 **    WITH c(n) AS (VALUES(47.49))
5350 **          ---------------^^^^^---- Replace with whatever you want
5351 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5352 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5353 **
5354 ** Here is a query to show various boundry values for the binary64
5355 ** number format:
5356 **
5357 **    WITH c(name,bin) AS (VALUES
5358 **       ('minimum positive value',        x'0000000000000001'),
5359 **       ('maximum subnormal value',       x'000fffffffffffff'),
5360 **       ('mininum positive nornal value', x'0010000000000000'),
5361 **       ('maximum value',                 x'7fefffffffffffff'))
5362 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5363 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5364 **
5365 */
5366 /* #include "sqlite3ext.h" */
5367 SQLITE_EXTENSION_INIT1
5368 #include <assert.h>
5369 #include <string.h>
5370 
5371 /* Mark a function parameter as unused, to suppress nuisance compiler
5372 ** warnings. */
5373 #ifndef UNUSED_PARAMETER
5374 # define UNUSED_PARAMETER(X)  (void)(X)
5375 #endif
5376 
5377 /*
5378 ** Implementation of the ieee754() function
5379 */
ieee754func(sqlite3_context * context,int argc,sqlite3_value ** argv)5380 static void ieee754func(
5381   sqlite3_context *context,
5382   int argc,
5383   sqlite3_value **argv
5384 ){
5385   if( argc==1 ){
5386     sqlite3_int64 m, a;
5387     double r;
5388     int e;
5389     int isNeg;
5390     char zResult[100];
5391     assert( sizeof(m)==sizeof(r) );
5392     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5393      && sqlite3_value_bytes(argv[0])==sizeof(r)
5394     ){
5395       const unsigned char *x = sqlite3_value_blob(argv[0]);
5396       unsigned int i;
5397       sqlite3_uint64 v = 0;
5398       for(i=0; i<sizeof(r); i++){
5399         v = (v<<8) | x[i];
5400       }
5401       memcpy(&r, &v, sizeof(r));
5402     }else{
5403       r = sqlite3_value_double(argv[0]);
5404     }
5405     if( r<0.0 ){
5406       isNeg = 1;
5407       r = -r;
5408     }else{
5409       isNeg = 0;
5410     }
5411     memcpy(&a,&r,sizeof(a));
5412     if( a==0 ){
5413       e = 0;
5414       m = 0;
5415     }else{
5416       e = a>>52;
5417       m = a & ((((sqlite3_int64)1)<<52)-1);
5418       if( e==0 ){
5419         m <<= 1;
5420       }else{
5421         m |= ((sqlite3_int64)1)<<52;
5422       }
5423       while( e<1075 && m>0 && (m&1)==0 ){
5424         m >>= 1;
5425         e++;
5426       }
5427       if( isNeg ) m = -m;
5428     }
5429     switch( *(int*)sqlite3_user_data(context) ){
5430       case 0:
5431         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5432                          m, e-1075);
5433         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5434         break;
5435       case 1:
5436         sqlite3_result_int64(context, m);
5437         break;
5438       case 2:
5439         sqlite3_result_int(context, e-1075);
5440         break;
5441     }
5442   }else{
5443     sqlite3_int64 m, e, a;
5444     double r;
5445     int isNeg = 0;
5446     m = sqlite3_value_int64(argv[0]);
5447     e = sqlite3_value_int64(argv[1]);
5448 
5449     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
5450     if( e>10000 ){
5451       e = 10000;
5452     }else if( e<-10000 ){
5453       e = -10000;
5454     }
5455 
5456     if( m<0 ){
5457       isNeg = 1;
5458       m = -m;
5459       if( m<0 ) return;
5460     }else if( m==0 && e>-1000 && e<1000 ){
5461       sqlite3_result_double(context, 0.0);
5462       return;
5463     }
5464     while( (m>>32)&0xffe00000 ){
5465       m >>= 1;
5466       e++;
5467     }
5468     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5469       m <<= 1;
5470       e--;
5471     }
5472     e += 1075;
5473     if( e<=0 ){
5474       /* Subnormal */
5475       if( 1-e >= 64 ){
5476         m = 0;
5477       }else{
5478         m >>= 1-e;
5479       }
5480       e = 0;
5481     }else if( e>0x7ff ){
5482       e = 0x7ff;
5483     }
5484     a = m & ((((sqlite3_int64)1)<<52)-1);
5485     a |= e<<52;
5486     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5487     memcpy(&r, &a, sizeof(r));
5488     sqlite3_result_double(context, r);
5489   }
5490 }
5491 
5492 /*
5493 ** Functions to convert between blobs and floats.
5494 */
ieee754func_from_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5495 static void ieee754func_from_blob(
5496   sqlite3_context *context,
5497   int argc,
5498   sqlite3_value **argv
5499 ){
5500   UNUSED_PARAMETER(argc);
5501   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5502    && sqlite3_value_bytes(argv[0])==sizeof(double)
5503   ){
5504     double r;
5505     const unsigned char *x = sqlite3_value_blob(argv[0]);
5506     unsigned int i;
5507     sqlite3_uint64 v = 0;
5508     for(i=0; i<sizeof(r); i++){
5509       v = (v<<8) | x[i];
5510     }
5511     memcpy(&r, &v, sizeof(r));
5512     sqlite3_result_double(context, r);
5513   }
5514 }
ieee754func_to_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5515 static void ieee754func_to_blob(
5516   sqlite3_context *context,
5517   int argc,
5518   sqlite3_value **argv
5519 ){
5520   UNUSED_PARAMETER(argc);
5521   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5522    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5523   ){
5524     double r = sqlite3_value_double(argv[0]);
5525     sqlite3_uint64 v;
5526     unsigned char a[sizeof(r)];
5527     unsigned int i;
5528     memcpy(&v, &r, sizeof(r));
5529     for(i=1; i<=sizeof(r); i++){
5530       a[sizeof(r)-i] = v&0xff;
5531       v >>= 8;
5532     }
5533     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5534   }
5535 }
5536 
5537 /*
5538 ** SQL Function:   ieee754_inc(r,N)
5539 **
5540 ** Move the floating point value r by N quantums and return the new
5541 ** values.
5542 **
5543 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
5544 ** integer, adds N, then casts the value back into float.
5545 **
5546 ** Example:  To find the smallest positive number:
5547 **
5548 **     SELECT ieee754_inc(0.0,+1);
5549 */
ieee754inc(sqlite3_context * context,int argc,sqlite3_value ** argv)5550 static void ieee754inc(
5551   sqlite3_context *context,
5552   int argc,
5553   sqlite3_value **argv
5554 ){
5555   double r;
5556   sqlite3_int64 N;
5557   sqlite3_uint64 m1, m2;
5558   double r2;
5559   UNUSED_PARAMETER(argc);
5560   r = sqlite3_value_double(argv[0]);
5561   N = sqlite3_value_int64(argv[1]);
5562   memcpy(&m1, &r, 8);
5563   m2 = m1 + N;
5564   memcpy(&r2, &m2, 8);
5565   sqlite3_result_double(context, r2);
5566 }
5567 
5568 
5569 #ifdef _WIN32
5570 
5571 #endif
sqlite3_ieee_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)5572 int sqlite3_ieee_init(
5573   sqlite3 *db,
5574   char **pzErrMsg,
5575   const sqlite3_api_routines *pApi
5576 ){
5577   static const struct {
5578     char *zFName;
5579     int nArg;
5580     int iAux;
5581     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5582   } aFunc[] = {
5583     { "ieee754",           1,   0, ieee754func },
5584     { "ieee754",           2,   0, ieee754func },
5585     { "ieee754_mantissa",  1,   1, ieee754func },
5586     { "ieee754_exponent",  1,   2, ieee754func },
5587     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5588     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5589     { "ieee754_inc",       2,   0, ieee754inc  },
5590   };
5591   unsigned int i;
5592   int rc = SQLITE_OK;
5593   SQLITE_EXTENSION_INIT2(pApi);
5594   (void)pzErrMsg;  /* Unused parameter */
5595   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5596     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
5597                                SQLITE_UTF8|SQLITE_INNOCUOUS,
5598                                (void*)&aFunc[i].iAux,
5599                                aFunc[i].xFunc, 0, 0);
5600   }
5601   return rc;
5602 }
5603 
5604 /************************* End ../ext/misc/ieee754.c ********************/
5605 /************************* Begin ../ext/misc/series.c ******************/
5606 /*
5607 ** 2015-08-18, 2023-04-28
5608 **
5609 ** The author disclaims copyright to this source code.  In place of
5610 ** a legal notice, here is a blessing:
5611 **
5612 **    May you do good and not evil.
5613 **    May you find forgiveness for yourself and forgive others.
5614 **    May you share freely, never taking more than you give.
5615 **
5616 *************************************************************************
5617 **
5618 ** This file demonstrates how to create a table-valued-function using
5619 ** a virtual table.  This demo implements the generate_series() function
5620 ** which gives the same results as the eponymous function in PostgreSQL,
5621 ** within the limitation that its arguments are signed 64-bit integers.
5622 **
5623 ** Considering its equivalents to generate_series(start,stop,step): A
5624 ** value V[n] sequence is produced for integer n ascending from 0 where
5625 **  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
5626 ** for each produced value (independent of production time ordering.)
5627 **
5628 ** All parameters must be either integer or convertable to integer.
5629 ** The start parameter is required.
5630 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
5631 ** The step parameter defaults to 1 and 0 is treated as 1.
5632 **
5633 ** Examples:
5634 **
5635 **      SELECT * FROM generate_series(0,100,5);
5636 **
5637 ** The query above returns integers from 0 through 100 counting by steps
5638 ** of 5.
5639 **
5640 **      SELECT * FROM generate_series(0,100);
5641 **
5642 ** Integers from 0 through 100 with a step size of 1.
5643 **
5644 **      SELECT * FROM generate_series(20) LIMIT 10;
5645 **
5646 ** Integers 20 through 29.
5647 **
5648 **      SELECT * FROM generate_series(0,-100,-5);
5649 **
5650 ** Integers 0 -5 -10 ... -100.
5651 **
5652 **      SELECT * FROM generate_series(0,-1);
5653 **
5654 ** Empty sequence.
5655 **
5656 ** HOW IT WORKS
5657 **
5658 ** The generate_series "function" is really a virtual table with the
5659 ** following schema:
5660 **
5661 **     CREATE TABLE generate_series(
5662 **       value,
5663 **       start HIDDEN,
5664 **       stop HIDDEN,
5665 **       step HIDDEN
5666 **     );
5667 **
5668 ** The virtual table also has a rowid, logically equivalent to n+1 where
5669 ** "n" is the ascending integer in the aforesaid production definition.
5670 **
5671 ** Function arguments in queries against this virtual table are translated
5672 ** into equality constraints against successive hidden columns.  In other
5673 ** words, the following pairs of queries are equivalent to each other:
5674 **
5675 **    SELECT * FROM generate_series(0,100,5);
5676 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5677 **
5678 **    SELECT * FROM generate_series(0,100);
5679 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5680 **
5681 **    SELECT * FROM generate_series(20) LIMIT 10;
5682 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5683 **
5684 ** The generate_series virtual table implementation leaves the xCreate method
5685 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5686 ** TABLE command with "generate_series" as the USING argument.  Instead, there
5687 ** is a single generate_series virtual table that is always available without
5688 ** having to be created first.
5689 **
5690 ** The xBestIndex method looks for equality constraints against the hidden
5691 ** start, stop, and step columns, and if present, it uses those constraints
5692 ** to bound the sequence of generated values.  If the equality constraints
5693 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5694 ** xBestIndex returns a small cost when both start and stop are available,
5695 ** and a very large cost if either start or stop are unavailable.  This
5696 ** encourages the query planner to order joins such that the bounds of the
5697 ** series are well-defined.
5698 */
5699 /* #include "sqlite3ext.h" */
5700 SQLITE_EXTENSION_INIT1
5701 #include <assert.h>
5702 #include <string.h>
5703 #include <limits.h>
5704 
5705 #ifndef SQLITE_OMIT_VIRTUALTABLE
5706 /*
5707 ** Return that member of a generate_series(...) sequence whose 0-based
5708 ** index is ix. The 0th member is given by smBase. The sequence members
5709 ** progress per ix increment by smStep.
5710 */
genSeqMember(sqlite3_int64 smBase,sqlite3_int64 smStep,sqlite3_uint64 ix)5711 static sqlite3_int64 genSeqMember(sqlite3_int64 smBase,
5712                                   sqlite3_int64 smStep,
5713                                   sqlite3_uint64 ix){
5714   if( ix>=(sqlite3_uint64)LLONG_MAX ){
5715     /* Get ix into signed i64 range. */
5716     ix -= (sqlite3_uint64)LLONG_MAX;
5717     /* With 2's complement ALU, this next can be 1 step, but is split into
5718      * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
5719     smBase += (LLONG_MAX/2) * smStep;
5720     smBase += (LLONG_MAX - LLONG_MAX/2) * smStep;
5721   }
5722   /* Under UBSAN (or on 1's complement machines), must do this last term
5723    * in steps to avoid the dreaded (and harmless) signed multiply overlow. */
5724   if( ix>=2 ){
5725     sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
5726     smBase += ix2*smStep;
5727     ix -= ix2;
5728   }
5729   return smBase + ((sqlite3_int64)ix)*smStep;
5730 }
5731 
5732 /* typedef unsigned char u8; */
5733 
5734 typedef struct SequenceSpec {
5735   sqlite3_int64 iBase;         /* Starting value ("start") */
5736   sqlite3_int64 iTerm;         /* Given terminal value ("stop") */
5737   sqlite3_int64 iStep;         /* Increment ("step") */
5738   sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
5739   sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
5740   sqlite3_int64 iValueNow;     /* Current value during generation */
5741   u8 isNotEOF;                 /* Sequence generation not exhausted */
5742   u8 isReversing;              /* Sequence is being reverse generated */
5743 } SequenceSpec;
5744 
5745 /*
5746 ** Prepare a SequenceSpec for use in generating an integer series
5747 ** given initialized iBase, iTerm and iStep values. Sequence is
5748 ** initialized per given isReversing. Other members are computed.
5749 */
setupSequence(SequenceSpec * pss)5750 static void setupSequence( SequenceSpec *pss ){
5751   int bSameSigns;
5752   pss->uSeqIndexMax = 0;
5753   pss->isNotEOF = 0;
5754   bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
5755   if( pss->iTerm < pss->iBase ){
5756     sqlite3_uint64 nuspan = 0;
5757     if( bSameSigns ){
5758       nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
5759     }else{
5760       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5761        * In this clause, iBase>=0 and iTerm<0 . */
5762       nuspan = 1;
5763       nuspan += pss->iBase;
5764       nuspan += -(pss->iTerm+1);
5765     }
5766     if( pss->iStep<0 ){
5767       pss->isNotEOF = 1;
5768       if( nuspan==ULONG_MAX ){
5769         pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
5770       }else if( pss->iStep>LLONG_MIN ){
5771         pss->uSeqIndexMax = nuspan/-pss->iStep;
5772       }
5773     }
5774   }else if( pss->iTerm > pss->iBase ){
5775     sqlite3_uint64 puspan = 0;
5776     if( bSameSigns ){
5777       puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
5778     }else{
5779       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5780        * In this clause, iTerm>=0 and iBase<0 . */
5781       puspan = 1;
5782       puspan += pss->iTerm;
5783       puspan += -(pss->iBase+1);
5784     }
5785     if( pss->iStep>0 ){
5786       pss->isNotEOF = 1;
5787       pss->uSeqIndexMax = puspan/pss->iStep;
5788     }
5789   }else if( pss->iTerm == pss->iBase ){
5790       pss->isNotEOF = 1;
5791       pss->uSeqIndexMax = 0;
5792   }
5793   pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
5794   pss->iValueNow = (pss->isReversing)
5795     ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
5796     : pss->iBase;
5797 }
5798 
5799 /*
5800 ** Progress sequence generator to yield next value, if any.
5801 ** Leave its state to either yield next value or be at EOF.
5802 ** Return whether there is a next value, or 0 at EOF.
5803 */
progressSequence(SequenceSpec * pss)5804 static int progressSequence( SequenceSpec *pss ){
5805   if( !pss->isNotEOF ) return 0;
5806   if( pss->isReversing ){
5807     if( pss->uSeqIndexNow > 0 ){
5808       pss->uSeqIndexNow--;
5809       pss->iValueNow -= pss->iStep;
5810     }else{
5811       pss->isNotEOF = 0;
5812     }
5813   }else{
5814     if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
5815       pss->uSeqIndexNow++;
5816       pss->iValueNow += pss->iStep;
5817     }else{
5818       pss->isNotEOF = 0;
5819     }
5820   }
5821   return pss->isNotEOF;
5822 }
5823 
5824 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
5825 ** serve as the underlying representation of a cursor that scans
5826 ** over rows of the result
5827 */
5828 typedef struct series_cursor series_cursor;
5829 struct series_cursor {
5830   sqlite3_vtab_cursor base;  /* Base class - must be first */
5831   SequenceSpec ss;           /* (this) Derived class data */
5832 };
5833 
5834 /*
5835 ** The seriesConnect() method is invoked to create a new
5836 ** series_vtab that describes the generate_series virtual table.
5837 **
5838 ** Think of this routine as the constructor for series_vtab objects.
5839 **
5840 ** All this routine needs to do is:
5841 **
5842 **    (1) Allocate the series_vtab object and initialize all fields.
5843 **
5844 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5845 **        result set of queries against generate_series will look like.
5846 */
seriesConnect(sqlite3 * db,void * pUnused,int argcUnused,const char * const * argvUnused,sqlite3_vtab ** ppVtab,char ** pzErrUnused)5847 static int seriesConnect(
5848   sqlite3 *db,
5849   void *pUnused,
5850   int argcUnused, const char *const*argvUnused,
5851   sqlite3_vtab **ppVtab,
5852   char **pzErrUnused
5853 ){
5854   sqlite3_vtab *pNew;
5855   int rc;
5856 
5857 /* Column numbers */
5858 #define SERIES_COLUMN_VALUE 0
5859 #define SERIES_COLUMN_START 1
5860 #define SERIES_COLUMN_STOP  2
5861 #define SERIES_COLUMN_STEP  3
5862 
5863   (void)pUnused;
5864   (void)argcUnused;
5865   (void)argvUnused;
5866   (void)pzErrUnused;
5867   rc = sqlite3_declare_vtab(db,
5868      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5869   if( rc==SQLITE_OK ){
5870     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5871     if( pNew==0 ) return SQLITE_NOMEM;
5872     memset(pNew, 0, sizeof(*pNew));
5873     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5874   }
5875   return rc;
5876 }
5877 
5878 /*
5879 ** This method is the destructor for series_cursor objects.
5880 */
seriesDisconnect(sqlite3_vtab * pVtab)5881 static int seriesDisconnect(sqlite3_vtab *pVtab){
5882   sqlite3_free(pVtab);
5883   return SQLITE_OK;
5884 }
5885 
5886 /*
5887 ** Constructor for a new series_cursor object.
5888 */
seriesOpen(sqlite3_vtab * pUnused,sqlite3_vtab_cursor ** ppCursor)5889 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5890   series_cursor *pCur;
5891   (void)pUnused;
5892   pCur = sqlite3_malloc( sizeof(*pCur) );
5893   if( pCur==0 ) return SQLITE_NOMEM;
5894   memset(pCur, 0, sizeof(*pCur));
5895   *ppCursor = &pCur->base;
5896   return SQLITE_OK;
5897 }
5898 
5899 /*
5900 ** Destructor for a series_cursor.
5901 */
seriesClose(sqlite3_vtab_cursor * cur)5902 static int seriesClose(sqlite3_vtab_cursor *cur){
5903   sqlite3_free(cur);
5904   return SQLITE_OK;
5905 }
5906 
5907 
5908 /*
5909 ** Advance a series_cursor to its next row of output.
5910 */
seriesNext(sqlite3_vtab_cursor * cur)5911 static int seriesNext(sqlite3_vtab_cursor *cur){
5912   series_cursor *pCur = (series_cursor*)cur;
5913   progressSequence( & pCur->ss );
5914   return SQLITE_OK;
5915 }
5916 
5917 /*
5918 ** Return values of columns for the row at which the series_cursor
5919 ** is currently pointing.
5920 */
seriesColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)5921 static int seriesColumn(
5922   sqlite3_vtab_cursor *cur,   /* The cursor */
5923   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5924   int i                       /* Which column to return */
5925 ){
5926   series_cursor *pCur = (series_cursor*)cur;
5927   sqlite3_int64 x = 0;
5928   switch( i ){
5929     case SERIES_COLUMN_START:  x = pCur->ss.iBase; break;
5930     case SERIES_COLUMN_STOP:   x = pCur->ss.iTerm; break;
5931     case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;   break;
5932     default:                   x = pCur->ss.iValueNow;  break;
5933   }
5934   sqlite3_result_int64(ctx, x);
5935   return SQLITE_OK;
5936 }
5937 
5938 #ifndef LARGEST_UINT64
5939 #define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32))
5940 #endif
5941 
5942 /*
5943 ** Return the rowid for the current row, logically equivalent to n+1 where
5944 ** "n" is the ascending integer in the aforesaid production definition.
5945 */
seriesRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)5946 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5947   series_cursor *pCur = (series_cursor*)cur;
5948   sqlite3_uint64 n = pCur->ss.uSeqIndexNow;
5949   *pRowid = (sqlite3_int64)((n<LARGEST_UINT64)? n+1 : 0);
5950   return SQLITE_OK;
5951 }
5952 
5953 /*
5954 ** Return TRUE if the cursor has been moved off of the last
5955 ** row of output.
5956 */
seriesEof(sqlite3_vtab_cursor * cur)5957 static int seriesEof(sqlite3_vtab_cursor *cur){
5958   series_cursor *pCur = (series_cursor*)cur;
5959   return !pCur->ss.isNotEOF;
5960 }
5961 
5962 /* True to cause run-time checking of the start=, stop=, and/or step=
5963 ** parameters.  The only reason to do this is for testing the
5964 ** constraint checking logic for virtual tables in the SQLite core.
5965 */
5966 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5967 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5968 #endif
5969 
5970 /*
5971 ** This method is called to "rewind" the series_cursor object back
5972 ** to the first row of output.  This method is always called at least
5973 ** once prior to any call to seriesColumn() or seriesRowid() or
5974 ** seriesEof().
5975 **
5976 ** The query plan selected by seriesBestIndex is passed in the idxNum
5977 ** parameter.  (idxStr is not used in this implementation.)  idxNum
5978 ** is a bitmask showing which constraints are available:
5979 **
5980 **    1:    start=VALUE
5981 **    2:    stop=VALUE
5982 **    4:    step=VALUE
5983 **
5984 ** Also, if bit 8 is set, that means that the series should be output
5985 ** in descending order rather than in ascending order.  If bit 16 is
5986 ** set, then output must appear in ascending order.
5987 **
5988 ** This routine should initialize the cursor and position it so that it
5989 ** is pointing at the first row, or pointing off the end of the table
5990 ** (so that seriesEof() will return true) if the table is empty.
5991 */
seriesFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStrUnused,int argc,sqlite3_value ** argv)5992 static int seriesFilter(
5993   sqlite3_vtab_cursor *pVtabCursor,
5994   int idxNum, const char *idxStrUnused,
5995   int argc, sqlite3_value **argv
5996 ){
5997   series_cursor *pCur = (series_cursor *)pVtabCursor;
5998   int i = 0;
5999   (void)idxStrUnused;
6000   if( idxNum & 1 ){
6001     pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
6002   }else{
6003     pCur->ss.iBase = 0;
6004   }
6005   if( idxNum & 2 ){
6006     pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
6007   }else{
6008     pCur->ss.iTerm = 0xffffffff;
6009   }
6010   if( idxNum & 4 ){
6011     pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
6012     if( pCur->ss.iStep==0 ){
6013       pCur->ss.iStep = 1;
6014     }else if( pCur->ss.iStep<0 ){
6015       if( (idxNum & 16)==0 ) idxNum |= 8;
6016     }
6017   }else{
6018     pCur->ss.iStep = 1;
6019   }
6020   for(i=0; i<argc; i++){
6021     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
6022       /* If any of the constraints have a NULL value, then return no rows.
6023       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
6024       pCur->ss.iBase = 1;
6025       pCur->ss.iTerm = 0;
6026       pCur->ss.iStep = 1;
6027       break;
6028     }
6029   }
6030   if( idxNum & 8 ){
6031     pCur->ss.isReversing = pCur->ss.iStep > 0;
6032   }else{
6033     pCur->ss.isReversing = pCur->ss.iStep < 0;
6034   }
6035   setupSequence( &pCur->ss );
6036   return SQLITE_OK;
6037 }
6038 
6039 /*
6040 ** SQLite will invoke this method one or more times while planning a query
6041 ** that uses the generate_series virtual table.  This routine needs to create
6042 ** a query plan for each invocation and compute an estimated cost for that
6043 ** plan.
6044 **
6045 ** In this implementation idxNum is used to represent the
6046 ** query plan.  idxStr is unused.
6047 **
6048 ** The query plan is represented by bits in idxNum:
6049 **
6050 **  (1)  start = $value  -- constraint exists
6051 **  (2)  stop = $value   -- constraint exists
6052 **  (4)  step = $value   -- constraint exists
6053 **  (8)  output in descending order
6054 */
seriesBestIndex(sqlite3_vtab * pVTab,sqlite3_index_info * pIdxInfo)6055 static int seriesBestIndex(
6056   sqlite3_vtab *pVTab,
6057   sqlite3_index_info *pIdxInfo
6058 ){
6059   int i, j;              /* Loop over constraints */
6060   int idxNum = 0;        /* The query plan bitmask */
6061   int bStartSeen = 0;    /* EQ constraint seen on the START column */
6062   int unusableMask = 0;  /* Mask of unusable constraints */
6063   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
6064   int aIdx[3];           /* Constraints on start, stop, and step */
6065   const struct sqlite3_index_constraint *pConstraint;
6066 
6067   /* This implementation assumes that the start, stop, and step columns
6068   ** are the last three columns in the virtual table. */
6069   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
6070   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
6071 
6072   aIdx[0] = aIdx[1] = aIdx[2] = -1;
6073   pConstraint = pIdxInfo->aConstraint;
6074   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6075     int iCol;    /* 0 for start, 1 for stop, 2 for step */
6076     int iMask;   /* bitmask for those column */
6077     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
6078     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
6079     assert( iCol>=0 && iCol<=2 );
6080     iMask = 1 << iCol;
6081     if( iCol==0 ) bStartSeen = 1;
6082     if( pConstraint->usable==0 ){
6083       unusableMask |=  iMask;
6084       continue;
6085     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
6086       idxNum |= iMask;
6087       aIdx[iCol] = i;
6088     }
6089   }
6090   for(i=0; i<3; i++){
6091     if( (j = aIdx[i])>=0 ){
6092       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
6093       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
6094     }
6095   }
6096   /* The current generate_column() implementation requires at least one
6097   ** argument (the START value).  Legacy versions assumed START=0 if the
6098   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
6099   ** to obtain the legacy behavior */
6100 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6101   if( !bStartSeen ){
6102     sqlite3_free(pVTab->zErrMsg);
6103     pVTab->zErrMsg = sqlite3_mprintf(
6104         "first argument to \"generate_series()\" missing or unusable");
6105     return SQLITE_ERROR;
6106   }
6107 #endif
6108   if( (unusableMask & ~idxNum)!=0 ){
6109     /* The start, stop, and step columns are inputs.  Therefore if there
6110     ** are unusable constraints on any of start, stop, or step then
6111     ** this plan is unusable */
6112     return SQLITE_CONSTRAINT;
6113   }
6114   if( (idxNum & 3)==3 ){
6115     /* Both start= and stop= boundaries are available.  This is the
6116     ** the preferred case */
6117     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
6118     pIdxInfo->estimatedRows = 1000;
6119     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
6120       if( pIdxInfo->aOrderBy[0].desc ){
6121         idxNum |= 8;
6122       }else{
6123         idxNum |= 16;
6124       }
6125       pIdxInfo->orderByConsumed = 1;
6126     }
6127   }else{
6128     /* If either boundary is missing, we have to generate a huge span
6129     ** of numbers.  Make this case very expensive so that the query
6130     ** planner will work hard to avoid it. */
6131     pIdxInfo->estimatedRows = 2147483647;
6132   }
6133   pIdxInfo->idxNum = idxNum;
6134   return SQLITE_OK;
6135 }
6136 
6137 /*
6138 ** This following structure defines all the methods for the
6139 ** generate_series virtual table.
6140 */
6141 static sqlite3_module seriesModule = {
6142   0,                         /* iVersion */
6143   0,                         /* xCreate */
6144   seriesConnect,             /* xConnect */
6145   seriesBestIndex,           /* xBestIndex */
6146   seriesDisconnect,          /* xDisconnect */
6147   0,                         /* xDestroy */
6148   seriesOpen,                /* xOpen - open a cursor */
6149   seriesClose,               /* xClose - close a cursor */
6150   seriesFilter,              /* xFilter - configure scan constraints */
6151   seriesNext,                /* xNext - advance a cursor */
6152   seriesEof,                 /* xEof - check for end of scan */
6153   seriesColumn,              /* xColumn - read data */
6154   seriesRowid,               /* xRowid - read data */
6155   0,                         /* xUpdate */
6156   0,                         /* xBegin */
6157   0,                         /* xSync */
6158   0,                         /* xCommit */
6159   0,                         /* xRollback */
6160   0,                         /* xFindMethod */
6161   0,                         /* xRename */
6162   0,                         /* xSavepoint */
6163   0,                         /* xRelease */
6164   0,                         /* xRollbackTo */
6165   0,                         /* xShadowName */
6166   0                          /* xIntegrity */
6167 };
6168 
6169 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6170 
6171 #ifdef _WIN32
6172 
6173 #endif
sqlite3_series_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)6174 int sqlite3_series_init(
6175   sqlite3 *db,
6176   char **pzErrMsg,
6177   const sqlite3_api_routines *pApi
6178 ){
6179   int rc = SQLITE_OK;
6180   SQLITE_EXTENSION_INIT2(pApi);
6181 #ifndef SQLITE_OMIT_VIRTUALTABLE
6182   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
6183     *pzErrMsg = sqlite3_mprintf(
6184         "generate_series() requires SQLite 3.8.12 or later");
6185     return SQLITE_ERROR;
6186   }
6187   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
6188 #endif
6189   return rc;
6190 }
6191 
6192 /************************* End ../ext/misc/series.c ********************/
6193 /************************* Begin ../ext/misc/regexp.c ******************/
6194 /*
6195 ** 2012-11-13
6196 **
6197 ** The author disclaims copyright to this source code.  In place of
6198 ** a legal notice, here is a blessing:
6199 **
6200 **    May you do good and not evil.
6201 **    May you find forgiveness for yourself and forgive others.
6202 **    May you share freely, never taking more than you give.
6203 **
6204 ******************************************************************************
6205 **
6206 ** The code in this file implements a compact but reasonably
6207 ** efficient regular-expression matcher for posix extended regular
6208 ** expressions against UTF8 text.
6209 **
6210 ** This file is an SQLite extension.  It registers a single function
6211 ** named "regexp(A,B)" where A is the regular expression and B is the
6212 ** string to be matched.  By registering this function, SQLite will also
6213 ** then implement the "B regexp A" operator.  Note that with the function
6214 ** the regular expression comes first, but with the operator it comes
6215 ** second.
6216 **
6217 **  The following regular expression syntax is supported:
6218 **
6219 **     X*      zero or more occurrences of X
6220 **     X+      one or more occurrences of X
6221 **     X?      zero or one occurrences of X
6222 **     X{p,q}  between p and q occurrences of X
6223 **     (X)     match X
6224 **     X|Y     X or Y
6225 **     ^X      X occurring at the beginning of the string
6226 **     X$      X occurring at the end of the string
6227 **     .       Match any single character
6228 **     \c      Character c where c is one of \{}()[]|*+?.
6229 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
6230 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
6231 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
6232 **     [abc]   Any single character from the set abc
6233 **     [^abc]  Any single character not in the set abc
6234 **     [a-z]   Any single character in the range a-z
6235 **     [^a-z]  Any single character not in the range a-z
6236 **     \b      Word boundary
6237 **     \w      Word character.  [A-Za-z0-9_]
6238 **     \W      Non-word character
6239 **     \d      Digit
6240 **     \D      Non-digit
6241 **     \s      Whitespace character
6242 **     \S      Non-whitespace character
6243 **
6244 ** A nondeterministic finite automaton (NFA) is used for matching, so the
6245 ** performance is bounded by O(N*M) where N is the size of the regular
6246 ** expression and M is the size of the input string.  The matcher never
6247 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
6248 ** to p copies of X following by q-p copies of X? and that the size of the
6249 ** regular expression in the O(N*M) performance bound is computed after
6250 ** this expansion.
6251 */
6252 #include <string.h>
6253 #include <stdlib.h>
6254 /* #include "sqlite3ext.h" */
6255 SQLITE_EXTENSION_INIT1
6256 
6257 /*
6258 ** The following #defines change the names of some functions implemented in
6259 ** this file to prevent name collisions with C-library functions of the
6260 ** same name.
6261 */
6262 #define re_match   sqlite3re_match
6263 #define re_compile sqlite3re_compile
6264 #define re_free    sqlite3re_free
6265 
6266 /* The end-of-input character */
6267 #define RE_EOF            0    /* End of input */
6268 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
6269 
6270 /* The NFA is implemented as sequence of opcodes taken from the following
6271 ** set.  Each opcode has a single integer argument.
6272 */
6273 #define RE_OP_MATCH       1    /* Match the one character in the argument */
6274 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
6275 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
6276 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
6277 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
6278 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
6279 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
6280 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
6281 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
6282 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
6283 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
6284 #define RE_OP_NOTWORD    12    /* Not a perl word character */
6285 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
6286 #define RE_OP_NOTDIGIT   14    /* Not a digit */
6287 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
6288 #define RE_OP_NOTSPACE   16    /* Not a digit */
6289 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
6290 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
6291 
6292 #if defined(SQLITE_DEBUG)
6293 /* Opcode names used for symbolic debugging */
6294 static const char *ReOpName[] = {
6295   "EOF",
6296   "MATCH",
6297   "ANY",
6298   "ANYSTAR",
6299   "FORK",
6300   "GOTO",
6301   "ACCEPT",
6302   "CC_INC",
6303   "CC_EXC",
6304   "CC_VALUE",
6305   "CC_RANGE",
6306   "WORD",
6307   "NOTWORD",
6308   "DIGIT",
6309   "NOTDIGIT",
6310   "SPACE",
6311   "NOTSPACE",
6312   "BOUNDARY",
6313   "ATSTART",
6314 };
6315 #endif /* SQLITE_DEBUG */
6316 
6317 
6318 /* Each opcode is a "state" in the NFA */
6319 typedef unsigned short ReStateNumber;
6320 
6321 /* Because this is an NFA and not a DFA, multiple states can be active at
6322 ** once.  An instance of the following object records all active states in
6323 ** the NFA.  The implementation is optimized for the common case where the
6324 ** number of actives states is small.
6325 */
6326 typedef struct ReStateSet {
6327   unsigned nState;            /* Number of current states */
6328   ReStateNumber *aState;      /* Current states */
6329 } ReStateSet;
6330 
6331 /* An input string read one character at a time.
6332 */
6333 typedef struct ReInput ReInput;
6334 struct ReInput {
6335   const unsigned char *z;  /* All text */
6336   int i;                   /* Next byte to read */
6337   int mx;                  /* EOF when i>=mx */
6338 };
6339 
6340 /* A compiled NFA (or an NFA that is in the process of being compiled) is
6341 ** an instance of the following object.
6342 */
6343 typedef struct ReCompiled ReCompiled;
6344 struct ReCompiled {
6345   ReInput sIn;                /* Regular expression text */
6346   const char *zErr;           /* Error message to return */
6347   char *aOp;                  /* Operators for the virtual machine */
6348   int *aArg;                  /* Arguments to each operator */
6349   unsigned (*xNextChar)(ReInput*);  /* Next character function */
6350   unsigned char zInit[12];    /* Initial text to match */
6351   int nInit;                  /* Number of bytes in zInit */
6352   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
6353   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
6354 };
6355 
6356 /* Add a state to the given state set if it is not already there */
re_add_state(ReStateSet * pSet,int newState)6357 static void re_add_state(ReStateSet *pSet, int newState){
6358   unsigned i;
6359   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
6360   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
6361 }
6362 
6363 /* Extract the next unicode character from *pzIn and return it.  Advance
6364 ** *pzIn to the first byte past the end of the character returned.  To
6365 ** be clear:  this routine converts utf8 to unicode.  This routine is
6366 ** optimized for the common case where the next character is a single byte.
6367 */
re_next_char(ReInput * p)6368 static unsigned re_next_char(ReInput *p){
6369   unsigned c;
6370   if( p->i>=p->mx ) return 0;
6371   c = p->z[p->i++];
6372   if( c>=0x80 ){
6373     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
6374       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
6375       if( c<0x80 ) c = 0xfffd;
6376     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
6377            && (p->z[p->i+1]&0xc0)==0x80 ){
6378       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
6379       p->i += 2;
6380       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
6381     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
6382            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
6383       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
6384                        | (p->z[p->i+2]&0x3f);
6385       p->i += 3;
6386       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
6387     }else{
6388       c = 0xfffd;
6389     }
6390   }
6391   return c;
6392 }
re_next_char_nocase(ReInput * p)6393 static unsigned re_next_char_nocase(ReInput *p){
6394   unsigned c = re_next_char(p);
6395   if( c>='A' && c<='Z' ) c += 'a' - 'A';
6396   return c;
6397 }
6398 
6399 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
re_word_char(int c)6400 static int re_word_char(int c){
6401   return (c>='0' && c<='9') || (c>='a' && c<='z')
6402       || (c>='A' && c<='Z') || c=='_';
6403 }
6404 
6405 /* Return true if c is a "digit" character:  [0-9] */
re_digit_char(int c)6406 static int re_digit_char(int c){
6407   return (c>='0' && c<='9');
6408 }
6409 
6410 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
re_space_char(int c)6411 static int re_space_char(int c){
6412   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
6413 }
6414 
6415 /* Run a compiled regular expression on the zero-terminated input
6416 ** string zIn[].  Return true on a match and false if there is no match.
6417 */
re_match(ReCompiled * pRe,const unsigned char * zIn,int nIn)6418 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
6419   ReStateSet aStateSet[2], *pThis, *pNext;
6420   ReStateNumber aSpace[100];
6421   ReStateNumber *pToFree;
6422   unsigned int i = 0;
6423   unsigned int iSwap = 0;
6424   int c = RE_START;
6425   int cPrev = 0;
6426   int rc = 0;
6427   ReInput in;
6428 
6429   in.z = zIn;
6430   in.i = 0;
6431   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
6432 
6433   /* Look for the initial prefix match, if there is one. */
6434   if( pRe->nInit ){
6435     unsigned char x = pRe->zInit[0];
6436     while( in.i+pRe->nInit<=in.mx
6437      && (zIn[in.i]!=x ||
6438          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
6439     ){
6440       in.i++;
6441     }
6442     if( in.i+pRe->nInit>in.mx ) return 0;
6443     c = RE_START-1;
6444   }
6445 
6446   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
6447     pToFree = 0;
6448     aStateSet[0].aState = aSpace;
6449   }else{
6450     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
6451     if( pToFree==0 ) return -1;
6452     aStateSet[0].aState = pToFree;
6453   }
6454   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
6455   pNext = &aStateSet[1];
6456   pNext->nState = 0;
6457   re_add_state(pNext, 0);
6458   while( c!=RE_EOF && pNext->nState>0 ){
6459     cPrev = c;
6460     c = pRe->xNextChar(&in);
6461     pThis = pNext;
6462     pNext = &aStateSet[iSwap];
6463     iSwap = 1 - iSwap;
6464     pNext->nState = 0;
6465     for(i=0; i<pThis->nState; i++){
6466       int x = pThis->aState[i];
6467       switch( pRe->aOp[x] ){
6468         case RE_OP_MATCH: {
6469           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
6470           break;
6471         }
6472         case RE_OP_ATSTART: {
6473           if( cPrev==RE_START ) re_add_state(pThis, x+1);
6474           break;
6475         }
6476         case RE_OP_ANY: {
6477           if( c!=0 ) re_add_state(pNext, x+1);
6478           break;
6479         }
6480         case RE_OP_WORD: {
6481           if( re_word_char(c) ) re_add_state(pNext, x+1);
6482           break;
6483         }
6484         case RE_OP_NOTWORD: {
6485           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
6486           break;
6487         }
6488         case RE_OP_DIGIT: {
6489           if( re_digit_char(c) ) re_add_state(pNext, x+1);
6490           break;
6491         }
6492         case RE_OP_NOTDIGIT: {
6493           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
6494           break;
6495         }
6496         case RE_OP_SPACE: {
6497           if( re_space_char(c) ) re_add_state(pNext, x+1);
6498           break;
6499         }
6500         case RE_OP_NOTSPACE: {
6501           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
6502           break;
6503         }
6504         case RE_OP_BOUNDARY: {
6505           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
6506           break;
6507         }
6508         case RE_OP_ANYSTAR: {
6509           re_add_state(pNext, x);
6510           re_add_state(pThis, x+1);
6511           break;
6512         }
6513         case RE_OP_FORK: {
6514           re_add_state(pThis, x+pRe->aArg[x]);
6515           re_add_state(pThis, x+1);
6516           break;
6517         }
6518         case RE_OP_GOTO: {
6519           re_add_state(pThis, x+pRe->aArg[x]);
6520           break;
6521         }
6522         case RE_OP_ACCEPT: {
6523           rc = 1;
6524           goto re_match_end;
6525         }
6526         case RE_OP_CC_EXC: {
6527           if( c==0 ) break;
6528           /* fall-through */ goto re_op_cc_inc;
6529         }
6530         case RE_OP_CC_INC: re_op_cc_inc: {
6531           int j = 1;
6532           int n = pRe->aArg[x];
6533           int hit = 0;
6534           for(j=1; j>0 && j<n; j++){
6535             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
6536               if( pRe->aArg[x+j]==c ){
6537                 hit = 1;
6538                 j = -1;
6539               }
6540             }else{
6541               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
6542                 hit = 1;
6543                 j = -1;
6544               }else{
6545                 j++;
6546               }
6547             }
6548           }
6549           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
6550           if( hit ) re_add_state(pNext, x+n);
6551           break;
6552         }
6553       }
6554     }
6555   }
6556   for(i=0; i<pNext->nState; i++){
6557     int x = pNext->aState[i];
6558     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
6559     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
6560   }
6561 re_match_end:
6562   sqlite3_free(pToFree);
6563   return rc;
6564 }
6565 
6566 /* Resize the opcode and argument arrays for an RE under construction.
6567 */
re_resize(ReCompiled * p,int N)6568 static int re_resize(ReCompiled *p, int N){
6569   char *aOp;
6570   int *aArg;
6571   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
6572   if( aOp==0 ) return 1;
6573   p->aOp = aOp;
6574   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
6575   if( aArg==0 ) return 1;
6576   p->aArg = aArg;
6577   p->nAlloc = N;
6578   return 0;
6579 }
6580 
6581 /* Insert a new opcode and argument into an RE under construction.  The
6582 ** insertion point is just prior to existing opcode iBefore.
6583 */
re_insert(ReCompiled * p,int iBefore,int op,int arg)6584 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
6585   int i;
6586   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
6587   for(i=p->nState; i>iBefore; i--){
6588     p->aOp[i] = p->aOp[i-1];
6589     p->aArg[i] = p->aArg[i-1];
6590   }
6591   p->nState++;
6592   p->aOp[iBefore] = (char)op;
6593   p->aArg[iBefore] = arg;
6594   return iBefore;
6595 }
6596 
6597 /* Append a new opcode and argument to the end of the RE under construction.
6598 */
re_append(ReCompiled * p,int op,int arg)6599 static int re_append(ReCompiled *p, int op, int arg){
6600   return re_insert(p, p->nState, op, arg);
6601 }
6602 
6603 /* Make a copy of N opcodes starting at iStart onto the end of the RE
6604 ** under construction.
6605 */
re_copy(ReCompiled * p,int iStart,int N)6606 static void re_copy(ReCompiled *p, int iStart, int N){
6607   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
6608   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
6609   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
6610   p->nState += N;
6611 }
6612 
6613 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
6614 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
6615 ** c is not a hex digit *pV is unchanged.
6616 */
re_hex(int c,int * pV)6617 static int re_hex(int c, int *pV){
6618   if( c>='0' && c<='9' ){
6619     c -= '0';
6620   }else if( c>='a' && c<='f' ){
6621     c -= 'a' - 10;
6622   }else if( c>='A' && c<='F' ){
6623     c -= 'A' - 10;
6624   }else{
6625     return 0;
6626   }
6627   *pV = (*pV)*16 + (c & 0xff);
6628   return 1;
6629 }
6630 
6631 /* A backslash character has been seen, read the next character and
6632 ** return its interpretation.
6633 */
re_esc_char(ReCompiled * p)6634 static unsigned re_esc_char(ReCompiled *p){
6635   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
6636   static const char zTrans[] = "\a\f\n\r\t\v";
6637   int i, v = 0;
6638   char c;
6639   if( p->sIn.i>=p->sIn.mx ) return 0;
6640   c = p->sIn.z[p->sIn.i];
6641   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
6642     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6643     if( re_hex(zIn[1],&v)
6644      && re_hex(zIn[2],&v)
6645      && re_hex(zIn[3],&v)
6646      && re_hex(zIn[4],&v)
6647     ){
6648       p->sIn.i += 5;
6649       return v;
6650     }
6651   }
6652   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
6653     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6654     if( re_hex(zIn[1],&v)
6655      && re_hex(zIn[2],&v)
6656     ){
6657       p->sIn.i += 3;
6658       return v;
6659     }
6660   }
6661   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
6662   if( zEsc[i] ){
6663     if( i<6 ) c = zTrans[i];
6664     p->sIn.i++;
6665   }else{
6666     p->zErr = "unknown \\ escape";
6667   }
6668   return c;
6669 }
6670 
6671 /* Forward declaration */
6672 static const char *re_subcompile_string(ReCompiled*);
6673 
6674 /* Peek at the next byte of input */
rePeek(ReCompiled * p)6675 static unsigned char rePeek(ReCompiled *p){
6676   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
6677 }
6678 
6679 /* Compile RE text into a sequence of opcodes.  Continue up to the
6680 ** first unmatched ")" character, then return.  If an error is found,
6681 ** return a pointer to the error message string.
6682 */
re_subcompile_re(ReCompiled * p)6683 static const char *re_subcompile_re(ReCompiled *p){
6684   const char *zErr;
6685   int iStart, iEnd, iGoto;
6686   iStart = p->nState;
6687   zErr = re_subcompile_string(p);
6688   if( zErr ) return zErr;
6689   while( rePeek(p)=='|' ){
6690     iEnd = p->nState;
6691     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
6692     iGoto = re_append(p, RE_OP_GOTO, 0);
6693     p->sIn.i++;
6694     zErr = re_subcompile_string(p);
6695     if( zErr ) return zErr;
6696     p->aArg[iGoto] = p->nState - iGoto;
6697   }
6698   return 0;
6699 }
6700 
6701 /* Compile an element of regular expression text (anything that can be
6702 ** an operand to the "|" operator).  Return NULL on success or a pointer
6703 ** to the error message if there is a problem.
6704 */
re_subcompile_string(ReCompiled * p)6705 static const char *re_subcompile_string(ReCompiled *p){
6706   int iPrev = -1;
6707   int iStart;
6708   unsigned c;
6709   const char *zErr;
6710   while( (c = p->xNextChar(&p->sIn))!=0 ){
6711     iStart = p->nState;
6712     switch( c ){
6713       case '|':
6714       case ')': {
6715         p->sIn.i--;
6716         return 0;
6717       }
6718       case '(': {
6719         zErr = re_subcompile_re(p);
6720         if( zErr ) return zErr;
6721         if( rePeek(p)!=')' ) return "unmatched '('";
6722         p->sIn.i++;
6723         break;
6724       }
6725       case '.': {
6726         if( rePeek(p)=='*' ){
6727           re_append(p, RE_OP_ANYSTAR, 0);
6728           p->sIn.i++;
6729         }else{
6730           re_append(p, RE_OP_ANY, 0);
6731         }
6732         break;
6733       }
6734       case '*': {
6735         if( iPrev<0 ) return "'*' without operand";
6736         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
6737         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
6738         break;
6739       }
6740       case '+': {
6741         if( iPrev<0 ) return "'+' without operand";
6742         re_append(p, RE_OP_FORK, iPrev - p->nState);
6743         break;
6744       }
6745       case '?': {
6746         if( iPrev<0 ) return "'?' without operand";
6747         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
6748         break;
6749       }
6750       case '$': {
6751         re_append(p, RE_OP_MATCH, RE_EOF);
6752         break;
6753       }
6754       case '^': {
6755         re_append(p, RE_OP_ATSTART, 0);
6756         break;
6757       }
6758       case '{': {
6759         int m = 0, n = 0;
6760         int sz, j;
6761         if( iPrev<0 ) return "'{m,n}' without operand";
6762         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
6763         n = m;
6764         if( c==',' ){
6765           p->sIn.i++;
6766           n = 0;
6767           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
6768         }
6769         if( c!='}' ) return "unmatched '{'";
6770         if( n>0 && n<m ) return "n less than m in '{m,n}'";
6771         p->sIn.i++;
6772         sz = p->nState - iPrev;
6773         if( m==0 ){
6774           if( n==0 ) return "both m and n are zero in '{m,n}'";
6775           re_insert(p, iPrev, RE_OP_FORK, sz+1);
6776           iPrev++;
6777           n--;
6778         }else{
6779           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
6780         }
6781         for(j=m; j<n; j++){
6782           re_append(p, RE_OP_FORK, sz+1);
6783           re_copy(p, iPrev, sz);
6784         }
6785         if( n==0 && m>0 ){
6786           re_append(p, RE_OP_FORK, -sz);
6787         }
6788         break;
6789       }
6790       case '[': {
6791         unsigned int iFirst = p->nState;
6792         if( rePeek(p)=='^' ){
6793           re_append(p, RE_OP_CC_EXC, 0);
6794           p->sIn.i++;
6795         }else{
6796           re_append(p, RE_OP_CC_INC, 0);
6797         }
6798         while( (c = p->xNextChar(&p->sIn))!=0 ){
6799           if( c=='[' && rePeek(p)==':' ){
6800             return "POSIX character classes not supported";
6801           }
6802           if( c=='\\' ) c = re_esc_char(p);
6803           if( rePeek(p)=='-' ){
6804             re_append(p, RE_OP_CC_RANGE, c);
6805             p->sIn.i++;
6806             c = p->xNextChar(&p->sIn);
6807             if( c=='\\' ) c = re_esc_char(p);
6808             re_append(p, RE_OP_CC_RANGE, c);
6809           }else{
6810             re_append(p, RE_OP_CC_VALUE, c);
6811           }
6812           if( rePeek(p)==']' ){ p->sIn.i++; break; }
6813         }
6814         if( c==0 ) return "unclosed '['";
6815         if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
6816         break;
6817       }
6818       case '\\': {
6819         int specialOp = 0;
6820         switch( rePeek(p) ){
6821           case 'b': specialOp = RE_OP_BOUNDARY;   break;
6822           case 'd': specialOp = RE_OP_DIGIT;      break;
6823           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
6824           case 's': specialOp = RE_OP_SPACE;      break;
6825           case 'S': specialOp = RE_OP_NOTSPACE;   break;
6826           case 'w': specialOp = RE_OP_WORD;       break;
6827           case 'W': specialOp = RE_OP_NOTWORD;    break;
6828         }
6829         if( specialOp ){
6830           p->sIn.i++;
6831           re_append(p, specialOp, 0);
6832         }else{
6833           c = re_esc_char(p);
6834           re_append(p, RE_OP_MATCH, c);
6835         }
6836         break;
6837       }
6838       default: {
6839         re_append(p, RE_OP_MATCH, c);
6840         break;
6841       }
6842     }
6843     iPrev = iStart;
6844   }
6845   return 0;
6846 }
6847 
6848 /* Free and reclaim all the memory used by a previously compiled
6849 ** regular expression.  Applications should invoke this routine once
6850 ** for every call to re_compile() to avoid memory leaks.
6851 */
re_free(ReCompiled * pRe)6852 static void re_free(ReCompiled *pRe){
6853   if( pRe ){
6854     sqlite3_free(pRe->aOp);
6855     sqlite3_free(pRe->aArg);
6856     sqlite3_free(pRe);
6857   }
6858 }
6859 
6860 /*
6861 ** Compile a textual regular expression in zIn[] into a compiled regular
6862 ** expression suitable for us by re_match() and return a pointer to the
6863 ** compiled regular expression in *ppRe.  Return NULL on success or an
6864 ** error message if something goes wrong.
6865 */
re_compile(ReCompiled ** ppRe,const char * zIn,int noCase)6866 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
6867   ReCompiled *pRe;
6868   const char *zErr;
6869   int i, j;
6870 
6871   *ppRe = 0;
6872   pRe = sqlite3_malloc( sizeof(*pRe) );
6873   if( pRe==0 ){
6874     return "out of memory";
6875   }
6876   memset(pRe, 0, sizeof(*pRe));
6877   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
6878   if( re_resize(pRe, 30) ){
6879     re_free(pRe);
6880     return "out of memory";
6881   }
6882   if( zIn[0]=='^' ){
6883     zIn++;
6884   }else{
6885     re_append(pRe, RE_OP_ANYSTAR, 0);
6886   }
6887   pRe->sIn.z = (unsigned char*)zIn;
6888   pRe->sIn.i = 0;
6889   pRe->sIn.mx = (int)strlen(zIn);
6890   zErr = re_subcompile_re(pRe);
6891   if( zErr ){
6892     re_free(pRe);
6893     return zErr;
6894   }
6895   if( pRe->sIn.i>=pRe->sIn.mx ){
6896     re_append(pRe, RE_OP_ACCEPT, 0);
6897     *ppRe = pRe;
6898   }else{
6899     re_free(pRe);
6900     return "unrecognized character";
6901   }
6902 
6903   /* The following is a performance optimization.  If the regex begins with
6904   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
6905   ** one or more matching characters, enter those matching characters into
6906   ** zInit[].  The re_match() routine can then search ahead in the input
6907   ** string looking for the initial match without having to run the whole
6908   ** regex engine over the string.  Do not worry about trying to match
6909   ** unicode characters beyond plane 0 - those are very rare and this is
6910   ** just an optimization. */
6911   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
6912     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
6913       unsigned x = pRe->aArg[i];
6914       if( x<=0x7f ){
6915         pRe->zInit[j++] = (unsigned char)x;
6916       }else if( x<=0x7ff ){
6917         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
6918         pRe->zInit[j++] = 0x80 | (x&0x3f);
6919       }else if( x<=0xffff ){
6920         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
6921         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
6922         pRe->zInit[j++] = 0x80 | (x&0x3f);
6923       }else{
6924         break;
6925       }
6926     }
6927     if( j>0 && pRe->zInit[j-1]==0 ) j--;
6928     pRe->nInit = j;
6929   }
6930   return pRe->zErr;
6931 }
6932 
6933 /*
6934 ** Implementation of the regexp() SQL function.  This function implements
6935 ** the build-in REGEXP operator.  The first argument to the function is the
6936 ** pattern and the second argument is the string.  So, the SQL statements:
6937 **
6938 **       A REGEXP B
6939 **
6940 ** is implemented as regexp(B,A).
6941 */
re_sql_func(sqlite3_context * context,int argc,sqlite3_value ** argv)6942 static void re_sql_func(
6943   sqlite3_context *context,
6944   int argc,
6945   sqlite3_value **argv
6946 ){
6947   ReCompiled *pRe;          /* Compiled regular expression */
6948   const char *zPattern;     /* The regular expression */
6949   const unsigned char *zStr;/* String being searched */
6950   const char *zErr;         /* Compile error message */
6951   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
6952 
6953   (void)argc;  /* Unused */
6954   pRe = sqlite3_get_auxdata(context, 0);
6955   if( pRe==0 ){
6956     zPattern = (const char*)sqlite3_value_text(argv[0]);
6957     if( zPattern==0 ) return;
6958     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
6959     if( zErr ){
6960       re_free(pRe);
6961       sqlite3_result_error(context, zErr, -1);
6962       return;
6963     }
6964     if( pRe==0 ){
6965       sqlite3_result_error_nomem(context);
6966       return;
6967     }
6968     setAux = 1;
6969   }
6970   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
6971   if( zStr!=0 ){
6972     sqlite3_result_int(context, re_match(pRe, zStr, -1));
6973   }
6974   if( setAux ){
6975     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
6976   }
6977 }
6978 
6979 #if defined(SQLITE_DEBUG)
6980 /*
6981 ** This function is used for testing and debugging only.  It is only available
6982 ** if the SQLITE_DEBUG compile-time option is used.
6983 **
6984 ** Compile a regular expression and then convert the compiled expression into
6985 ** text and return that text.
6986 */
re_bytecode_func(sqlite3_context * context,int argc,sqlite3_value ** argv)6987 static void re_bytecode_func(
6988   sqlite3_context *context,
6989   int argc,
6990   sqlite3_value **argv
6991 ){
6992   const char *zPattern;
6993   const char *zErr;
6994   ReCompiled *pRe;
6995   sqlite3_str *pStr;
6996   int i;
6997   int n;
6998   char *z;
6999   (void)argc;
7000 
7001   zPattern = (const char*)sqlite3_value_text(argv[0]);
7002   if( zPattern==0 ) return;
7003   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7004   if( zErr ){
7005     re_free(pRe);
7006     sqlite3_result_error(context, zErr, -1);
7007     return;
7008   }
7009   if( pRe==0 ){
7010     sqlite3_result_error_nomem(context);
7011     return;
7012   }
7013   pStr = sqlite3_str_new(0);
7014   if( pStr==0 ) goto re_bytecode_func_err;
7015   if( pRe->nInit>0 ){
7016     sqlite3_str_appendf(pStr, "INIT     ");
7017     for(i=0; i<pRe->nInit; i++){
7018       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
7019     }
7020     sqlite3_str_appendf(pStr, "\n");
7021   }
7022   for(i=0; (unsigned)i<pRe->nState; i++){
7023     sqlite3_str_appendf(pStr, "%-8s %4d\n",
7024          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
7025   }
7026   n = sqlite3_str_length(pStr);
7027   z = sqlite3_str_finish(pStr);
7028   if( n==0 ){
7029     sqlite3_free(z);
7030   }else{
7031     sqlite3_result_text(context, z, n-1, sqlite3_free);
7032   }
7033 
7034 re_bytecode_func_err:
7035   re_free(pRe);
7036 }
7037 
7038 #endif /* SQLITE_DEBUG */
7039 
7040 
7041 /*
7042 ** Invoke this routine to register the regexp() function with the
7043 ** SQLite database connection.
7044 */
7045 #ifdef _WIN32
7046 
7047 #endif
sqlite3_regexp_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)7048 int sqlite3_regexp_init(
7049   sqlite3 *db,
7050   char **pzErrMsg,
7051   const sqlite3_api_routines *pApi
7052 ){
7053   int rc = SQLITE_OK;
7054   SQLITE_EXTENSION_INIT2(pApi);
7055   (void)pzErrMsg;  /* Unused */
7056   rc = sqlite3_create_function(db, "regexp", 2,
7057                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7058                             0, re_sql_func, 0, 0);
7059   if( rc==SQLITE_OK ){
7060     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
7061     ** of regexp(PATTERN,STRING). */
7062     rc = sqlite3_create_function(db, "regexpi", 2,
7063                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7064                             (void*)db, re_sql_func, 0, 0);
7065 #if defined(SQLITE_DEBUG)
7066     if( rc==SQLITE_OK ){
7067       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
7068                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7069                             0, re_bytecode_func, 0, 0);
7070     }
7071 #endif /* SQLITE_DEBUG */
7072   }
7073   return rc;
7074 }
7075 
7076 /************************* End ../ext/misc/regexp.c ********************/
7077 #ifndef SQLITE_SHELL_FIDDLE
7078 /************************* Begin ../ext/misc/fileio.c ******************/
7079 /*
7080 ** 2014-06-13
7081 **
7082 ** The author disclaims copyright to this source code.  In place of
7083 ** a legal notice, here is a blessing:
7084 **
7085 **    May you do good and not evil.
7086 **    May you find forgiveness for yourself and forgive others.
7087 **    May you share freely, never taking more than you give.
7088 **
7089 ******************************************************************************
7090 **
7091 ** This SQLite extension implements SQL functions readfile() and
7092 ** writefile(), and eponymous virtual type "fsdir".
7093 **
7094 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
7095 **
7096 **   If neither of the optional arguments is present, then this UDF
7097 **   function writes blob DATA to file FILE. If successful, the number
7098 **   of bytes written is returned. If an error occurs, NULL is returned.
7099 **
7100 **   If the first option argument - MODE - is present, then it must
7101 **   be passed an integer value that corresponds to a POSIX mode
7102 **   value (file type + permissions, as returned in the stat.st_mode
7103 **   field by the stat() system call). Three types of files may
7104 **   be written/created:
7105 **
7106 **     regular files:  (mode & 0170000)==0100000
7107 **     symbolic links: (mode & 0170000)==0120000
7108 **     directories:    (mode & 0170000)==0040000
7109 **
7110 **   For a directory, the DATA is ignored. For a symbolic link, it is
7111 **   interpreted as text and used as the target of the link. For a
7112 **   regular file, it is interpreted as a blob and written into the
7113 **   named file. Regardless of the type of file, its permissions are
7114 **   set to (mode & 0777) before returning.
7115 **
7116 **   If the optional MTIME argument is present, then it is interpreted
7117 **   as an integer - the number of seconds since the unix epoch. The
7118 **   modification-time of the target file is set to this value before
7119 **   returning.
7120 **
7121 **   If three or more arguments are passed to this function and an
7122 **   error is encountered, an exception is raised.
7123 **
7124 ** READFILE(FILE):
7125 **
7126 **   Read and return the contents of file FILE (type blob) from disk.
7127 **
7128 ** FSDIR:
7129 **
7130 **   Used as follows:
7131 **
7132 **     SELECT * FROM fsdir($path [, $dir]);
7133 **
7134 **   Parameter $path is an absolute or relative pathname. If the file that it
7135 **   refers to does not exist, it is an error. If the path refers to a regular
7136 **   file or symbolic link, it returns a single row. Or, if the path refers
7137 **   to a directory, it returns one row for the directory, and one row for each
7138 **   file within the hierarchy rooted at $path.
7139 **
7140 **   Each row has the following columns:
7141 **
7142 **     name:  Path to file or directory (text value).
7143 **     mode:  Value of stat.st_mode for directory entry (an integer).
7144 **     mtime: Value of stat.st_mtime for directory entry (an integer).
7145 **     data:  For a regular file, a blob containing the file data. For a
7146 **            symlink, a text value containing the text of the link. For a
7147 **            directory, NULL.
7148 **
7149 **   If a non-NULL value is specified for the optional $dir parameter and
7150 **   $path is a relative path, then $path is interpreted relative to $dir.
7151 **   And the paths returned in the "name" column of the table are also
7152 **   relative to directory $dir.
7153 **
7154 ** Notes on building this extension for Windows:
7155 **   Unless linked statically with the SQLite library, a preprocessor
7156 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
7157 **   DLL form of this extension for WIN32. See its use below for details.
7158 */
7159 /* #include "sqlite3ext.h" */
7160 SQLITE_EXTENSION_INIT1
7161 #include <stdio.h>
7162 #include <string.h>
7163 #include <assert.h>
7164 
7165 #include <sys/types.h>
7166 #include <sys/stat.h>
7167 #include <fcntl.h>
7168 #if !defined(_WIN32) && !defined(WIN32)
7169 #  include <unistd.h>
7170 #  include <dirent.h>
7171 #  include <utime.h>
7172 #  include <sys/time.h>
7173 #else
7174 #  include "windows.h"
7175 #  include <io.h>
7176 #  include <direct.h>
7177 /* #  include "test_windirent.h" */
7178 #  define dirent DIRENT
7179 #  ifndef chmod
7180 #    define chmod _chmod
7181 #  endif
7182 #  ifndef stat
7183 #    define stat _stat
7184 #  endif
7185 #  define mkdir(path,mode) _mkdir(path)
7186 #  define lstat(path,buf) stat(path,buf)
7187 #endif
7188 #include <time.h>
7189 #include <errno.h>
7190 
7191 
7192 /*
7193 ** Structure of the fsdir() table-valued function
7194 */
7195                  /*    0    1    2     3    4           5             */
7196 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
7197 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
7198 #define FSDIR_COLUMN_MODE     1     /* Access mode */
7199 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
7200 #define FSDIR_COLUMN_DATA     3     /* File content */
7201 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
7202 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
7203 
7204 
7205 /*
7206 ** Set the result stored by context ctx to a blob containing the
7207 ** contents of file zName.  Or, leave the result unchanged (NULL)
7208 ** if the file does not exist or is unreadable.
7209 **
7210 ** If the file exceeds the SQLite blob size limit, through an
7211 ** SQLITE_TOOBIG error.
7212 **
7213 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
7214 ** off of disk.
7215 */
readFileContents(sqlite3_context * ctx,const char * zName)7216 static void readFileContents(sqlite3_context *ctx, const char *zName){
7217   FILE *in;
7218   sqlite3_int64 nIn;
7219   void *pBuf;
7220   sqlite3 *db;
7221   int mxBlob;
7222 
7223   in = fopen(zName, "rb");
7224   if( in==0 ){
7225     /* File does not exist or is unreadable. Leave the result set to NULL. */
7226     return;
7227   }
7228   fseek(in, 0, SEEK_END);
7229   nIn = ftell(in);
7230   rewind(in);
7231   db = sqlite3_context_db_handle(ctx);
7232   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
7233   if( nIn>mxBlob ){
7234     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
7235     fclose(in);
7236     return;
7237   }
7238   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
7239   if( pBuf==0 ){
7240     sqlite3_result_error_nomem(ctx);
7241     fclose(in);
7242     return;
7243   }
7244   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
7245     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
7246   }else{
7247     sqlite3_result_error_code(ctx, SQLITE_IOERR);
7248     sqlite3_free(pBuf);
7249   }
7250   fclose(in);
7251 }
7252 
7253 /*
7254 ** Implementation of the "readfile(X)" SQL function.  The entire content
7255 ** of the file named X is read and returned as a BLOB.  NULL is returned
7256 ** if the file does not exist or is unreadable.
7257 */
readfileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7258 static void readfileFunc(
7259   sqlite3_context *context,
7260   int argc,
7261   sqlite3_value **argv
7262 ){
7263   const char *zName;
7264   (void)(argc);  /* Unused parameter */
7265   zName = (const char*)sqlite3_value_text(argv[0]);
7266   if( zName==0 ) return;
7267   readFileContents(context, zName);
7268 }
7269 
7270 /*
7271 ** Set the error message contained in context ctx to the results of
7272 ** vprintf(zFmt, ...).
7273 */
ctxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)7274 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7275   char *zMsg = 0;
7276   va_list ap;
7277   va_start(ap, zFmt);
7278   zMsg = sqlite3_vmprintf(zFmt, ap);
7279   sqlite3_result_error(ctx, zMsg, -1);
7280   sqlite3_free(zMsg);
7281   va_end(ap);
7282 }
7283 
7284 #if defined(_WIN32)
7285 /*
7286 ** This function is designed to convert a Win32 FILETIME structure into the
7287 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
7288 */
fileTimeToUnixTime(LPFILETIME pFileTime)7289 static sqlite3_uint64 fileTimeToUnixTime(
7290   LPFILETIME pFileTime
7291 ){
7292   SYSTEMTIME epochSystemTime;
7293   ULARGE_INTEGER epochIntervals;
7294   FILETIME epochFileTime;
7295   ULARGE_INTEGER fileIntervals;
7296 
7297   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
7298   epochSystemTime.wYear = 1970;
7299   epochSystemTime.wMonth = 1;
7300   epochSystemTime.wDay = 1;
7301   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
7302   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
7303   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
7304 
7305   fileIntervals.LowPart = pFileTime->dwLowDateTime;
7306   fileIntervals.HighPart = pFileTime->dwHighDateTime;
7307 
7308   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
7309 }
7310 
7311 
7312 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
7313 #  /* To allow a standalone DLL, use this next replacement function: */
7314 #  undef sqlite3_win32_utf8_to_unicode
7315 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
7316 #
utf8_to_utf16(const char * z)7317 LPWSTR utf8_to_utf16(const char *z){
7318   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
7319   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
7320   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
7321     return rv;
7322   sqlite3_free(rv);
7323   return 0;
7324 }
7325 #endif
7326 
7327 /*
7328 ** This function attempts to normalize the time values found in the stat()
7329 ** buffer to UTC.  This is necessary on Win32, where the runtime library
7330 ** appears to return these values as local times.
7331 */
statTimesToUtc(const char * zPath,struct stat * pStatBuf)7332 static void statTimesToUtc(
7333   const char *zPath,
7334   struct stat *pStatBuf
7335 ){
7336   HANDLE hFindFile;
7337   WIN32_FIND_DATAW fd;
7338   LPWSTR zUnicodeName;
7339   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7340   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
7341   if( zUnicodeName ){
7342     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
7343     hFindFile = FindFirstFileW(zUnicodeName, &fd);
7344     if( hFindFile!=NULL ){
7345       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
7346       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
7347       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
7348       FindClose(hFindFile);
7349     }
7350     sqlite3_free(zUnicodeName);
7351   }
7352 }
7353 #endif
7354 
7355 /*
7356 ** This function is used in place of stat().  On Windows, special handling
7357 ** is required in order for the included time to be returned as UTC.  On all
7358 ** other systems, this function simply calls stat().
7359 */
fileStat(const char * zPath,struct stat * pStatBuf)7360 static int fileStat(
7361   const char *zPath,
7362   struct stat *pStatBuf
7363 ){
7364 #if defined(_WIN32)
7365   int rc = stat(zPath, pStatBuf);
7366   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7367   return rc;
7368 #else
7369   return stat(zPath, pStatBuf);
7370 #endif
7371 }
7372 
7373 /*
7374 ** This function is used in place of lstat().  On Windows, special handling
7375 ** is required in order for the included time to be returned as UTC.  On all
7376 ** other systems, this function simply calls lstat().
7377 */
fileLinkStat(const char * zPath,struct stat * pStatBuf)7378 static int fileLinkStat(
7379   const char *zPath,
7380   struct stat *pStatBuf
7381 ){
7382 #if defined(_WIN32)
7383   int rc = lstat(zPath, pStatBuf);
7384   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7385   return rc;
7386 #else
7387   return lstat(zPath, pStatBuf);
7388 #endif
7389 }
7390 
7391 /*
7392 ** Argument zFile is the name of a file that will be created and/or written
7393 ** by SQL function writefile(). This function ensures that the directory
7394 ** zFile will be written to exists, creating it if required. The permissions
7395 ** for any path components created by this function are set in accordance
7396 ** with the current umask.
7397 **
7398 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
7399 ** SQLITE_OK is returned if the directory is successfully created, or
7400 ** SQLITE_ERROR otherwise.
7401 */
makeDirectory(const char * zFile)7402 static int makeDirectory(
7403   const char *zFile
7404 ){
7405   char *zCopy = sqlite3_mprintf("%s", zFile);
7406   int rc = SQLITE_OK;
7407 
7408   if( zCopy==0 ){
7409     rc = SQLITE_NOMEM;
7410   }else{
7411     int nCopy = (int)strlen(zCopy);
7412     int i = 1;
7413 
7414     while( rc==SQLITE_OK ){
7415       struct stat sStat;
7416       int rc2;
7417 
7418       for(; zCopy[i]!='/' && i<nCopy; i++);
7419       if( i==nCopy ) break;
7420       zCopy[i] = '\0';
7421 
7422       rc2 = fileStat(zCopy, &sStat);
7423       if( rc2!=0 ){
7424         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
7425       }else{
7426         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
7427       }
7428       zCopy[i] = '/';
7429       i++;
7430     }
7431 
7432     sqlite3_free(zCopy);
7433   }
7434 
7435   return rc;
7436 }
7437 
7438 /*
7439 ** This function does the work for the writefile() UDF. Refer to
7440 ** header comments at the top of this file for details.
7441 */
writeFile(sqlite3_context * pCtx,const char * zFile,sqlite3_value * pData,mode_t mode,sqlite3_int64 mtime)7442 static int writeFile(
7443   sqlite3_context *pCtx,          /* Context to return bytes written in */
7444   const char *zFile,              /* File to write */
7445   sqlite3_value *pData,           /* Data to write */
7446   mode_t mode,                    /* MODE parameter passed to writefile() */
7447   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
7448 ){
7449   if( zFile==0 ) return 1;
7450 #if !defined(_WIN32) && !defined(WIN32)
7451   if( S_ISLNK(mode) ){
7452     const char *zTo = (const char*)sqlite3_value_text(pData);
7453     if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
7454   }else
7455 #endif
7456   {
7457     if( S_ISDIR(mode) ){
7458       if( mkdir(zFile, mode) ){
7459         /* The mkdir() call to create the directory failed. This might not
7460         ** be an error though - if there is already a directory at the same
7461         ** path and either the permissions already match or can be changed
7462         ** to do so using chmod(), it is not an error.  */
7463         struct stat sStat;
7464         if( errno!=EEXIST
7465          || 0!=fileStat(zFile, &sStat)
7466          || !S_ISDIR(sStat.st_mode)
7467          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
7468         ){
7469           return 1;
7470         }
7471       }
7472     }else{
7473       sqlite3_int64 nWrite = 0;
7474       const char *z;
7475       int rc = 0;
7476       FILE *out = fopen(zFile, "wb");
7477       if( out==0 ) return 1;
7478       z = (const char*)sqlite3_value_blob(pData);
7479       if( z ){
7480         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
7481         nWrite = sqlite3_value_bytes(pData);
7482         if( nWrite!=n ){
7483           rc = 1;
7484         }
7485       }
7486       fclose(out);
7487       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
7488         rc = 1;
7489       }
7490       if( rc ) return 2;
7491       sqlite3_result_int64(pCtx, nWrite);
7492     }
7493   }
7494 
7495   if( mtime>=0 ){
7496 #if defined(_WIN32)
7497 #if !SQLITE_OS_WINRT
7498     /* Windows */
7499     FILETIME lastAccess;
7500     FILETIME lastWrite;
7501     SYSTEMTIME currentTime;
7502     LONGLONG intervals;
7503     HANDLE hFile;
7504     LPWSTR zUnicodeName;
7505     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7506 
7507     GetSystemTime(&currentTime);
7508     SystemTimeToFileTime(&currentTime, &lastAccess);
7509     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
7510     lastWrite.dwLowDateTime = (DWORD)intervals;
7511     lastWrite.dwHighDateTime = intervals >> 32;
7512     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
7513     if( zUnicodeName==0 ){
7514       return 1;
7515     }
7516     hFile = CreateFileW(
7517       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
7518       FILE_FLAG_BACKUP_SEMANTICS, NULL
7519     );
7520     sqlite3_free(zUnicodeName);
7521     if( hFile!=INVALID_HANDLE_VALUE ){
7522       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
7523       CloseHandle(hFile);
7524       return !bResult;
7525     }else{
7526       return 1;
7527     }
7528 #endif
7529 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
7530     /* Recent unix */
7531     struct timespec times[2];
7532     times[0].tv_nsec = times[1].tv_nsec = 0;
7533     times[0].tv_sec = time(0);
7534     times[1].tv_sec = mtime;
7535     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
7536       return 1;
7537     }
7538 #else
7539     /* Legacy unix */
7540     struct timeval times[2];
7541     times[0].tv_usec = times[1].tv_usec = 0;
7542     times[0].tv_sec = time(0);
7543     times[1].tv_sec = mtime;
7544     if( utimes(zFile, times) ){
7545       return 1;
7546     }
7547 #endif
7548   }
7549 
7550   return 0;
7551 }
7552 
7553 /*
7554 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
7555 ** Refer to header comments at the top of this file for details.
7556 */
writefileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7557 static void writefileFunc(
7558   sqlite3_context *context,
7559   int argc,
7560   sqlite3_value **argv
7561 ){
7562   const char *zFile;
7563   mode_t mode = 0;
7564   int res;
7565   sqlite3_int64 mtime = -1;
7566 
7567   if( argc<2 || argc>4 ){
7568     sqlite3_result_error(context,
7569         "wrong number of arguments to function writefile()", -1
7570     );
7571     return;
7572   }
7573 
7574   zFile = (const char*)sqlite3_value_text(argv[0]);
7575   if( zFile==0 ) return;
7576   if( argc>=3 ){
7577     mode = (mode_t)sqlite3_value_int(argv[2]);
7578   }
7579   if( argc==4 ){
7580     mtime = sqlite3_value_int64(argv[3]);
7581   }
7582 
7583   res = writeFile(context, zFile, argv[1], mode, mtime);
7584   if( res==1 && errno==ENOENT ){
7585     if( makeDirectory(zFile)==SQLITE_OK ){
7586       res = writeFile(context, zFile, argv[1], mode, mtime);
7587     }
7588   }
7589 
7590   if( argc>2 && res!=0 ){
7591     if( S_ISLNK(mode) ){
7592       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
7593     }else if( S_ISDIR(mode) ){
7594       ctxErrorMsg(context, "failed to create directory: %s", zFile);
7595     }else{
7596       ctxErrorMsg(context, "failed to write file: %s", zFile);
7597     }
7598   }
7599 }
7600 
7601 /*
7602 ** SQL function:   lsmode(MODE)
7603 **
7604 ** Given a numberic st_mode from stat(), convert it into a human-readable
7605 ** text string in the style of "ls -l".
7606 */
lsModeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7607 static void lsModeFunc(
7608   sqlite3_context *context,
7609   int argc,
7610   sqlite3_value **argv
7611 ){
7612   int i;
7613   int iMode = sqlite3_value_int(argv[0]);
7614   char z[16];
7615   (void)argc;
7616   if( S_ISLNK(iMode) ){
7617     z[0] = 'l';
7618   }else if( S_ISREG(iMode) ){
7619     z[0] = '-';
7620   }else if( S_ISDIR(iMode) ){
7621     z[0] = 'd';
7622   }else{
7623     z[0] = '?';
7624   }
7625   for(i=0; i<3; i++){
7626     int m = (iMode >> ((2-i)*3));
7627     char *a = &z[1 + i*3];
7628     a[0] = (m & 0x4) ? 'r' : '-';
7629     a[1] = (m & 0x2) ? 'w' : '-';
7630     a[2] = (m & 0x1) ? 'x' : '-';
7631   }
7632   z[10] = '\0';
7633   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
7634 }
7635 
7636 #ifndef SQLITE_OMIT_VIRTUALTABLE
7637 
7638 /*
7639 ** Cursor type for recursively iterating through a directory structure.
7640 */
7641 typedef struct fsdir_cursor fsdir_cursor;
7642 typedef struct FsdirLevel FsdirLevel;
7643 
7644 struct FsdirLevel {
7645   DIR *pDir;                 /* From opendir() */
7646   char *zDir;                /* Name of directory (nul-terminated) */
7647 };
7648 
7649 struct fsdir_cursor {
7650   sqlite3_vtab_cursor base;  /* Base class - must be first */
7651 
7652   int nLvl;                  /* Number of entries in aLvl[] array */
7653   int iLvl;                  /* Index of current entry */
7654   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
7655 
7656   const char *zBase;
7657   int nBase;
7658 
7659   struct stat sStat;         /* Current lstat() results */
7660   char *zPath;               /* Path to current entry */
7661   sqlite3_int64 iRowid;      /* Current rowid */
7662 };
7663 
7664 typedef struct fsdir_tab fsdir_tab;
7665 struct fsdir_tab {
7666   sqlite3_vtab base;         /* Base class - must be first */
7667 };
7668 
7669 /*
7670 ** Construct a new fsdir virtual table object.
7671 */
fsdirConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)7672 static int fsdirConnect(
7673   sqlite3 *db,
7674   void *pAux,
7675   int argc, const char *const*argv,
7676   sqlite3_vtab **ppVtab,
7677   char **pzErr
7678 ){
7679   fsdir_tab *pNew = 0;
7680   int rc;
7681   (void)pAux;
7682   (void)argc;
7683   (void)argv;
7684   (void)pzErr;
7685   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
7686   if( rc==SQLITE_OK ){
7687     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
7688     if( pNew==0 ) return SQLITE_NOMEM;
7689     memset(pNew, 0, sizeof(*pNew));
7690     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
7691   }
7692   *ppVtab = (sqlite3_vtab*)pNew;
7693   return rc;
7694 }
7695 
7696 /*
7697 ** This method is the destructor for fsdir vtab objects.
7698 */
fsdirDisconnect(sqlite3_vtab * pVtab)7699 static int fsdirDisconnect(sqlite3_vtab *pVtab){
7700   sqlite3_free(pVtab);
7701   return SQLITE_OK;
7702 }
7703 
7704 /*
7705 ** Constructor for a new fsdir_cursor object.
7706 */
fsdirOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)7707 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
7708   fsdir_cursor *pCur;
7709   (void)p;
7710   pCur = sqlite3_malloc( sizeof(*pCur) );
7711   if( pCur==0 ) return SQLITE_NOMEM;
7712   memset(pCur, 0, sizeof(*pCur));
7713   pCur->iLvl = -1;
7714   *ppCursor = &pCur->base;
7715   return SQLITE_OK;
7716 }
7717 
7718 /*
7719 ** Reset a cursor back to the state it was in when first returned
7720 ** by fsdirOpen().
7721 */
fsdirResetCursor(fsdir_cursor * pCur)7722 static void fsdirResetCursor(fsdir_cursor *pCur){
7723   int i;
7724   for(i=0; i<=pCur->iLvl; i++){
7725     FsdirLevel *pLvl = &pCur->aLvl[i];
7726     if( pLvl->pDir ) closedir(pLvl->pDir);
7727     sqlite3_free(pLvl->zDir);
7728   }
7729   sqlite3_free(pCur->zPath);
7730   sqlite3_free(pCur->aLvl);
7731   pCur->aLvl = 0;
7732   pCur->zPath = 0;
7733   pCur->zBase = 0;
7734   pCur->nBase = 0;
7735   pCur->nLvl = 0;
7736   pCur->iLvl = -1;
7737   pCur->iRowid = 1;
7738 }
7739 
7740 /*
7741 ** Destructor for an fsdir_cursor.
7742 */
fsdirClose(sqlite3_vtab_cursor * cur)7743 static int fsdirClose(sqlite3_vtab_cursor *cur){
7744   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7745 
7746   fsdirResetCursor(pCur);
7747   sqlite3_free(pCur);
7748   return SQLITE_OK;
7749 }
7750 
7751 /*
7752 ** Set the error message for the virtual table associated with cursor
7753 ** pCur to the results of vprintf(zFmt, ...).
7754 */
fsdirSetErrmsg(fsdir_cursor * pCur,const char * zFmt,...)7755 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
7756   va_list ap;
7757   va_start(ap, zFmt);
7758   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7759   va_end(ap);
7760 }
7761 
7762 
7763 /*
7764 ** Advance an fsdir_cursor to its next row of output.
7765 */
fsdirNext(sqlite3_vtab_cursor * cur)7766 static int fsdirNext(sqlite3_vtab_cursor *cur){
7767   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7768   mode_t m = pCur->sStat.st_mode;
7769 
7770   pCur->iRowid++;
7771   if( S_ISDIR(m) ){
7772     /* Descend into this directory */
7773     int iNew = pCur->iLvl + 1;
7774     FsdirLevel *pLvl;
7775     if( iNew>=pCur->nLvl ){
7776       int nNew = iNew+1;
7777       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
7778       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
7779       if( aNew==0 ) return SQLITE_NOMEM;
7780       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
7781       pCur->aLvl = aNew;
7782       pCur->nLvl = nNew;
7783     }
7784     pCur->iLvl = iNew;
7785     pLvl = &pCur->aLvl[iNew];
7786 
7787     pLvl->zDir = pCur->zPath;
7788     pCur->zPath = 0;
7789     pLvl->pDir = opendir(pLvl->zDir);
7790     if( pLvl->pDir==0 ){
7791       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
7792       return SQLITE_ERROR;
7793     }
7794   }
7795 
7796   while( pCur->iLvl>=0 ){
7797     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
7798     struct dirent *pEntry = readdir(pLvl->pDir);
7799     if( pEntry ){
7800       if( pEntry->d_name[0]=='.' ){
7801        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
7802        if( pEntry->d_name[1]=='\0' ) continue;
7803       }
7804       sqlite3_free(pCur->zPath);
7805       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
7806       if( pCur->zPath==0 ) return SQLITE_NOMEM;
7807       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7808         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7809         return SQLITE_ERROR;
7810       }
7811       return SQLITE_OK;
7812     }
7813     closedir(pLvl->pDir);
7814     sqlite3_free(pLvl->zDir);
7815     pLvl->pDir = 0;
7816     pLvl->zDir = 0;
7817     pCur->iLvl--;
7818   }
7819 
7820   /* EOF */
7821   sqlite3_free(pCur->zPath);
7822   pCur->zPath = 0;
7823   return SQLITE_OK;
7824 }
7825 
7826 /*
7827 ** Return values of columns for the row at which the series_cursor
7828 ** is currently pointing.
7829 */
fsdirColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)7830 static int fsdirColumn(
7831   sqlite3_vtab_cursor *cur,   /* The cursor */
7832   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7833   int i                       /* Which column to return */
7834 ){
7835   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7836   switch( i ){
7837     case FSDIR_COLUMN_NAME: {
7838       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
7839       break;
7840     }
7841 
7842     case FSDIR_COLUMN_MODE:
7843       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
7844       break;
7845 
7846     case FSDIR_COLUMN_MTIME:
7847       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
7848       break;
7849 
7850     case FSDIR_COLUMN_DATA: {
7851       mode_t m = pCur->sStat.st_mode;
7852       if( S_ISDIR(m) ){
7853         sqlite3_result_null(ctx);
7854 #if !defined(_WIN32) && !defined(WIN32)
7855       }else if( S_ISLNK(m) ){
7856         char aStatic[64];
7857         char *aBuf = aStatic;
7858         sqlite3_int64 nBuf = 64;
7859         int n;
7860 
7861         while( 1 ){
7862           n = readlink(pCur->zPath, aBuf, nBuf);
7863           if( n<nBuf ) break;
7864           if( aBuf!=aStatic ) sqlite3_free(aBuf);
7865           nBuf = nBuf*2;
7866           aBuf = sqlite3_malloc64(nBuf);
7867           if( aBuf==0 ){
7868             sqlite3_result_error_nomem(ctx);
7869             return SQLITE_NOMEM;
7870           }
7871         }
7872 
7873         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
7874         if( aBuf!=aStatic ) sqlite3_free(aBuf);
7875 #endif
7876       }else{
7877         readFileContents(ctx, pCur->zPath);
7878       }
7879     }
7880     case FSDIR_COLUMN_PATH:
7881     default: {
7882       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
7883       ** always return their values as NULL */
7884       break;
7885     }
7886   }
7887   return SQLITE_OK;
7888 }
7889 
7890 /*
7891 ** Return the rowid for the current row. In this implementation, the
7892 ** first row returned is assigned rowid value 1, and each subsequent
7893 ** row a value 1 more than that of the previous.
7894 */
fsdirRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)7895 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7896   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7897   *pRowid = pCur->iRowid;
7898   return SQLITE_OK;
7899 }
7900 
7901 /*
7902 ** Return TRUE if the cursor has been moved off of the last
7903 ** row of output.
7904 */
fsdirEof(sqlite3_vtab_cursor * cur)7905 static int fsdirEof(sqlite3_vtab_cursor *cur){
7906   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7907   return (pCur->zPath==0);
7908 }
7909 
7910 /*
7911 ** xFilter callback.
7912 **
7913 ** idxNum==1   PATH parameter only
7914 ** idxNum==2   Both PATH and DIR supplied
7915 */
fsdirFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)7916 static int fsdirFilter(
7917   sqlite3_vtab_cursor *cur,
7918   int idxNum, const char *idxStr,
7919   int argc, sqlite3_value **argv
7920 ){
7921   const char *zDir = 0;
7922   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7923   (void)idxStr;
7924   fsdirResetCursor(pCur);
7925 
7926   if( idxNum==0 ){
7927     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
7928     return SQLITE_ERROR;
7929   }
7930 
7931   assert( argc==idxNum && (argc==1 || argc==2) );
7932   zDir = (const char*)sqlite3_value_text(argv[0]);
7933   if( zDir==0 ){
7934     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
7935     return SQLITE_ERROR;
7936   }
7937   if( argc==2 ){
7938     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
7939   }
7940   if( pCur->zBase ){
7941     pCur->nBase = (int)strlen(pCur->zBase)+1;
7942     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
7943   }else{
7944     pCur->zPath = sqlite3_mprintf("%s", zDir);
7945   }
7946 
7947   if( pCur->zPath==0 ){
7948     return SQLITE_NOMEM;
7949   }
7950   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7951     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7952     return SQLITE_ERROR;
7953   }
7954 
7955   return SQLITE_OK;
7956 }
7957 
7958 /*
7959 ** SQLite will invoke this method one or more times while planning a query
7960 ** that uses the generate_series virtual table.  This routine needs to create
7961 ** a query plan for each invocation and compute an estimated cost for that
7962 ** plan.
7963 **
7964 ** In this implementation idxNum is used to represent the
7965 ** query plan.  idxStr is unused.
7966 **
7967 ** The query plan is represented by values of idxNum:
7968 **
7969 **  (1)  The path value is supplied by argv[0]
7970 **  (2)  Path is in argv[0] and dir is in argv[1]
7971 */
fsdirBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)7972 static int fsdirBestIndex(
7973   sqlite3_vtab *tab,
7974   sqlite3_index_info *pIdxInfo
7975 ){
7976   int i;                 /* Loop over constraints */
7977   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
7978   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
7979   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
7980   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
7981   const struct sqlite3_index_constraint *pConstraint;
7982 
7983   (void)tab;
7984   pConstraint = pIdxInfo->aConstraint;
7985   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
7986     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
7987     switch( pConstraint->iColumn ){
7988       case FSDIR_COLUMN_PATH: {
7989         if( pConstraint->usable ){
7990           idxPath = i;
7991           seenPath = 0;
7992         }else if( idxPath<0 ){
7993           seenPath = 1;
7994         }
7995         break;
7996       }
7997       case FSDIR_COLUMN_DIR: {
7998         if( pConstraint->usable ){
7999           idxDir = i;
8000           seenDir = 0;
8001         }else if( idxDir<0 ){
8002           seenDir = 1;
8003         }
8004         break;
8005       }
8006     }
8007   }
8008   if( seenPath || seenDir ){
8009     /* If input parameters are unusable, disallow this plan */
8010     return SQLITE_CONSTRAINT;
8011   }
8012 
8013   if( idxPath<0 ){
8014     pIdxInfo->idxNum = 0;
8015     /* The pIdxInfo->estimatedCost should have been initialized to a huge
8016     ** number.  Leave it unchanged. */
8017     pIdxInfo->estimatedRows = 0x7fffffff;
8018   }else{
8019     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
8020     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
8021     if( idxDir>=0 ){
8022       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
8023       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
8024       pIdxInfo->idxNum = 2;
8025       pIdxInfo->estimatedCost = 10.0;
8026     }else{
8027       pIdxInfo->idxNum = 1;
8028       pIdxInfo->estimatedCost = 100.0;
8029     }
8030   }
8031 
8032   return SQLITE_OK;
8033 }
8034 
8035 /*
8036 ** Register the "fsdir" virtual table.
8037 */
fsdirRegister(sqlite3 * db)8038 static int fsdirRegister(sqlite3 *db){
8039   static sqlite3_module fsdirModule = {
8040     0,                         /* iVersion */
8041     0,                         /* xCreate */
8042     fsdirConnect,              /* xConnect */
8043     fsdirBestIndex,            /* xBestIndex */
8044     fsdirDisconnect,           /* xDisconnect */
8045     0,                         /* xDestroy */
8046     fsdirOpen,                 /* xOpen - open a cursor */
8047     fsdirClose,                /* xClose - close a cursor */
8048     fsdirFilter,               /* xFilter - configure scan constraints */
8049     fsdirNext,                 /* xNext - advance a cursor */
8050     fsdirEof,                  /* xEof - check for end of scan */
8051     fsdirColumn,               /* xColumn - read data */
8052     fsdirRowid,                /* xRowid - read data */
8053     0,                         /* xUpdate */
8054     0,                         /* xBegin */
8055     0,                         /* xSync */
8056     0,                         /* xCommit */
8057     0,                         /* xRollback */
8058     0,                         /* xFindMethod */
8059     0,                         /* xRename */
8060     0,                         /* xSavepoint */
8061     0,                         /* xRelease */
8062     0,                         /* xRollbackTo */
8063     0,                         /* xShadowName */
8064     0                          /* xIntegrity */
8065   };
8066 
8067   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
8068   return rc;
8069 }
8070 #else         /* SQLITE_OMIT_VIRTUALTABLE */
8071 # define fsdirRegister(x) SQLITE_OK
8072 #endif
8073 
8074 #ifdef _WIN32
8075 
8076 #endif
sqlite3_fileio_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8077 int sqlite3_fileio_init(
8078   sqlite3 *db,
8079   char **pzErrMsg,
8080   const sqlite3_api_routines *pApi
8081 ){
8082   int rc = SQLITE_OK;
8083   SQLITE_EXTENSION_INIT2(pApi);
8084   (void)pzErrMsg;  /* Unused parameter */
8085   rc = sqlite3_create_function(db, "readfile", 1,
8086                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8087                                readfileFunc, 0, 0);
8088   if( rc==SQLITE_OK ){
8089     rc = sqlite3_create_function(db, "writefile", -1,
8090                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8091                                  writefileFunc, 0, 0);
8092   }
8093   if( rc==SQLITE_OK ){
8094     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
8095                                  lsModeFunc, 0, 0);
8096   }
8097   if( rc==SQLITE_OK ){
8098     rc = fsdirRegister(db);
8099   }
8100   return rc;
8101 }
8102 
8103 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
8104 /* To allow a standalone DLL, make test_windirent.c use the same
8105  * redefined SQLite API calls as the above extension code does.
8106  * Just pull in this .c to accomplish this. As a beneficial side
8107  * effect, this extension becomes a single translation unit. */
8108 #  include "test_windirent.c"
8109 #endif
8110 
8111 /************************* End ../ext/misc/fileio.c ********************/
8112 /************************* Begin ../ext/misc/completion.c ******************/
8113 /*
8114 ** 2017-07-10
8115 **
8116 ** The author disclaims copyright to this source code.  In place of
8117 ** a legal notice, here is a blessing:
8118 **
8119 **    May you do good and not evil.
8120 **    May you find forgiveness for yourself and forgive others.
8121 **    May you share freely, never taking more than you give.
8122 **
8123 *************************************************************************
8124 **
8125 ** This file implements an eponymous virtual table that returns suggested
8126 ** completions for a partial SQL input.
8127 **
8128 ** Suggested usage:
8129 **
8130 **     SELECT DISTINCT candidate COLLATE nocase
8131 **       FROM completion($prefix,$wholeline)
8132 **      ORDER BY 1;
8133 **
8134 ** The two query parameters are optional.  $prefix is the text of the
8135 ** current word being typed and that is to be completed.  $wholeline is
8136 ** the complete input line, used for context.
8137 **
8138 ** The raw completion() table might return the same candidate multiple
8139 ** times, for example if the same column name is used to two or more
8140 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
8141 ** the DISTINCT and ORDER BY are recommended.
8142 **
8143 ** This virtual table operates at the speed of human typing, and so there
8144 ** is no attempt to make it fast.  Even a slow implementation will be much
8145 ** faster than any human can type.
8146 **
8147 */
8148 /* #include "sqlite3ext.h" */
8149 SQLITE_EXTENSION_INIT1
8150 #include <assert.h>
8151 #include <string.h>
8152 #include <ctype.h>
8153 
8154 #ifndef SQLITE_OMIT_VIRTUALTABLE
8155 
8156 /* completion_vtab is a subclass of sqlite3_vtab which will
8157 ** serve as the underlying representation of a completion virtual table
8158 */
8159 typedef struct completion_vtab completion_vtab;
8160 struct completion_vtab {
8161   sqlite3_vtab base;  /* Base class - must be first */
8162   sqlite3 *db;        /* Database connection for this completion vtab */
8163 };
8164 
8165 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
8166 ** serve as the underlying representation of a cursor that scans
8167 ** over rows of the result
8168 */
8169 typedef struct completion_cursor completion_cursor;
8170 struct completion_cursor {
8171   sqlite3_vtab_cursor base;  /* Base class - must be first */
8172   sqlite3 *db;               /* Database connection for this cursor */
8173   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
8174   char *zPrefix;             /* The prefix for the word we want to complete */
8175   char *zLine;               /* The whole that we want to complete */
8176   const char *zCurrentRow;   /* Current output row */
8177   int szRow;                 /* Length of the zCurrentRow string */
8178   sqlite3_stmt *pStmt;       /* Current statement */
8179   sqlite3_int64 iRowid;      /* The rowid */
8180   int ePhase;                /* Current phase */
8181   int j;                     /* inter-phase counter */
8182 };
8183 
8184 /* Values for ePhase:
8185 */
8186 #define COMPLETION_FIRST_PHASE   1
8187 #define COMPLETION_KEYWORDS      1
8188 #define COMPLETION_PRAGMAS       2
8189 #define COMPLETION_FUNCTIONS     3
8190 #define COMPLETION_COLLATIONS    4
8191 #define COMPLETION_INDEXES       5
8192 #define COMPLETION_TRIGGERS      6
8193 #define COMPLETION_DATABASES     7
8194 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
8195 #define COMPLETION_COLUMNS       9
8196 #define COMPLETION_MODULES       10
8197 #define COMPLETION_EOF           11
8198 
8199 /*
8200 ** The completionConnect() method is invoked to create a new
8201 ** completion_vtab that describes the completion virtual table.
8202 **
8203 ** Think of this routine as the constructor for completion_vtab objects.
8204 **
8205 ** All this routine needs to do is:
8206 **
8207 **    (1) Allocate the completion_vtab object and initialize all fields.
8208 **
8209 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
8210 **        result set of queries against completion will look like.
8211 */
completionConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)8212 static int completionConnect(
8213   sqlite3 *db,
8214   void *pAux,
8215   int argc, const char *const*argv,
8216   sqlite3_vtab **ppVtab,
8217   char **pzErr
8218 ){
8219   completion_vtab *pNew;
8220   int rc;
8221 
8222   (void)(pAux);    /* Unused parameter */
8223   (void)(argc);    /* Unused parameter */
8224   (void)(argv);    /* Unused parameter */
8225   (void)(pzErr);   /* Unused parameter */
8226 
8227 /* Column numbers */
8228 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
8229 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
8230 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
8231 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
8232 
8233   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
8234   rc = sqlite3_declare_vtab(db,
8235       "CREATE TABLE x("
8236       "  candidate TEXT,"
8237       "  prefix TEXT HIDDEN,"
8238       "  wholeline TEXT HIDDEN,"
8239       "  phase INT HIDDEN"        /* Used for debugging only */
8240       ")");
8241   if( rc==SQLITE_OK ){
8242     pNew = sqlite3_malloc( sizeof(*pNew) );
8243     *ppVtab = (sqlite3_vtab*)pNew;
8244     if( pNew==0 ) return SQLITE_NOMEM;
8245     memset(pNew, 0, sizeof(*pNew));
8246     pNew->db = db;
8247   }
8248   return rc;
8249 }
8250 
8251 /*
8252 ** This method is the destructor for completion_cursor objects.
8253 */
completionDisconnect(sqlite3_vtab * pVtab)8254 static int completionDisconnect(sqlite3_vtab *pVtab){
8255   sqlite3_free(pVtab);
8256   return SQLITE_OK;
8257 }
8258 
8259 /*
8260 ** Constructor for a new completion_cursor object.
8261 */
completionOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)8262 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
8263   completion_cursor *pCur;
8264   pCur = sqlite3_malloc( sizeof(*pCur) );
8265   if( pCur==0 ) return SQLITE_NOMEM;
8266   memset(pCur, 0, sizeof(*pCur));
8267   pCur->db = ((completion_vtab*)p)->db;
8268   *ppCursor = &pCur->base;
8269   return SQLITE_OK;
8270 }
8271 
8272 /*
8273 ** Reset the completion_cursor.
8274 */
completionCursorReset(completion_cursor * pCur)8275 static void completionCursorReset(completion_cursor *pCur){
8276   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
8277   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
8278   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
8279   pCur->j = 0;
8280 }
8281 
8282 /*
8283 ** Destructor for a completion_cursor.
8284 */
completionClose(sqlite3_vtab_cursor * cur)8285 static int completionClose(sqlite3_vtab_cursor *cur){
8286   completionCursorReset((completion_cursor*)cur);
8287   sqlite3_free(cur);
8288   return SQLITE_OK;
8289 }
8290 
8291 /*
8292 ** Advance a completion_cursor to its next row of output.
8293 **
8294 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
8295 ** record the current state of the scan.  This routine sets ->zCurrentRow
8296 ** to the current row of output and then returns.  If no more rows remain,
8297 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
8298 ** table that has reached the end of its scan.
8299 **
8300 ** The current implementation just lists potential identifiers and
8301 ** keywords and filters them by zPrefix.  Future enhancements should
8302 ** take zLine into account to try to restrict the set of identifiers and
8303 ** keywords based on what would be legal at the current point of input.
8304 */
completionNext(sqlite3_vtab_cursor * cur)8305 static int completionNext(sqlite3_vtab_cursor *cur){
8306   completion_cursor *pCur = (completion_cursor*)cur;
8307   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
8308   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
8309   pCur->iRowid++;
8310   while( pCur->ePhase!=COMPLETION_EOF ){
8311     switch( pCur->ePhase ){
8312       case COMPLETION_KEYWORDS: {
8313         if( pCur->j >= sqlite3_keyword_count() ){
8314           pCur->zCurrentRow = 0;
8315           pCur->ePhase = COMPLETION_DATABASES;
8316         }else{
8317           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
8318         }
8319         iCol = -1;
8320         break;
8321       }
8322       case COMPLETION_DATABASES: {
8323         if( pCur->pStmt==0 ){
8324           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
8325                              &pCur->pStmt, 0);
8326         }
8327         iCol = 1;
8328         eNextPhase = COMPLETION_TABLES;
8329         break;
8330       }
8331       case COMPLETION_TABLES: {
8332         if( pCur->pStmt==0 ){
8333           sqlite3_stmt *pS2;
8334           char *zSql = 0;
8335           const char *zSep = "";
8336           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8337           while( sqlite3_step(pS2)==SQLITE_ROW ){
8338             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8339             zSql = sqlite3_mprintf(
8340                "%z%s"
8341                "SELECT name FROM \"%w\".sqlite_schema",
8342                zSql, zSep, zDb
8343             );
8344             if( zSql==0 ) return SQLITE_NOMEM;
8345             zSep = " UNION ";
8346           }
8347           sqlite3_finalize(pS2);
8348           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8349           sqlite3_free(zSql);
8350         }
8351         iCol = 0;
8352         eNextPhase = COMPLETION_COLUMNS;
8353         break;
8354       }
8355       case COMPLETION_COLUMNS: {
8356         if( pCur->pStmt==0 ){
8357           sqlite3_stmt *pS2;
8358           char *zSql = 0;
8359           const char *zSep = "";
8360           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8361           while( sqlite3_step(pS2)==SQLITE_ROW ){
8362             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8363             zSql = sqlite3_mprintf(
8364                "%z%s"
8365                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
8366                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
8367                " WHERE sm.type='table'",
8368                zSql, zSep, zDb, zDb
8369             );
8370             if( zSql==0 ) return SQLITE_NOMEM;
8371             zSep = " UNION ";
8372           }
8373           sqlite3_finalize(pS2);
8374           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8375           sqlite3_free(zSql);
8376         }
8377         iCol = 0;
8378         eNextPhase = COMPLETION_EOF;
8379         break;
8380       }
8381     }
8382     if( iCol<0 ){
8383       /* This case is when the phase presets zCurrentRow */
8384       if( pCur->zCurrentRow==0 ) continue;
8385     }else{
8386       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
8387         /* Extract the next row of content */
8388         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
8389         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
8390       }else{
8391         /* When all rows are finished, advance to the next phase */
8392         sqlite3_finalize(pCur->pStmt);
8393         pCur->pStmt = 0;
8394         pCur->ePhase = eNextPhase;
8395         continue;
8396       }
8397     }
8398     if( pCur->nPrefix==0 ) break;
8399     if( pCur->nPrefix<=pCur->szRow
8400      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
8401     ){
8402       break;
8403     }
8404   }
8405 
8406   return SQLITE_OK;
8407 }
8408 
8409 /*
8410 ** Return values of columns for the row at which the completion_cursor
8411 ** is currently pointing.
8412 */
completionColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)8413 static int completionColumn(
8414   sqlite3_vtab_cursor *cur,   /* The cursor */
8415   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8416   int i                       /* Which column to return */
8417 ){
8418   completion_cursor *pCur = (completion_cursor*)cur;
8419   switch( i ){
8420     case COMPLETION_COLUMN_CANDIDATE: {
8421       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
8422       break;
8423     }
8424     case COMPLETION_COLUMN_PREFIX: {
8425       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
8426       break;
8427     }
8428     case COMPLETION_COLUMN_WHOLELINE: {
8429       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
8430       break;
8431     }
8432     case COMPLETION_COLUMN_PHASE: {
8433       sqlite3_result_int(ctx, pCur->ePhase);
8434       break;
8435     }
8436   }
8437   return SQLITE_OK;
8438 }
8439 
8440 /*
8441 ** Return the rowid for the current row.  In this implementation, the
8442 ** rowid is the same as the output value.
8443 */
completionRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)8444 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8445   completion_cursor *pCur = (completion_cursor*)cur;
8446   *pRowid = pCur->iRowid;
8447   return SQLITE_OK;
8448 }
8449 
8450 /*
8451 ** Return TRUE if the cursor has been moved off of the last
8452 ** row of output.
8453 */
completionEof(sqlite3_vtab_cursor * cur)8454 static int completionEof(sqlite3_vtab_cursor *cur){
8455   completion_cursor *pCur = (completion_cursor*)cur;
8456   return pCur->ePhase >= COMPLETION_EOF;
8457 }
8458 
8459 /*
8460 ** This method is called to "rewind" the completion_cursor object back
8461 ** to the first row of output.  This method is always called at least
8462 ** once prior to any call to completionColumn() or completionRowid() or
8463 ** completionEof().
8464 */
completionFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)8465 static int completionFilter(
8466   sqlite3_vtab_cursor *pVtabCursor,
8467   int idxNum, const char *idxStr,
8468   int argc, sqlite3_value **argv
8469 ){
8470   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
8471   int iArg = 0;
8472   (void)(idxStr);   /* Unused parameter */
8473   (void)(argc);     /* Unused parameter */
8474   completionCursorReset(pCur);
8475   if( idxNum & 1 ){
8476     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
8477     if( pCur->nPrefix>0 ){
8478       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8479       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8480     }
8481     iArg = 1;
8482   }
8483   if( idxNum & 2 ){
8484     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
8485     if( pCur->nLine>0 ){
8486       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8487       if( pCur->zLine==0 ) return SQLITE_NOMEM;
8488     }
8489   }
8490   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
8491     int i = pCur->nLine;
8492     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
8493       i--;
8494     }
8495     pCur->nPrefix = pCur->nLine - i;
8496     if( pCur->nPrefix>0 ){
8497       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
8498       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8499     }
8500   }
8501   pCur->iRowid = 0;
8502   pCur->ePhase = COMPLETION_FIRST_PHASE;
8503   return completionNext(pVtabCursor);
8504 }
8505 
8506 /*
8507 ** SQLite will invoke this method one or more times while planning a query
8508 ** that uses the completion virtual table.  This routine needs to create
8509 ** a query plan for each invocation and compute an estimated cost for that
8510 ** plan.
8511 **
8512 ** There are two hidden parameters that act as arguments to the table-valued
8513 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
8514 ** is available and bit 1 is set if "wholeline" is available.
8515 */
completionBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)8516 static int completionBestIndex(
8517   sqlite3_vtab *tab,
8518   sqlite3_index_info *pIdxInfo
8519 ){
8520   int i;                 /* Loop over constraints */
8521   int idxNum = 0;        /* The query plan bitmask */
8522   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
8523   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
8524   int nArg = 0;          /* Number of arguments that completeFilter() expects */
8525   const struct sqlite3_index_constraint *pConstraint;
8526 
8527   (void)(tab);    /* Unused parameter */
8528   pConstraint = pIdxInfo->aConstraint;
8529   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8530     if( pConstraint->usable==0 ) continue;
8531     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8532     switch( pConstraint->iColumn ){
8533       case COMPLETION_COLUMN_PREFIX:
8534         prefixIdx = i;
8535         idxNum |= 1;
8536         break;
8537       case COMPLETION_COLUMN_WHOLELINE:
8538         wholelineIdx = i;
8539         idxNum |= 2;
8540         break;
8541     }
8542   }
8543   if( prefixIdx>=0 ){
8544     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
8545     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
8546   }
8547   if( wholelineIdx>=0 ){
8548     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
8549     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
8550   }
8551   pIdxInfo->idxNum = idxNum;
8552   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
8553   pIdxInfo->estimatedRows = 500 - 100*nArg;
8554   return SQLITE_OK;
8555 }
8556 
8557 /*
8558 ** This following structure defines all the methods for the
8559 ** completion virtual table.
8560 */
8561 static sqlite3_module completionModule = {
8562   0,                         /* iVersion */
8563   0,                         /* xCreate */
8564   completionConnect,         /* xConnect */
8565   completionBestIndex,       /* xBestIndex */
8566   completionDisconnect,      /* xDisconnect */
8567   0,                         /* xDestroy */
8568   completionOpen,            /* xOpen - open a cursor */
8569   completionClose,           /* xClose - close a cursor */
8570   completionFilter,          /* xFilter - configure scan constraints */
8571   completionNext,            /* xNext - advance a cursor */
8572   completionEof,             /* xEof - check for end of scan */
8573   completionColumn,          /* xColumn - read data */
8574   completionRowid,           /* xRowid - read data */
8575   0,                         /* xUpdate */
8576   0,                         /* xBegin */
8577   0,                         /* xSync */
8578   0,                         /* xCommit */
8579   0,                         /* xRollback */
8580   0,                         /* xFindMethod */
8581   0,                         /* xRename */
8582   0,                         /* xSavepoint */
8583   0,                         /* xRelease */
8584   0,                         /* xRollbackTo */
8585   0,                         /* xShadowName */
8586   0                          /* xIntegrity */
8587 };
8588 
8589 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8590 
sqlite3CompletionVtabInit(sqlite3 * db)8591 int sqlite3CompletionVtabInit(sqlite3 *db){
8592   int rc = SQLITE_OK;
8593 #ifndef SQLITE_OMIT_VIRTUALTABLE
8594   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
8595 #endif
8596   return rc;
8597 }
8598 
8599 #ifdef _WIN32
8600 
8601 #endif
sqlite3_completion_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8602 int sqlite3_completion_init(
8603   sqlite3 *db,
8604   char **pzErrMsg,
8605   const sqlite3_api_routines *pApi
8606 ){
8607   int rc = SQLITE_OK;
8608   SQLITE_EXTENSION_INIT2(pApi);
8609   (void)(pzErrMsg);  /* Unused parameter */
8610 #ifndef SQLITE_OMIT_VIRTUALTABLE
8611   rc = sqlite3CompletionVtabInit(db);
8612 #endif
8613   return rc;
8614 }
8615 
8616 /************************* End ../ext/misc/completion.c ********************/
8617 /************************* Begin ../ext/misc/appendvfs.c ******************/
8618 /*
8619 ** 2017-10-20
8620 **
8621 ** The author disclaims copyright to this source code.  In place of
8622 ** a legal notice, here is a blessing:
8623 **
8624 **    May you do good and not evil.
8625 **    May you find forgiveness for yourself and forgive others.
8626 **    May you share freely, never taking more than you give.
8627 **
8628 ******************************************************************************
8629 **
8630 ** This file implements a VFS shim that allows an SQLite database to be
8631 ** appended onto the end of some other file, such as an executable.
8632 **
8633 ** A special record must appear at the end of the file that identifies the
8634 ** file as an appended database and provides the offset to the first page
8635 ** of the exposed content. (Or, it is the length of the content prefix.)
8636 ** For best performance page 1 should be located at a disk page boundary,
8637 ** though that is not required.
8638 **
8639 ** When opening a database using this VFS, the connection might treat
8640 ** the file as an ordinary SQLite database, or it might treat it as a
8641 ** database appended onto some other file.  The decision is made by
8642 ** applying the following rules in order:
8643 **
8644 **  (1)  An empty file is an ordinary database.
8645 **
8646 **  (2)  If the file ends with the appendvfs trailer string
8647 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
8648 **
8649 **  (3)  If the file begins with the standard SQLite prefix string
8650 **       "SQLite format 3", that file is an ordinary database.
8651 **
8652 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
8653 **       set, then a new database is appended to the already existing file.
8654 **
8655 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
8656 **
8657 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
8658 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
8659 ** This VFS will not read or write past the 1GiB mark.  This restriction
8660 ** might be lifted in future versions.  For now, if you need a larger
8661 ** database, then keep it in a separate file.
8662 **
8663 ** If the file being opened is a plain database (not an appended one), then
8664 ** this shim is a pass-through into the default underlying VFS. (rule 3)
8665 **/
8666 /* #include "sqlite3ext.h" */
8667 SQLITE_EXTENSION_INIT1
8668 #include <string.h>
8669 #include <assert.h>
8670 
8671 /* The append mark at the end of the database is:
8672 **
8673 **     Start-Of-SQLite3-NNNNNNNN
8674 **     123456789 123456789 12345
8675 **
8676 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
8677 ** the offset to page 1, and also the length of the prefix content.
8678 */
8679 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
8680 #define APND_MARK_PREFIX_SZ  17
8681 #define APND_MARK_FOS_SZ      8
8682 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
8683 
8684 /*
8685 ** Maximum size of the combined prefix + database + append-mark.  This
8686 ** must be less than 0x40000000 to avoid locking issues on Windows.
8687 */
8688 #define APND_MAX_SIZE  (0x40000000)
8689 
8690 /*
8691 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
8692 */
8693 #ifndef APND_ROUNDUP
8694 #define APND_ROUNDUP 4096
8695 #endif
8696 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
8697 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
8698 
8699 /*
8700 ** Forward declaration of objects used by this utility
8701 */
8702 typedef struct sqlite3_vfs ApndVfs;
8703 typedef struct ApndFile ApndFile;
8704 
8705 /* Access to a lower-level VFS that (might) implement dynamic loading,
8706 ** access to randomness, etc.
8707 */
8708 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
8709 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
8710 
8711 /* An open appendvfs file
8712 **
8713 ** An instance of this structure describes the appended database file.
8714 ** A separate sqlite3_file object is always appended. The appended
8715 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
8716 ** the entire file, including the prefix, the database, and the
8717 ** append-mark.
8718 **
8719 ** The structure of an AppendVFS database is like this:
8720 **
8721 **   +-------------+---------+----------+-------------+
8722 **   | prefix-file | padding | database | append-mark |
8723 **   +-------------+---------+----------+-------------+
8724 **                           ^          ^
8725 **                           |          |
8726 **                         iPgOne      iMark
8727 **
8728 **
8729 ** "prefix file" -  file onto which the database has been appended.
8730 ** "padding"     -  zero or more bytes inserted so that "database"
8731 **                  starts on an APND_ROUNDUP boundary
8732 ** "database"    -  The SQLite database file
8733 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8734 **                  the offset from the start of prefix-file to the start
8735 **                  of "database".
8736 **
8737 ** The size of the database is iMark - iPgOne.
8738 **
8739 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8740 ** of iPgOne stored as a big-ending 64-bit integer.
8741 **
8742 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
8743 ** Or, iMark is -1 to indicate that it has not yet been written.
8744 */
8745 struct ApndFile {
8746   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
8747   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
8748   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
8749   /* Always followed by another sqlite3_file that describes the whole file */
8750 };
8751 
8752 /*
8753 ** Methods for ApndFile
8754 */
8755 static int apndClose(sqlite3_file*);
8756 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
8757 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
8758 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
8759 static int apndSync(sqlite3_file*, int flags);
8760 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
8761 static int apndLock(sqlite3_file*, int);
8762 static int apndUnlock(sqlite3_file*, int);
8763 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
8764 static int apndFileControl(sqlite3_file*, int op, void *pArg);
8765 static int apndSectorSize(sqlite3_file*);
8766 static int apndDeviceCharacteristics(sqlite3_file*);
8767 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
8768 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
8769 static void apndShmBarrier(sqlite3_file*);
8770 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
8771 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
8772 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
8773 
8774 /*
8775 ** Methods for ApndVfs
8776 */
8777 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
8778 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
8779 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
8780 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
8781 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
8782 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
8783 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
8784 static void apndDlClose(sqlite3_vfs*, void*);
8785 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
8786 static int apndSleep(sqlite3_vfs*, int microseconds);
8787 static int apndCurrentTime(sqlite3_vfs*, double*);
8788 static int apndGetLastError(sqlite3_vfs*, int, char *);
8789 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
8790 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
8791 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
8792 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
8793 
8794 static sqlite3_vfs apnd_vfs = {
8795   3,                            /* iVersion (set when registered) */
8796   0,                            /* szOsFile (set when registered) */
8797   1024,                         /* mxPathname */
8798   0,                            /* pNext */
8799   "apndvfs",                    /* zName */
8800   0,                            /* pAppData (set when registered) */
8801   apndOpen,                     /* xOpen */
8802   apndDelete,                   /* xDelete */
8803   apndAccess,                   /* xAccess */
8804   apndFullPathname,             /* xFullPathname */
8805   apndDlOpen,                   /* xDlOpen */
8806   apndDlError,                  /* xDlError */
8807   apndDlSym,                    /* xDlSym */
8808   apndDlClose,                  /* xDlClose */
8809   apndRandomness,               /* xRandomness */
8810   apndSleep,                    /* xSleep */
8811   apndCurrentTime,              /* xCurrentTime */
8812   apndGetLastError,             /* xGetLastError */
8813   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
8814   apndSetSystemCall,            /* xSetSystemCall */
8815   apndGetSystemCall,            /* xGetSystemCall */
8816   apndNextSystemCall            /* xNextSystemCall */
8817 };
8818 
8819 static const sqlite3_io_methods apnd_io_methods = {
8820   3,                              /* iVersion */
8821   apndClose,                      /* xClose */
8822   apndRead,                       /* xRead */
8823   apndWrite,                      /* xWrite */
8824   apndTruncate,                   /* xTruncate */
8825   apndSync,                       /* xSync */
8826   apndFileSize,                   /* xFileSize */
8827   apndLock,                       /* xLock */
8828   apndUnlock,                     /* xUnlock */
8829   apndCheckReservedLock,          /* xCheckReservedLock */
8830   apndFileControl,                /* xFileControl */
8831   apndSectorSize,                 /* xSectorSize */
8832   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
8833   apndShmMap,                     /* xShmMap */
8834   apndShmLock,                    /* xShmLock */
8835   apndShmBarrier,                 /* xShmBarrier */
8836   apndShmUnmap,                   /* xShmUnmap */
8837   apndFetch,                      /* xFetch */
8838   apndUnfetch                     /* xUnfetch */
8839 };
8840 
8841 /*
8842 ** Close an apnd-file.
8843 */
apndClose(sqlite3_file * pFile)8844 static int apndClose(sqlite3_file *pFile){
8845   pFile = ORIGFILE(pFile);
8846   return pFile->pMethods->xClose(pFile);
8847 }
8848 
8849 /*
8850 ** Read data from an apnd-file.
8851 */
apndRead(sqlite3_file * pFile,void * zBuf,int iAmt,sqlite_int64 iOfst)8852 static int apndRead(
8853   sqlite3_file *pFile,
8854   void *zBuf,
8855   int iAmt,
8856   sqlite_int64 iOfst
8857 ){
8858   ApndFile *paf = (ApndFile *)pFile;
8859   pFile = ORIGFILE(pFile);
8860   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8861 }
8862 
8863 /*
8864 ** Add the append-mark onto what should become the end of the file.
8865 *  If and only if this succeeds, internal ApndFile.iMark is updated.
8866 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8867 */
apndWriteMark(ApndFile * paf,sqlite3_file * pFile,sqlite_int64 iWriteEnd)8868 static int apndWriteMark(
8869   ApndFile *paf,
8870   sqlite3_file *pFile,
8871   sqlite_int64 iWriteEnd
8872 ){
8873   sqlite_int64 iPgOne = paf->iPgOne;
8874   unsigned char a[APND_MARK_SIZE];
8875   int i = APND_MARK_FOS_SZ;
8876   int rc;
8877   assert(pFile == ORIGFILE(paf));
8878   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
8879   while( --i >= 0 ){
8880     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
8881     iPgOne >>= 8;
8882   }
8883   iWriteEnd += paf->iPgOne;
8884   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
8885                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
8886     paf->iMark = iWriteEnd;
8887   }
8888   return rc;
8889 }
8890 
8891 /*
8892 ** Write data to an apnd-file.
8893 */
apndWrite(sqlite3_file * pFile,const void * zBuf,int iAmt,sqlite_int64 iOfst)8894 static int apndWrite(
8895   sqlite3_file *pFile,
8896   const void *zBuf,
8897   int iAmt,
8898   sqlite_int64 iOfst
8899 ){
8900   ApndFile *paf = (ApndFile *)pFile;
8901   sqlite_int64 iWriteEnd = iOfst + iAmt;
8902   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
8903   pFile = ORIGFILE(pFile);
8904   /* If append-mark is absent or will be overwritten, write it. */
8905   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
8906     int rc = apndWriteMark(paf, pFile, iWriteEnd);
8907     if( SQLITE_OK!=rc ) return rc;
8908   }
8909   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8910 }
8911 
8912 /*
8913 ** Truncate an apnd-file.
8914 */
apndTruncate(sqlite3_file * pFile,sqlite_int64 size)8915 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
8916   ApndFile *paf = (ApndFile *)pFile;
8917   pFile = ORIGFILE(pFile);
8918   /* The append mark goes out first so truncate failure does not lose it. */
8919   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
8920   /* Truncate underlying file just past append mark */
8921   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
8922 }
8923 
8924 /*
8925 ** Sync an apnd-file.
8926 */
apndSync(sqlite3_file * pFile,int flags)8927 static int apndSync(sqlite3_file *pFile, int flags){
8928   pFile = ORIGFILE(pFile);
8929   return pFile->pMethods->xSync(pFile, flags);
8930 }
8931 
8932 /*
8933 ** Return the current file-size of an apnd-file.
8934 ** If the append mark is not yet there, the file-size is 0.
8935 */
apndFileSize(sqlite3_file * pFile,sqlite_int64 * pSize)8936 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
8937   ApndFile *paf = (ApndFile *)pFile;
8938   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
8939   return SQLITE_OK;
8940 }
8941 
8942 /*
8943 ** Lock an apnd-file.
8944 */
apndLock(sqlite3_file * pFile,int eLock)8945 static int apndLock(sqlite3_file *pFile, int eLock){
8946   pFile = ORIGFILE(pFile);
8947   return pFile->pMethods->xLock(pFile, eLock);
8948 }
8949 
8950 /*
8951 ** Unlock an apnd-file.
8952 */
apndUnlock(sqlite3_file * pFile,int eLock)8953 static int apndUnlock(sqlite3_file *pFile, int eLock){
8954   pFile = ORIGFILE(pFile);
8955   return pFile->pMethods->xUnlock(pFile, eLock);
8956 }
8957 
8958 /*
8959 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
8960 */
apndCheckReservedLock(sqlite3_file * pFile,int * pResOut)8961 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
8962   pFile = ORIGFILE(pFile);
8963   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
8964 }
8965 
8966 /*
8967 ** File control method. For custom operations on an apnd-file.
8968 */
apndFileControl(sqlite3_file * pFile,int op,void * pArg)8969 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
8970   ApndFile *paf = (ApndFile *)pFile;
8971   int rc;
8972   pFile = ORIGFILE(pFile);
8973   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
8974   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
8975   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
8976     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
8977   }
8978   return rc;
8979 }
8980 
8981 /*
8982 ** Return the sector-size in bytes for an apnd-file.
8983 */
apndSectorSize(sqlite3_file * pFile)8984 static int apndSectorSize(sqlite3_file *pFile){
8985   pFile = ORIGFILE(pFile);
8986   return pFile->pMethods->xSectorSize(pFile);
8987 }
8988 
8989 /*
8990 ** Return the device characteristic flags supported by an apnd-file.
8991 */
apndDeviceCharacteristics(sqlite3_file * pFile)8992 static int apndDeviceCharacteristics(sqlite3_file *pFile){
8993   pFile = ORIGFILE(pFile);
8994   return pFile->pMethods->xDeviceCharacteristics(pFile);
8995 }
8996 
8997 /* Create a shared memory file mapping */
apndShmMap(sqlite3_file * pFile,int iPg,int pgsz,int bExtend,void volatile ** pp)8998 static int apndShmMap(
8999   sqlite3_file *pFile,
9000   int iPg,
9001   int pgsz,
9002   int bExtend,
9003   void volatile **pp
9004 ){
9005   pFile = ORIGFILE(pFile);
9006   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
9007 }
9008 
9009 /* Perform locking on a shared-memory segment */
apndShmLock(sqlite3_file * pFile,int offset,int n,int flags)9010 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
9011   pFile = ORIGFILE(pFile);
9012   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
9013 }
9014 
9015 /* Memory barrier operation on shared memory */
apndShmBarrier(sqlite3_file * pFile)9016 static void apndShmBarrier(sqlite3_file *pFile){
9017   pFile = ORIGFILE(pFile);
9018   pFile->pMethods->xShmBarrier(pFile);
9019 }
9020 
9021 /* Unmap a shared memory segment */
apndShmUnmap(sqlite3_file * pFile,int deleteFlag)9022 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
9023   pFile = ORIGFILE(pFile);
9024   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
9025 }
9026 
9027 /* Fetch a page of a memory-mapped file */
apndFetch(sqlite3_file * pFile,sqlite3_int64 iOfst,int iAmt,void ** pp)9028 static int apndFetch(
9029   sqlite3_file *pFile,
9030   sqlite3_int64 iOfst,
9031   int iAmt,
9032   void **pp
9033 ){
9034   ApndFile *p = (ApndFile *)pFile;
9035   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
9036     return SQLITE_IOERR; /* Cannot read what is not yet there. */
9037   }
9038   pFile = ORIGFILE(pFile);
9039   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
9040 }
9041 
9042 /* Release a memory-mapped page */
apndUnfetch(sqlite3_file * pFile,sqlite3_int64 iOfst,void * pPage)9043 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
9044   ApndFile *p = (ApndFile *)pFile;
9045   pFile = ORIGFILE(pFile);
9046   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
9047 }
9048 
9049 /*
9050 ** Try to read the append-mark off the end of a file.  Return the
9051 ** start of the appended database if the append-mark is present.
9052 ** If there is no valid append-mark, return -1;
9053 **
9054 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
9055 ** indicates that the appended database contains at least one page.  The
9056 ** start-of-database value must be a multiple of 512.
9057 */
apndReadMark(sqlite3_int64 sz,sqlite3_file * pFile)9058 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
9059   int rc, i;
9060   sqlite3_int64 iMark;
9061   int msbs = 8 * (APND_MARK_FOS_SZ-1);
9062   unsigned char a[APND_MARK_SIZE];
9063 
9064   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
9065   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
9066   if( rc ) return -1;
9067   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
9068   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
9069   for(i=1; i<8; i++){
9070     msbs -= 8;
9071     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
9072   }
9073   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
9074   if( iMark & 0x1ff ) return -1;
9075   return iMark;
9076 }
9077 
9078 static const char apvfsSqliteHdr[] = "SQLite format 3";
9079 /*
9080 ** Check to see if the file is an appendvfs SQLite database file.
9081 ** Return true iff it is such. Parameter sz is the file's size.
9082 */
apndIsAppendvfsDatabase(sqlite3_int64 sz,sqlite3_file * pFile)9083 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
9084   int rc;
9085   char zHdr[16];
9086   sqlite3_int64 iMark = apndReadMark(sz, pFile);
9087   if( iMark>=0 ){
9088     /* If file has the correct end-marker, the expected odd size, and the
9089     ** SQLite DB type marker where the end-marker puts it, then it
9090     ** is an appendvfs database.
9091     */
9092     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
9093     if( SQLITE_OK==rc
9094      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
9095      && (sz & 0x1ff) == APND_MARK_SIZE
9096      && sz>=512+APND_MARK_SIZE
9097     ){
9098       return 1; /* It's an appendvfs database */
9099     }
9100   }
9101   return 0;
9102 }
9103 
9104 /*
9105 ** Check to see if the file is an ordinary SQLite database file.
9106 ** Return true iff so. Parameter sz is the file's size.
9107 */
apndIsOrdinaryDatabaseFile(sqlite3_int64 sz,sqlite3_file * pFile)9108 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
9109   char zHdr[16];
9110   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
9111    || (sz & 0x1ff) != 0
9112    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
9113    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
9114   ){
9115     return 0;
9116   }else{
9117     return 1;
9118   }
9119 }
9120 
9121 /*
9122 ** Open an apnd file handle.
9123 */
apndOpen(sqlite3_vfs * pApndVfs,const char * zName,sqlite3_file * pFile,int flags,int * pOutFlags)9124 static int apndOpen(
9125   sqlite3_vfs *pApndVfs,
9126   const char *zName,
9127   sqlite3_file *pFile,
9128   int flags,
9129   int *pOutFlags
9130 ){
9131   ApndFile *pApndFile = (ApndFile*)pFile;
9132   sqlite3_file *pBaseFile = ORIGFILE(pFile);
9133   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
9134   int rc;
9135   sqlite3_int64 sz = 0;
9136   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
9137     /* The appendvfs is not to be used for transient or temporary databases.
9138     ** Just use the base VFS open to initialize the given file object and
9139     ** open the underlying file. (Appendvfs is then unused for this file.)
9140     */
9141     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
9142   }
9143   memset(pApndFile, 0, sizeof(ApndFile));
9144   pFile->pMethods = &apnd_io_methods;
9145   pApndFile->iMark = -1;    /* Append mark not yet written */
9146 
9147   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
9148   if( rc==SQLITE_OK ){
9149     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
9150     if( rc ){
9151       pBaseFile->pMethods->xClose(pBaseFile);
9152     }
9153   }
9154   if( rc ){
9155     pFile->pMethods = 0;
9156     return rc;
9157   }
9158   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
9159     /* The file being opened appears to be just an ordinary DB. Copy
9160     ** the base dispatch-table so this instance mimics the base VFS.
9161     */
9162     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
9163     return SQLITE_OK;
9164   }
9165   pApndFile->iPgOne = apndReadMark(sz, pFile);
9166   if( pApndFile->iPgOne>=0 ){
9167     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
9168     return SQLITE_OK;
9169   }
9170   if( (flags & SQLITE_OPEN_CREATE)==0 ){
9171     pBaseFile->pMethods->xClose(pBaseFile);
9172     rc = SQLITE_CANTOPEN;
9173     pFile->pMethods = 0;
9174   }else{
9175     /* Round newly added appendvfs location to #define'd page boundary.
9176     ** Note that nothing has yet been written to the underlying file.
9177     ** The append mark will be written along with first content write.
9178     ** Until then, paf->iMark value indicates it is not yet written.
9179     */
9180     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
9181   }
9182   return rc;
9183 }
9184 
9185 /*
9186 ** Delete an apnd file.
9187 ** For an appendvfs, this could mean delete the appendvfs portion,
9188 ** leaving the appendee as it was before it gained an appendvfs.
9189 ** For now, this code deletes the underlying file too.
9190 */
apndDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)9191 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
9192   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
9193 }
9194 
9195 /*
9196 ** All other VFS methods are pass-thrus.
9197 */
apndAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)9198 static int apndAccess(
9199   sqlite3_vfs *pVfs,
9200   const char *zPath,
9201   int flags,
9202   int *pResOut
9203 ){
9204   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
9205 }
apndFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nOut,char * zOut)9206 static int apndFullPathname(
9207   sqlite3_vfs *pVfs,
9208   const char *zPath,
9209   int nOut,
9210   char *zOut
9211 ){
9212   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
9213 }
apndDlOpen(sqlite3_vfs * pVfs,const char * zPath)9214 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
9215   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
9216 }
apndDlError(sqlite3_vfs * pVfs,int nByte,char * zErrMsg)9217 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
9218   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
9219 }
apndDlSym(sqlite3_vfs * pVfs,void * p,const char * zSym)9220 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
9221   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
9222 }
apndDlClose(sqlite3_vfs * pVfs,void * pHandle)9223 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
9224   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
9225 }
apndRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)9226 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
9227   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
9228 }
apndSleep(sqlite3_vfs * pVfs,int nMicro)9229 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
9230   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
9231 }
apndCurrentTime(sqlite3_vfs * pVfs,double * pTimeOut)9232 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
9233   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
9234 }
apndGetLastError(sqlite3_vfs * pVfs,int a,char * b)9235 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
9236   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
9237 }
apndCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * p)9238 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
9239   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
9240 }
apndSetSystemCall(sqlite3_vfs * pVfs,const char * zName,sqlite3_syscall_ptr pCall)9241 static int apndSetSystemCall(
9242   sqlite3_vfs *pVfs,
9243   const char *zName,
9244   sqlite3_syscall_ptr pCall
9245 ){
9246   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
9247 }
apndGetSystemCall(sqlite3_vfs * pVfs,const char * zName)9248 static sqlite3_syscall_ptr apndGetSystemCall(
9249   sqlite3_vfs *pVfs,
9250   const char *zName
9251 ){
9252   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
9253 }
apndNextSystemCall(sqlite3_vfs * pVfs,const char * zName)9254 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
9255   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
9256 }
9257 
9258 
9259 #ifdef _WIN32
9260 
9261 #endif
9262 /*
9263 ** This routine is called when the extension is loaded.
9264 ** Register the new VFS.
9265 */
sqlite3_appendvfs_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)9266 int sqlite3_appendvfs_init(
9267   sqlite3 *db,
9268   char **pzErrMsg,
9269   const sqlite3_api_routines *pApi
9270 ){
9271   int rc = SQLITE_OK;
9272   sqlite3_vfs *pOrig;
9273   SQLITE_EXTENSION_INIT2(pApi);
9274   (void)pzErrMsg;
9275   (void)db;
9276   pOrig = sqlite3_vfs_find(0);
9277   if( pOrig==0 ) return SQLITE_ERROR;
9278   apnd_vfs.iVersion = pOrig->iVersion;
9279   apnd_vfs.pAppData = pOrig;
9280   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
9281   rc = sqlite3_vfs_register(&apnd_vfs, 0);
9282 #ifdef APPENDVFS_TEST
9283   if( rc==SQLITE_OK ){
9284     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
9285   }
9286 #endif
9287   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
9288   return rc;
9289 }
9290 
9291 /************************* End ../ext/misc/appendvfs.c ********************/
9292 #endif
9293 #ifdef SQLITE_HAVE_ZLIB
9294 /************************* Begin ../ext/misc/zipfile.c ******************/
9295 /*
9296 ** 2017-12-26
9297 **
9298 ** The author disclaims copyright to this source code.  In place of
9299 ** a legal notice, here is a blessing:
9300 **
9301 **    May you do good and not evil.
9302 **    May you find forgiveness for yourself and forgive others.
9303 **    May you share freely, never taking more than you give.
9304 **
9305 ******************************************************************************
9306 **
9307 ** This file implements a virtual table for reading and writing ZIP archive
9308 ** files.
9309 **
9310 ** Usage example:
9311 **
9312 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
9313 **
9314 ** Current limitations:
9315 **
9316 **    *  No support for encryption
9317 **    *  No support for ZIP archives spanning multiple files
9318 **    *  No support for zip64 extensions
9319 **    *  Only the "inflate/deflate" (zlib) compression method is supported
9320 */
9321 /* #include "sqlite3ext.h" */
9322 SQLITE_EXTENSION_INIT1
9323 #include <stdio.h>
9324 #include <string.h>
9325 #include <assert.h>
9326 #include <stdint.h>
9327 
9328 #include <zlib.h>
9329 
9330 #ifndef SQLITE_OMIT_VIRTUALTABLE
9331 
9332 #ifndef SQLITE_AMALGAMATION
9333 
9334 #ifndef UINT32_TYPE
9335 # ifdef HAVE_UINT32_T
9336 #  define UINT32_TYPE uint32_t
9337 # else
9338 #  define UINT32_TYPE unsigned int
9339 # endif
9340 #endif
9341 #ifndef UINT16_TYPE
9342 # ifdef HAVE_UINT16_T
9343 #  define UINT16_TYPE uint16_t
9344 # else
9345 #  define UINT16_TYPE unsigned short int
9346 # endif
9347 #endif
9348 /* typedef sqlite3_int64 i64; */
9349 /* typedef unsigned char u8; */
9350 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
9351 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
9352 #define MIN(a,b) ((a)<(b) ? (a) : (b))
9353 
9354 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
9355 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
9356 #endif
9357 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
9358 # define ALWAYS(X)      (1)
9359 # define NEVER(X)       (0)
9360 #elif !defined(NDEBUG)
9361 # define ALWAYS(X)      ((X)?1:(assert(0),0))
9362 # define NEVER(X)       ((X)?(assert(0),1):0)
9363 #else
9364 # define ALWAYS(X)      (X)
9365 # define NEVER(X)       (X)
9366 #endif
9367 
9368 #endif   /* SQLITE_AMALGAMATION */
9369 
9370 /*
9371 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
9372 **
9373 ** In some ways it would be better to obtain these values from system
9374 ** header files. But, the dependency is undesirable and (a) these
9375 ** have been stable for decades, (b) the values are part of POSIX and
9376 ** are also made explicit in [man stat], and (c) are part of the
9377 ** file format for zip archives.
9378 */
9379 #ifndef S_IFDIR
9380 # define S_IFDIR 0040000
9381 #endif
9382 #ifndef S_IFREG
9383 # define S_IFREG 0100000
9384 #endif
9385 #ifndef S_IFLNK
9386 # define S_IFLNK 0120000
9387 #endif
9388 
9389 static const char ZIPFILE_SCHEMA[] =
9390   "CREATE TABLE y("
9391     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
9392     "mode,"              /* 1: POSIX mode for file */
9393     "mtime,"             /* 2: Last modification time (secs since 1970)*/
9394     "sz,"                /* 3: Size of object */
9395     "rawdata,"           /* 4: Raw data */
9396     "data,"              /* 5: Uncompressed data */
9397     "method,"            /* 6: Compression method (integer) */
9398     "z HIDDEN"           /* 7: Name of zip file */
9399   ") WITHOUT ROWID;";
9400 
9401 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
9402 #define ZIPFILE_BUFFER_SIZE (64*1024)
9403 
9404 
9405 /*
9406 ** Magic numbers used to read and write zip files.
9407 **
9408 ** ZIPFILE_NEWENTRY_MADEBY:
9409 **   Use this value for the "version-made-by" field in new zip file
9410 **   entries. The upper byte indicates "unix", and the lower byte
9411 **   indicates that the zip file matches pkzip specification 3.0.
9412 **   This is what info-zip seems to do.
9413 **
9414 ** ZIPFILE_NEWENTRY_REQUIRED:
9415 **   Value for "version-required-to-extract" field of new entries.
9416 **   Version 2.0 is required to support folders and deflate compression.
9417 **
9418 ** ZIPFILE_NEWENTRY_FLAGS:
9419 **   Value for "general-purpose-bit-flags" field of new entries. Bit
9420 **   11 means "utf-8 filename and comment".
9421 **
9422 ** ZIPFILE_SIGNATURE_CDS:
9423 **   First 4 bytes of a valid CDS record.
9424 **
9425 ** ZIPFILE_SIGNATURE_LFH:
9426 **   First 4 bytes of a valid LFH record.
9427 **
9428 ** ZIPFILE_SIGNATURE_EOCD
9429 **   First 4 bytes of a valid EOCD record.
9430 */
9431 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
9432 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
9433 #define ZIPFILE_NEWENTRY_REQUIRED 20
9434 #define ZIPFILE_NEWENTRY_FLAGS    0x800
9435 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
9436 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
9437 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
9438 
9439 /*
9440 ** The sizes of the fixed-size part of each of the three main data
9441 ** structures in a zip archive.
9442 */
9443 #define ZIPFILE_LFH_FIXED_SZ      30
9444 #define ZIPFILE_EOCD_FIXED_SZ     22
9445 #define ZIPFILE_CDS_FIXED_SZ      46
9446 
9447 /*
9448 *** 4.3.16  End of central directory record:
9449 ***
9450 ***   end of central dir signature    4 bytes  (0x06054b50)
9451 ***   number of this disk             2 bytes
9452 ***   number of the disk with the
9453 ***   start of the central directory  2 bytes
9454 ***   total number of entries in the
9455 ***   central directory on this disk  2 bytes
9456 ***   total number of entries in
9457 ***   the central directory           2 bytes
9458 ***   size of the central directory   4 bytes
9459 ***   offset of start of central
9460 ***   directory with respect to
9461 ***   the starting disk number        4 bytes
9462 ***   .ZIP file comment length        2 bytes
9463 ***   .ZIP file comment       (variable size)
9464 */
9465 typedef struct ZipfileEOCD ZipfileEOCD;
9466 struct ZipfileEOCD {
9467   u16 iDisk;
9468   u16 iFirstDisk;
9469   u16 nEntry;
9470   u16 nEntryTotal;
9471   u32 nSize;
9472   u32 iOffset;
9473 };
9474 
9475 /*
9476 *** 4.3.12  Central directory structure:
9477 ***
9478 *** ...
9479 ***
9480 ***   central file header signature   4 bytes  (0x02014b50)
9481 ***   version made by                 2 bytes
9482 ***   version needed to extract       2 bytes
9483 ***   general purpose bit flag        2 bytes
9484 ***   compression method              2 bytes
9485 ***   last mod file time              2 bytes
9486 ***   last mod file date              2 bytes
9487 ***   crc-32                          4 bytes
9488 ***   compressed size                 4 bytes
9489 ***   uncompressed size               4 bytes
9490 ***   file name length                2 bytes
9491 ***   extra field length              2 bytes
9492 ***   file comment length             2 bytes
9493 ***   disk number start               2 bytes
9494 ***   internal file attributes        2 bytes
9495 ***   external file attributes        4 bytes
9496 ***   relative offset of local header 4 bytes
9497 */
9498 typedef struct ZipfileCDS ZipfileCDS;
9499 struct ZipfileCDS {
9500   u16 iVersionMadeBy;
9501   u16 iVersionExtract;
9502   u16 flags;
9503   u16 iCompression;
9504   u16 mTime;
9505   u16 mDate;
9506   u32 crc32;
9507   u32 szCompressed;
9508   u32 szUncompressed;
9509   u16 nFile;
9510   u16 nExtra;
9511   u16 nComment;
9512   u16 iDiskStart;
9513   u16 iInternalAttr;
9514   u32 iExternalAttr;
9515   u32 iOffset;
9516   char *zFile;                    /* Filename (sqlite3_malloc()) */
9517 };
9518 
9519 /*
9520 *** 4.3.7  Local file header:
9521 ***
9522 ***   local file header signature     4 bytes  (0x04034b50)
9523 ***   version needed to extract       2 bytes
9524 ***   general purpose bit flag        2 bytes
9525 ***   compression method              2 bytes
9526 ***   last mod file time              2 bytes
9527 ***   last mod file date              2 bytes
9528 ***   crc-32                          4 bytes
9529 ***   compressed size                 4 bytes
9530 ***   uncompressed size               4 bytes
9531 ***   file name length                2 bytes
9532 ***   extra field length              2 bytes
9533 ***
9534 */
9535 typedef struct ZipfileLFH ZipfileLFH;
9536 struct ZipfileLFH {
9537   u16 iVersionExtract;
9538   u16 flags;
9539   u16 iCompression;
9540   u16 mTime;
9541   u16 mDate;
9542   u32 crc32;
9543   u32 szCompressed;
9544   u32 szUncompressed;
9545   u16 nFile;
9546   u16 nExtra;
9547 };
9548 
9549 typedef struct ZipfileEntry ZipfileEntry;
9550 struct ZipfileEntry {
9551   ZipfileCDS cds;            /* Parsed CDS record */
9552   u32 mUnixTime;             /* Modification time, in UNIX format */
9553   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
9554   i64 iDataOff;              /* Offset to data in file (if aData==0) */
9555   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
9556   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
9557 };
9558 
9559 /*
9560 ** Cursor type for zipfile tables.
9561 */
9562 typedef struct ZipfileCsr ZipfileCsr;
9563 struct ZipfileCsr {
9564   sqlite3_vtab_cursor base;  /* Base class - must be first */
9565   i64 iId;                   /* Cursor ID */
9566   u8 bEof;                   /* True when at EOF */
9567   u8 bNoop;                  /* If next xNext() call is no-op */
9568 
9569   /* Used outside of write transactions */
9570   FILE *pFile;               /* Zip file */
9571   i64 iNextOff;              /* Offset of next record in central directory */
9572   ZipfileEOCD eocd;          /* Parse of central directory record */
9573 
9574   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
9575   ZipfileEntry *pCurrent;    /* Current entry */
9576   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
9577 };
9578 
9579 typedef struct ZipfileTab ZipfileTab;
9580 struct ZipfileTab {
9581   sqlite3_vtab base;         /* Base class - must be first */
9582   char *zFile;               /* Zip file this table accesses (may be NULL) */
9583   sqlite3 *db;               /* Host database connection */
9584   u8 *aBuffer;               /* Temporary buffer used for various tasks */
9585 
9586   ZipfileCsr *pCsrList;      /* List of cursors */
9587   i64 iNextCsrid;
9588 
9589   /* The following are used by write transactions only */
9590   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
9591   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
9592   FILE *pWriteFd;            /* File handle open on zip archive */
9593   i64 szCurrent;             /* Current size of zip archive */
9594   i64 szOrig;                /* Size of archive at start of transaction */
9595 };
9596 
9597 /*
9598 ** Set the error message contained in context ctx to the results of
9599 ** vprintf(zFmt, ...).
9600 */
zipfileCtxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)9601 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
9602   char *zMsg = 0;
9603   va_list ap;
9604   va_start(ap, zFmt);
9605   zMsg = sqlite3_vmprintf(zFmt, ap);
9606   sqlite3_result_error(ctx, zMsg, -1);
9607   sqlite3_free(zMsg);
9608   va_end(ap);
9609 }
9610 
9611 /*
9612 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
9613 ** is not quoted, do nothing.
9614 */
zipfileDequote(char * zIn)9615 static void zipfileDequote(char *zIn){
9616   char q = zIn[0];
9617   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
9618     int iIn = 1;
9619     int iOut = 0;
9620     if( q=='[' ) q = ']';
9621     while( ALWAYS(zIn[iIn]) ){
9622       char c = zIn[iIn++];
9623       if( c==q && zIn[iIn++]!=q ) break;
9624       zIn[iOut++] = c;
9625     }
9626     zIn[iOut] = '\0';
9627   }
9628 }
9629 
9630 /*
9631 ** Construct a new ZipfileTab virtual table object.
9632 **
9633 **   argv[0]   -> module name  ("zipfile")
9634 **   argv[1]   -> database name
9635 **   argv[2]   -> table name
9636 **   argv[...] -> "column name" and other module argument fields.
9637 */
zipfileConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)9638 static int zipfileConnect(
9639   sqlite3 *db,
9640   void *pAux,
9641   int argc, const char *const*argv,
9642   sqlite3_vtab **ppVtab,
9643   char **pzErr
9644 ){
9645   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
9646   int nFile = 0;
9647   const char *zFile = 0;
9648   ZipfileTab *pNew = 0;
9649   int rc;
9650   (void)pAux;
9651 
9652   /* If the table name is not "zipfile", require that the argument be
9653   ** specified. This stops zipfile tables from being created as:
9654   **
9655   **   CREATE VIRTUAL TABLE zzz USING zipfile();
9656   **
9657   ** It does not prevent:
9658   **
9659   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
9660   */
9661   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
9662   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
9663     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
9664     return SQLITE_ERROR;
9665   }
9666 
9667   if( argc>3 ){
9668     zFile = argv[3];
9669     nFile = (int)strlen(zFile)+1;
9670   }
9671 
9672   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
9673   if( rc==SQLITE_OK ){
9674     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
9675     if( pNew==0 ) return SQLITE_NOMEM;
9676     memset(pNew, 0, nByte+nFile);
9677     pNew->db = db;
9678     pNew->aBuffer = (u8*)&pNew[1];
9679     if( zFile ){
9680       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
9681       memcpy(pNew->zFile, zFile, nFile);
9682       zipfileDequote(pNew->zFile);
9683     }
9684   }
9685   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
9686   *ppVtab = (sqlite3_vtab*)pNew;
9687   return rc;
9688 }
9689 
9690 /*
9691 ** Free the ZipfileEntry structure indicated by the only argument.
9692 */
zipfileEntryFree(ZipfileEntry * p)9693 static void zipfileEntryFree(ZipfileEntry *p){
9694   if( p ){
9695     sqlite3_free(p->cds.zFile);
9696     sqlite3_free(p);
9697   }
9698 }
9699 
9700 /*
9701 ** Release resources that should be freed at the end of a write
9702 ** transaction.
9703 */
zipfileCleanupTransaction(ZipfileTab * pTab)9704 static void zipfileCleanupTransaction(ZipfileTab *pTab){
9705   ZipfileEntry *pEntry;
9706   ZipfileEntry *pNext;
9707 
9708   if( pTab->pWriteFd ){
9709     fclose(pTab->pWriteFd);
9710     pTab->pWriteFd = 0;
9711   }
9712   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
9713     pNext = pEntry->pNext;
9714     zipfileEntryFree(pEntry);
9715   }
9716   pTab->pFirstEntry = 0;
9717   pTab->pLastEntry = 0;
9718   pTab->szCurrent = 0;
9719   pTab->szOrig = 0;
9720 }
9721 
9722 /*
9723 ** This method is the destructor for zipfile vtab objects.
9724 */
zipfileDisconnect(sqlite3_vtab * pVtab)9725 static int zipfileDisconnect(sqlite3_vtab *pVtab){
9726   zipfileCleanupTransaction((ZipfileTab*)pVtab);
9727   sqlite3_free(pVtab);
9728   return SQLITE_OK;
9729 }
9730 
9731 /*
9732 ** Constructor for a new ZipfileCsr object.
9733 */
zipfileOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCsr)9734 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
9735   ZipfileTab *pTab = (ZipfileTab*)p;
9736   ZipfileCsr *pCsr;
9737   pCsr = sqlite3_malloc(sizeof(*pCsr));
9738   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
9739   if( pCsr==0 ){
9740     return SQLITE_NOMEM;
9741   }
9742   memset(pCsr, 0, sizeof(*pCsr));
9743   pCsr->iId = ++pTab->iNextCsrid;
9744   pCsr->pCsrNext = pTab->pCsrList;
9745   pTab->pCsrList = pCsr;
9746   return SQLITE_OK;
9747 }
9748 
9749 /*
9750 ** Reset a cursor back to the state it was in when first returned
9751 ** by zipfileOpen().
9752 */
zipfileResetCursor(ZipfileCsr * pCsr)9753 static void zipfileResetCursor(ZipfileCsr *pCsr){
9754   ZipfileEntry *p;
9755   ZipfileEntry *pNext;
9756 
9757   pCsr->bEof = 0;
9758   if( pCsr->pFile ){
9759     fclose(pCsr->pFile);
9760     pCsr->pFile = 0;
9761     zipfileEntryFree(pCsr->pCurrent);
9762     pCsr->pCurrent = 0;
9763   }
9764 
9765   for(p=pCsr->pFreeEntry; p; p=pNext){
9766     pNext = p->pNext;
9767     zipfileEntryFree(p);
9768   }
9769 }
9770 
9771 /*
9772 ** Destructor for an ZipfileCsr.
9773 */
zipfileClose(sqlite3_vtab_cursor * cur)9774 static int zipfileClose(sqlite3_vtab_cursor *cur){
9775   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9776   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
9777   ZipfileCsr **pp;
9778   zipfileResetCursor(pCsr);
9779 
9780   /* Remove this cursor from the ZipfileTab.pCsrList list. */
9781   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
9782   *pp = pCsr->pCsrNext;
9783 
9784   sqlite3_free(pCsr);
9785   return SQLITE_OK;
9786 }
9787 
9788 /*
9789 ** Set the error message for the virtual table associated with cursor
9790 ** pCsr to the results of vprintf(zFmt, ...).
9791 */
zipfileTableErr(ZipfileTab * pTab,const char * zFmt,...)9792 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
9793   va_list ap;
9794   va_start(ap, zFmt);
9795   sqlite3_free(pTab->base.zErrMsg);
9796   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
9797   va_end(ap);
9798 }
zipfileCursorErr(ZipfileCsr * pCsr,const char * zFmt,...)9799 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
9800   va_list ap;
9801   va_start(ap, zFmt);
9802   sqlite3_free(pCsr->base.pVtab->zErrMsg);
9803   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
9804   va_end(ap);
9805 }
9806 
9807 /*
9808 ** Read nRead bytes of data from offset iOff of file pFile into buffer
9809 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
9810 ** otherwise.
9811 **
9812 ** If an error does occur, output variable (*pzErrmsg) may be set to point
9813 ** to an English language error message. It is the responsibility of the
9814 ** caller to eventually free this buffer using
9815 ** sqlite3_free().
9816 */
zipfileReadData(FILE * pFile,u8 * aRead,int nRead,i64 iOff,char ** pzErrmsg)9817 static int zipfileReadData(
9818   FILE *pFile,                    /* Read from this file */
9819   u8 *aRead,                      /* Read into this buffer */
9820   int nRead,                      /* Number of bytes to read */
9821   i64 iOff,                       /* Offset to read from */
9822   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
9823 ){
9824   size_t n;
9825   fseek(pFile, (long)iOff, SEEK_SET);
9826   n = fread(aRead, 1, nRead, pFile);
9827   if( (int)n!=nRead ){
9828     *pzErrmsg = sqlite3_mprintf("error in fread()");
9829     return SQLITE_ERROR;
9830   }
9831   return SQLITE_OK;
9832 }
9833 
zipfileAppendData(ZipfileTab * pTab,const u8 * aWrite,int nWrite)9834 static int zipfileAppendData(
9835   ZipfileTab *pTab,
9836   const u8 *aWrite,
9837   int nWrite
9838 ){
9839   if( nWrite>0 ){
9840     size_t n = nWrite;
9841     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
9842     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
9843     if( (int)n!=nWrite ){
9844       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
9845       return SQLITE_ERROR;
9846     }
9847     pTab->szCurrent += nWrite;
9848   }
9849   return SQLITE_OK;
9850 }
9851 
9852 /*
9853 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9854 */
zipfileGetU16(const u8 * aBuf)9855 static u16 zipfileGetU16(const u8 *aBuf){
9856   return (aBuf[1] << 8) + aBuf[0];
9857 }
9858 
9859 /*
9860 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9861 */
zipfileGetU32(const u8 * aBuf)9862 static u32 zipfileGetU32(const u8 *aBuf){
9863   if( aBuf==0 ) return 0;
9864   return ((u32)(aBuf[3]) << 24)
9865        + ((u32)(aBuf[2]) << 16)
9866        + ((u32)(aBuf[1]) <<  8)
9867        + ((u32)(aBuf[0]) <<  0);
9868 }
9869 
9870 /*
9871 ** Write a 16-bit little endiate integer into buffer aBuf.
9872 */
zipfilePutU16(u8 * aBuf,u16 val)9873 static void zipfilePutU16(u8 *aBuf, u16 val){
9874   aBuf[0] = val & 0xFF;
9875   aBuf[1] = (val>>8) & 0xFF;
9876 }
9877 
9878 /*
9879 ** Write a 32-bit little endiate integer into buffer aBuf.
9880 */
zipfilePutU32(u8 * aBuf,u32 val)9881 static void zipfilePutU32(u8 *aBuf, u32 val){
9882   aBuf[0] = val & 0xFF;
9883   aBuf[1] = (val>>8) & 0xFF;
9884   aBuf[2] = (val>>16) & 0xFF;
9885   aBuf[3] = (val>>24) & 0xFF;
9886 }
9887 
9888 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9889 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9890 
9891 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
9892 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
9893 
9894 /*
9895 ** Magic numbers used to read CDS records.
9896 */
9897 #define ZIPFILE_CDS_NFILE_OFF        28
9898 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
9899 
9900 /*
9901 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
9902 ** if the record is not well-formed, or SQLITE_OK otherwise.
9903 */
zipfileReadCDS(u8 * aBuf,ZipfileCDS * pCDS)9904 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
9905   u8 *aRead = aBuf;
9906   u32 sig = zipfileRead32(aRead);
9907   int rc = SQLITE_OK;
9908   if( sig!=ZIPFILE_SIGNATURE_CDS ){
9909     rc = SQLITE_ERROR;
9910   }else{
9911     pCDS->iVersionMadeBy = zipfileRead16(aRead);
9912     pCDS->iVersionExtract = zipfileRead16(aRead);
9913     pCDS->flags = zipfileRead16(aRead);
9914     pCDS->iCompression = zipfileRead16(aRead);
9915     pCDS->mTime = zipfileRead16(aRead);
9916     pCDS->mDate = zipfileRead16(aRead);
9917     pCDS->crc32 = zipfileRead32(aRead);
9918     pCDS->szCompressed = zipfileRead32(aRead);
9919     pCDS->szUncompressed = zipfileRead32(aRead);
9920     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
9921     pCDS->nFile = zipfileRead16(aRead);
9922     pCDS->nExtra = zipfileRead16(aRead);
9923     pCDS->nComment = zipfileRead16(aRead);
9924     pCDS->iDiskStart = zipfileRead16(aRead);
9925     pCDS->iInternalAttr = zipfileRead16(aRead);
9926     pCDS->iExternalAttr = zipfileRead32(aRead);
9927     pCDS->iOffset = zipfileRead32(aRead);
9928     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
9929   }
9930 
9931   return rc;
9932 }
9933 
9934 /*
9935 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
9936 ** if the record is not well-formed, or SQLITE_OK otherwise.
9937 */
zipfileReadLFH(u8 * aBuffer,ZipfileLFH * pLFH)9938 static int zipfileReadLFH(
9939   u8 *aBuffer,
9940   ZipfileLFH *pLFH
9941 ){
9942   u8 *aRead = aBuffer;
9943   int rc = SQLITE_OK;
9944 
9945   u32 sig = zipfileRead32(aRead);
9946   if( sig!=ZIPFILE_SIGNATURE_LFH ){
9947     rc = SQLITE_ERROR;
9948   }else{
9949     pLFH->iVersionExtract = zipfileRead16(aRead);
9950     pLFH->flags = zipfileRead16(aRead);
9951     pLFH->iCompression = zipfileRead16(aRead);
9952     pLFH->mTime = zipfileRead16(aRead);
9953     pLFH->mDate = zipfileRead16(aRead);
9954     pLFH->crc32 = zipfileRead32(aRead);
9955     pLFH->szCompressed = zipfileRead32(aRead);
9956     pLFH->szUncompressed = zipfileRead32(aRead);
9957     pLFH->nFile = zipfileRead16(aRead);
9958     pLFH->nExtra = zipfileRead16(aRead);
9959   }
9960   return rc;
9961 }
9962 
9963 
9964 /*
9965 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
9966 ** Scan through this buffer to find an "extra-timestamp" field. If one
9967 ** exists, extract the 32-bit modification-timestamp from it and store
9968 ** the value in output parameter *pmTime.
9969 **
9970 ** Zero is returned if no extra-timestamp record could be found (and so
9971 ** *pmTime is left unchanged), or non-zero otherwise.
9972 **
9973 ** The general format of an extra field is:
9974 **
9975 **   Header ID    2 bytes
9976 **   Data Size    2 bytes
9977 **   Data         N bytes
9978 */
zipfileScanExtra(u8 * aExtra,int nExtra,u32 * pmTime)9979 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
9980   int ret = 0;
9981   u8 *p = aExtra;
9982   u8 *pEnd = &aExtra[nExtra];
9983 
9984   while( p<pEnd ){
9985     u16 id = zipfileRead16(p);
9986     u16 nByte = zipfileRead16(p);
9987 
9988     switch( id ){
9989       case ZIPFILE_EXTRA_TIMESTAMP: {
9990         u8 b = p[0];
9991         if( b & 0x01 ){     /* 0x01 -> modtime is present */
9992           *pmTime = zipfileGetU32(&p[1]);
9993           ret = 1;
9994         }
9995         break;
9996       }
9997     }
9998 
9999     p += nByte;
10000   }
10001   return ret;
10002 }
10003 
10004 /*
10005 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10006 ** fields of the CDS structure passed as the only argument to a 32-bit
10007 ** UNIX seconds-since-the-epoch timestamp. Return the result.
10008 **
10009 ** "Standard" MS-DOS time format:
10010 **
10011 **   File modification time:
10012 **     Bits 00-04: seconds divided by 2
10013 **     Bits 05-10: minute
10014 **     Bits 11-15: hour
10015 **   File modification date:
10016 **     Bits 00-04: day
10017 **     Bits 05-08: month (1-12)
10018 **     Bits 09-15: years from 1980
10019 **
10020 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10021 */
zipfileMtime(ZipfileCDS * pCDS)10022 static u32 zipfileMtime(ZipfileCDS *pCDS){
10023   int Y,M,D,X1,X2,A,B,sec,min,hr;
10024   i64 JDsec;
10025   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
10026   M = ((pCDS->mDate >> 5) & 0x0F);
10027   D = (pCDS->mDate & 0x1F);
10028   sec = (pCDS->mTime & 0x1F)*2;
10029   min = (pCDS->mTime >> 5) & 0x3F;
10030   hr = (pCDS->mTime >> 11) & 0x1F;
10031   if( M<=2 ){
10032     Y--;
10033     M += 12;
10034   }
10035   X1 = 36525*(Y+4716)/100;
10036   X2 = 306001*(M+1)/10000;
10037   A = Y/100;
10038   B = 2 - A + (A/4);
10039   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
10040   return (u32)(JDsec - (i64)24405875*(i64)8640);
10041 }
10042 
10043 /*
10044 ** The opposite of zipfileMtime(). This function populates the mTime and
10045 ** mDate fields of the CDS structure passed as the first argument according
10046 ** to the UNIX timestamp value passed as the second.
10047 */
zipfileMtimeToDos(ZipfileCDS * pCds,u32 mUnixTime)10048 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
10049   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
10050   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
10051 
10052   int A, B, C, D, E;
10053   int yr, mon, day;
10054   int hr, min, sec;
10055 
10056   A = (int)((JD - 1867216.25)/36524.25);
10057   A = (int)(JD + 1 + A - (A/4));
10058   B = A + 1524;
10059   C = (int)((B - 122.1)/365.25);
10060   D = (36525*(C&32767))/100;
10061   E = (int)((B-D)/30.6001);
10062 
10063   day = B - D - (int)(30.6001*E);
10064   mon = (E<14 ? E-1 : E-13);
10065   yr = mon>2 ? C-4716 : C-4715;
10066 
10067   hr = (mUnixTime % (24*60*60)) / (60*60);
10068   min = (mUnixTime % (60*60)) / 60;
10069   sec = (mUnixTime % 60);
10070 
10071   if( yr>=1980 ){
10072     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
10073     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
10074   }else{
10075     pCds->mDate = pCds->mTime = 0;
10076   }
10077 
10078   assert( mUnixTime<315507600
10079        || mUnixTime==zipfileMtime(pCds)
10080        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
10081        /* || (mUnixTime % 2) */
10082   );
10083 }
10084 
10085 /*
10086 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
10087 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
10088 ** then pFile is a file-handle open on a zip file. In either case, this
10089 ** function creates a ZipfileEntry object based on the zip archive entry
10090 ** for which the CDS record is at offset iOff.
10091 **
10092 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
10093 ** the new object. Otherwise, an SQLite error code is returned and the
10094 ** final value of (*ppEntry) undefined.
10095 */
zipfileGetEntry(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,i64 iOff,ZipfileEntry ** ppEntry)10096 static int zipfileGetEntry(
10097   ZipfileTab *pTab,               /* Store any error message here */
10098   const u8 *aBlob,                /* Pointer to in-memory file image */
10099   int nBlob,                      /* Size of aBlob[] in bytes */
10100   FILE *pFile,                    /* If aBlob==0, read from this file */
10101   i64 iOff,                       /* Offset of CDS record */
10102   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
10103 ){
10104   u8 *aRead;
10105   char **pzErr = &pTab->base.zErrMsg;
10106   int rc = SQLITE_OK;
10107   (void)nBlob;
10108 
10109   if( aBlob==0 ){
10110     aRead = pTab->aBuffer;
10111     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
10112   }else{
10113     aRead = (u8*)&aBlob[iOff];
10114   }
10115 
10116   if( rc==SQLITE_OK ){
10117     sqlite3_int64 nAlloc;
10118     ZipfileEntry *pNew;
10119 
10120     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
10121     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
10122     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
10123 
10124     nAlloc = sizeof(ZipfileEntry) + nExtra;
10125     if( aBlob ){
10126       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
10127     }
10128 
10129     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
10130     if( pNew==0 ){
10131       rc = SQLITE_NOMEM;
10132     }else{
10133       memset(pNew, 0, sizeof(ZipfileEntry));
10134       rc = zipfileReadCDS(aRead, &pNew->cds);
10135       if( rc!=SQLITE_OK ){
10136         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
10137       }else if( aBlob==0 ){
10138         rc = zipfileReadData(
10139             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
10140         );
10141       }else{
10142         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
10143       }
10144     }
10145 
10146     if( rc==SQLITE_OK ){
10147       u32 *pt = &pNew->mUnixTime;
10148       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
10149       pNew->aExtra = (u8*)&pNew[1];
10150       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
10151       if( pNew->cds.zFile==0 ){
10152         rc = SQLITE_NOMEM;
10153       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
10154         pNew->mUnixTime = zipfileMtime(&pNew->cds);
10155       }
10156     }
10157 
10158     if( rc==SQLITE_OK ){
10159       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
10160       ZipfileLFH lfh;
10161       if( pFile ){
10162         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
10163       }else{
10164         aRead = (u8*)&aBlob[pNew->cds.iOffset];
10165       }
10166 
10167       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
10168       if( rc==SQLITE_OK ){
10169         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
10170         pNew->iDataOff += lfh.nFile + lfh.nExtra;
10171         if( aBlob && pNew->cds.szCompressed ){
10172           pNew->aData = &pNew->aExtra[nExtra];
10173           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
10174         }
10175       }else{
10176         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
10177             (int)pNew->cds.iOffset
10178         );
10179       }
10180     }
10181 
10182     if( rc!=SQLITE_OK ){
10183       zipfileEntryFree(pNew);
10184     }else{
10185       *ppEntry = pNew;
10186     }
10187   }
10188 
10189   return rc;
10190 }
10191 
10192 /*
10193 ** Advance an ZipfileCsr to its next row of output.
10194 */
zipfileNext(sqlite3_vtab_cursor * cur)10195 static int zipfileNext(sqlite3_vtab_cursor *cur){
10196   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10197   int rc = SQLITE_OK;
10198 
10199   if( pCsr->pFile ){
10200     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
10201     zipfileEntryFree(pCsr->pCurrent);
10202     pCsr->pCurrent = 0;
10203     if( pCsr->iNextOff>=iEof ){
10204       pCsr->bEof = 1;
10205     }else{
10206       ZipfileEntry *p = 0;
10207       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
10208       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
10209       if( rc==SQLITE_OK ){
10210         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
10211         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
10212       }
10213       pCsr->pCurrent = p;
10214     }
10215   }else{
10216     if( !pCsr->bNoop ){
10217       pCsr->pCurrent = pCsr->pCurrent->pNext;
10218     }
10219     if( pCsr->pCurrent==0 ){
10220       pCsr->bEof = 1;
10221     }
10222   }
10223 
10224   pCsr->bNoop = 0;
10225   return rc;
10226 }
10227 
zipfileFree(void * p)10228 static void zipfileFree(void *p) {
10229   sqlite3_free(p);
10230 }
10231 
10232 /*
10233 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
10234 ** size is nOut bytes. This function uncompresses the data and sets the
10235 ** return value in context pCtx to the result (a blob).
10236 **
10237 ** If an error occurs, an error code is left in pCtx instead.
10238 */
zipfileInflate(sqlite3_context * pCtx,const u8 * aIn,int nIn,int nOut)10239 static void zipfileInflate(
10240   sqlite3_context *pCtx,          /* Store result here */
10241   const u8 *aIn,                  /* Compressed data */
10242   int nIn,                        /* Size of buffer aIn[] in bytes */
10243   int nOut                        /* Expected output size */
10244 ){
10245   u8 *aRes = sqlite3_malloc(nOut);
10246   if( aRes==0 ){
10247     sqlite3_result_error_nomem(pCtx);
10248   }else{
10249     int err;
10250     z_stream str;
10251     memset(&str, 0, sizeof(str));
10252 
10253     str.next_in = (Byte*)aIn;
10254     str.avail_in = nIn;
10255     str.next_out = (Byte*)aRes;
10256     str.avail_out = nOut;
10257 
10258     err = inflateInit2(&str, -15);
10259     if( err!=Z_OK ){
10260       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
10261     }else{
10262       err = inflate(&str, Z_NO_FLUSH);
10263       if( err!=Z_STREAM_END ){
10264         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
10265       }else{
10266         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
10267         aRes = 0;
10268       }
10269     }
10270     sqlite3_free(aRes);
10271     inflateEnd(&str);
10272   }
10273 }
10274 
10275 /*
10276 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
10277 ** compresses it and sets (*ppOut) to point to a buffer containing the
10278 ** compressed data. The caller is responsible for eventually calling
10279 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
10280 ** is set to the size of buffer (*ppOut) in bytes.
10281 **
10282 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
10283 ** code is returned and an error message left in virtual-table handle
10284 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
10285 ** case.
10286 */
zipfileDeflate(const u8 * aIn,int nIn,u8 ** ppOut,int * pnOut,char ** pzErr)10287 static int zipfileDeflate(
10288   const u8 *aIn, int nIn,         /* Input */
10289   u8 **ppOut, int *pnOut,         /* Output */
10290   char **pzErr                    /* OUT: Error message */
10291 ){
10292   int rc = SQLITE_OK;
10293   sqlite3_int64 nAlloc;
10294   z_stream str;
10295   u8 *aOut;
10296 
10297   memset(&str, 0, sizeof(str));
10298   str.next_in = (Bytef*)aIn;
10299   str.avail_in = nIn;
10300   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
10301 
10302   nAlloc = deflateBound(&str, nIn);
10303   aOut = (u8*)sqlite3_malloc64(nAlloc);
10304   if( aOut==0 ){
10305     rc = SQLITE_NOMEM;
10306   }else{
10307     int res;
10308     str.next_out = aOut;
10309     str.avail_out = nAlloc;
10310     res = deflate(&str, Z_FINISH);
10311     if( res==Z_STREAM_END ){
10312       *ppOut = aOut;
10313       *pnOut = (int)str.total_out;
10314     }else{
10315       sqlite3_free(aOut);
10316       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
10317       rc = SQLITE_ERROR;
10318     }
10319     deflateEnd(&str);
10320   }
10321 
10322   return rc;
10323 }
10324 
10325 
10326 /*
10327 ** Return values of columns for the row at which the series_cursor
10328 ** is currently pointing.
10329 */
zipfileColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)10330 static int zipfileColumn(
10331   sqlite3_vtab_cursor *cur,   /* The cursor */
10332   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
10333   int i                       /* Which column to return */
10334 ){
10335   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10336   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
10337   int rc = SQLITE_OK;
10338   switch( i ){
10339     case 0:   /* name */
10340       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
10341       break;
10342     case 1:   /* mode */
10343       /* TODO: Whether or not the following is correct surely depends on
10344       ** the platform on which the archive was created.  */
10345       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
10346       break;
10347     case 2: { /* mtime */
10348       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
10349       break;
10350     }
10351     case 3: { /* sz */
10352       if( sqlite3_vtab_nochange(ctx)==0 ){
10353         sqlite3_result_int64(ctx, pCDS->szUncompressed);
10354       }
10355       break;
10356     }
10357     case 4:   /* rawdata */
10358       if( sqlite3_vtab_nochange(ctx) ) break;
10359     case 5: { /* data */
10360       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
10361         int sz = pCDS->szCompressed;
10362         int szFinal = pCDS->szUncompressed;
10363         if( szFinal>0 ){
10364           u8 *aBuf;
10365           u8 *aFree = 0;
10366           if( pCsr->pCurrent->aData ){
10367             aBuf = pCsr->pCurrent->aData;
10368           }else{
10369             aBuf = aFree = sqlite3_malloc64(sz);
10370             if( aBuf==0 ){
10371               rc = SQLITE_NOMEM;
10372             }else{
10373               FILE *pFile = pCsr->pFile;
10374               if( pFile==0 ){
10375                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
10376               }
10377               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
10378                   &pCsr->base.pVtab->zErrMsg
10379               );
10380             }
10381           }
10382           if( rc==SQLITE_OK ){
10383             if( i==5 && pCDS->iCompression ){
10384               zipfileInflate(ctx, aBuf, sz, szFinal);
10385             }else{
10386               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
10387             }
10388           }
10389           sqlite3_free(aFree);
10390         }else{
10391           /* Figure out if this is a directory or a zero-sized file. Consider
10392           ** it to be a directory either if the mode suggests so, or if
10393           ** the final character in the name is '/'.  */
10394           u32 mode = pCDS->iExternalAttr >> 16;
10395           if( !(mode & S_IFDIR)
10396            && pCDS->nFile>=1
10397            && pCDS->zFile[pCDS->nFile-1]!='/'
10398           ){
10399             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
10400           }
10401         }
10402       }
10403       break;
10404     }
10405     case 6:   /* method */
10406       sqlite3_result_int(ctx, pCDS->iCompression);
10407       break;
10408     default:  /* z */
10409       assert( i==7 );
10410       sqlite3_result_int64(ctx, pCsr->iId);
10411       break;
10412   }
10413 
10414   return rc;
10415 }
10416 
10417 /*
10418 ** Return TRUE if the cursor is at EOF.
10419 */
zipfileEof(sqlite3_vtab_cursor * cur)10420 static int zipfileEof(sqlite3_vtab_cursor *cur){
10421   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10422   return pCsr->bEof;
10423 }
10424 
10425 /*
10426 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
10427 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
10428 ** is guaranteed to be a file-handle open on a zip file.
10429 **
10430 ** This function attempts to locate the EOCD record within the zip archive
10431 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
10432 ** returned if successful. Otherwise, an SQLite error code is returned and
10433 ** an English language error message may be left in virtual-table pTab.
10434 */
zipfileReadEOCD(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,ZipfileEOCD * pEOCD)10435 static int zipfileReadEOCD(
10436   ZipfileTab *pTab,               /* Return errors here */
10437   const u8 *aBlob,                /* Pointer to in-memory file image */
10438   int nBlob,                      /* Size of aBlob[] in bytes */
10439   FILE *pFile,                    /* Read from this file if aBlob==0 */
10440   ZipfileEOCD *pEOCD              /* Object to populate */
10441 ){
10442   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
10443   int nRead;                      /* Bytes to read from file */
10444   int rc = SQLITE_OK;
10445 
10446   memset(pEOCD, 0, sizeof(ZipfileEOCD));
10447   if( aBlob==0 ){
10448     i64 iOff;                     /* Offset to read from */
10449     i64 szFile;                   /* Total size of file in bytes */
10450     fseek(pFile, 0, SEEK_END);
10451     szFile = (i64)ftell(pFile);
10452     if( szFile==0 ){
10453       return SQLITE_OK;
10454     }
10455     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
10456     iOff = szFile - nRead;
10457     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
10458   }else{
10459     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
10460     aRead = (u8*)&aBlob[nBlob-nRead];
10461   }
10462 
10463   if( rc==SQLITE_OK ){
10464     int i;
10465 
10466     /* Scan backwards looking for the signature bytes */
10467     for(i=nRead-20; i>=0; i--){
10468       if( aRead[i]==0x50 && aRead[i+1]==0x4b
10469        && aRead[i+2]==0x05 && aRead[i+3]==0x06
10470       ){
10471         break;
10472       }
10473     }
10474     if( i<0 ){
10475       pTab->base.zErrMsg = sqlite3_mprintf(
10476           "cannot find end of central directory record"
10477       );
10478       return SQLITE_ERROR;
10479     }
10480 
10481     aRead += i+4;
10482     pEOCD->iDisk = zipfileRead16(aRead);
10483     pEOCD->iFirstDisk = zipfileRead16(aRead);
10484     pEOCD->nEntry = zipfileRead16(aRead);
10485     pEOCD->nEntryTotal = zipfileRead16(aRead);
10486     pEOCD->nSize = zipfileRead32(aRead);
10487     pEOCD->iOffset = zipfileRead32(aRead);
10488   }
10489 
10490   return rc;
10491 }
10492 
10493 /*
10494 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
10495 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
10496 ** to the end of the list. Otherwise, it is added to the list immediately
10497 ** before pBefore (which is guaranteed to be a part of said list).
10498 */
zipfileAddEntry(ZipfileTab * pTab,ZipfileEntry * pBefore,ZipfileEntry * pNew)10499 static void zipfileAddEntry(
10500   ZipfileTab *pTab,
10501   ZipfileEntry *pBefore,
10502   ZipfileEntry *pNew
10503 ){
10504   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
10505   assert( pNew->pNext==0 );
10506   if( pBefore==0 ){
10507     if( pTab->pFirstEntry==0 ){
10508       pTab->pFirstEntry = pTab->pLastEntry = pNew;
10509     }else{
10510       assert( pTab->pLastEntry->pNext==0 );
10511       pTab->pLastEntry->pNext = pNew;
10512       pTab->pLastEntry = pNew;
10513     }
10514   }else{
10515     ZipfileEntry **pp;
10516     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
10517     pNew->pNext = pBefore;
10518     *pp = pNew;
10519   }
10520 }
10521 
zipfileLoadDirectory(ZipfileTab * pTab,const u8 * aBlob,int nBlob)10522 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
10523   ZipfileEOCD eocd;
10524   int rc;
10525   int i;
10526   i64 iOff;
10527 
10528   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
10529   iOff = eocd.iOffset;
10530   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
10531     ZipfileEntry *pNew = 0;
10532     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
10533 
10534     if( rc==SQLITE_OK ){
10535       zipfileAddEntry(pTab, 0, pNew);
10536       iOff += ZIPFILE_CDS_FIXED_SZ;
10537       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
10538     }
10539   }
10540   return rc;
10541 }
10542 
10543 /*
10544 ** xFilter callback.
10545 */
zipfileFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)10546 static int zipfileFilter(
10547   sqlite3_vtab_cursor *cur,
10548   int idxNum, const char *idxStr,
10549   int argc, sqlite3_value **argv
10550 ){
10551   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
10552   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10553   const char *zFile = 0;          /* Zip file to scan */
10554   int rc = SQLITE_OK;             /* Return Code */
10555   int bInMemory = 0;              /* True for an in-memory zipfile */
10556 
10557   (void)idxStr;
10558   (void)argc;
10559 
10560   zipfileResetCursor(pCsr);
10561 
10562   if( pTab->zFile ){
10563     zFile = pTab->zFile;
10564   }else if( idxNum==0 ){
10565     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
10566     return SQLITE_ERROR;
10567   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
10568     static const u8 aEmptyBlob = 0;
10569     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
10570     int nBlob = sqlite3_value_bytes(argv[0]);
10571     assert( pTab->pFirstEntry==0 );
10572     if( aBlob==0 ){
10573       aBlob = &aEmptyBlob;
10574       nBlob = 0;
10575     }
10576     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
10577     pCsr->pFreeEntry = pTab->pFirstEntry;
10578     pTab->pFirstEntry = pTab->pLastEntry = 0;
10579     if( rc!=SQLITE_OK ) return rc;
10580     bInMemory = 1;
10581   }else{
10582     zFile = (const char*)sqlite3_value_text(argv[0]);
10583   }
10584 
10585   if( 0==pTab->pWriteFd && 0==bInMemory ){
10586     pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
10587     if( pCsr->pFile==0 ){
10588       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
10589       rc = SQLITE_ERROR;
10590     }else{
10591       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
10592       if( rc==SQLITE_OK ){
10593         if( pCsr->eocd.nEntry==0 ){
10594           pCsr->bEof = 1;
10595         }else{
10596           pCsr->iNextOff = pCsr->eocd.iOffset;
10597           rc = zipfileNext(cur);
10598         }
10599       }
10600     }
10601   }else{
10602     pCsr->bNoop = 1;
10603     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
10604     rc = zipfileNext(cur);
10605   }
10606 
10607   return rc;
10608 }
10609 
10610 /*
10611 ** xBestIndex callback.
10612 */
zipfileBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)10613 static int zipfileBestIndex(
10614   sqlite3_vtab *tab,
10615   sqlite3_index_info *pIdxInfo
10616 ){
10617   int i;
10618   int idx = -1;
10619   int unusable = 0;
10620   (void)tab;
10621 
10622   for(i=0; i<pIdxInfo->nConstraint; i++){
10623     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
10624     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
10625     if( pCons->usable==0 ){
10626       unusable = 1;
10627     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10628       idx = i;
10629     }
10630   }
10631   pIdxInfo->estimatedCost = 1000.0;
10632   if( idx>=0 ){
10633     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
10634     pIdxInfo->aConstraintUsage[idx].omit = 1;
10635     pIdxInfo->idxNum = 1;
10636   }else if( unusable ){
10637     return SQLITE_CONSTRAINT;
10638   }
10639   return SQLITE_OK;
10640 }
10641 
zipfileNewEntry(const char * zPath)10642 static ZipfileEntry *zipfileNewEntry(const char *zPath){
10643   ZipfileEntry *pNew;
10644   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
10645   if( pNew ){
10646     memset(pNew, 0, sizeof(ZipfileEntry));
10647     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
10648     if( pNew->cds.zFile==0 ){
10649       sqlite3_free(pNew);
10650       pNew = 0;
10651     }
10652   }
10653   return pNew;
10654 }
10655 
zipfileSerializeLFH(ZipfileEntry * pEntry,u8 * aBuf)10656 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
10657   ZipfileCDS *pCds = &pEntry->cds;
10658   u8 *a = aBuf;
10659 
10660   pCds->nExtra = 9;
10661 
10662   /* Write the LFH itself */
10663   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
10664   zipfileWrite16(a, pCds->iVersionExtract);
10665   zipfileWrite16(a, pCds->flags);
10666   zipfileWrite16(a, pCds->iCompression);
10667   zipfileWrite16(a, pCds->mTime);
10668   zipfileWrite16(a, pCds->mDate);
10669   zipfileWrite32(a, pCds->crc32);
10670   zipfileWrite32(a, pCds->szCompressed);
10671   zipfileWrite32(a, pCds->szUncompressed);
10672   zipfileWrite16(a, (u16)pCds->nFile);
10673   zipfileWrite16(a, pCds->nExtra);
10674   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
10675 
10676   /* Add the file name */
10677   memcpy(a, pCds->zFile, (int)pCds->nFile);
10678   a += (int)pCds->nFile;
10679 
10680   /* The "extra" data */
10681   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
10682   zipfileWrite16(a, 5);
10683   *a++ = 0x01;
10684   zipfileWrite32(a, pEntry->mUnixTime);
10685 
10686   return a-aBuf;
10687 }
10688 
zipfileAppendEntry(ZipfileTab * pTab,ZipfileEntry * pEntry,const u8 * pData,int nData)10689 static int zipfileAppendEntry(
10690   ZipfileTab *pTab,
10691   ZipfileEntry *pEntry,
10692   const u8 *pData,
10693   int nData
10694 ){
10695   u8 *aBuf = pTab->aBuffer;
10696   int nBuf;
10697   int rc;
10698 
10699   nBuf = zipfileSerializeLFH(pEntry, aBuf);
10700   rc = zipfileAppendData(pTab, aBuf, nBuf);
10701   if( rc==SQLITE_OK ){
10702     pEntry->iDataOff = pTab->szCurrent;
10703     rc = zipfileAppendData(pTab, pData, nData);
10704   }
10705 
10706   return rc;
10707 }
10708 
zipfileGetMode(sqlite3_value * pVal,int bIsDir,u32 * pMode,char ** pzErr)10709 static int zipfileGetMode(
10710   sqlite3_value *pVal,
10711   int bIsDir,                     /* If true, default to directory */
10712   u32 *pMode,                     /* OUT: Mode value */
10713   char **pzErr                    /* OUT: Error message */
10714 ){
10715   const char *z = (const char*)sqlite3_value_text(pVal);
10716   u32 mode = 0;
10717   if( z==0 ){
10718     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
10719   }else if( z[0]>='0' && z[0]<='9' ){
10720     mode = (unsigned int)sqlite3_value_int(pVal);
10721   }else{
10722     const char zTemplate[11] = "-rwxrwxrwx";
10723     int i;
10724     if( strlen(z)!=10 ) goto parse_error;
10725     switch( z[0] ){
10726       case '-': mode |= S_IFREG; break;
10727       case 'd': mode |= S_IFDIR; break;
10728       case 'l': mode |= S_IFLNK; break;
10729       default: goto parse_error;
10730     }
10731     for(i=1; i<10; i++){
10732       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
10733       else if( z[i]!='-' ) goto parse_error;
10734     }
10735   }
10736   if( ((mode & S_IFDIR)==0)==bIsDir ){
10737     /* The "mode" attribute is a directory, but data has been specified.
10738     ** Or vice-versa - no data but "mode" is a file or symlink.  */
10739     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
10740     return SQLITE_CONSTRAINT;
10741   }
10742   *pMode = mode;
10743   return SQLITE_OK;
10744 
10745  parse_error:
10746   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
10747   return SQLITE_ERROR;
10748 }
10749 
10750 /*
10751 ** Both (const char*) arguments point to nul-terminated strings. Argument
10752 ** nB is the value of strlen(zB). This function returns 0 if the strings are
10753 ** identical, ignoring any trailing '/' character in either path.  */
zipfileComparePath(const char * zA,const char * zB,int nB)10754 static int zipfileComparePath(const char *zA, const char *zB, int nB){
10755   int nA = (int)strlen(zA);
10756   if( nA>0 && zA[nA-1]=='/' ) nA--;
10757   if( nB>0 && zB[nB-1]=='/' ) nB--;
10758   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
10759   return 1;
10760 }
10761 
zipfileBegin(sqlite3_vtab * pVtab)10762 static int zipfileBegin(sqlite3_vtab *pVtab){
10763   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10764   int rc = SQLITE_OK;
10765 
10766   assert( pTab->pWriteFd==0 );
10767   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
10768     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
10769     return SQLITE_ERROR;
10770   }
10771 
10772   /* Open a write fd on the file. Also load the entire central directory
10773   ** structure into memory. During the transaction any new file data is
10774   ** appended to the archive file, but the central directory is accumulated
10775   ** in main-memory until the transaction is committed.  */
10776   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
10777   if( pTab->pWriteFd==0 ){
10778     pTab->base.zErrMsg = sqlite3_mprintf(
10779         "zipfile: failed to open file %s for writing", pTab->zFile
10780         );
10781     rc = SQLITE_ERROR;
10782   }else{
10783     fseek(pTab->pWriteFd, 0, SEEK_END);
10784     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
10785     rc = zipfileLoadDirectory(pTab, 0, 0);
10786   }
10787 
10788   if( rc!=SQLITE_OK ){
10789     zipfileCleanupTransaction(pTab);
10790   }
10791 
10792   return rc;
10793 }
10794 
10795 /*
10796 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10797 ** time(2)).
10798 */
zipfileTime(void)10799 static u32 zipfileTime(void){
10800   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
10801   u32 ret;
10802   if( pVfs==0 ) return 0;
10803   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
10804     i64 ms;
10805     pVfs->xCurrentTimeInt64(pVfs, &ms);
10806     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
10807   }else{
10808     double day;
10809     pVfs->xCurrentTime(pVfs, &day);
10810     ret = (u32)((day - 2440587.5) * 86400);
10811   }
10812   return ret;
10813 }
10814 
10815 /*
10816 ** Return a 32-bit timestamp in UNIX epoch format.
10817 **
10818 ** If the value passed as the only argument is either NULL or an SQL NULL,
10819 ** return the current time. Otherwise, return the value stored in (*pVal)
10820 ** cast to a 32-bit unsigned integer.
10821 */
zipfileGetTime(sqlite3_value * pVal)10822 static u32 zipfileGetTime(sqlite3_value *pVal){
10823   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
10824     return zipfileTime();
10825   }
10826   return (u32)sqlite3_value_int64(pVal);
10827 }
10828 
10829 /*
10830 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10831 ** linked list.  Remove it from the list and free the object.
10832 */
zipfileRemoveEntryFromList(ZipfileTab * pTab,ZipfileEntry * pOld)10833 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
10834   if( pOld ){
10835     if( pTab->pFirstEntry==pOld ){
10836       pTab->pFirstEntry = pOld->pNext;
10837       if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
10838     }else{
10839       ZipfileEntry *p;
10840       for(p=pTab->pFirstEntry; p; p=p->pNext){
10841         if( p->pNext==pOld ){
10842           p->pNext = pOld->pNext;
10843           if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
10844           break;
10845         }
10846       }
10847     }
10848     zipfileEntryFree(pOld);
10849   }
10850 }
10851 
10852 /*
10853 ** xUpdate method.
10854 */
zipfileUpdate(sqlite3_vtab * pVtab,int nVal,sqlite3_value ** apVal,sqlite_int64 * pRowid)10855 static int zipfileUpdate(
10856   sqlite3_vtab *pVtab,
10857   int nVal,
10858   sqlite3_value **apVal,
10859   sqlite_int64 *pRowid
10860 ){
10861   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10862   int rc = SQLITE_OK;             /* Return Code */
10863   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
10864 
10865   u32 mode = 0;                   /* Mode for new entry */
10866   u32 mTime = 0;                  /* Modification time for new entry */
10867   i64 sz = 0;                     /* Uncompressed size */
10868   const char *zPath = 0;          /* Path for new entry */
10869   int nPath = 0;                  /* strlen(zPath) */
10870   const u8 *pData = 0;            /* Pointer to buffer containing content */
10871   int nData = 0;                  /* Size of pData buffer in bytes */
10872   int iMethod = 0;                /* Compression method for new entry */
10873   u8 *pFree = 0;                  /* Free this */
10874   char *zFree = 0;                /* Also free this */
10875   ZipfileEntry *pOld = 0;
10876   ZipfileEntry *pOld2 = 0;
10877   int bUpdate = 0;                /* True for an update that modifies "name" */
10878   int bIsDir = 0;
10879   u32 iCrc32 = 0;
10880 
10881   (void)pRowid;
10882 
10883   if( pTab->pWriteFd==0 ){
10884     rc = zipfileBegin(pVtab);
10885     if( rc!=SQLITE_OK ) return rc;
10886   }
10887 
10888   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
10889   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
10890     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
10891     int nDelete = (int)strlen(zDelete);
10892     if( nVal>1 ){
10893       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
10894       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
10895         bUpdate = 1;
10896       }
10897     }
10898     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
10899       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
10900         break;
10901       }
10902       assert( pOld->pNext );
10903     }
10904   }
10905 
10906   if( nVal>1 ){
10907     /* Check that "sz" and "rawdata" are both NULL: */
10908     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
10909       zipfileTableErr(pTab, "sz must be NULL");
10910       rc = SQLITE_CONSTRAINT;
10911     }
10912     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
10913       zipfileTableErr(pTab, "rawdata must be NULL");
10914       rc = SQLITE_CONSTRAINT;
10915     }
10916 
10917     if( rc==SQLITE_OK ){
10918       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
10919         /* data=NULL. A directory */
10920         bIsDir = 1;
10921       }else{
10922         /* Value specified for "data", and possibly "method". This must be
10923         ** a regular file or a symlink. */
10924         const u8 *aIn = sqlite3_value_blob(apVal[7]);
10925         int nIn = sqlite3_value_bytes(apVal[7]);
10926         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
10927 
10928         iMethod = sqlite3_value_int(apVal[8]);
10929         sz = nIn;
10930         pData = aIn;
10931         nData = nIn;
10932         if( iMethod!=0 && iMethod!=8 ){
10933           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
10934           rc = SQLITE_CONSTRAINT;
10935         }else{
10936           if( bAuto || iMethod ){
10937             int nCmp;
10938             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
10939             if( rc==SQLITE_OK ){
10940               if( iMethod || nCmp<nIn ){
10941                 iMethod = 8;
10942                 pData = pFree;
10943                 nData = nCmp;
10944               }
10945             }
10946           }
10947           iCrc32 = crc32(0, aIn, nIn);
10948         }
10949       }
10950     }
10951 
10952     if( rc==SQLITE_OK ){
10953       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
10954     }
10955 
10956     if( rc==SQLITE_OK ){
10957       zPath = (const char*)sqlite3_value_text(apVal[2]);
10958       if( zPath==0 ) zPath = "";
10959       nPath = (int)strlen(zPath);
10960       mTime = zipfileGetTime(apVal[4]);
10961     }
10962 
10963     if( rc==SQLITE_OK && bIsDir ){
10964       /* For a directory, check that the last character in the path is a
10965       ** '/'. This appears to be required for compatibility with info-zip
10966       ** (the unzip command on unix). It does not create directories
10967       ** otherwise.  */
10968       if( nPath<=0 || zPath[nPath-1]!='/' ){
10969         zFree = sqlite3_mprintf("%s/", zPath);
10970         zPath = (const char*)zFree;
10971         if( zFree==0 ){
10972           rc = SQLITE_NOMEM;
10973           nPath = 0;
10974         }else{
10975           nPath = (int)strlen(zPath);
10976         }
10977       }
10978     }
10979 
10980     /* Check that we're not inserting a duplicate entry -OR- updating an
10981     ** entry with a path, thereby making it into a duplicate. */
10982     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
10983       ZipfileEntry *p;
10984       for(p=pTab->pFirstEntry; p; p=p->pNext){
10985         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
10986           switch( sqlite3_vtab_on_conflict(pTab->db) ){
10987             case SQLITE_IGNORE: {
10988               goto zipfile_update_done;
10989             }
10990             case SQLITE_REPLACE: {
10991               pOld2 = p;
10992               break;
10993             }
10994             default: {
10995               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
10996               rc = SQLITE_CONSTRAINT;
10997               break;
10998             }
10999           }
11000           break;
11001         }
11002       }
11003     }
11004 
11005     if( rc==SQLITE_OK ){
11006       /* Create the new CDS record. */
11007       pNew = zipfileNewEntry(zPath);
11008       if( pNew==0 ){
11009         rc = SQLITE_NOMEM;
11010       }else{
11011         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11012         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11013         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11014         pNew->cds.iCompression = (u16)iMethod;
11015         zipfileMtimeToDos(&pNew->cds, mTime);
11016         pNew->cds.crc32 = iCrc32;
11017         pNew->cds.szCompressed = nData;
11018         pNew->cds.szUncompressed = (u32)sz;
11019         pNew->cds.iExternalAttr = (mode<<16);
11020         pNew->cds.iOffset = (u32)pTab->szCurrent;
11021         pNew->cds.nFile = (u16)nPath;
11022         pNew->mUnixTime = (u32)mTime;
11023         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
11024         zipfileAddEntry(pTab, pOld, pNew);
11025       }
11026     }
11027   }
11028 
11029   if( rc==SQLITE_OK && (pOld || pOld2) ){
11030     ZipfileCsr *pCsr;
11031     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11032       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
11033         pCsr->pCurrent = pCsr->pCurrent->pNext;
11034         pCsr->bNoop = 1;
11035       }
11036     }
11037 
11038     zipfileRemoveEntryFromList(pTab, pOld);
11039     zipfileRemoveEntryFromList(pTab, pOld2);
11040   }
11041 
11042 zipfile_update_done:
11043   sqlite3_free(pFree);
11044   sqlite3_free(zFree);
11045   return rc;
11046 }
11047 
zipfileSerializeEOCD(ZipfileEOCD * p,u8 * aBuf)11048 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
11049   u8 *a = aBuf;
11050   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
11051   zipfileWrite16(a, p->iDisk);
11052   zipfileWrite16(a, p->iFirstDisk);
11053   zipfileWrite16(a, p->nEntry);
11054   zipfileWrite16(a, p->nEntryTotal);
11055   zipfileWrite32(a, p->nSize);
11056   zipfileWrite32(a, p->iOffset);
11057   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
11058 
11059   return a-aBuf;
11060 }
11061 
zipfileAppendEOCD(ZipfileTab * pTab,ZipfileEOCD * p)11062 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
11063   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
11064   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
11065   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
11066 }
11067 
11068 /*
11069 ** Serialize the CDS structure into buffer aBuf[]. Return the number
11070 ** of bytes written.
11071 */
zipfileSerializeCDS(ZipfileEntry * pEntry,u8 * aBuf)11072 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
11073   u8 *a = aBuf;
11074   ZipfileCDS *pCDS = &pEntry->cds;
11075 
11076   if( pEntry->aExtra==0 ){
11077     pCDS->nExtra = 9;
11078   }
11079 
11080   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
11081   zipfileWrite16(a, pCDS->iVersionMadeBy);
11082   zipfileWrite16(a, pCDS->iVersionExtract);
11083   zipfileWrite16(a, pCDS->flags);
11084   zipfileWrite16(a, pCDS->iCompression);
11085   zipfileWrite16(a, pCDS->mTime);
11086   zipfileWrite16(a, pCDS->mDate);
11087   zipfileWrite32(a, pCDS->crc32);
11088   zipfileWrite32(a, pCDS->szCompressed);
11089   zipfileWrite32(a, pCDS->szUncompressed);
11090   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
11091   zipfileWrite16(a, pCDS->nFile);
11092   zipfileWrite16(a, pCDS->nExtra);
11093   zipfileWrite16(a, pCDS->nComment);
11094   zipfileWrite16(a, pCDS->iDiskStart);
11095   zipfileWrite16(a, pCDS->iInternalAttr);
11096   zipfileWrite32(a, pCDS->iExternalAttr);
11097   zipfileWrite32(a, pCDS->iOffset);
11098 
11099   memcpy(a, pCDS->zFile, pCDS->nFile);
11100   a += pCDS->nFile;
11101 
11102   if( pEntry->aExtra ){
11103     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
11104     memcpy(a, pEntry->aExtra, n);
11105     a += n;
11106   }else{
11107     assert( pCDS->nExtra==9 );
11108     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
11109     zipfileWrite16(a, 5);
11110     *a++ = 0x01;
11111     zipfileWrite32(a, pEntry->mUnixTime);
11112   }
11113 
11114   return a-aBuf;
11115 }
11116 
zipfileCommit(sqlite3_vtab * pVtab)11117 static int zipfileCommit(sqlite3_vtab *pVtab){
11118   ZipfileTab *pTab = (ZipfileTab*)pVtab;
11119   int rc = SQLITE_OK;
11120   if( pTab->pWriteFd ){
11121     i64 iOffset = pTab->szCurrent;
11122     ZipfileEntry *p;
11123     ZipfileEOCD eocd;
11124     int nEntry = 0;
11125 
11126     /* Write out all entries */
11127     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
11128       int n = zipfileSerializeCDS(p, pTab->aBuffer);
11129       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
11130       nEntry++;
11131     }
11132 
11133     /* Write out the EOCD record */
11134     eocd.iDisk = 0;
11135     eocd.iFirstDisk = 0;
11136     eocd.nEntry = (u16)nEntry;
11137     eocd.nEntryTotal = (u16)nEntry;
11138     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
11139     eocd.iOffset = (u32)iOffset;
11140     rc = zipfileAppendEOCD(pTab, &eocd);
11141 
11142     zipfileCleanupTransaction(pTab);
11143   }
11144   return rc;
11145 }
11146 
zipfileRollback(sqlite3_vtab * pVtab)11147 static int zipfileRollback(sqlite3_vtab *pVtab){
11148   return zipfileCommit(pVtab);
11149 }
11150 
zipfileFindCursor(ZipfileTab * pTab,i64 iId)11151 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
11152   ZipfileCsr *pCsr;
11153   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11154     if( iId==pCsr->iId ) break;
11155   }
11156   return pCsr;
11157 }
11158 
zipfileFunctionCds(sqlite3_context * context,int argc,sqlite3_value ** argv)11159 static void zipfileFunctionCds(
11160   sqlite3_context *context,
11161   int argc,
11162   sqlite3_value **argv
11163 ){
11164   ZipfileCsr *pCsr;
11165   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
11166   assert( argc>0 );
11167 
11168   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
11169   if( pCsr ){
11170     ZipfileCDS *p = &pCsr->pCurrent->cds;
11171     char *zRes = sqlite3_mprintf("{"
11172         "\"version-made-by\" : %u, "
11173         "\"version-to-extract\" : %u, "
11174         "\"flags\" : %u, "
11175         "\"compression\" : %u, "
11176         "\"time\" : %u, "
11177         "\"date\" : %u, "
11178         "\"crc32\" : %u, "
11179         "\"compressed-size\" : %u, "
11180         "\"uncompressed-size\" : %u, "
11181         "\"file-name-length\" : %u, "
11182         "\"extra-field-length\" : %u, "
11183         "\"file-comment-length\" : %u, "
11184         "\"disk-number-start\" : %u, "
11185         "\"internal-attr\" : %u, "
11186         "\"external-attr\" : %u, "
11187         "\"offset\" : %u }",
11188         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
11189         (u32)p->flags, (u32)p->iCompression,
11190         (u32)p->mTime, (u32)p->mDate,
11191         (u32)p->crc32, (u32)p->szCompressed,
11192         (u32)p->szUncompressed, (u32)p->nFile,
11193         (u32)p->nExtra, (u32)p->nComment,
11194         (u32)p->iDiskStart, (u32)p->iInternalAttr,
11195         (u32)p->iExternalAttr, (u32)p->iOffset
11196     );
11197 
11198     if( zRes==0 ){
11199       sqlite3_result_error_nomem(context);
11200     }else{
11201       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
11202       sqlite3_free(zRes);
11203     }
11204   }
11205 }
11206 
11207 /*
11208 ** xFindFunction method.
11209 */
zipfileFindFunction(sqlite3_vtab * pVtab,int nArg,const char * zName,void (** pxFunc)(sqlite3_context *,int,sqlite3_value **),void ** ppArg)11210 static int zipfileFindFunction(
11211   sqlite3_vtab *pVtab,            /* Virtual table handle */
11212   int nArg,                       /* Number of SQL function arguments */
11213   const char *zName,              /* Name of SQL function */
11214   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
11215   void **ppArg                    /* OUT: User data for *pxFunc */
11216 ){
11217   (void)nArg;
11218   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
11219     *pxFunc = zipfileFunctionCds;
11220     *ppArg = (void*)pVtab;
11221     return 1;
11222   }
11223   return 0;
11224 }
11225 
11226 typedef struct ZipfileBuffer ZipfileBuffer;
11227 struct ZipfileBuffer {
11228   u8 *a;                          /* Pointer to buffer */
11229   int n;                          /* Size of buffer in bytes */
11230   int nAlloc;                     /* Byte allocated at a[] */
11231 };
11232 
11233 typedef struct ZipfileCtx ZipfileCtx;
11234 struct ZipfileCtx {
11235   int nEntry;
11236   ZipfileBuffer body;
11237   ZipfileBuffer cds;
11238 };
11239 
zipfileBufferGrow(ZipfileBuffer * pBuf,int nByte)11240 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
11241   if( pBuf->n+nByte>pBuf->nAlloc ){
11242     u8 *aNew;
11243     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
11244     int nReq = pBuf->n + nByte;
11245 
11246     while( nNew<nReq ) nNew = nNew*2;
11247     aNew = sqlite3_realloc64(pBuf->a, nNew);
11248     if( aNew==0 ) return SQLITE_NOMEM;
11249     pBuf->a = aNew;
11250     pBuf->nAlloc = (int)nNew;
11251   }
11252   return SQLITE_OK;
11253 }
11254 
11255 /*
11256 ** xStep() callback for the zipfile() aggregate. This can be called in
11257 ** any of the following ways:
11258 **
11259 **   SELECT zipfile(name,data) ...
11260 **   SELECT zipfile(name,mode,mtime,data) ...
11261 **   SELECT zipfile(name,mode,mtime,data,method) ...
11262 */
zipfileStep(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)11263 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
11264   ZipfileCtx *p;                  /* Aggregate function context */
11265   ZipfileEntry e;                 /* New entry to add to zip archive */
11266 
11267   sqlite3_value *pName = 0;
11268   sqlite3_value *pMode = 0;
11269   sqlite3_value *pMtime = 0;
11270   sqlite3_value *pData = 0;
11271   sqlite3_value *pMethod = 0;
11272 
11273   int bIsDir = 0;
11274   u32 mode;
11275   int rc = SQLITE_OK;
11276   char *zErr = 0;
11277 
11278   int iMethod = -1;               /* Compression method to use (0 or 8) */
11279 
11280   const u8 *aData = 0;            /* Possibly compressed data for new entry */
11281   int nData = 0;                  /* Size of aData[] in bytes */
11282   int szUncompressed = 0;         /* Size of data before compression */
11283   u8 *aFree = 0;                  /* Free this before returning */
11284   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
11285 
11286   char *zName = 0;                /* Path (name) of new entry */
11287   int nName = 0;                  /* Size of zName in bytes */
11288   char *zFree = 0;                /* Free this before returning */
11289   int nByte;
11290 
11291   memset(&e, 0, sizeof(e));
11292   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11293   if( p==0 ) return;
11294 
11295   /* Martial the arguments into stack variables */
11296   if( nVal!=2 && nVal!=4 && nVal!=5 ){
11297     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
11298     rc = SQLITE_ERROR;
11299     goto zipfile_step_out;
11300   }
11301   pName = apVal[0];
11302   if( nVal==2 ){
11303     pData = apVal[1];
11304   }else{
11305     pMode = apVal[1];
11306     pMtime = apVal[2];
11307     pData = apVal[3];
11308     if( nVal==5 ){
11309       pMethod = apVal[4];
11310     }
11311   }
11312 
11313   /* Check that the 'name' parameter looks ok. */
11314   zName = (char*)sqlite3_value_text(pName);
11315   nName = sqlite3_value_bytes(pName);
11316   if( zName==0 ){
11317     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
11318     rc = SQLITE_ERROR;
11319     goto zipfile_step_out;
11320   }
11321 
11322   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
11323   ** deflate compression) or NULL (choose automatically).  */
11324   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
11325     iMethod = (int)sqlite3_value_int64(pMethod);
11326     if( iMethod!=0 && iMethod!=8 ){
11327       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
11328       rc = SQLITE_ERROR;
11329       goto zipfile_step_out;
11330     }
11331   }
11332 
11333   /* Now inspect the data. If this is NULL, then the new entry must be a
11334   ** directory.  Otherwise, figure out whether or not the data should
11335   ** be deflated or simply stored in the zip archive. */
11336   if( sqlite3_value_type(pData)==SQLITE_NULL ){
11337     bIsDir = 1;
11338     iMethod = 0;
11339   }else{
11340     aData = sqlite3_value_blob(pData);
11341     szUncompressed = nData = sqlite3_value_bytes(pData);
11342     iCrc32 = crc32(0, aData, nData);
11343     if( iMethod<0 || iMethod==8 ){
11344       int nOut = 0;
11345       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
11346       if( rc!=SQLITE_OK ){
11347         goto zipfile_step_out;
11348       }
11349       if( iMethod==8 || nOut<nData ){
11350         aData = aFree;
11351         nData = nOut;
11352         iMethod = 8;
11353       }else{
11354         iMethod = 0;
11355       }
11356     }
11357   }
11358 
11359   /* Decode the "mode" argument. */
11360   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
11361   if( rc ) goto zipfile_step_out;
11362 
11363   /* Decode the "mtime" argument. */
11364   e.mUnixTime = zipfileGetTime(pMtime);
11365 
11366   /* If this is a directory entry, ensure that there is exactly one '/'
11367   ** at the end of the path. Or, if this is not a directory and the path
11368   ** ends in '/' it is an error. */
11369   if( bIsDir==0 ){
11370     if( nName>0 && zName[nName-1]=='/' ){
11371       zErr = sqlite3_mprintf("non-directory name must not end with /");
11372       rc = SQLITE_ERROR;
11373       goto zipfile_step_out;
11374     }
11375   }else{
11376     if( nName==0 || zName[nName-1]!='/' ){
11377       zName = zFree = sqlite3_mprintf("%s/", zName);
11378       if( zName==0 ){
11379         rc = SQLITE_NOMEM;
11380         goto zipfile_step_out;
11381       }
11382       nName = (int)strlen(zName);
11383     }else{
11384       while( nName>1 && zName[nName-2]=='/' ) nName--;
11385     }
11386   }
11387 
11388   /* Assemble the ZipfileEntry object for the new zip archive entry */
11389   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11390   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11391   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11392   e.cds.iCompression = (u16)iMethod;
11393   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
11394   e.cds.crc32 = iCrc32;
11395   e.cds.szCompressed = nData;
11396   e.cds.szUncompressed = szUncompressed;
11397   e.cds.iExternalAttr = (mode<<16);
11398   e.cds.iOffset = p->body.n;
11399   e.cds.nFile = (u16)nName;
11400   e.cds.zFile = zName;
11401 
11402   /* Append the LFH to the body of the new archive */
11403   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
11404   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
11405   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
11406 
11407   /* Append the data to the body of the new archive */
11408   if( nData>0 ){
11409     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
11410     memcpy(&p->body.a[p->body.n], aData, nData);
11411     p->body.n += nData;
11412   }
11413 
11414   /* Append the CDS record to the directory of the new archive */
11415   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
11416   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
11417   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
11418 
11419   /* Increment the count of entries in the archive */
11420   p->nEntry++;
11421 
11422  zipfile_step_out:
11423   sqlite3_free(aFree);
11424   sqlite3_free(zFree);
11425   if( rc ){
11426     if( zErr ){
11427       sqlite3_result_error(pCtx, zErr, -1);
11428     }else{
11429       sqlite3_result_error_code(pCtx, rc);
11430     }
11431   }
11432   sqlite3_free(zErr);
11433 }
11434 
11435 /*
11436 ** xFinalize() callback for zipfile aggregate function.
11437 */
zipfileFinal(sqlite3_context * pCtx)11438 static void zipfileFinal(sqlite3_context *pCtx){
11439   ZipfileCtx *p;
11440   ZipfileEOCD eocd;
11441   sqlite3_int64 nZip;
11442   u8 *aZip;
11443 
11444   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11445   if( p==0 ) return;
11446   if( p->nEntry>0 ){
11447     memset(&eocd, 0, sizeof(eocd));
11448     eocd.nEntry = (u16)p->nEntry;
11449     eocd.nEntryTotal = (u16)p->nEntry;
11450     eocd.nSize = p->cds.n;
11451     eocd.iOffset = p->body.n;
11452 
11453     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
11454     aZip = (u8*)sqlite3_malloc64(nZip);
11455     if( aZip==0 ){
11456       sqlite3_result_error_nomem(pCtx);
11457     }else{
11458       memcpy(aZip, p->body.a, p->body.n);
11459       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
11460       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
11461       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
11462     }
11463   }
11464 
11465   sqlite3_free(p->body.a);
11466   sqlite3_free(p->cds.a);
11467 }
11468 
11469 
11470 /*
11471 ** Register the "zipfile" virtual table.
11472 */
zipfileRegister(sqlite3 * db)11473 static int zipfileRegister(sqlite3 *db){
11474   static sqlite3_module zipfileModule = {
11475     1,                         /* iVersion */
11476     zipfileConnect,            /* xCreate */
11477     zipfileConnect,            /* xConnect */
11478     zipfileBestIndex,          /* xBestIndex */
11479     zipfileDisconnect,         /* xDisconnect */
11480     zipfileDisconnect,         /* xDestroy */
11481     zipfileOpen,               /* xOpen - open a cursor */
11482     zipfileClose,              /* xClose - close a cursor */
11483     zipfileFilter,             /* xFilter - configure scan constraints */
11484     zipfileNext,               /* xNext - advance a cursor */
11485     zipfileEof,                /* xEof - check for end of scan */
11486     zipfileColumn,             /* xColumn - read data */
11487     0,                         /* xRowid - read data */
11488     zipfileUpdate,             /* xUpdate */
11489     zipfileBegin,              /* xBegin */
11490     0,                         /* xSync */
11491     zipfileCommit,             /* xCommit */
11492     zipfileRollback,           /* xRollback */
11493     zipfileFindFunction,       /* xFindMethod */
11494     0,                         /* xRename */
11495     0,                         /* xSavepoint */
11496     0,                         /* xRelease */
11497     0,                         /* xRollback */
11498     0,                         /* xShadowName */
11499     0                          /* xIntegrity */
11500   };
11501 
11502   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
11503   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
11504   if( rc==SQLITE_OK ){
11505     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
11506         zipfileStep, zipfileFinal
11507     );
11508   }
11509   assert( sizeof(i64)==8 );
11510   assert( sizeof(u32)==4 );
11511   assert( sizeof(u16)==2 );
11512   assert( sizeof(u8)==1 );
11513   return rc;
11514 }
11515 #else         /* SQLITE_OMIT_VIRTUALTABLE */
11516 # define zipfileRegister(x) SQLITE_OK
11517 #endif
11518 
11519 #ifdef _WIN32
11520 
11521 #endif
sqlite3_zipfile_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)11522 int sqlite3_zipfile_init(
11523   sqlite3 *db,
11524   char **pzErrMsg,
11525   const sqlite3_api_routines *pApi
11526 ){
11527   SQLITE_EXTENSION_INIT2(pApi);
11528   (void)pzErrMsg;  /* Unused parameter */
11529   return zipfileRegister(db);
11530 }
11531 
11532 /************************* End ../ext/misc/zipfile.c ********************/
11533 /************************* Begin ../ext/misc/sqlar.c ******************/
11534 /*
11535 ** 2017-12-17
11536 **
11537 ** The author disclaims copyright to this source code.  In place of
11538 ** a legal notice, here is a blessing:
11539 **
11540 **    May you do good and not evil.
11541 **    May you find forgiveness for yourself and forgive others.
11542 **    May you share freely, never taking more than you give.
11543 **
11544 ******************************************************************************
11545 **
11546 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
11547 ** for working with sqlar archives and used by the shell tool's built-in
11548 ** sqlar support.
11549 */
11550 /* #include "sqlite3ext.h" */
11551 SQLITE_EXTENSION_INIT1
11552 #include <zlib.h>
11553 #include <assert.h>
11554 
11555 /*
11556 ** Implementation of the "sqlar_compress(X)" SQL function.
11557 **
11558 ** If the type of X is SQLITE_BLOB, and compressing that blob using
11559 ** zlib utility function compress() yields a smaller blob, return the
11560 ** compressed blob. Otherwise, return a copy of X.
11561 **
11562 ** SQLar uses the "zlib format" for compressed content.  The zlib format
11563 ** contains a two-byte identification header and a four-byte checksum at
11564 ** the end.  This is different from ZIP which uses the raw deflate format.
11565 **
11566 ** Future enhancements to SQLar might add support for new compression formats.
11567 ** If so, those new formats will be identified by alternative headers in the
11568 ** compressed data.
11569 */
sqlarCompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)11570 static void sqlarCompressFunc(
11571   sqlite3_context *context,
11572   int argc,
11573   sqlite3_value **argv
11574 ){
11575   assert( argc==1 );
11576   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
11577     const Bytef *pData = sqlite3_value_blob(argv[0]);
11578     uLong nData = sqlite3_value_bytes(argv[0]);
11579     uLongf nOut = compressBound(nData);
11580     Bytef *pOut;
11581 
11582     pOut = (Bytef*)sqlite3_malloc(nOut);
11583     if( pOut==0 ){
11584       sqlite3_result_error_nomem(context);
11585       return;
11586     }else{
11587       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
11588         sqlite3_result_error(context, "error in compress()", -1);
11589       }else if( nOut<nData ){
11590         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
11591       }else{
11592         sqlite3_result_value(context, argv[0]);
11593       }
11594       sqlite3_free(pOut);
11595     }
11596   }else{
11597     sqlite3_result_value(context, argv[0]);
11598   }
11599 }
11600 
11601 /*
11602 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
11603 **
11604 ** Parameter SZ is interpreted as an integer. If it is less than or
11605 ** equal to zero, then this function returns a copy of X. Or, if
11606 ** SZ is equal to the size of X when interpreted as a blob, also
11607 ** return a copy of X. Otherwise, decompress blob X using zlib
11608 ** utility function uncompress() and return the results (another
11609 ** blob).
11610 */
sqlarUncompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)11611 static void sqlarUncompressFunc(
11612   sqlite3_context *context,
11613   int argc,
11614   sqlite3_value **argv
11615 ){
11616   uLong nData;
11617   uLongf sz;
11618 
11619   assert( argc==2 );
11620   sz = sqlite3_value_int(argv[1]);
11621 
11622   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
11623     sqlite3_result_value(context, argv[0]);
11624   }else{
11625     const Bytef *pData= sqlite3_value_blob(argv[0]);
11626     Bytef *pOut = sqlite3_malloc(sz);
11627     if( pOut==0 ){
11628       sqlite3_result_error_nomem(context);
11629     }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
11630       sqlite3_result_error(context, "error in uncompress()", -1);
11631     }else{
11632       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
11633     }
11634     sqlite3_free(pOut);
11635   }
11636 }
11637 
11638 #ifdef _WIN32
11639 
11640 #endif
sqlite3_sqlar_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)11641 int sqlite3_sqlar_init(
11642   sqlite3 *db,
11643   char **pzErrMsg,
11644   const sqlite3_api_routines *pApi
11645 ){
11646   int rc = SQLITE_OK;
11647   SQLITE_EXTENSION_INIT2(pApi);
11648   (void)pzErrMsg;  /* Unused parameter */
11649   rc = sqlite3_create_function(db, "sqlar_compress", 1,
11650                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11651                                sqlarCompressFunc, 0, 0);
11652   if( rc==SQLITE_OK ){
11653     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
11654                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11655                                  sqlarUncompressFunc, 0, 0);
11656   }
11657   return rc;
11658 }
11659 
11660 /************************* End ../ext/misc/sqlar.c ********************/
11661 #endif
11662 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
11663 /*
11664 ** 2017 April 07
11665 **
11666 ** The author disclaims copyright to this source code.  In place of
11667 ** a legal notice, here is a blessing:
11668 **
11669 **    May you do good and not evil.
11670 **    May you find forgiveness for yourself and forgive others.
11671 **    May you share freely, never taking more than you give.
11672 **
11673 *************************************************************************
11674 */
11675 #if !defined(SQLITEEXPERT_H)
11676 #define SQLITEEXPERT_H 1
11677 /* #include "sqlite3.h" */
11678 
11679 typedef struct sqlite3expert sqlite3expert;
11680 
11681 /*
11682 ** Create a new sqlite3expert object.
11683 **
11684 ** If successful, a pointer to the new object is returned and (*pzErr) set
11685 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
11686 ** an English-language error message. In this case it is the responsibility
11687 ** of the caller to eventually free the error message buffer using
11688 ** sqlite3_free().
11689 */
11690 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
11691 
11692 /*
11693 ** Configure an sqlite3expert object.
11694 **
11695 ** EXPERT_CONFIG_SAMPLE:
11696 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
11697 **   each candidate index. This involves scanning and sorting the entire
11698 **   contents of each user database table once for each candidate index
11699 **   associated with the table. For large databases, this can be
11700 **   prohibitively slow. This option allows the sqlite3expert object to
11701 **   be configured so that sqlite_stat1 data is instead generated based on a
11702 **   subset of each table, or so that no sqlite_stat1 data is used at all.
11703 **
11704 **   A single integer argument is passed to this option. If the value is less
11705 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
11706 **   the analysis - indexes are recommended based on the database schema only.
11707 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
11708 **   generated for each candidate index (this is the default). Finally, if the
11709 **   value falls between 0 and 100, then it represents the percentage of user
11710 **   table rows that should be considered when generating sqlite_stat1 data.
11711 **
11712 **   Examples:
11713 **
11714 **     // Do not generate any sqlite_stat1 data
11715 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
11716 **
11717 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
11718 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
11719 */
11720 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
11721 
11722 #define EXPERT_CONFIG_SAMPLE 1    /* int */
11723 
11724 /*
11725 ** Specify zero or more SQL statements to be included in the analysis.
11726 **
11727 ** Buffer zSql must contain zero or more complete SQL statements. This
11728 ** function parses all statements contained in the buffer and adds them
11729 ** to the internal list of statements to analyze. If successful, SQLITE_OK
11730 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11731 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11732 ** may be set to point to an English language error message. In this case
11733 ** the caller is responsible for eventually freeing the error message buffer
11734 ** using sqlite3_free().
11735 **
11736 ** If an error does occur while processing one of the statements in the
11737 ** buffer passed as the second argument, none of the statements in the
11738 ** buffer are added to the analysis.
11739 **
11740 ** This function must be called before sqlite3_expert_analyze(). If a call
11741 ** to this function is made on an sqlite3expert object that has already
11742 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
11743 ** immediately and no statements are added to the analysis.
11744 */
11745 int sqlite3_expert_sql(
11746   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
11747   const char *zSql,               /* SQL statement(s) to add */
11748   char **pzErr                    /* OUT: Error message (if any) */
11749 );
11750 
11751 
11752 /*
11753 ** This function is called after the sqlite3expert object has been configured
11754 ** with all SQL statements using sqlite3_expert_sql() to actually perform
11755 ** the analysis. Once this function has been called, it is not possible to
11756 ** add further SQL statements to the analysis.
11757 **
11758 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
11759 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
11760 ** point to a buffer containing an English language error message. In this
11761 ** case it is the responsibility of the caller to eventually free the buffer
11762 ** using sqlite3_free().
11763 **
11764 ** If an error does occur within this function, the sqlite3expert object
11765 ** is no longer useful for any purpose. At that point it is no longer
11766 ** possible to add further SQL statements to the object or to re-attempt
11767 ** the analysis. The sqlite3expert object must still be freed using a call
11768 ** sqlite3_expert_destroy().
11769 */
11770 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
11771 
11772 /*
11773 ** Return the total number of statements loaded using sqlite3_expert_sql().
11774 ** The total number of SQL statements may be different from the total number
11775 ** to calls to sqlite3_expert_sql().
11776 */
11777 int sqlite3_expert_count(sqlite3expert*);
11778 
11779 /*
11780 ** Return a component of the report.
11781 **
11782 ** This function is called after sqlite3_expert_analyze() to extract the
11783 ** results of the analysis. Each call to this function returns either a
11784 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11785 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
11786 ** #define constants defined below.
11787 **
11788 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
11789 ** information relating to a specific SQL statement. In these cases that
11790 ** SQL statement is identified by the value passed as the second argument.
11791 ** SQL statements are numbered from 0 in the order in which they are parsed.
11792 ** If an out-of-range value (less than zero or equal to or greater than the
11793 ** value returned by sqlite3_expert_count()) is passed as the second argument
11794 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
11795 **
11796 ** EXPERT_REPORT_SQL:
11797 **   Return the text of SQL statement iStmt.
11798 **
11799 ** EXPERT_REPORT_INDEXES:
11800 **   Return a buffer containing the CREATE INDEX statements for all recommended
11801 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
11802 **   is returned.
11803 **
11804 ** EXPERT_REPORT_PLAN:
11805 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
11806 **   iStmt after the proposed indexes have been added to the database schema.
11807 **
11808 ** EXPERT_REPORT_CANDIDATES:
11809 **   Return a pointer to a buffer containing the CREATE INDEX statements
11810 **   for all indexes that were tested (for all SQL statements). The iStmt
11811 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
11812 */
11813 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
11814 
11815 /*
11816 ** Values for the third argument passed to sqlite3_expert_report().
11817 */
11818 #define EXPERT_REPORT_SQL        1
11819 #define EXPERT_REPORT_INDEXES    2
11820 #define EXPERT_REPORT_PLAN       3
11821 #define EXPERT_REPORT_CANDIDATES 4
11822 
11823 /*
11824 ** Free an (sqlite3expert*) handle and all associated resources. There
11825 ** should be one call to this function for each successful call to
11826 ** sqlite3-expert_new().
11827 */
11828 void sqlite3_expert_destroy(sqlite3expert*);
11829 
11830 #endif  /* !defined(SQLITEEXPERT_H) */
11831 
11832 /************************* End ../ext/expert/sqlite3expert.h ********************/
11833 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
11834 /*
11835 ** 2017 April 09
11836 **
11837 ** The author disclaims copyright to this source code.  In place of
11838 ** a legal notice, here is a blessing:
11839 **
11840 **    May you do good and not evil.
11841 **    May you find forgiveness for yourself and forgive others.
11842 **    May you share freely, never taking more than you give.
11843 **
11844 *************************************************************************
11845 */
11846 /* #include "sqlite3expert.h" */
11847 #include <assert.h>
11848 #include <string.h>
11849 #include <stdio.h>
11850 
11851 #if !defined(SQLITE_AMALGAMATION)
11852 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11853 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
11854 #endif
11855 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
11856 # define ALWAYS(X)      (1)
11857 # define NEVER(X)       (0)
11858 #elif !defined(NDEBUG)
11859 # define ALWAYS(X)      ((X)?1:(assert(0),0))
11860 # define NEVER(X)       ((X)?(assert(0),1):0)
11861 #else
11862 # define ALWAYS(X)      (X)
11863 # define NEVER(X)       (X)
11864 #endif
11865 #endif /* !defined(SQLITE_AMALGAMATION) */
11866 
11867 
11868 #ifndef SQLITE_OMIT_VIRTUALTABLE
11869 
11870 /* typedef sqlite3_int64 i64; */
11871 /* typedef sqlite3_uint64 u64; */
11872 
11873 typedef struct IdxColumn IdxColumn;
11874 typedef struct IdxConstraint IdxConstraint;
11875 typedef struct IdxScan IdxScan;
11876 typedef struct IdxStatement IdxStatement;
11877 typedef struct IdxTable IdxTable;
11878 typedef struct IdxWrite IdxWrite;
11879 
11880 #define STRLEN  (int)strlen
11881 
11882 /*
11883 ** A temp table name that we assume no user database will actually use.
11884 ** If this assumption proves incorrect triggers on the table with the
11885 ** conflicting name will be ignored.
11886 */
11887 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
11888 
11889 /*
11890 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
11891 ** any other type of single-ended range constraint on a column).
11892 **
11893 ** pLink:
11894 **   Used to temporarily link IdxConstraint objects into lists while
11895 **   creating candidate indexes.
11896 */
11897 struct IdxConstraint {
11898   char *zColl;                    /* Collation sequence */
11899   int bRange;                     /* True for range, false for eq */
11900   int iCol;                       /* Constrained table column */
11901   int bFlag;                      /* Used by idxFindCompatible() */
11902   int bDesc;                      /* True if ORDER BY <expr> DESC */
11903   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
11904   IdxConstraint *pLink;           /* See above */
11905 };
11906 
11907 /*
11908 ** A single scan of a single table.
11909 */
11910 struct IdxScan {
11911   IdxTable *pTab;                 /* Associated table object */
11912   int iDb;                        /* Database containing table zTable */
11913   i64 covering;                   /* Mask of columns required for cov. index */
11914   IdxConstraint *pOrder;          /* ORDER BY columns */
11915   IdxConstraint *pEq;             /* List of == constraints */
11916   IdxConstraint *pRange;          /* List of < constraints */
11917   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
11918 };
11919 
11920 /*
11921 ** Information regarding a single database table. Extracted from
11922 ** "PRAGMA table_info" by function idxGetTableInfo().
11923 */
11924 struct IdxColumn {
11925   char *zName;
11926   char *zColl;
11927   int iPk;
11928 };
11929 struct IdxTable {
11930   int nCol;
11931   char *zName;                    /* Table name */
11932   IdxColumn *aCol;
11933   IdxTable *pNext;                /* Next table in linked list of all tables */
11934 };
11935 
11936 /*
11937 ** An object of the following type is created for each unique table/write-op
11938 ** seen. The objects are stored in a singly-linked list beginning at
11939 ** sqlite3expert.pWrite.
11940 */
11941 struct IdxWrite {
11942   IdxTable *pTab;
11943   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
11944   IdxWrite *pNext;
11945 };
11946 
11947 /*
11948 ** Each statement being analyzed is represented by an instance of this
11949 ** structure.
11950 */
11951 struct IdxStatement {
11952   int iId;                        /* Statement number */
11953   char *zSql;                     /* SQL statement */
11954   char *zIdx;                     /* Indexes */
11955   char *zEQP;                     /* Plan */
11956   IdxStatement *pNext;
11957 };
11958 
11959 
11960 /*
11961 ** A hash table for storing strings. With space for a payload string
11962 ** with each entry. Methods are:
11963 **
11964 **   idxHashInit()
11965 **   idxHashClear()
11966 **   idxHashAdd()
11967 **   idxHashSearch()
11968 */
11969 #define IDX_HASH_SIZE 1023
11970 typedef struct IdxHashEntry IdxHashEntry;
11971 typedef struct IdxHash IdxHash;
11972 struct IdxHashEntry {
11973   char *zKey;                     /* nul-terminated key */
11974   char *zVal;                     /* nul-terminated value string */
11975   char *zVal2;                    /* nul-terminated value string 2 */
11976   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
11977   IdxHashEntry *pNext;            /* Next entry in hash */
11978 };
11979 struct IdxHash {
11980   IdxHashEntry *pFirst;
11981   IdxHashEntry *aHash[IDX_HASH_SIZE];
11982 };
11983 
11984 /*
11985 ** sqlite3expert object.
11986 */
11987 struct sqlite3expert {
11988   int iSample;                    /* Percentage of tables to sample for stat1 */
11989   sqlite3 *db;                    /* User database */
11990   sqlite3 *dbm;                   /* In-memory db for this analysis */
11991   sqlite3 *dbv;                   /* Vtab schema for this analysis */
11992   IdxTable *pTable;               /* List of all IdxTable objects */
11993   IdxScan *pScan;                 /* List of scan objects */
11994   IdxWrite *pWrite;               /* List of write objects */
11995   IdxStatement *pStatement;       /* List of IdxStatement objects */
11996   int bRun;                       /* True once analysis has run */
11997   char **pzErrmsg;
11998   int rc;                         /* Error code from whereinfo hook */
11999   IdxHash hIdx;                   /* Hash containing all candidate indexes */
12000   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
12001 };
12002 
12003 
12004 /*
12005 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
12006 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
12007 */
idxMalloc(int * pRc,int nByte)12008 static void *idxMalloc(int *pRc, int nByte){
12009   void *pRet;
12010   assert( *pRc==SQLITE_OK );
12011   assert( nByte>0 );
12012   pRet = sqlite3_malloc(nByte);
12013   if( pRet ){
12014     memset(pRet, 0, nByte);
12015   }else{
12016     *pRc = SQLITE_NOMEM;
12017   }
12018   return pRet;
12019 }
12020 
12021 /*
12022 ** Initialize an IdxHash hash table.
12023 */
idxHashInit(IdxHash * pHash)12024 static void idxHashInit(IdxHash *pHash){
12025   memset(pHash, 0, sizeof(IdxHash));
12026 }
12027 
12028 /*
12029 ** Reset an IdxHash hash table.
12030 */
idxHashClear(IdxHash * pHash)12031 static void idxHashClear(IdxHash *pHash){
12032   int i;
12033   for(i=0; i<IDX_HASH_SIZE; i++){
12034     IdxHashEntry *pEntry;
12035     IdxHashEntry *pNext;
12036     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
12037       pNext = pEntry->pHashNext;
12038       sqlite3_free(pEntry->zVal2);
12039       sqlite3_free(pEntry);
12040     }
12041   }
12042   memset(pHash, 0, sizeof(IdxHash));
12043 }
12044 
12045 /*
12046 ** Return the index of the hash bucket that the string specified by the
12047 ** arguments to this function belongs.
12048 */
idxHashString(const char * z,int n)12049 static int idxHashString(const char *z, int n){
12050   unsigned int ret = 0;
12051   int i;
12052   for(i=0; i<n; i++){
12053     ret += (ret<<3) + (unsigned char)(z[i]);
12054   }
12055   return (int)(ret % IDX_HASH_SIZE);
12056 }
12057 
12058 /*
12059 ** If zKey is already present in the hash table, return non-zero and do
12060 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
12061 ** the hash table passed as the second argument.
12062 */
idxHashAdd(int * pRc,IdxHash * pHash,const char * zKey,const char * zVal)12063 static int idxHashAdd(
12064   int *pRc,
12065   IdxHash *pHash,
12066   const char *zKey,
12067   const char *zVal
12068 ){
12069   int nKey = STRLEN(zKey);
12070   int iHash = idxHashString(zKey, nKey);
12071   int nVal = (zVal ? STRLEN(zVal) : 0);
12072   IdxHashEntry *pEntry;
12073   assert( iHash>=0 );
12074   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12075     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12076       return 1;
12077     }
12078   }
12079   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
12080   if( pEntry ){
12081     pEntry->zKey = (char*)&pEntry[1];
12082     memcpy(pEntry->zKey, zKey, nKey);
12083     if( zVal ){
12084       pEntry->zVal = &pEntry->zKey[nKey+1];
12085       memcpy(pEntry->zVal, zVal, nVal);
12086     }
12087     pEntry->pHashNext = pHash->aHash[iHash];
12088     pHash->aHash[iHash] = pEntry;
12089 
12090     pEntry->pNext = pHash->pFirst;
12091     pHash->pFirst = pEntry;
12092   }
12093   return 0;
12094 }
12095 
12096 /*
12097 ** If zKey/nKey is present in the hash table, return a pointer to the
12098 ** hash-entry object.
12099 */
idxHashFind(IdxHash * pHash,const char * zKey,int nKey)12100 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
12101   int iHash;
12102   IdxHashEntry *pEntry;
12103   if( nKey<0 ) nKey = STRLEN(zKey);
12104   iHash = idxHashString(zKey, nKey);
12105   assert( iHash>=0 );
12106   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12107     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12108       return pEntry;
12109     }
12110   }
12111   return 0;
12112 }
12113 
12114 /*
12115 ** If the hash table contains an entry with a key equal to the string
12116 ** passed as the final two arguments to this function, return a pointer
12117 ** to the payload string. Otherwise, if zKey/nKey is not present in the
12118 ** hash table, return NULL.
12119 */
idxHashSearch(IdxHash * pHash,const char * zKey,int nKey)12120 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
12121   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
12122   if( pEntry ) return pEntry->zVal;
12123   return 0;
12124 }
12125 
12126 /*
12127 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
12128 ** variable to point to a copy of nul-terminated string zColl.
12129 */
idxNewConstraint(int * pRc,const char * zColl)12130 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
12131   IdxConstraint *pNew;
12132   int nColl = STRLEN(zColl);
12133 
12134   assert( *pRc==SQLITE_OK );
12135   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
12136   if( pNew ){
12137     pNew->zColl = (char*)&pNew[1];
12138     memcpy(pNew->zColl, zColl, nColl+1);
12139   }
12140   return pNew;
12141 }
12142 
12143 /*
12144 ** An error associated with database handle db has just occurred. Pass
12145 ** the error message to callback function xOut.
12146 */
idxDatabaseError(sqlite3 * db,char ** pzErrmsg)12147 static void idxDatabaseError(
12148   sqlite3 *db,                    /* Database handle */
12149   char **pzErrmsg                 /* Write error here */
12150 ){
12151   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
12152 }
12153 
12154 /*
12155 ** Prepare an SQL statement.
12156 */
idxPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zSql)12157 static int idxPrepareStmt(
12158   sqlite3 *db,                    /* Database handle to compile against */
12159   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12160   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12161   const char *zSql                /* SQL statement to compile */
12162 ){
12163   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12164   if( rc!=SQLITE_OK ){
12165     *ppStmt = 0;
12166     idxDatabaseError(db, pzErrmsg);
12167   }
12168   return rc;
12169 }
12170 
12171 /*
12172 ** Prepare an SQL statement using the results of a printf() formatting.
12173 */
idxPrintfPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zFmt,...)12174 static int idxPrintfPrepareStmt(
12175   sqlite3 *db,                    /* Database handle to compile against */
12176   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12177   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12178   const char *zFmt,               /* printf() format of SQL statement */
12179   ...                             /* Trailing printf() arguments */
12180 ){
12181   va_list ap;
12182   int rc;
12183   char *zSql;
12184   va_start(ap, zFmt);
12185   zSql = sqlite3_vmprintf(zFmt, ap);
12186   if( zSql==0 ){
12187     rc = SQLITE_NOMEM;
12188   }else{
12189     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
12190     sqlite3_free(zSql);
12191   }
12192   va_end(ap);
12193   return rc;
12194 }
12195 
12196 
12197 /*************************************************************************
12198 ** Beginning of virtual table implementation.
12199 */
12200 typedef struct ExpertVtab ExpertVtab;
12201 struct ExpertVtab {
12202   sqlite3_vtab base;
12203   IdxTable *pTab;
12204   sqlite3expert *pExpert;
12205 };
12206 
12207 typedef struct ExpertCsr ExpertCsr;
12208 struct ExpertCsr {
12209   sqlite3_vtab_cursor base;
12210   sqlite3_stmt *pData;
12211 };
12212 
expertDequote(const char * zIn)12213 static char *expertDequote(const char *zIn){
12214   int n = STRLEN(zIn);
12215   char *zRet = sqlite3_malloc(n);
12216 
12217   assert( zIn[0]=='\'' );
12218   assert( zIn[n-1]=='\'' );
12219 
12220   if( zRet ){
12221     int iOut = 0;
12222     int iIn = 0;
12223     for(iIn=1; iIn<(n-1); iIn++){
12224       if( zIn[iIn]=='\'' ){
12225         assert( zIn[iIn+1]=='\'' );
12226         iIn++;
12227       }
12228       zRet[iOut++] = zIn[iIn];
12229     }
12230     zRet[iOut] = '\0';
12231   }
12232 
12233   return zRet;
12234 }
12235 
12236 /*
12237 ** This function is the implementation of both the xConnect and xCreate
12238 ** methods of the r-tree virtual table.
12239 **
12240 **   argv[0]   -> module name
12241 **   argv[1]   -> database name
12242 **   argv[2]   -> table name
12243 **   argv[...] -> column names...
12244 */
expertConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)12245 static int expertConnect(
12246   sqlite3 *db,
12247   void *pAux,
12248   int argc, const char *const*argv,
12249   sqlite3_vtab **ppVtab,
12250   char **pzErr
12251 ){
12252   sqlite3expert *pExpert = (sqlite3expert*)pAux;
12253   ExpertVtab *p = 0;
12254   int rc;
12255 
12256   if( argc!=4 ){
12257     *pzErr = sqlite3_mprintf("internal error!");
12258     rc = SQLITE_ERROR;
12259   }else{
12260     char *zCreateTable = expertDequote(argv[3]);
12261     if( zCreateTable ){
12262       rc = sqlite3_declare_vtab(db, zCreateTable);
12263       if( rc==SQLITE_OK ){
12264         p = idxMalloc(&rc, sizeof(ExpertVtab));
12265       }
12266       if( rc==SQLITE_OK ){
12267         p->pExpert = pExpert;
12268         p->pTab = pExpert->pTable;
12269         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
12270       }
12271       sqlite3_free(zCreateTable);
12272     }else{
12273       rc = SQLITE_NOMEM;
12274     }
12275   }
12276 
12277   *ppVtab = (sqlite3_vtab*)p;
12278   return rc;
12279 }
12280 
expertDisconnect(sqlite3_vtab * pVtab)12281 static int expertDisconnect(sqlite3_vtab *pVtab){
12282   ExpertVtab *p = (ExpertVtab*)pVtab;
12283   sqlite3_free(p);
12284   return SQLITE_OK;
12285 }
12286 
expertBestIndex(sqlite3_vtab * pVtab,sqlite3_index_info * pIdxInfo)12287 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
12288   ExpertVtab *p = (ExpertVtab*)pVtab;
12289   int rc = SQLITE_OK;
12290   int n = 0;
12291   IdxScan *pScan;
12292   const int opmask =
12293     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
12294     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
12295     SQLITE_INDEX_CONSTRAINT_LE;
12296 
12297   pScan = idxMalloc(&rc, sizeof(IdxScan));
12298   if( pScan ){
12299     int i;
12300 
12301     /* Link the new scan object into the list */
12302     pScan->pTab = p->pTab;
12303     pScan->pNextScan = p->pExpert->pScan;
12304     p->pExpert->pScan = pScan;
12305 
12306     /* Add the constraints to the IdxScan object */
12307     for(i=0; i<pIdxInfo->nConstraint; i++){
12308       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
12309       if( pCons->usable
12310        && pCons->iColumn>=0
12311        && p->pTab->aCol[pCons->iColumn].iPk==0
12312        && (pCons->op & opmask)
12313       ){
12314         IdxConstraint *pNew;
12315         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
12316         pNew = idxNewConstraint(&rc, zColl);
12317         if( pNew ){
12318           pNew->iCol = pCons->iColumn;
12319           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
12320             pNew->pNext = pScan->pEq;
12321             pScan->pEq = pNew;
12322           }else{
12323             pNew->bRange = 1;
12324             pNew->pNext = pScan->pRange;
12325             pScan->pRange = pNew;
12326           }
12327         }
12328         n++;
12329         pIdxInfo->aConstraintUsage[i].argvIndex = n;
12330       }
12331     }
12332 
12333     /* Add the ORDER BY to the IdxScan object */
12334     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
12335       int iCol = pIdxInfo->aOrderBy[i].iColumn;
12336       if( iCol>=0 ){
12337         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
12338         if( pNew ){
12339           pNew->iCol = iCol;
12340           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
12341           pNew->pNext = pScan->pOrder;
12342           pNew->pLink = pScan->pOrder;
12343           pScan->pOrder = pNew;
12344           n++;
12345         }
12346       }
12347     }
12348   }
12349 
12350   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
12351   return rc;
12352 }
12353 
expertUpdate(sqlite3_vtab * pVtab,int nData,sqlite3_value ** azData,sqlite_int64 * pRowid)12354 static int expertUpdate(
12355   sqlite3_vtab *pVtab,
12356   int nData,
12357   sqlite3_value **azData,
12358   sqlite_int64 *pRowid
12359 ){
12360   (void)pVtab;
12361   (void)nData;
12362   (void)azData;
12363   (void)pRowid;
12364   return SQLITE_OK;
12365 }
12366 
12367 /*
12368 ** Virtual table module xOpen method.
12369 */
expertOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)12370 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
12371   int rc = SQLITE_OK;
12372   ExpertCsr *pCsr;
12373   (void)pVTab;
12374   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
12375   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
12376   return rc;
12377 }
12378 
12379 /*
12380 ** Virtual table module xClose method.
12381 */
expertClose(sqlite3_vtab_cursor * cur)12382 static int expertClose(sqlite3_vtab_cursor *cur){
12383   ExpertCsr *pCsr = (ExpertCsr*)cur;
12384   sqlite3_finalize(pCsr->pData);
12385   sqlite3_free(pCsr);
12386   return SQLITE_OK;
12387 }
12388 
12389 /*
12390 ** Virtual table module xEof method.
12391 **
12392 ** Return non-zero if the cursor does not currently point to a valid
12393 ** record (i.e if the scan has finished), or zero otherwise.
12394 */
expertEof(sqlite3_vtab_cursor * cur)12395 static int expertEof(sqlite3_vtab_cursor *cur){
12396   ExpertCsr *pCsr = (ExpertCsr*)cur;
12397   return pCsr->pData==0;
12398 }
12399 
12400 /*
12401 ** Virtual table module xNext method.
12402 */
expertNext(sqlite3_vtab_cursor * cur)12403 static int expertNext(sqlite3_vtab_cursor *cur){
12404   ExpertCsr *pCsr = (ExpertCsr*)cur;
12405   int rc = SQLITE_OK;
12406 
12407   assert( pCsr->pData );
12408   rc = sqlite3_step(pCsr->pData);
12409   if( rc!=SQLITE_ROW ){
12410     rc = sqlite3_finalize(pCsr->pData);
12411     pCsr->pData = 0;
12412   }else{
12413     rc = SQLITE_OK;
12414   }
12415 
12416   return rc;
12417 }
12418 
12419 /*
12420 ** Virtual table module xRowid method.
12421 */
expertRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)12422 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
12423   (void)cur;
12424   *pRowid = 0;
12425   return SQLITE_OK;
12426 }
12427 
12428 /*
12429 ** Virtual table module xColumn method.
12430 */
expertColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)12431 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
12432   ExpertCsr *pCsr = (ExpertCsr*)cur;
12433   sqlite3_value *pVal;
12434   pVal = sqlite3_column_value(pCsr->pData, i);
12435   if( pVal ){
12436     sqlite3_result_value(ctx, pVal);
12437   }
12438   return SQLITE_OK;
12439 }
12440 
12441 /*
12442 ** Virtual table module xFilter method.
12443 */
expertFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)12444 static int expertFilter(
12445   sqlite3_vtab_cursor *cur,
12446   int idxNum, const char *idxStr,
12447   int argc, sqlite3_value **argv
12448 ){
12449   ExpertCsr *pCsr = (ExpertCsr*)cur;
12450   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
12451   sqlite3expert *pExpert = pVtab->pExpert;
12452   int rc;
12453 
12454   (void)idxNum;
12455   (void)idxStr;
12456   (void)argc;
12457   (void)argv;
12458   rc = sqlite3_finalize(pCsr->pData);
12459   pCsr->pData = 0;
12460   if( rc==SQLITE_OK ){
12461     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
12462         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
12463     );
12464   }
12465 
12466   if( rc==SQLITE_OK ){
12467     rc = expertNext(cur);
12468   }
12469   return rc;
12470 }
12471 
idxRegisterVtab(sqlite3expert * p)12472 static int idxRegisterVtab(sqlite3expert *p){
12473   static sqlite3_module expertModule = {
12474     2,                            /* iVersion */
12475     expertConnect,                /* xCreate - create a table */
12476     expertConnect,                /* xConnect - connect to an existing table */
12477     expertBestIndex,              /* xBestIndex - Determine search strategy */
12478     expertDisconnect,             /* xDisconnect - Disconnect from a table */
12479     expertDisconnect,             /* xDestroy - Drop a table */
12480     expertOpen,                   /* xOpen - open a cursor */
12481     expertClose,                  /* xClose - close a cursor */
12482     expertFilter,                 /* xFilter - configure scan constraints */
12483     expertNext,                   /* xNext - advance a cursor */
12484     expertEof,                    /* xEof */
12485     expertColumn,                 /* xColumn - read data */
12486     expertRowid,                  /* xRowid - read data */
12487     expertUpdate,                 /* xUpdate - write data */
12488     0,                            /* xBegin - begin transaction */
12489     0,                            /* xSync - sync transaction */
12490     0,                            /* xCommit - commit transaction */
12491     0,                            /* xRollback - rollback transaction */
12492     0,                            /* xFindFunction - function overloading */
12493     0,                            /* xRename - rename the table */
12494     0,                            /* xSavepoint */
12495     0,                            /* xRelease */
12496     0,                            /* xRollbackTo */
12497     0,                            /* xShadowName */
12498     0,                            /* xIntegrity */
12499   };
12500 
12501   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
12502 }
12503 /*
12504 ** End of virtual table implementation.
12505 *************************************************************************/
12506 /*
12507 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
12508 ** is called, set it to the return value of sqlite3_finalize() before
12509 ** returning. Otherwise, discard the sqlite3_finalize() return value.
12510 */
idxFinalize(int * pRc,sqlite3_stmt * pStmt)12511 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
12512   int rc = sqlite3_finalize(pStmt);
12513   if( *pRc==SQLITE_OK ) *pRc = rc;
12514 }
12515 
12516 /*
12517 ** Attempt to allocate an IdxTable structure corresponding to table zTab
12518 ** in the main database of connection db. If successful, set (*ppOut) to
12519 ** point to the new object and return SQLITE_OK. Otherwise, return an
12520 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
12521 ** set to point to an error string.
12522 **
12523 ** It is the responsibility of the caller to eventually free either the
12524 ** IdxTable object or error message using sqlite3_free().
12525 */
idxGetTableInfo(sqlite3 * db,const char * zTab,IdxTable ** ppOut,char ** pzErrmsg)12526 static int idxGetTableInfo(
12527   sqlite3 *db,                    /* Database connection to read details from */
12528   const char *zTab,               /* Table name */
12529   IdxTable **ppOut,               /* OUT: New object (if successful) */
12530   char **pzErrmsg                 /* OUT: Error message (if not) */
12531 ){
12532   sqlite3_stmt *p1 = 0;
12533   int nCol = 0;
12534   int nTab;
12535   int nByte;
12536   IdxTable *pNew = 0;
12537   int rc, rc2;
12538   char *pCsr = 0;
12539   int nPk = 0;
12540 
12541   *ppOut = 0;
12542   if( zTab==0 ) return SQLITE_ERROR;
12543   nTab = STRLEN(zTab);
12544   nByte = sizeof(IdxTable) + nTab + 1;
12545   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
12546   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12547     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12548     const char *zColSeq = 0;
12549     if( zCol==0 ){
12550       rc = SQLITE_ERROR;
12551       break;
12552     }
12553     nByte += 1 + STRLEN(zCol);
12554     rc = sqlite3_table_column_metadata(
12555         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12556     );
12557     if( zColSeq==0 ) zColSeq = "binary";
12558     nByte += 1 + STRLEN(zColSeq);
12559     nCol++;
12560     nPk += (sqlite3_column_int(p1, 5)>0);
12561   }
12562   rc2 = sqlite3_reset(p1);
12563   if( rc==SQLITE_OK ) rc = rc2;
12564 
12565   nByte += sizeof(IdxColumn) * nCol;
12566   if( rc==SQLITE_OK ){
12567     pNew = idxMalloc(&rc, nByte);
12568   }
12569   if( rc==SQLITE_OK ){
12570     pNew->aCol = (IdxColumn*)&pNew[1];
12571     pNew->nCol = nCol;
12572     pCsr = (char*)&pNew->aCol[nCol];
12573   }
12574 
12575   nCol = 0;
12576   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12577     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12578     const char *zColSeq = 0;
12579     int nCopy;
12580     if( zCol==0 ) continue;
12581     nCopy = STRLEN(zCol) + 1;
12582     pNew->aCol[nCol].zName = pCsr;
12583     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
12584     memcpy(pCsr, zCol, nCopy);
12585     pCsr += nCopy;
12586 
12587     rc = sqlite3_table_column_metadata(
12588         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12589     );
12590     if( rc==SQLITE_OK ){
12591       if( zColSeq==0 ) zColSeq = "binary";
12592       nCopy = STRLEN(zColSeq) + 1;
12593       pNew->aCol[nCol].zColl = pCsr;
12594       memcpy(pCsr, zColSeq, nCopy);
12595       pCsr += nCopy;
12596     }
12597 
12598     nCol++;
12599   }
12600   idxFinalize(&rc, p1);
12601 
12602   if( rc!=SQLITE_OK ){
12603     sqlite3_free(pNew);
12604     pNew = 0;
12605   }else if( ALWAYS(pNew!=0) ){
12606     pNew->zName = pCsr;
12607     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
12608   }
12609 
12610   *ppOut = pNew;
12611   return rc;
12612 }
12613 
12614 /*
12615 ** This function is a no-op if *pRc is set to anything other than
12616 ** SQLITE_OK when it is called.
12617 **
12618 ** If *pRc is initially set to SQLITE_OK, then the text specified by
12619 ** the printf() style arguments is appended to zIn and the result returned
12620 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
12621 ** zIn before returning.
12622 */
idxAppendText(int * pRc,char * zIn,const char * zFmt,...)12623 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
12624   va_list ap;
12625   char *zAppend = 0;
12626   char *zRet = 0;
12627   int nIn = zIn ? STRLEN(zIn) : 0;
12628   int nAppend = 0;
12629   va_start(ap, zFmt);
12630   if( *pRc==SQLITE_OK ){
12631     zAppend = sqlite3_vmprintf(zFmt, ap);
12632     if( zAppend ){
12633       nAppend = STRLEN(zAppend);
12634       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
12635     }
12636     if( zAppend && zRet ){
12637       if( nIn ) memcpy(zRet, zIn, nIn);
12638       memcpy(&zRet[nIn], zAppend, nAppend+1);
12639     }else{
12640       sqlite3_free(zRet);
12641       zRet = 0;
12642       *pRc = SQLITE_NOMEM;
12643     }
12644     sqlite3_free(zAppend);
12645     sqlite3_free(zIn);
12646   }
12647   va_end(ap);
12648   return zRet;
12649 }
12650 
12651 /*
12652 ** Return true if zId must be quoted in order to use it as an SQL
12653 ** identifier, or false otherwise.
12654 */
idxIdentifierRequiresQuotes(const char * zId)12655 static int idxIdentifierRequiresQuotes(const char *zId){
12656   int i;
12657   int nId = STRLEN(zId);
12658 
12659   if( sqlite3_keyword_check(zId, nId) ) return 1;
12660 
12661   for(i=0; zId[i]; i++){
12662     if( !(zId[i]=='_')
12663      && !(zId[i]>='0' && zId[i]<='9')
12664      && !(zId[i]>='a' && zId[i]<='z')
12665      && !(zId[i]>='A' && zId[i]<='Z')
12666     ){
12667       return 1;
12668     }
12669   }
12670   return 0;
12671 }
12672 
12673 /*
12674 ** This function appends an index column definition suitable for constraint
12675 ** pCons to the string passed as zIn and returns the result.
12676 */
idxAppendColDefn(int * pRc,char * zIn,IdxTable * pTab,IdxConstraint * pCons)12677 static char *idxAppendColDefn(
12678   int *pRc,                       /* IN/OUT: Error code */
12679   char *zIn,                      /* Column defn accumulated so far */
12680   IdxTable *pTab,                 /* Table index will be created on */
12681   IdxConstraint *pCons
12682 ){
12683   char *zRet = zIn;
12684   IdxColumn *p = &pTab->aCol[pCons->iCol];
12685   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
12686 
12687   if( idxIdentifierRequiresQuotes(p->zName) ){
12688     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
12689   }else{
12690     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
12691   }
12692 
12693   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
12694     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
12695       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
12696     }else{
12697       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
12698     }
12699   }
12700 
12701   if( pCons->bDesc ){
12702     zRet = idxAppendText(pRc, zRet, " DESC");
12703   }
12704   return zRet;
12705 }
12706 
12707 /*
12708 ** Search database dbm for an index compatible with the one idxCreateFromCons()
12709 ** would create from arguments pScan, pEq and pTail. If no error occurs and
12710 ** such an index is found, return non-zero. Or, if no such index is found,
12711 ** return zero.
12712 **
12713 ** If an error occurs, set *pRc to an SQLite error code and return zero.
12714 */
idxFindCompatible(int * pRc,sqlite3 * dbm,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)12715 static int idxFindCompatible(
12716   int *pRc,                       /* OUT: Error code */
12717   sqlite3* dbm,                   /* Database to search */
12718   IdxScan *pScan,                 /* Scan for table to search for index on */
12719   IdxConstraint *pEq,             /* List of == constraints */
12720   IdxConstraint *pTail            /* List of range constraints */
12721 ){
12722   const char *zTbl = pScan->pTab->zName;
12723   sqlite3_stmt *pIdxList = 0;
12724   IdxConstraint *pIter;
12725   int nEq = 0;                    /* Number of elements in pEq */
12726   int rc;
12727 
12728   /* Count the elements in list pEq */
12729   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
12730 
12731   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
12732   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
12733     int bMatch = 1;
12734     IdxConstraint *pT = pTail;
12735     sqlite3_stmt *pInfo = 0;
12736     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
12737     if( zIdx==0 ) continue;
12738 
12739     /* Zero the IdxConstraint.bFlag values in the pEq list */
12740     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
12741 
12742     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
12743     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
12744       int iIdx = sqlite3_column_int(pInfo, 0);
12745       int iCol = sqlite3_column_int(pInfo, 1);
12746       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
12747 
12748       if( iIdx<nEq ){
12749         for(pIter=pEq; pIter; pIter=pIter->pLink){
12750           if( pIter->bFlag ) continue;
12751           if( pIter->iCol!=iCol ) continue;
12752           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
12753           pIter->bFlag = 1;
12754           break;
12755         }
12756         if( pIter==0 ){
12757           bMatch = 0;
12758           break;
12759         }
12760       }else{
12761         if( pT ){
12762           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
12763             bMatch = 0;
12764             break;
12765           }
12766           pT = pT->pLink;
12767         }
12768       }
12769     }
12770     idxFinalize(&rc, pInfo);
12771 
12772     if( rc==SQLITE_OK && bMatch ){
12773       sqlite3_finalize(pIdxList);
12774       return 1;
12775     }
12776   }
12777   idxFinalize(&rc, pIdxList);
12778 
12779   *pRc = rc;
12780   return 0;
12781 }
12782 
12783 /* Callback for sqlite3_exec() with query with leading count(*) column.
12784  * The first argument is expected to be an int*, referent to be incremented
12785  * if that leading column is not exactly '0'.
12786  */
countNonzeros(void * pCount,int nc,char * azResults[],char * azColumns[])12787 static int countNonzeros(void* pCount, int nc,
12788                          char* azResults[], char* azColumns[]){
12789   (void)azColumns;  /* Suppress unused parameter warning */
12790   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
12791     *((int *)pCount) += 1;
12792   }
12793   return 0;
12794 }
12795 
idxCreateFromCons(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)12796 static int idxCreateFromCons(
12797   sqlite3expert *p,
12798   IdxScan *pScan,
12799   IdxConstraint *pEq,
12800   IdxConstraint *pTail
12801 ){
12802   sqlite3 *dbm = p->dbm;
12803   int rc = SQLITE_OK;
12804   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
12805     IdxTable *pTab = pScan->pTab;
12806     char *zCols = 0;
12807     char *zIdx = 0;
12808     IdxConstraint *pCons;
12809     unsigned int h = 0;
12810     const char *zFmt;
12811 
12812     for(pCons=pEq; pCons; pCons=pCons->pLink){
12813       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12814     }
12815     for(pCons=pTail; pCons; pCons=pCons->pLink){
12816       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12817     }
12818 
12819     if( rc==SQLITE_OK ){
12820       /* Hash the list of columns to come up with a name for the index */
12821       const char *zTable = pScan->pTab->zName;
12822       int quoteTable = idxIdentifierRequiresQuotes(zTable);
12823       char *zName = 0;          /* Index name */
12824       int collisions = 0;
12825       do{
12826         int i;
12827         char *zFind;
12828         for(i=0; zCols[i]; i++){
12829           h += ((h<<3) + zCols[i]);
12830         }
12831         sqlite3_free(zName);
12832         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
12833         if( zName==0 ) break;
12834         /* Is is unique among table, view and index names? */
12835         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
12836           " AND type in ('index','table','view')";
12837         zFind = sqlite3_mprintf(zFmt, zName);
12838         i = 0;
12839         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
12840         assert(rc==SQLITE_OK);
12841         sqlite3_free(zFind);
12842         if( i==0 ){
12843           collisions = 0;
12844           break;
12845         }
12846         ++collisions;
12847       }while( collisions<50 && zName!=0 );
12848       if( collisions ){
12849         /* This return means "Gave up trying to find a unique index name." */
12850         rc = SQLITE_BUSY_TIMEOUT;
12851       }else if( zName==0 ){
12852         rc = SQLITE_NOMEM;
12853       }else{
12854         if( quoteTable ){
12855           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
12856         }else{
12857           zFmt = "CREATE INDEX %s ON %s(%s)";
12858         }
12859         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
12860         if( !zIdx ){
12861           rc = SQLITE_NOMEM;
12862         }else{
12863           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
12864           if( rc!=SQLITE_OK ){
12865             rc = SQLITE_BUSY_TIMEOUT;
12866           }else{
12867             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
12868           }
12869         }
12870         sqlite3_free(zName);
12871         sqlite3_free(zIdx);
12872       }
12873     }
12874 
12875     sqlite3_free(zCols);
12876   }
12877   return rc;
12878 }
12879 
12880 /*
12881 ** Return true if list pList (linked by IdxConstraint.pLink) contains
12882 ** a constraint compatible with *p. Otherwise return false.
12883 */
idxFindConstraint(IdxConstraint * pList,IdxConstraint * p)12884 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
12885   IdxConstraint *pCmp;
12886   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
12887     if( p->iCol==pCmp->iCol ) return 1;
12888   }
12889   return 0;
12890 }
12891 
idxCreateFromWhere(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pTail)12892 static int idxCreateFromWhere(
12893   sqlite3expert *p,
12894   IdxScan *pScan,                 /* Create indexes for this scan */
12895   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
12896 ){
12897   IdxConstraint *p1 = 0;
12898   IdxConstraint *pCon;
12899   int rc;
12900 
12901   /* Gather up all the == constraints. */
12902   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
12903     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12904       pCon->pLink = p1;
12905       p1 = pCon;
12906     }
12907   }
12908 
12909   /* Create an index using the == constraints collected above. And the
12910   ** range constraint/ORDER BY terms passed in by the caller, if any. */
12911   rc = idxCreateFromCons(p, pScan, p1, pTail);
12912 
12913   /* If no range/ORDER BY passed by the caller, create a version of the
12914   ** index for each range constraint.  */
12915   if( pTail==0 ){
12916     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
12917       assert( pCon->pLink==0 );
12918       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12919         rc = idxCreateFromCons(p, pScan, p1, pCon);
12920       }
12921     }
12922   }
12923 
12924   return rc;
12925 }
12926 
12927 /*
12928 ** Create candidate indexes in database [dbm] based on the data in
12929 ** linked-list pScan.
12930 */
idxCreateCandidates(sqlite3expert * p)12931 static int idxCreateCandidates(sqlite3expert *p){
12932   int rc = SQLITE_OK;
12933   IdxScan *pIter;
12934 
12935   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
12936     rc = idxCreateFromWhere(p, pIter, 0);
12937     if( rc==SQLITE_OK && pIter->pOrder ){
12938       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
12939     }
12940   }
12941 
12942   return rc;
12943 }
12944 
12945 /*
12946 ** Free all elements of the linked list starting at pConstraint.
12947 */
idxConstraintFree(IdxConstraint * pConstraint)12948 static void idxConstraintFree(IdxConstraint *pConstraint){
12949   IdxConstraint *pNext;
12950   IdxConstraint *p;
12951 
12952   for(p=pConstraint; p; p=pNext){
12953     pNext = p->pNext;
12954     sqlite3_free(p);
12955   }
12956 }
12957 
12958 /*
12959 ** Free all elements of the linked list starting from pScan up until pLast
12960 ** (pLast is not freed).
12961 */
idxScanFree(IdxScan * pScan,IdxScan * pLast)12962 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
12963   IdxScan *p;
12964   IdxScan *pNext;
12965   for(p=pScan; p!=pLast; p=pNext){
12966     pNext = p->pNextScan;
12967     idxConstraintFree(p->pOrder);
12968     idxConstraintFree(p->pEq);
12969     idxConstraintFree(p->pRange);
12970     sqlite3_free(p);
12971   }
12972 }
12973 
12974 /*
12975 ** Free all elements of the linked list starting from pStatement up
12976 ** until pLast (pLast is not freed).
12977 */
idxStatementFree(IdxStatement * pStatement,IdxStatement * pLast)12978 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
12979   IdxStatement *p;
12980   IdxStatement *pNext;
12981   for(p=pStatement; p!=pLast; p=pNext){
12982     pNext = p->pNext;
12983     sqlite3_free(p->zEQP);
12984     sqlite3_free(p->zIdx);
12985     sqlite3_free(p);
12986   }
12987 }
12988 
12989 /*
12990 ** Free the linked list of IdxTable objects starting at pTab.
12991 */
idxTableFree(IdxTable * pTab)12992 static void idxTableFree(IdxTable *pTab){
12993   IdxTable *pIter;
12994   IdxTable *pNext;
12995   for(pIter=pTab; pIter; pIter=pNext){
12996     pNext = pIter->pNext;
12997     sqlite3_free(pIter);
12998   }
12999 }
13000 
13001 /*
13002 ** Free the linked list of IdxWrite objects starting at pTab.
13003 */
idxWriteFree(IdxWrite * pTab)13004 static void idxWriteFree(IdxWrite *pTab){
13005   IdxWrite *pIter;
13006   IdxWrite *pNext;
13007   for(pIter=pTab; pIter; pIter=pNext){
13008     pNext = pIter->pNext;
13009     sqlite3_free(pIter);
13010   }
13011 }
13012 
13013 
13014 
13015 /*
13016 ** This function is called after candidate indexes have been created. It
13017 ** runs all the queries to see which indexes they prefer, and populates
13018 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
13019 */
idxFindIndexes(sqlite3expert * p,char ** pzErr)13020 static int idxFindIndexes(
13021   sqlite3expert *p,
13022   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
13023 ){
13024   IdxStatement *pStmt;
13025   sqlite3 *dbm = p->dbm;
13026   int rc = SQLITE_OK;
13027 
13028   IdxHash hIdx;
13029   idxHashInit(&hIdx);
13030 
13031   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
13032     IdxHashEntry *pEntry;
13033     sqlite3_stmt *pExplain = 0;
13034     idxHashClear(&hIdx);
13035     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
13036         "EXPLAIN QUERY PLAN %s", pStmt->zSql
13037     );
13038     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
13039       /* int iId = sqlite3_column_int(pExplain, 0); */
13040       /* int iParent = sqlite3_column_int(pExplain, 1); */
13041       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
13042       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
13043       int nDetail;
13044       int i;
13045 
13046       if( !zDetail ) continue;
13047       nDetail = STRLEN(zDetail);
13048 
13049       for(i=0; i<nDetail; i++){
13050         const char *zIdx = 0;
13051         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
13052           zIdx = &zDetail[i+13];
13053         }else if( i+22<nDetail
13054             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
13055         ){
13056           zIdx = &zDetail[i+22];
13057         }
13058         if( zIdx ){
13059           const char *zSql;
13060           int nIdx = 0;
13061           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
13062             nIdx++;
13063           }
13064           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
13065           if( zSql ){
13066             idxHashAdd(&rc, &hIdx, zSql, 0);
13067             if( rc ) goto find_indexes_out;
13068           }
13069           break;
13070         }
13071       }
13072 
13073       if( zDetail[0]!='-' ){
13074         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
13075       }
13076     }
13077 
13078     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13079       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
13080     }
13081 
13082     idxFinalize(&rc, pExplain);
13083   }
13084 
13085  find_indexes_out:
13086   idxHashClear(&hIdx);
13087   return rc;
13088 }
13089 
idxAuthCallback(void * pCtx,int eOp,const char * z3,const char * z4,const char * zDb,const char * zTrigger)13090 static int idxAuthCallback(
13091   void *pCtx,
13092   int eOp,
13093   const char *z3,
13094   const char *z4,
13095   const char *zDb,
13096   const char *zTrigger
13097 ){
13098   int rc = SQLITE_OK;
13099   (void)z4;
13100   (void)zTrigger;
13101   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
13102     if( sqlite3_stricmp(zDb, "main")==0 ){
13103       sqlite3expert *p = (sqlite3expert*)pCtx;
13104       IdxTable *pTab;
13105       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
13106         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
13107       }
13108       if( pTab ){
13109         IdxWrite *pWrite;
13110         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
13111           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
13112         }
13113         if( pWrite==0 ){
13114           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
13115           if( rc==SQLITE_OK ){
13116             pWrite->pTab = pTab;
13117             pWrite->eOp = eOp;
13118             pWrite->pNext = p->pWrite;
13119             p->pWrite = pWrite;
13120           }
13121         }
13122       }
13123     }
13124   }
13125   return rc;
13126 }
13127 
idxProcessOneTrigger(sqlite3expert * p,IdxWrite * pWrite,char ** pzErr)13128 static int idxProcessOneTrigger(
13129   sqlite3expert *p,
13130   IdxWrite *pWrite,
13131   char **pzErr
13132 ){
13133   static const char *zInt = UNIQUE_TABLE_NAME;
13134   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
13135   IdxTable *pTab = pWrite->pTab;
13136   const char *zTab = pTab->zName;
13137   const char *zSql =
13138     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
13139     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
13140     "ORDER BY type;";
13141   sqlite3_stmt *pSelect = 0;
13142   int rc = SQLITE_OK;
13143   char *zWrite = 0;
13144 
13145   /* Create the table and its triggers in the temp schema */
13146   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
13147   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
13148     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
13149     if( zCreate==0 ) continue;
13150     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
13151   }
13152   idxFinalize(&rc, pSelect);
13153 
13154   /* Rename the table in the temp schema to zInt */
13155   if( rc==SQLITE_OK ){
13156     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
13157     if( z==0 ){
13158       rc = SQLITE_NOMEM;
13159     }else{
13160       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
13161       sqlite3_free(z);
13162     }
13163   }
13164 
13165   switch( pWrite->eOp ){
13166     case SQLITE_INSERT: {
13167       int i;
13168       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
13169       for(i=0; i<pTab->nCol; i++){
13170         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
13171       }
13172       zWrite = idxAppendText(&rc, zWrite, ")");
13173       break;
13174     }
13175     case SQLITE_UPDATE: {
13176       int i;
13177       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
13178       for(i=0; i<pTab->nCol; i++){
13179         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
13180             pTab->aCol[i].zName
13181         );
13182       }
13183       break;
13184     }
13185     default: {
13186       assert( pWrite->eOp==SQLITE_DELETE );
13187       if( rc==SQLITE_OK ){
13188         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
13189         if( zWrite==0 ) rc = SQLITE_NOMEM;
13190       }
13191     }
13192   }
13193 
13194   if( rc==SQLITE_OK ){
13195     sqlite3_stmt *pX = 0;
13196     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
13197     idxFinalize(&rc, pX);
13198     if( rc!=SQLITE_OK ){
13199       idxDatabaseError(p->dbv, pzErr);
13200     }
13201   }
13202   sqlite3_free(zWrite);
13203 
13204   if( rc==SQLITE_OK ){
13205     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
13206   }
13207 
13208   return rc;
13209 }
13210 
idxProcessTriggers(sqlite3expert * p,char ** pzErr)13211 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
13212   int rc = SQLITE_OK;
13213   IdxWrite *pEnd = 0;
13214   IdxWrite *pFirst = p->pWrite;
13215 
13216   while( rc==SQLITE_OK && pFirst!=pEnd ){
13217     IdxWrite *pIter;
13218     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
13219       rc = idxProcessOneTrigger(p, pIter, pzErr);
13220     }
13221     pEnd = pFirst;
13222     pFirst = p->pWrite;
13223   }
13224 
13225   return rc;
13226 }
13227 
13228 
idxCreateVtabSchema(sqlite3expert * p,char ** pzErrmsg)13229 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
13230   int rc = idxRegisterVtab(p);
13231   sqlite3_stmt *pSchema = 0;
13232 
13233   /* For each table in the main db schema:
13234   **
13235   **   1) Add an entry to the p->pTable list, and
13236   **   2) Create the equivalent virtual table in dbv.
13237   */
13238   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
13239       "SELECT type, name, sql, 1 FROM sqlite_schema "
13240       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
13241       " UNION ALL "
13242       "SELECT type, name, sql, 2 FROM sqlite_schema "
13243       "WHERE type = 'trigger'"
13244       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
13245       "ORDER BY 4, 1"
13246   );
13247   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
13248     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
13249     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
13250     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
13251 
13252     if( zType==0 || zName==0 ) continue;
13253     if( zType[0]=='v' || zType[1]=='r' ){
13254       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
13255     }else{
13256       IdxTable *pTab;
13257       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
13258       if( rc==SQLITE_OK ){
13259         int i;
13260         char *zInner = 0;
13261         char *zOuter = 0;
13262         pTab->pNext = p->pTable;
13263         p->pTable = pTab;
13264 
13265         /* The statement the vtab will pass to sqlite3_declare_vtab() */
13266         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
13267         for(i=0; i<pTab->nCol; i++){
13268           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
13269               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
13270           );
13271         }
13272         zInner = idxAppendText(&rc, zInner, ")");
13273 
13274         /* The CVT statement to create the vtab */
13275         zOuter = idxAppendText(&rc, 0,
13276             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
13277         );
13278         if( rc==SQLITE_OK ){
13279           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
13280         }
13281         sqlite3_free(zInner);
13282         sqlite3_free(zOuter);
13283       }
13284     }
13285   }
13286   idxFinalize(&rc, pSchema);
13287   return rc;
13288 }
13289 
13290 struct IdxSampleCtx {
13291   int iTarget;
13292   double target;                  /* Target nRet/nRow value */
13293   double nRow;                    /* Number of rows seen */
13294   double nRet;                    /* Number of rows returned */
13295 };
13296 
idxSampleFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)13297 static void idxSampleFunc(
13298   sqlite3_context *pCtx,
13299   int argc,
13300   sqlite3_value **argv
13301 ){
13302   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
13303   int bRet;
13304 
13305   (void)argv;
13306   assert( argc==0 );
13307   if( p->nRow==0.0 ){
13308     bRet = 1;
13309   }else{
13310     bRet = (p->nRet / p->nRow) <= p->target;
13311     if( bRet==0 ){
13312       unsigned short rnd;
13313       sqlite3_randomness(2, (void*)&rnd);
13314       bRet = ((int)rnd % 100) <= p->iTarget;
13315     }
13316   }
13317 
13318   sqlite3_result_int(pCtx, bRet);
13319   p->nRow += 1.0;
13320   p->nRet += (double)bRet;
13321 }
13322 
13323 struct IdxRemCtx {
13324   int nSlot;
13325   struct IdxRemSlot {
13326     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
13327     i64 iVal;                     /* SQLITE_INTEGER value */
13328     double rVal;                  /* SQLITE_FLOAT value */
13329     int nByte;                    /* Bytes of space allocated at z */
13330     int n;                        /* Size of buffer z */
13331     char *z;                      /* SQLITE_TEXT/BLOB value */
13332   } aSlot[1];
13333 };
13334 
13335 /*
13336 ** Implementation of scalar function rem().
13337 */
idxRemFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)13338 static void idxRemFunc(
13339   sqlite3_context *pCtx,
13340   int argc,
13341   sqlite3_value **argv
13342 ){
13343   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
13344   struct IdxRemSlot *pSlot;
13345   int iSlot;
13346   assert( argc==2 );
13347 
13348   iSlot = sqlite3_value_int(argv[0]);
13349   assert( iSlot<=p->nSlot );
13350   pSlot = &p->aSlot[iSlot];
13351 
13352   switch( pSlot->eType ){
13353     case SQLITE_NULL:
13354       /* no-op */
13355       break;
13356 
13357     case SQLITE_INTEGER:
13358       sqlite3_result_int64(pCtx, pSlot->iVal);
13359       break;
13360 
13361     case SQLITE_FLOAT:
13362       sqlite3_result_double(pCtx, pSlot->rVal);
13363       break;
13364 
13365     case SQLITE_BLOB:
13366       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13367       break;
13368 
13369     case SQLITE_TEXT:
13370       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13371       break;
13372   }
13373 
13374   pSlot->eType = sqlite3_value_type(argv[1]);
13375   switch( pSlot->eType ){
13376     case SQLITE_NULL:
13377       /* no-op */
13378       break;
13379 
13380     case SQLITE_INTEGER:
13381       pSlot->iVal = sqlite3_value_int64(argv[1]);
13382       break;
13383 
13384     case SQLITE_FLOAT:
13385       pSlot->rVal = sqlite3_value_double(argv[1]);
13386       break;
13387 
13388     case SQLITE_BLOB:
13389     case SQLITE_TEXT: {
13390       int nByte = sqlite3_value_bytes(argv[1]);
13391       const void *pData = 0;
13392       if( nByte>pSlot->nByte ){
13393         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
13394         if( zNew==0 ){
13395           sqlite3_result_error_nomem(pCtx);
13396           return;
13397         }
13398         pSlot->nByte = nByte*2;
13399         pSlot->z = zNew;
13400       }
13401       pSlot->n = nByte;
13402       if( pSlot->eType==SQLITE_BLOB ){
13403         pData = sqlite3_value_blob(argv[1]);
13404         if( pData ) memcpy(pSlot->z, pData, nByte);
13405       }else{
13406         pData = sqlite3_value_text(argv[1]);
13407         memcpy(pSlot->z, pData, nByte);
13408       }
13409       break;
13410     }
13411   }
13412 }
13413 
idxLargestIndex(sqlite3 * db,int * pnMax,char ** pzErr)13414 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
13415   int rc = SQLITE_OK;
13416   const char *zMax =
13417     "SELECT max(i.seqno) FROM "
13418     "  sqlite_schema AS s, "
13419     "  pragma_index_list(s.name) AS l, "
13420     "  pragma_index_info(l.name) AS i "
13421     "WHERE s.type = 'table'";
13422   sqlite3_stmt *pMax = 0;
13423 
13424   *pnMax = 0;
13425   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
13426   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
13427     *pnMax = sqlite3_column_int(pMax, 0) + 1;
13428   }
13429   idxFinalize(&rc, pMax);
13430 
13431   return rc;
13432 }
13433 
idxPopulateOneStat1(sqlite3expert * p,sqlite3_stmt * pIndexXInfo,sqlite3_stmt * pWriteStat,const char * zTab,const char * zIdx,char ** pzErr)13434 static int idxPopulateOneStat1(
13435   sqlite3expert *p,
13436   sqlite3_stmt *pIndexXInfo,
13437   sqlite3_stmt *pWriteStat,
13438   const char *zTab,
13439   const char *zIdx,
13440   char **pzErr
13441 ){
13442   char *zCols = 0;
13443   char *zOrder = 0;
13444   char *zQuery = 0;
13445   int nCol = 0;
13446   int i;
13447   sqlite3_stmt *pQuery = 0;
13448   int *aStat = 0;
13449   int rc = SQLITE_OK;
13450 
13451   assert( p->iSample>0 );
13452 
13453   /* Formulate the query text */
13454   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
13455   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
13456     const char *zComma = zCols==0 ? "" : ", ";
13457     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
13458     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
13459     zCols = idxAppendText(&rc, zCols,
13460         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
13461     );
13462     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
13463   }
13464   sqlite3_reset(pIndexXInfo);
13465   if( rc==SQLITE_OK ){
13466     if( p->iSample==100 ){
13467       zQuery = sqlite3_mprintf(
13468           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
13469       );
13470     }else{
13471       zQuery = sqlite3_mprintf(
13472           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
13473       );
13474     }
13475   }
13476   sqlite3_free(zCols);
13477   sqlite3_free(zOrder);
13478 
13479   /* Formulate the query text */
13480   if( rc==SQLITE_OK ){
13481     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13482     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
13483   }
13484   sqlite3_free(zQuery);
13485 
13486   if( rc==SQLITE_OK ){
13487     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
13488   }
13489   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13490     IdxHashEntry *pEntry;
13491     char *zStat = 0;
13492     for(i=0; i<=nCol; i++) aStat[i] = 1;
13493     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13494       aStat[0]++;
13495       for(i=0; i<nCol; i++){
13496         if( sqlite3_column_int(pQuery, i)==0 ) break;
13497       }
13498       for(/*no-op*/; i<nCol; i++){
13499         aStat[i+1]++;
13500       }
13501     }
13502 
13503     if( rc==SQLITE_OK ){
13504       int s0 = aStat[0];
13505       zStat = sqlite3_mprintf("%d", s0);
13506       if( zStat==0 ) rc = SQLITE_NOMEM;
13507       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
13508         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
13509       }
13510     }
13511 
13512     if( rc==SQLITE_OK ){
13513       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
13514       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
13515       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
13516       sqlite3_step(pWriteStat);
13517       rc = sqlite3_reset(pWriteStat);
13518     }
13519 
13520     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
13521     if( pEntry ){
13522       assert( pEntry->zVal2==0 );
13523       pEntry->zVal2 = zStat;
13524     }else{
13525       sqlite3_free(zStat);
13526     }
13527   }
13528   sqlite3_free(aStat);
13529   idxFinalize(&rc, pQuery);
13530 
13531   return rc;
13532 }
13533 
idxBuildSampleTable(sqlite3expert * p,const char * zTab)13534 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
13535   int rc;
13536   char *zSql;
13537 
13538   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13539   if( rc!=SQLITE_OK ) return rc;
13540 
13541   zSql = sqlite3_mprintf(
13542       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
13543   );
13544   if( zSql==0 ) return SQLITE_NOMEM;
13545   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
13546   sqlite3_free(zSql);
13547 
13548   return rc;
13549 }
13550 
13551 /*
13552 ** This function is called as part of sqlite3_expert_analyze(). Candidate
13553 ** indexes have already been created in database sqlite3expert.dbm, this
13554 ** function populates sqlite_stat1 table in the same database.
13555 **
13556 ** The stat1 data is generated by querying the
13557 */
idxPopulateStat1(sqlite3expert * p,char ** pzErr)13558 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
13559   int rc = SQLITE_OK;
13560   int nMax =0;
13561   struct IdxRemCtx *pCtx = 0;
13562   struct IdxSampleCtx samplectx;
13563   int i;
13564   i64 iPrev = -100000;
13565   sqlite3_stmt *pAllIndex = 0;
13566   sqlite3_stmt *pIndexXInfo = 0;
13567   sqlite3_stmt *pWrite = 0;
13568 
13569   const char *zAllIndex =
13570     "SELECT s.rowid, s.name, l.name FROM "
13571     "  sqlite_schema AS s, "
13572     "  pragma_index_list(s.name) AS l "
13573     "WHERE s.type = 'table'";
13574   const char *zIndexXInfo =
13575     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
13576   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
13577 
13578   /* If iSample==0, no sqlite_stat1 data is required. */
13579   if( p->iSample==0 ) return SQLITE_OK;
13580 
13581   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
13582   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
13583 
13584   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
13585 
13586   if( rc==SQLITE_OK ){
13587     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
13588     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
13589   }
13590 
13591   if( rc==SQLITE_OK ){
13592     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13593     rc = sqlite3_create_function(
13594         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
13595     );
13596   }
13597   if( rc==SQLITE_OK ){
13598     rc = sqlite3_create_function(
13599         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
13600     );
13601   }
13602 
13603   if( rc==SQLITE_OK ){
13604     pCtx->nSlot = nMax+1;
13605     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
13606   }
13607   if( rc==SQLITE_OK ){
13608     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
13609   }
13610   if( rc==SQLITE_OK ){
13611     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
13612   }
13613 
13614   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
13615     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
13616     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
13617     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
13618     if( zTab==0 || zIdx==0 ) continue;
13619     if( p->iSample<100 && iPrev!=iRowid ){
13620       samplectx.target = (double)p->iSample / 100.0;
13621       samplectx.iTarget = p->iSample;
13622       samplectx.nRow = 0.0;
13623       samplectx.nRet = 0.0;
13624       rc = idxBuildSampleTable(p, zTab);
13625       if( rc!=SQLITE_OK ) break;
13626     }
13627     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
13628     iPrev = iRowid;
13629   }
13630   if( rc==SQLITE_OK && p->iSample<100 ){
13631     rc = sqlite3_exec(p->dbv,
13632         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
13633     );
13634   }
13635 
13636   idxFinalize(&rc, pAllIndex);
13637   idxFinalize(&rc, pIndexXInfo);
13638   idxFinalize(&rc, pWrite);
13639 
13640   if( pCtx ){
13641     for(i=0; i<pCtx->nSlot; i++){
13642       sqlite3_free(pCtx->aSlot[i].z);
13643     }
13644     sqlite3_free(pCtx);
13645   }
13646 
13647   if( rc==SQLITE_OK ){
13648     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
13649   }
13650 
13651   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13652   return rc;
13653 }
13654 
13655 /*
13656 ** Define and possibly pretend to use a useless collation sequence.
13657 ** This pretense allows expert to accept SQL using custom collations.
13658 */
dummyCompare(void * up1,int up2,const void * up3,int up4,const void * up5)13659 int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
13660   (void)up1;
13661   (void)up2;
13662   (void)up3;
13663   (void)up4;
13664   (void)up5;
13665   assert(0); /* VDBE should never be run. */
13666   return 0;
13667 }
13668 /* And a callback to register above upon actual need */
useDummyCS(void * up1,sqlite3 * db,int etr,const char * zName)13669 void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
13670   (void)up1;
13671   sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
13672 }
13673 
13674 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13675   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13676 /*
13677 ** dummy functions for no-op implementation of UDFs during expert's work
13678 */
dummyUDF(sqlite3_context * up1,int up2,sqlite3_value ** up3)13679 void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
13680   (void)up1;
13681   (void)up2;
13682   (void)up3;
13683   assert(0); /* VDBE should never be run. */
13684 }
dummyUDFvalue(sqlite3_context * up1)13685 void dummyUDFvalue(sqlite3_context *up1){
13686   (void)up1;
13687   assert(0); /* VDBE should never be run. */
13688 }
13689 
13690 /*
13691 ** Register UDFs from user database with another.
13692 */
registerUDFs(sqlite3 * dbSrc,sqlite3 * dbDst)13693 int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
13694   sqlite3_stmt *pStmt;
13695   int rc = sqlite3_prepare_v2(dbSrc,
13696             "SELECT name,type,enc,narg,flags "
13697             "FROM pragma_function_list() "
13698             "WHERE builtin==0", -1, &pStmt, 0);
13699   if( rc==SQLITE_OK ){
13700     while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
13701       int nargs = sqlite3_column_int(pStmt,3);
13702       int flags = sqlite3_column_int(pStmt,4);
13703       const char *name = (char*)sqlite3_column_text(pStmt,0);
13704       const char *type = (char*)sqlite3_column_text(pStmt,1);
13705       const char *enc = (char*)sqlite3_column_text(pStmt,2);
13706       if( name==0 || type==0 || enc==0 ){
13707         /* no-op.  Only happens on OOM */
13708       }else{
13709         int ienc = SQLITE_UTF8;
13710         int rcf = SQLITE_ERROR;
13711         if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
13712         else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
13713         ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
13714         if( strcmp(type,"w")==0 ){
13715           rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
13716                                                dummyUDF,dummyUDFvalue,0,0,0);
13717         }else if( strcmp(type,"a")==0 ){
13718           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13719                                         0,dummyUDF,dummyUDFvalue);
13720         }else if( strcmp(type,"s")==0 ){
13721           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13722                                         dummyUDF,0,0);
13723         }
13724         if( rcf!=SQLITE_OK ){
13725           rc = rcf;
13726           break;
13727         }
13728       }
13729     }
13730     sqlite3_finalize(pStmt);
13731     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
13732   }
13733   return rc;
13734 }
13735 #endif
13736 
13737 /*
13738 ** Allocate a new sqlite3expert object.
13739 */
sqlite3_expert_new(sqlite3 * db,char ** pzErrmsg)13740 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
13741   int rc = SQLITE_OK;
13742   sqlite3expert *pNew;
13743 
13744   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
13745 
13746   /* Open two in-memory databases to work with. The "vtab database" (dbv)
13747   ** will contain a virtual table corresponding to each real table in
13748   ** the user database schema, and a copy of each view. It is used to
13749   ** collect information regarding the WHERE, ORDER BY and other clauses
13750   ** of the user's query.
13751   */
13752   if( rc==SQLITE_OK ){
13753     pNew->db = db;
13754     pNew->iSample = 100;
13755     rc = sqlite3_open(":memory:", &pNew->dbv);
13756   }
13757   if( rc==SQLITE_OK ){
13758     rc = sqlite3_open(":memory:", &pNew->dbm);
13759     if( rc==SQLITE_OK ){
13760       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
13761     }
13762   }
13763 
13764   /* Allow custom collations to be dealt with through prepare. */
13765   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
13766   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
13767 
13768 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13769   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13770   /* Register UDFs from database [db] with [dbm] and [dbv]. */
13771   if( rc==SQLITE_OK ){
13772     rc = registerUDFs(pNew->db, pNew->dbm);
13773   }
13774   if( rc==SQLITE_OK ){
13775     rc = registerUDFs(pNew->db, pNew->dbv);
13776   }
13777 #endif
13778 
13779   /* Copy the entire schema of database [db] into [dbm]. */
13780   if( rc==SQLITE_OK ){
13781     sqlite3_stmt *pSql = 0;
13782     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
13783         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
13784         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
13785     );
13786     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
13787       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
13788       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
13789     }
13790     idxFinalize(&rc, pSql);
13791   }
13792 
13793   /* Create the vtab schema */
13794   if( rc==SQLITE_OK ){
13795     rc = idxCreateVtabSchema(pNew, pzErrmsg);
13796   }
13797 
13798   /* Register the auth callback with dbv */
13799   if( rc==SQLITE_OK ){
13800     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
13801   }
13802 
13803   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
13804   ** return the new sqlite3expert handle.  */
13805   if( rc!=SQLITE_OK ){
13806     sqlite3_expert_destroy(pNew);
13807     pNew = 0;
13808   }
13809   return pNew;
13810 }
13811 
13812 /*
13813 ** Configure an sqlite3expert object.
13814 */
sqlite3_expert_config(sqlite3expert * p,int op,...)13815 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
13816   int rc = SQLITE_OK;
13817   va_list ap;
13818   va_start(ap, op);
13819   switch( op ){
13820     case EXPERT_CONFIG_SAMPLE: {
13821       int iVal = va_arg(ap, int);
13822       if( iVal<0 ) iVal = 0;
13823       if( iVal>100 ) iVal = 100;
13824       p->iSample = iVal;
13825       break;
13826     }
13827     default:
13828       rc = SQLITE_NOTFOUND;
13829       break;
13830   }
13831 
13832   va_end(ap);
13833   return rc;
13834 }
13835 
13836 /*
13837 ** Add an SQL statement to the analysis.
13838 */
sqlite3_expert_sql(sqlite3expert * p,const char * zSql,char ** pzErr)13839 int sqlite3_expert_sql(
13840   sqlite3expert *p,               /* From sqlite3_expert_new() */
13841   const char *zSql,               /* SQL statement to add */
13842   char **pzErr                    /* OUT: Error message (if any) */
13843 ){
13844   IdxScan *pScanOrig = p->pScan;
13845   IdxStatement *pStmtOrig = p->pStatement;
13846   int rc = SQLITE_OK;
13847   const char *zStmt = zSql;
13848 
13849   if( p->bRun ) return SQLITE_MISUSE;
13850 
13851   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
13852     sqlite3_stmt *pStmt = 0;
13853     /* Ensure that the provided statement compiles against user's DB. */
13854     rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
13855     if( rc!=SQLITE_OK ) break;
13856     sqlite3_finalize(pStmt);
13857     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
13858     if( rc==SQLITE_OK ){
13859       if( pStmt ){
13860         IdxStatement *pNew;
13861         const char *z = sqlite3_sql(pStmt);
13862         int n = STRLEN(z);
13863         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
13864         if( rc==SQLITE_OK ){
13865           pNew->zSql = (char*)&pNew[1];
13866           memcpy(pNew->zSql, z, n+1);
13867           pNew->pNext = p->pStatement;
13868           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
13869           p->pStatement = pNew;
13870         }
13871         sqlite3_finalize(pStmt);
13872       }
13873     }else{
13874       idxDatabaseError(p->dbv, pzErr);
13875     }
13876   }
13877 
13878   if( rc!=SQLITE_OK ){
13879     idxScanFree(p->pScan, pScanOrig);
13880     idxStatementFree(p->pStatement, pStmtOrig);
13881     p->pScan = pScanOrig;
13882     p->pStatement = pStmtOrig;
13883   }
13884 
13885   return rc;
13886 }
13887 
sqlite3_expert_analyze(sqlite3expert * p,char ** pzErr)13888 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
13889   int rc;
13890   IdxHashEntry *pEntry;
13891 
13892   /* Do trigger processing to collect any extra IdxScan structures */
13893   rc = idxProcessTriggers(p, pzErr);
13894 
13895   /* Create candidate indexes within the in-memory database file */
13896   if( rc==SQLITE_OK ){
13897     rc = idxCreateCandidates(p);
13898   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
13899     if( pzErr )
13900       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
13901     return rc;
13902   }
13903 
13904   /* Generate the stat1 data */
13905   if( rc==SQLITE_OK ){
13906     rc = idxPopulateStat1(p, pzErr);
13907   }
13908 
13909   /* Formulate the EXPERT_REPORT_CANDIDATES text */
13910   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13911     p->zCandidates = idxAppendText(&rc, p->zCandidates,
13912         "%s;%s%s\n", pEntry->zVal,
13913         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
13914     );
13915   }
13916 
13917   /* Figure out which of the candidate indexes are preferred by the query
13918   ** planner and report the results to the user.  */
13919   if( rc==SQLITE_OK ){
13920     rc = idxFindIndexes(p, pzErr);
13921   }
13922 
13923   if( rc==SQLITE_OK ){
13924     p->bRun = 1;
13925   }
13926   return rc;
13927 }
13928 
13929 /*
13930 ** Return the total number of statements that have been added to this
13931 ** sqlite3expert using sqlite3_expert_sql().
13932 */
sqlite3_expert_count(sqlite3expert * p)13933 int sqlite3_expert_count(sqlite3expert *p){
13934   int nRet = 0;
13935   if( p->pStatement ) nRet = p->pStatement->iId+1;
13936   return nRet;
13937 }
13938 
13939 /*
13940 ** Return a component of the report.
13941 */
sqlite3_expert_report(sqlite3expert * p,int iStmt,int eReport)13942 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
13943   const char *zRet = 0;
13944   IdxStatement *pStmt;
13945 
13946   if( p->bRun==0 ) return 0;
13947   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
13948   switch( eReport ){
13949     case EXPERT_REPORT_SQL:
13950       if( pStmt ) zRet = pStmt->zSql;
13951       break;
13952     case EXPERT_REPORT_INDEXES:
13953       if( pStmt ) zRet = pStmt->zIdx;
13954       break;
13955     case EXPERT_REPORT_PLAN:
13956       if( pStmt ) zRet = pStmt->zEQP;
13957       break;
13958     case EXPERT_REPORT_CANDIDATES:
13959       zRet = p->zCandidates;
13960       break;
13961   }
13962   return zRet;
13963 }
13964 
13965 /*
13966 ** Free an sqlite3expert object.
13967 */
sqlite3_expert_destroy(sqlite3expert * p)13968 void sqlite3_expert_destroy(sqlite3expert *p){
13969   if( p ){
13970     sqlite3_close(p->dbm);
13971     sqlite3_close(p->dbv);
13972     idxScanFree(p->pScan, 0);
13973     idxStatementFree(p->pStatement, 0);
13974     idxTableFree(p->pTable);
13975     idxWriteFree(p->pWrite);
13976     idxHashClear(&p->hIdx);
13977     sqlite3_free(p->zCandidates);
13978     sqlite3_free(p);
13979   }
13980 }
13981 
13982 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13983 
13984 /************************* End ../ext/expert/sqlite3expert.c ********************/
13985 
13986 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
13987 #define SQLITE_SHELL_HAVE_RECOVER 1
13988 #else
13989 #define SQLITE_SHELL_HAVE_RECOVER 0
13990 #endif
13991 #if SQLITE_SHELL_HAVE_RECOVER
13992 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
13993 /*
13994 ** 2022-08-27
13995 **
13996 ** The author disclaims copyright to this source code.  In place of
13997 ** a legal notice, here is a blessing:
13998 **
13999 **    May you do good and not evil.
14000 **    May you find forgiveness for yourself and forgive others.
14001 **    May you share freely, never taking more than you give.
14002 **
14003 *************************************************************************
14004 **
14005 ** This file contains the public interface to the "recover" extension -
14006 ** an SQLite extension designed to recover data from corrupted database
14007 ** files.
14008 */
14009 
14010 /*
14011 ** OVERVIEW:
14012 **
14013 ** To use the API to recover data from a corrupted database, an
14014 ** application:
14015 **
14016 **   1) Creates an sqlite3_recover handle by calling either
14017 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
14018 **
14019 **   2) Configures the new handle using one or more calls to
14020 **      sqlite3_recover_config().
14021 **
14022 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
14023 **      the handle until it returns something other than SQLITE_OK. If it
14024 **      returns SQLITE_DONE, then the recovery operation completed without
14025 **      error. If it returns some other non-SQLITE_OK value, then an error
14026 **      has occurred.
14027 **
14028 **   4) Retrieves any error code and English language error message using the
14029 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
14030 **      respectively.
14031 **
14032 **   5) Destroys the sqlite3_recover handle and frees all resources
14033 **      using sqlite3_recover_finish().
14034 **
14035 ** The application may abandon the recovery operation at any point
14036 ** before it is finished by passing the sqlite3_recover handle to
14037 ** sqlite3_recover_finish(). This is not an error, but the final state
14038 ** of the output database, or the results of running the partial script
14039 ** delivered to the SQL callback, are undefined.
14040 */
14041 
14042 #ifndef _SQLITE_RECOVER_H
14043 #define _SQLITE_RECOVER_H
14044 
14045 /* #include "sqlite3.h" */
14046 
14047 #ifdef __cplusplus
14048 extern "C" {
14049 #endif
14050 
14051 /*
14052 ** An instance of the sqlite3_recover object represents a recovery
14053 ** operation in progress.
14054 **
14055 ** Constructors:
14056 **
14057 **    sqlite3_recover_init()
14058 **    sqlite3_recover_init_sql()
14059 **
14060 ** Destructor:
14061 **
14062 **    sqlite3_recover_finish()
14063 **
14064 ** Methods:
14065 **
14066 **    sqlite3_recover_config()
14067 **    sqlite3_recover_errcode()
14068 **    sqlite3_recover_errmsg()
14069 **    sqlite3_recover_run()
14070 **    sqlite3_recover_step()
14071 */
14072 typedef struct sqlite3_recover sqlite3_recover;
14073 
14074 /*
14075 ** These two APIs attempt to create and return a new sqlite3_recover object.
14076 ** In both cases the first two arguments identify the (possibly
14077 ** corrupt) database to recover data from. The first argument is an open
14078 ** database handle and the second the name of a database attached to that
14079 ** handle (i.e. "main", "temp" or the name of an attached database).
14080 **
14081 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
14082 ** handle, then data is recovered into a new database, identified by
14083 ** string parameter zUri. zUri may be an absolute or relative file path,
14084 ** or may be an SQLite URI. If the identified database file already exists,
14085 ** it is overwritten.
14086 **
14087 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
14088 ** be returned to the user as a series of SQL statements. Executing these
14089 ** SQL statements results in the same database as would have been created
14090 ** had sqlite3_recover_init() been used. For each SQL statement in the
14091 ** output, the callback function passed as the third argument (xSql) is
14092 ** invoked once. The first parameter is a passed a copy of the fourth argument
14093 ** to this function (pCtx) as its first parameter, and a pointer to a
14094 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
14095 ** the second. If the xSql callback returns any value other than SQLITE_OK,
14096 ** then processing is immediately abandoned and the value returned used as
14097 ** the recover handle error code (see below).
14098 **
14099 ** If an out-of-memory error occurs, NULL may be returned instead of
14100 ** a valid handle. In all other cases, it is the responsibility of the
14101 ** application to avoid resource leaks by ensuring that
14102 ** sqlite3_recover_finish() is called on all allocated handles.
14103 */
14104 sqlite3_recover *sqlite3_recover_init(
14105   sqlite3* db,
14106   const char *zDb,
14107   const char *zUri
14108 );
14109 sqlite3_recover *sqlite3_recover_init_sql(
14110   sqlite3* db,
14111   const char *zDb,
14112   int (*xSql)(void*, const char*),
14113   void *pCtx
14114 );
14115 
14116 /*
14117 ** Configure an sqlite3_recover object that has just been created using
14118 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
14119 ** may only be called before the first call to sqlite3_recover_step()
14120 ** or sqlite3_recover_run() on the object.
14121 **
14122 ** The second argument passed to this function must be one of the
14123 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
14124 ** depend on the specific SQLITE_RECOVER_* symbol in use.
14125 **
14126 ** SQLITE_OK is returned if the configuration operation was successful,
14127 ** or an SQLite error code otherwise.
14128 */
14129 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
14130 
14131 /*
14132 ** SQLITE_RECOVER_LOST_AND_FOUND:
14133 **   The pArg argument points to a string buffer containing the name
14134 **   of a "lost-and-found" table in the output database, or NULL. If
14135 **   the argument is non-NULL and the database contains seemingly
14136 **   valid pages that cannot be associated with any table in the
14137 **   recovered part of the schema, data is extracted from these
14138 **   pages to add to the lost-and-found table.
14139 **
14140 ** SQLITE_RECOVER_FREELIST_CORRUPT:
14141 **   The pArg value must actually be a pointer to a value of type
14142 **   int containing value 0 or 1 cast as a (void*). If this option is set
14143 **   (argument is 1) and a lost-and-found table has been configured using
14144 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
14145 **   corrupt and an attempt is made to recover records from pages that
14146 **   appear to be linked into the freelist. Otherwise, pages on the freelist
14147 **   are ignored. Setting this option can recover more data from the
14148 **   database, but often ends up "recovering" deleted records. The default
14149 **   value is 0 (clear).
14150 **
14151 ** SQLITE_RECOVER_ROWIDS:
14152 **   The pArg value must actually be a pointer to a value of type
14153 **   int containing value 0 or 1 cast as a (void*). If this option is set
14154 **   (argument is 1), then an attempt is made to recover rowid values
14155 **   that are not also INTEGER PRIMARY KEY values. If this option is
14156 **   clear, then new rowids are assigned to all recovered rows. The
14157 **   default value is 1 (set).
14158 **
14159 ** SQLITE_RECOVER_SLOWINDEXES:
14160 **   The pArg value must actually be a pointer to a value of type
14161 **   int containing value 0 or 1 cast as a (void*). If this option is clear
14162 **   (argument is 0), then when creating an output database, the recover
14163 **   module creates and populates non-UNIQUE indexes right at the end of the
14164 **   recovery operation - after all recoverable data has been inserted
14165 **   into the new database. This is faster overall, but means that the
14166 **   final call to sqlite3_recover_step() for a recovery operation may
14167 **   be need to create a large number of indexes, which may be very slow.
14168 **
14169 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
14170 **   are created in the output database before it is populated with
14171 **   recovered data. This is slower overall, but avoids the slow call
14172 **   to sqlite3_recover_step() at the end of the recovery operation.
14173 **
14174 **   The default option value is 0.
14175 */
14176 #define SQLITE_RECOVER_LOST_AND_FOUND   1
14177 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
14178 #define SQLITE_RECOVER_ROWIDS           3
14179 #define SQLITE_RECOVER_SLOWINDEXES      4
14180 
14181 /*
14182 ** Perform a unit of work towards the recovery operation. This function
14183 ** must normally be called multiple times to complete database recovery.
14184 **
14185 ** If no error occurs but the recovery operation is not completed, this
14186 ** function returns SQLITE_OK. If recovery has been completed successfully
14187 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
14188 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
14189 ** considered an error if some or all of the data cannot be recovered
14190 ** due to database corruption.
14191 **
14192 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
14193 ** all further such calls on the same recover handle are no-ops that return
14194 ** the same non-SQLITE_OK value.
14195 */
14196 int sqlite3_recover_step(sqlite3_recover*);
14197 
14198 /*
14199 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
14200 ** or an SQLite error code otherwise. Calling this function is the same
14201 ** as executing:
14202 **
14203 **     while( SQLITE_OK==sqlite3_recover_step(p) );
14204 **     return sqlite3_recover_errcode(p);
14205 */
14206 int sqlite3_recover_run(sqlite3_recover*);
14207 
14208 /*
14209 ** If an error has been encountered during a prior call to
14210 ** sqlite3_recover_step(), then this function attempts to return a
14211 ** pointer to a buffer containing an English language explanation of
14212 ** the error. If no error message is available, or if an out-of memory
14213 ** error occurs while attempting to allocate a buffer in which to format
14214 ** the error message, NULL is returned.
14215 **
14216 ** The returned buffer remains valid until the sqlite3_recover handle is
14217 ** destroyed using sqlite3_recover_finish().
14218 */
14219 const char *sqlite3_recover_errmsg(sqlite3_recover*);
14220 
14221 /*
14222 ** If this function is called on an sqlite3_recover handle after
14223 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
14224 */
14225 int sqlite3_recover_errcode(sqlite3_recover*);
14226 
14227 /*
14228 ** Clean up a recovery object created by a call to sqlite3_recover_init().
14229 ** The results of using a recovery object with any API after it has been
14230 ** passed to this function are undefined.
14231 **
14232 ** This function returns the same value as sqlite3_recover_errcode().
14233 */
14234 int sqlite3_recover_finish(sqlite3_recover*);
14235 
14236 
14237 #ifdef __cplusplus
14238 }  /* end of the 'extern "C"' block */
14239 #endif
14240 
14241 #endif /* ifndef _SQLITE_RECOVER_H */
14242 
14243 /************************* End ../ext/recover/sqlite3recover.h ********************/
14244 # ifndef SQLITE_HAVE_SQLITE3R
14245 /************************* Begin ../ext/recover/dbdata.c ******************/
14246 /*
14247 ** 2019-04-17
14248 **
14249 ** The author disclaims copyright to this source code.  In place of
14250 ** a legal notice, here is a blessing:
14251 **
14252 **    May you do good and not evil.
14253 **    May you find forgiveness for yourself and forgive others.
14254 **    May you share freely, never taking more than you give.
14255 **
14256 ******************************************************************************
14257 **
14258 ** This file contains an implementation of two eponymous virtual tables,
14259 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
14260 ** "sqlite_dbpage" eponymous virtual table be available.
14261 **
14262 ** SQLITE_DBDATA:
14263 **   sqlite_dbdata is used to extract data directly from a database b-tree
14264 **   page and its associated overflow pages, bypassing the b-tree layer.
14265 **   The table schema is equivalent to:
14266 **
14267 **     CREATE TABLE sqlite_dbdata(
14268 **       pgno INTEGER,
14269 **       cell INTEGER,
14270 **       field INTEGER,
14271 **       value ANY,
14272 **       schema TEXT HIDDEN
14273 **     );
14274 **
14275 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
14276 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
14277 **   "schema".
14278 **
14279 **   Each page of the database is inspected. If it cannot be interpreted as
14280 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
14281 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
14282 **   table contains one row for each field in the record associated with
14283 **   each cell on the page. For intkey b-trees, the key value is stored in
14284 **   field -1.
14285 **
14286 **   For example, for the database:
14287 **
14288 **     CREATE TABLE t1(a, b);     -- root page is page 2
14289 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
14290 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
14291 **
14292 **   the sqlite_dbdata table contains, as well as from entries related to
14293 **   page 1, content equivalent to:
14294 **
14295 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
14296 **         (2, 0, -1, 5     ),
14297 **         (2, 0,  0, 'v'   ),
14298 **         (2, 0,  1, 'five'),
14299 **         (2, 1, -1, 10    ),
14300 **         (2, 1,  0, 'x'   ),
14301 **         (2, 1,  1, 'ten' );
14302 **
14303 **   If database corruption is encountered, this module does not report an
14304 **   error. Instead, it attempts to extract as much data as possible and
14305 **   ignores the corruption.
14306 **
14307 ** SQLITE_DBPTR:
14308 **   The sqlite_dbptr table has the following schema:
14309 **
14310 **     CREATE TABLE sqlite_dbptr(
14311 **       pgno INTEGER,
14312 **       child INTEGER,
14313 **       schema TEXT HIDDEN
14314 **     );
14315 **
14316 **   It contains one entry for each b-tree pointer between a parent and
14317 **   child page in the database.
14318 */
14319 
14320 #if !defined(SQLITEINT_H)
14321 /* #include "sqlite3.h" */
14322 
14323 /* typedef unsigned char u8; */
14324 /* typedef unsigned int u32; */
14325 
14326 #endif
14327 #include <string.h>
14328 #include <assert.h>
14329 
14330 #ifndef SQLITE_OMIT_VIRTUALTABLE
14331 
14332 #define DBDATA_PADDING_BYTES 100
14333 
14334 typedef struct DbdataTable DbdataTable;
14335 typedef struct DbdataCursor DbdataCursor;
14336 
14337 /* Cursor object */
14338 struct DbdataCursor {
14339   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
14340   sqlite3_stmt *pStmt;            /* For fetching database pages */
14341 
14342   int iPgno;                      /* Current page number */
14343   u8 *aPage;                      /* Buffer containing page */
14344   int nPage;                      /* Size of aPage[] in bytes */
14345   int nCell;                      /* Number of cells on aPage[] */
14346   int iCell;                      /* Current cell number */
14347   int bOnePage;                   /* True to stop after one page */
14348   int szDb;
14349   sqlite3_int64 iRowid;
14350 
14351   /* Only for the sqlite_dbdata table */
14352   u8 *pRec;                       /* Buffer containing current record */
14353   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
14354   sqlite3_int64 nHdr;             /* Size of header in bytes */
14355   int iField;                     /* Current field number */
14356   u8 *pHdrPtr;
14357   u8 *pPtr;
14358   u32 enc;                        /* Text encoding */
14359 
14360   sqlite3_int64 iIntkey;          /* Integer key value */
14361 };
14362 
14363 /* Table object */
14364 struct DbdataTable {
14365   sqlite3_vtab base;              /* Base class.  Must be first */
14366   sqlite3 *db;                    /* The database connection */
14367   sqlite3_stmt *pStmt;            /* For fetching database pages */
14368   int bPtr;                       /* True for sqlite3_dbptr table */
14369 };
14370 
14371 /* Column and schema definitions for sqlite_dbdata */
14372 #define DBDATA_COLUMN_PGNO        0
14373 #define DBDATA_COLUMN_CELL        1
14374 #define DBDATA_COLUMN_FIELD       2
14375 #define DBDATA_COLUMN_VALUE       3
14376 #define DBDATA_COLUMN_SCHEMA      4
14377 #define DBDATA_SCHEMA             \
14378       "CREATE TABLE x("           \
14379       "  pgno INTEGER,"           \
14380       "  cell INTEGER,"           \
14381       "  field INTEGER,"          \
14382       "  value ANY,"              \
14383       "  schema TEXT HIDDEN"      \
14384       ")"
14385 
14386 /* Column and schema definitions for sqlite_dbptr */
14387 #define DBPTR_COLUMN_PGNO         0
14388 #define DBPTR_COLUMN_CHILD        1
14389 #define DBPTR_COLUMN_SCHEMA       2
14390 #define DBPTR_SCHEMA              \
14391       "CREATE TABLE x("           \
14392       "  pgno INTEGER,"           \
14393       "  child INTEGER,"          \
14394       "  schema TEXT HIDDEN"      \
14395       ")"
14396 
14397 /*
14398 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
14399 ** table.
14400 */
dbdataConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)14401 static int dbdataConnect(
14402   sqlite3 *db,
14403   void *pAux,
14404   int argc, const char *const*argv,
14405   sqlite3_vtab **ppVtab,
14406   char **pzErr
14407 ){
14408   DbdataTable *pTab = 0;
14409   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
14410 
14411   (void)argc;
14412   (void)argv;
14413   (void)pzErr;
14414   sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
14415   if( rc==SQLITE_OK ){
14416     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
14417     if( pTab==0 ){
14418       rc = SQLITE_NOMEM;
14419     }else{
14420       memset(pTab, 0, sizeof(DbdataTable));
14421       pTab->db = db;
14422       pTab->bPtr = (pAux!=0);
14423     }
14424   }
14425 
14426   *ppVtab = (sqlite3_vtab*)pTab;
14427   return rc;
14428 }
14429 
14430 /*
14431 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
14432 */
dbdataDisconnect(sqlite3_vtab * pVtab)14433 static int dbdataDisconnect(sqlite3_vtab *pVtab){
14434   DbdataTable *pTab = (DbdataTable*)pVtab;
14435   if( pTab ){
14436     sqlite3_finalize(pTab->pStmt);
14437     sqlite3_free(pVtab);
14438   }
14439   return SQLITE_OK;
14440 }
14441 
14442 /*
14443 ** This function interprets two types of constraints:
14444 **
14445 **       schema=?
14446 **       pgno=?
14447 **
14448 ** If neither are present, idxNum is set to 0. If schema=? is present,
14449 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
14450 ** in idxNum is set.
14451 **
14452 ** If both parameters are present, schema is in position 0 and pgno in
14453 ** position 1.
14454 */
dbdataBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdx)14455 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
14456   DbdataTable *pTab = (DbdataTable*)tab;
14457   int i;
14458   int iSchema = -1;
14459   int iPgno = -1;
14460   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
14461 
14462   for(i=0; i<pIdx->nConstraint; i++){
14463     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
14464     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
14465       if( p->iColumn==colSchema ){
14466         if( p->usable==0 ) return SQLITE_CONSTRAINT;
14467         iSchema = i;
14468       }
14469       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
14470         iPgno = i;
14471       }
14472     }
14473   }
14474 
14475   if( iSchema>=0 ){
14476     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
14477     pIdx->aConstraintUsage[iSchema].omit = 1;
14478   }
14479   if( iPgno>=0 ){
14480     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
14481     pIdx->aConstraintUsage[iPgno].omit = 1;
14482     pIdx->estimatedCost = 100;
14483     pIdx->estimatedRows =  50;
14484 
14485     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
14486       int iCol = pIdx->aOrderBy[0].iColumn;
14487       if( pIdx->nOrderBy==1 ){
14488         pIdx->orderByConsumed = (iCol==0 || iCol==1);
14489       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
14490         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
14491       }
14492     }
14493 
14494   }else{
14495     pIdx->estimatedCost = 100000000;
14496     pIdx->estimatedRows = 1000000000;
14497   }
14498   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
14499   return SQLITE_OK;
14500 }
14501 
14502 /*
14503 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
14504 */
dbdataOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)14505 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
14506   DbdataCursor *pCsr;
14507 
14508   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
14509   if( pCsr==0 ){
14510     return SQLITE_NOMEM;
14511   }else{
14512     memset(pCsr, 0, sizeof(DbdataCursor));
14513     pCsr->base.pVtab = pVTab;
14514   }
14515 
14516   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
14517   return SQLITE_OK;
14518 }
14519 
14520 /*
14521 ** Restore a cursor object to the state it was in when first allocated
14522 ** by dbdataOpen().
14523 */
dbdataResetCursor(DbdataCursor * pCsr)14524 static void dbdataResetCursor(DbdataCursor *pCsr){
14525   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
14526   if( pTab->pStmt==0 ){
14527     pTab->pStmt = pCsr->pStmt;
14528   }else{
14529     sqlite3_finalize(pCsr->pStmt);
14530   }
14531   pCsr->pStmt = 0;
14532   pCsr->iPgno = 1;
14533   pCsr->iCell = 0;
14534   pCsr->iField = 0;
14535   pCsr->bOnePage = 0;
14536   sqlite3_free(pCsr->aPage);
14537   sqlite3_free(pCsr->pRec);
14538   pCsr->pRec = 0;
14539   pCsr->aPage = 0;
14540 }
14541 
14542 /*
14543 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
14544 */
dbdataClose(sqlite3_vtab_cursor * pCursor)14545 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
14546   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14547   dbdataResetCursor(pCsr);
14548   sqlite3_free(pCsr);
14549   return SQLITE_OK;
14550 }
14551 
14552 /*
14553 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
14554 */
get_uint16(unsigned char * a)14555 static u32 get_uint16(unsigned char *a){
14556   return (a[0]<<8)|a[1];
14557 }
get_uint32(unsigned char * a)14558 static u32 get_uint32(unsigned char *a){
14559   return ((u32)a[0]<<24)
14560        | ((u32)a[1]<<16)
14561        | ((u32)a[2]<<8)
14562        | ((u32)a[3]);
14563 }
14564 
14565 /*
14566 ** Load page pgno from the database via the sqlite_dbpage virtual table.
14567 ** If successful, set (*ppPage) to point to a buffer containing the page
14568 ** data, (*pnPage) to the size of that buffer in bytes and return
14569 ** SQLITE_OK. In this case it is the responsibility of the caller to
14570 ** eventually free the buffer using sqlite3_free().
14571 **
14572 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
14573 ** return an SQLite error code.
14574 */
dbdataLoadPage(DbdataCursor * pCsr,u32 pgno,u8 ** ppPage,int * pnPage)14575 static int dbdataLoadPage(
14576   DbdataCursor *pCsr,             /* Cursor object */
14577   u32 pgno,                       /* Page number of page to load */
14578   u8 **ppPage,                    /* OUT: pointer to page buffer */
14579   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
14580 ){
14581   int rc2;
14582   int rc = SQLITE_OK;
14583   sqlite3_stmt *pStmt = pCsr->pStmt;
14584 
14585   *ppPage = 0;
14586   *pnPage = 0;
14587   if( pgno>0 ){
14588     sqlite3_bind_int64(pStmt, 2, pgno);
14589     if( SQLITE_ROW==sqlite3_step(pStmt) ){
14590       int nCopy = sqlite3_column_bytes(pStmt, 0);
14591       if( nCopy>0 ){
14592         u8 *pPage;
14593         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
14594         if( pPage==0 ){
14595           rc = SQLITE_NOMEM;
14596         }else{
14597           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
14598           memcpy(pPage, pCopy, nCopy);
14599           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
14600         }
14601         *ppPage = pPage;
14602         *pnPage = nCopy;
14603       }
14604     }
14605     rc2 = sqlite3_reset(pStmt);
14606     if( rc==SQLITE_OK ) rc = rc2;
14607   }
14608 
14609   return rc;
14610 }
14611 
14612 /*
14613 ** Read a varint.  Put the value in *pVal and return the number of bytes.
14614 */
dbdataGetVarint(const u8 * z,sqlite3_int64 * pVal)14615 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
14616   sqlite3_uint64 u = 0;
14617   int i;
14618   for(i=0; i<8; i++){
14619     u = (u<<7) + (z[i]&0x7f);
14620     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
14621   }
14622   u = (u<<8) + (z[i]&0xff);
14623   *pVal = (sqlite3_int64)u;
14624   return 9;
14625 }
14626 
14627 /*
14628 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
14629 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
14630 ** SQLite database except for key values in intkey tables.
14631 */
dbdataGetVarintU32(const u8 * z,sqlite3_int64 * pVal)14632 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
14633   sqlite3_int64 val;
14634   int nRet = dbdataGetVarint(z, &val);
14635   if( val<0 || val>0xFFFFFFFF ) val = 0;
14636   *pVal = val;
14637   return nRet;
14638 }
14639 
14640 /*
14641 ** Return the number of bytes of space used by an SQLite value of type
14642 ** eType.
14643 */
dbdataValueBytes(int eType)14644 static int dbdataValueBytes(int eType){
14645   switch( eType ){
14646     case 0: case 8: case 9:
14647     case 10: case 11:
14648       return 0;
14649     case 1:
14650       return 1;
14651     case 2:
14652       return 2;
14653     case 3:
14654       return 3;
14655     case 4:
14656       return 4;
14657     case 5:
14658       return 6;
14659     case 6:
14660     case 7:
14661       return 8;
14662     default:
14663       if( eType>0 ){
14664         return ((eType-12) / 2);
14665       }
14666       return 0;
14667   }
14668 }
14669 
14670 /*
14671 ** Load a value of type eType from buffer pData and use it to set the
14672 ** result of context object pCtx.
14673 */
dbdataValue(sqlite3_context * pCtx,u32 enc,int eType,u8 * pData,sqlite3_int64 nData)14674 static void dbdataValue(
14675   sqlite3_context *pCtx,
14676   u32 enc,
14677   int eType,
14678   u8 *pData,
14679   sqlite3_int64 nData
14680 ){
14681   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
14682     switch( eType ){
14683       case 0:
14684       case 10:
14685       case 11:
14686         sqlite3_result_null(pCtx);
14687         break;
14688 
14689       case 8:
14690         sqlite3_result_int(pCtx, 0);
14691         break;
14692       case 9:
14693         sqlite3_result_int(pCtx, 1);
14694         break;
14695 
14696       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
14697         sqlite3_uint64 v = (signed char)pData[0];
14698         pData++;
14699         switch( eType ){
14700           case 7:
14701           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
14702           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
14703           case 4:  v = (v<<8) + pData[0];  pData++;
14704           case 3:  v = (v<<8) + pData[0];  pData++;
14705           case 2:  v = (v<<8) + pData[0];  pData++;
14706         }
14707 
14708         if( eType==7 ){
14709           double r;
14710           memcpy(&r, &v, sizeof(r));
14711           sqlite3_result_double(pCtx, r);
14712         }else{
14713           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
14714         }
14715         break;
14716       }
14717 
14718       default: {
14719         int n = ((eType-12) / 2);
14720         if( eType % 2 ){
14721           switch( enc ){
14722 #ifndef SQLITE_OMIT_UTF16
14723             case SQLITE_UTF16BE:
14724               sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14725               break;
14726             case SQLITE_UTF16LE:
14727               sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14728               break;
14729 #endif
14730             default:
14731               sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
14732               break;
14733           }
14734         }else{
14735           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
14736         }
14737       }
14738     }
14739   }
14740 }
14741 
14742 /*
14743 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
14744 */
dbdataNext(sqlite3_vtab_cursor * pCursor)14745 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
14746   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14747   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
14748 
14749   pCsr->iRowid++;
14750   while( 1 ){
14751     int rc;
14752     int iOff = (pCsr->iPgno==1 ? 100 : 0);
14753     int bNextPage = 0;
14754 
14755     if( pCsr->aPage==0 ){
14756       while( 1 ){
14757         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
14758         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
14759         if( rc!=SQLITE_OK ) return rc;
14760         if( pCsr->aPage && pCsr->nPage>=256 ) break;
14761         sqlite3_free(pCsr->aPage);
14762         pCsr->aPage = 0;
14763         if( pCsr->bOnePage ) return SQLITE_OK;
14764         pCsr->iPgno++;
14765       }
14766 
14767       assert( iOff+3+2<=pCsr->nPage );
14768       pCsr->iCell = pTab->bPtr ? -2 : 0;
14769       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
14770     }
14771 
14772     if( pTab->bPtr ){
14773       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
14774         pCsr->iCell = pCsr->nCell;
14775       }
14776       pCsr->iCell++;
14777       if( pCsr->iCell>=pCsr->nCell ){
14778         sqlite3_free(pCsr->aPage);
14779         pCsr->aPage = 0;
14780         if( pCsr->bOnePage ) return SQLITE_OK;
14781         pCsr->iPgno++;
14782       }else{
14783         return SQLITE_OK;
14784       }
14785     }else{
14786       /* If there is no record loaded, load it now. */
14787       if( pCsr->pRec==0 ){
14788         int bHasRowid = 0;
14789         int nPointer = 0;
14790         sqlite3_int64 nPayload = 0;
14791         sqlite3_int64 nHdr = 0;
14792         int iHdr;
14793         int U, X;
14794         int nLocal;
14795 
14796         switch( pCsr->aPage[iOff] ){
14797           case 0x02:
14798             nPointer = 4;
14799             break;
14800           case 0x0a:
14801             break;
14802           case 0x0d:
14803             bHasRowid = 1;
14804             break;
14805           default:
14806             /* This is not a b-tree page with records on it. Continue. */
14807             pCsr->iCell = pCsr->nCell;
14808             break;
14809         }
14810 
14811         if( pCsr->iCell>=pCsr->nCell ){
14812           bNextPage = 1;
14813         }else{
14814 
14815           iOff += 8 + nPointer + pCsr->iCell*2;
14816           if( iOff>pCsr->nPage ){
14817             bNextPage = 1;
14818           }else{
14819             iOff = get_uint16(&pCsr->aPage[iOff]);
14820           }
14821 
14822           /* For an interior node cell, skip past the child-page number */
14823           iOff += nPointer;
14824 
14825           /* Load the "byte of payload including overflow" field */
14826           if( bNextPage || iOff>pCsr->nPage ){
14827             bNextPage = 1;
14828           }else{
14829             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
14830           }
14831 
14832           /* If this is a leaf intkey cell, load the rowid */
14833           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
14834             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
14835           }
14836 
14837           /* Figure out how much data to read from the local page */
14838           U = pCsr->nPage;
14839           if( bHasRowid ){
14840             X = U-35;
14841           }else{
14842             X = ((U-12)*64/255)-23;
14843           }
14844           if( nPayload<=X ){
14845             nLocal = nPayload;
14846           }else{
14847             int M, K;
14848             M = ((U-12)*32/255)-23;
14849             K = M+((nPayload-M)%(U-4));
14850             if( K<=X ){
14851               nLocal = K;
14852             }else{
14853               nLocal = M;
14854             }
14855           }
14856 
14857           if( bNextPage || nLocal+iOff>pCsr->nPage ){
14858             bNextPage = 1;
14859           }else{
14860 
14861             /* Allocate space for payload. And a bit more to catch small buffer
14862             ** overruns caused by attempting to read a varint or similar from
14863             ** near the end of a corrupt record.  */
14864             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
14865             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
14866             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
14867             pCsr->nRec = nPayload;
14868 
14869             /* Load the nLocal bytes of payload */
14870             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
14871             iOff += nLocal;
14872 
14873             /* Load content from overflow pages */
14874             if( nPayload>nLocal ){
14875               sqlite3_int64 nRem = nPayload - nLocal;
14876               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
14877               while( nRem>0 ){
14878                 u8 *aOvfl = 0;
14879                 int nOvfl = 0;
14880                 int nCopy;
14881                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
14882                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
14883                 if( rc!=SQLITE_OK ) return rc;
14884                 if( aOvfl==0 ) break;
14885 
14886                 nCopy = U-4;
14887                 if( nCopy>nRem ) nCopy = nRem;
14888                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
14889                 nRem -= nCopy;
14890 
14891                 pgnoOvfl = get_uint32(aOvfl);
14892                 sqlite3_free(aOvfl);
14893               }
14894             }
14895 
14896             iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
14897             if( nHdr>nPayload ) nHdr = 0;
14898             pCsr->nHdr = nHdr;
14899             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
14900             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
14901             pCsr->iField = (bHasRowid ? -1 : 0);
14902           }
14903         }
14904       }else{
14905         pCsr->iField++;
14906         if( pCsr->iField>0 ){
14907           sqlite3_int64 iType;
14908           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
14909             bNextPage = 1;
14910           }else{
14911             int szField = 0;
14912             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
14913             szField = dbdataValueBytes(iType);
14914             if( (pCsr->nRec - (pCsr->pPtr - pCsr->pRec))<szField ){
14915               pCsr->pPtr = &pCsr->pRec[pCsr->nRec];
14916             }else{
14917               pCsr->pPtr += szField;
14918             }
14919           }
14920         }
14921       }
14922 
14923       if( bNextPage ){
14924         sqlite3_free(pCsr->aPage);
14925         sqlite3_free(pCsr->pRec);
14926         pCsr->aPage = 0;
14927         pCsr->pRec = 0;
14928         if( pCsr->bOnePage ) return SQLITE_OK;
14929         pCsr->iPgno++;
14930       }else{
14931         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
14932           return SQLITE_OK;
14933         }
14934 
14935         /* Advance to the next cell. The next iteration of the loop will load
14936         ** the record and so on. */
14937         sqlite3_free(pCsr->pRec);
14938         pCsr->pRec = 0;
14939         pCsr->iCell++;
14940       }
14941     }
14942   }
14943 
14944   assert( !"can't get here" );
14945   return SQLITE_OK;
14946 }
14947 
14948 /*
14949 ** Return true if the cursor is at EOF.
14950 */
dbdataEof(sqlite3_vtab_cursor * pCursor)14951 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
14952   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14953   return pCsr->aPage==0;
14954 }
14955 
14956 /*
14957 ** Return true if nul-terminated string zSchema ends in "()". Or false
14958 ** otherwise.
14959 */
dbdataIsFunction(const char * zSchema)14960 static int dbdataIsFunction(const char *zSchema){
14961   size_t n = strlen(zSchema);
14962   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
14963     return (int)n-2;
14964   }
14965   return 0;
14966 }
14967 
14968 /*
14969 ** Determine the size in pages of database zSchema (where zSchema is
14970 ** "main", "temp" or the name of an attached database) and set
14971 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
14972 ** an SQLite error code.
14973 */
dbdataDbsize(DbdataCursor * pCsr,const char * zSchema)14974 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
14975   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
14976   char *zSql = 0;
14977   int rc, rc2;
14978   int nFunc = 0;
14979   sqlite3_stmt *pStmt = 0;
14980 
14981   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
14982     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
14983   }else{
14984     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
14985   }
14986   if( zSql==0 ) return SQLITE_NOMEM;
14987 
14988   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
14989   sqlite3_free(zSql);
14990   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
14991     pCsr->szDb = sqlite3_column_int(pStmt, 0);
14992   }
14993   rc2 = sqlite3_finalize(pStmt);
14994   if( rc==SQLITE_OK ) rc = rc2;
14995   return rc;
14996 }
14997 
14998 /*
14999 ** Attempt to figure out the encoding of the database by retrieving page 1
15000 ** and inspecting the header field. If successful, set the pCsr->enc variable
15001 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
15002 */
dbdataGetEncoding(DbdataCursor * pCsr)15003 static int dbdataGetEncoding(DbdataCursor *pCsr){
15004   int rc = SQLITE_OK;
15005   int nPg1 = 0;
15006   u8 *aPg1 = 0;
15007   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
15008   if( rc==SQLITE_OK && nPg1>=(56+4) ){
15009     pCsr->enc = get_uint32(&aPg1[56]);
15010   }
15011   sqlite3_free(aPg1);
15012   return rc;
15013 }
15014 
15015 
15016 /*
15017 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
15018 */
dbdataFilter(sqlite3_vtab_cursor * pCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)15019 static int dbdataFilter(
15020   sqlite3_vtab_cursor *pCursor,
15021   int idxNum, const char *idxStr,
15022   int argc, sqlite3_value **argv
15023 ){
15024   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15025   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
15026   int rc = SQLITE_OK;
15027   const char *zSchema = "main";
15028   (void)idxStr;
15029   (void)argc;
15030 
15031   dbdataResetCursor(pCsr);
15032   assert( pCsr->iPgno==1 );
15033   if( idxNum & 0x01 ){
15034     zSchema = (const char*)sqlite3_value_text(argv[0]);
15035     if( zSchema==0 ) zSchema = "";
15036   }
15037   if( idxNum & 0x02 ){
15038     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
15039     pCsr->bOnePage = 1;
15040   }else{
15041     rc = dbdataDbsize(pCsr, zSchema);
15042   }
15043 
15044   if( rc==SQLITE_OK ){
15045     int nFunc = 0;
15046     if( pTab->pStmt ){
15047       pCsr->pStmt = pTab->pStmt;
15048       pTab->pStmt = 0;
15049     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
15050       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
15051       if( zSql==0 ){
15052         rc = SQLITE_NOMEM;
15053       }else{
15054         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
15055         sqlite3_free(zSql);
15056       }
15057     }else{
15058       rc = sqlite3_prepare_v2(pTab->db,
15059           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
15060           &pCsr->pStmt, 0
15061       );
15062     }
15063   }
15064   if( rc==SQLITE_OK ){
15065     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
15066   }
15067 
15068   /* Try to determine the encoding of the db by inspecting the header
15069   ** field on page 1. */
15070   if( rc==SQLITE_OK ){
15071     rc = dbdataGetEncoding(pCsr);
15072   }
15073 
15074   if( rc!=SQLITE_OK ){
15075     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
15076   }
15077 
15078   if( rc==SQLITE_OK ){
15079     rc = dbdataNext(pCursor);
15080   }
15081   return rc;
15082 }
15083 
15084 /*
15085 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
15086 */
dbdataColumn(sqlite3_vtab_cursor * pCursor,sqlite3_context * ctx,int i)15087 static int dbdataColumn(
15088   sqlite3_vtab_cursor *pCursor,
15089   sqlite3_context *ctx,
15090   int i
15091 ){
15092   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15093   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
15094   if( pTab->bPtr ){
15095     switch( i ){
15096       case DBPTR_COLUMN_PGNO:
15097         sqlite3_result_int64(ctx, pCsr->iPgno);
15098         break;
15099       case DBPTR_COLUMN_CHILD: {
15100         int iOff = pCsr->iPgno==1 ? 100 : 0;
15101         if( pCsr->iCell<0 ){
15102           iOff += 8;
15103         }else{
15104           iOff += 12 + pCsr->iCell*2;
15105           if( iOff>pCsr->nPage ) return SQLITE_OK;
15106           iOff = get_uint16(&pCsr->aPage[iOff]);
15107         }
15108         if( iOff<=pCsr->nPage ){
15109           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
15110         }
15111         break;
15112       }
15113     }
15114   }else{
15115     switch( i ){
15116       case DBDATA_COLUMN_PGNO:
15117         sqlite3_result_int64(ctx, pCsr->iPgno);
15118         break;
15119       case DBDATA_COLUMN_CELL:
15120         sqlite3_result_int(ctx, pCsr->iCell);
15121         break;
15122       case DBDATA_COLUMN_FIELD:
15123         sqlite3_result_int(ctx, pCsr->iField);
15124         break;
15125       case DBDATA_COLUMN_VALUE: {
15126         if( pCsr->iField<0 ){
15127           sqlite3_result_int64(ctx, pCsr->iIntkey);
15128         }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
15129           sqlite3_int64 iType;
15130           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
15131           dbdataValue(
15132               ctx, pCsr->enc, iType, pCsr->pPtr,
15133               &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
15134           );
15135         }
15136         break;
15137       }
15138     }
15139   }
15140   return SQLITE_OK;
15141 }
15142 
15143 /*
15144 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
15145 */
dbdataRowid(sqlite3_vtab_cursor * pCursor,sqlite_int64 * pRowid)15146 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
15147   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15148   *pRowid = pCsr->iRowid;
15149   return SQLITE_OK;
15150 }
15151 
15152 
15153 /*
15154 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
15155 */
sqlite3DbdataRegister(sqlite3 * db)15156 static int sqlite3DbdataRegister(sqlite3 *db){
15157   static sqlite3_module dbdata_module = {
15158     0,                            /* iVersion */
15159     0,                            /* xCreate */
15160     dbdataConnect,                /* xConnect */
15161     dbdataBestIndex,              /* xBestIndex */
15162     dbdataDisconnect,             /* xDisconnect */
15163     0,                            /* xDestroy */
15164     dbdataOpen,                   /* xOpen - open a cursor */
15165     dbdataClose,                  /* xClose - close a cursor */
15166     dbdataFilter,                 /* xFilter - configure scan constraints */
15167     dbdataNext,                   /* xNext - advance a cursor */
15168     dbdataEof,                    /* xEof - check for end of scan */
15169     dbdataColumn,                 /* xColumn - read data */
15170     dbdataRowid,                  /* xRowid - read data */
15171     0,                            /* xUpdate */
15172     0,                            /* xBegin */
15173     0,                            /* xSync */
15174     0,                            /* xCommit */
15175     0,                            /* xRollback */
15176     0,                            /* xFindMethod */
15177     0,                            /* xRename */
15178     0,                            /* xSavepoint */
15179     0,                            /* xRelease */
15180     0,                            /* xRollbackTo */
15181     0,                            /* xShadowName */
15182     0                             /* xIntegrity */
15183   };
15184 
15185   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
15186   if( rc==SQLITE_OK ){
15187     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
15188   }
15189   return rc;
15190 }
15191 
sqlite3_dbdata_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)15192 int sqlite3_dbdata_init(
15193   sqlite3 *db,
15194   char **pzErrMsg,
15195   const sqlite3_api_routines *pApi
15196 ){
15197   (void)pzErrMsg;
15198   return sqlite3DbdataRegister(db);
15199 }
15200 
15201 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
15202 
15203 /************************* End ../ext/recover/dbdata.c ********************/
15204 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
15205 /*
15206 ** 2022-08-27
15207 **
15208 ** The author disclaims copyright to this source code.  In place of
15209 ** a legal notice, here is a blessing:
15210 **
15211 **    May you do good and not evil.
15212 **    May you find forgiveness for yourself and forgive others.
15213 **    May you share freely, never taking more than you give.
15214 **
15215 *************************************************************************
15216 **
15217 */
15218 
15219 
15220 /* #include "sqlite3recover.h" */
15221 #include <assert.h>
15222 #include <string.h>
15223 
15224 #ifndef SQLITE_OMIT_VIRTUALTABLE
15225 
15226 /*
15227 ** Declaration for public API function in file dbdata.c. This may be called
15228 ** with NULL as the final two arguments to register the sqlite_dbptr and
15229 ** sqlite_dbdata virtual tables with a database handle.
15230 */
15231 #ifdef _WIN32
15232 
15233 #endif
15234 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
15235 
15236 /* typedef unsigned int u32; */
15237 /* typedef unsigned char u8; */
15238 /* typedef sqlite3_int64 i64; */
15239 
15240 typedef struct RecoverTable RecoverTable;
15241 typedef struct RecoverColumn RecoverColumn;
15242 
15243 /*
15244 ** When recovering rows of data that can be associated with table
15245 ** definitions recovered from the sqlite_schema table, each table is
15246 ** represented by an instance of the following object.
15247 **
15248 ** iRoot:
15249 **   The root page in the original database. Not necessarily (and usually
15250 **   not) the same in the recovered database.
15251 **
15252 ** zTab:
15253 **   Name of the table.
15254 **
15255 ** nCol/aCol[]:
15256 **   aCol[] is an array of nCol columns. In the order in which they appear
15257 **   in the table.
15258 **
15259 ** bIntkey:
15260 **   Set to true for intkey tables, false for WITHOUT ROWID.
15261 **
15262 ** iRowidBind:
15263 **   Each column in the aCol[] array has associated with it the index of
15264 **   the bind parameter its values will be bound to in the INSERT statement
15265 **   used to construct the output database. If the table does has a rowid
15266 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
15267 **   index of the bind paramater to which the rowid value should be bound.
15268 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
15269 **   KEY column, then the rowid value should be bound to the index associated
15270 **   with the column.
15271 **
15272 ** pNext:
15273 **   All RecoverTable objects used by the recovery operation are allocated
15274 **   and populated as part of creating the recovered database schema in
15275 **   the output database, before any non-schema data are recovered. They
15276 **   are then stored in a singly-linked list linked by this variable beginning
15277 **   at sqlite3_recover.pTblList.
15278 */
15279 struct RecoverTable {
15280   u32 iRoot;                      /* Root page in original database */
15281   char *zTab;                     /* Name of table */
15282   int nCol;                       /* Number of columns in table */
15283   RecoverColumn *aCol;            /* Array of columns */
15284   int bIntkey;                    /* True for intkey, false for without rowid */
15285   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
15286   RecoverTable *pNext;
15287 };
15288 
15289 /*
15290 ** Each database column is represented by an instance of the following object
15291 ** stored in the RecoverTable.aCol[] array of the associated table.
15292 **
15293 ** iField:
15294 **   The index of the associated field within database records. Or -1 if
15295 **   there is no associated field (e.g. for virtual generated columns).
15296 **
15297 ** iBind:
15298 **   The bind index of the INSERT statement to bind this columns values
15299 **   to. Or 0 if there is no such index (iff (iField<0)).
15300 **
15301 ** bIPK:
15302 **   True if this is the INTEGER PRIMARY KEY column.
15303 **
15304 ** zCol:
15305 **   Name of column.
15306 **
15307 ** eHidden:
15308 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
15309 */
15310 struct RecoverColumn {
15311   int iField;                     /* Field in record on disk */
15312   int iBind;                      /* Binding to use in INSERT */
15313   int bIPK;                       /* True for IPK column */
15314   char *zCol;
15315   int eHidden;
15316 };
15317 
15318 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
15319 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
15320 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
15321 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
15322 
15323 /*
15324 ** Bitmap object used to track pages in the input database. Allocated
15325 ** and manipulated only by the following functions:
15326 **
15327 **     recoverBitmapAlloc()
15328 **     recoverBitmapFree()
15329 **     recoverBitmapSet()
15330 **     recoverBitmapQuery()
15331 **
15332 ** nPg:
15333 **   Largest page number that may be stored in the bitmap. The range
15334 **   of valid keys is 1 to nPg, inclusive.
15335 **
15336 ** aElem[]:
15337 **   Array large enough to contain a bit for each key. For key value
15338 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
15339 **   In other words, the following is true if bit iKey is set, or
15340 **   false if it is clear:
15341 **
15342 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
15343 */
15344 typedef struct RecoverBitmap RecoverBitmap;
15345 struct RecoverBitmap {
15346   i64 nPg;                        /* Size of bitmap */
15347   u32 aElem[1];                   /* Array of 32-bit bitmasks */
15348 };
15349 
15350 /*
15351 ** State variables (part of the sqlite3_recover structure) used while
15352 ** recovering data for tables identified in the recovered schema (state
15353 ** RECOVER_STATE_WRITING).
15354 */
15355 typedef struct RecoverStateW1 RecoverStateW1;
15356 struct RecoverStateW1 {
15357   sqlite3_stmt *pTbls;
15358   sqlite3_stmt *pSel;
15359   sqlite3_stmt *pInsert;
15360   int nInsert;
15361 
15362   RecoverTable *pTab;             /* Table currently being written */
15363   int nMax;                       /* Max column count in any schema table */
15364   sqlite3_value **apVal;          /* Array of nMax values */
15365   int nVal;                       /* Number of valid entries in apVal[] */
15366   int bHaveRowid;
15367   i64 iRowid;
15368   i64 iPrevPage;
15369   int iPrevCell;
15370 };
15371 
15372 /*
15373 ** State variables (part of the sqlite3_recover structure) used while
15374 ** recovering data destined for the lost and found table (states
15375 ** RECOVER_STATE_LOSTANDFOUND[123]).
15376 */
15377 typedef struct RecoverStateLAF RecoverStateLAF;
15378 struct RecoverStateLAF {
15379   RecoverBitmap *pUsed;
15380   i64 nPg;                        /* Size of db in pages */
15381   sqlite3_stmt *pAllAndParent;
15382   sqlite3_stmt *pMapInsert;
15383   sqlite3_stmt *pMaxField;
15384   sqlite3_stmt *pUsedPages;
15385   sqlite3_stmt *pFindRoot;
15386   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
15387   sqlite3_stmt *pAllPage;
15388   sqlite3_stmt *pPageData;
15389   sqlite3_value **apVal;
15390   int nMaxField;
15391 };
15392 
15393 /*
15394 ** Main recover handle structure.
15395 */
15396 struct sqlite3_recover {
15397   /* Copies of sqlite3_recover_init[_sql]() parameters */
15398   sqlite3 *dbIn;                  /* Input database */
15399   char *zDb;                      /* Name of input db ("main" etc.) */
15400   char *zUri;                     /* URI for output database */
15401   void *pSqlCtx;                  /* SQL callback context */
15402   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
15403 
15404   /* Values configured by sqlite3_recover_config() */
15405   char *zStateDb;                 /* State database to use (or NULL) */
15406   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
15407   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
15408   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
15409   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
15410 
15411   int pgsz;
15412   int detected_pgsz;
15413   int nReserve;
15414   u8 *pPage1Disk;
15415   u8 *pPage1Cache;
15416 
15417   /* Error code and error message */
15418   int errCode;                    /* For sqlite3_recover_errcode() */
15419   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
15420 
15421   int eState;
15422   int bCloseTransaction;
15423 
15424   /* Variables used with eState==RECOVER_STATE_WRITING */
15425   RecoverStateW1 w1;
15426 
15427   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
15428   RecoverStateLAF laf;
15429 
15430   /* Fields used within sqlite3_recover_run() */
15431   sqlite3 *dbOut;                 /* Output database */
15432   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
15433   RecoverTable *pTblList;         /* List of tables recovered from schema */
15434 };
15435 
15436 /*
15437 ** The various states in which an sqlite3_recover object may exist:
15438 **
15439 **   RECOVER_STATE_INIT:
15440 **    The object is initially created in this state. sqlite3_recover_step()
15441 **    has yet to be called. This is the only state in which it is permitted
15442 **    to call sqlite3_recover_config().
15443 **
15444 **   RECOVER_STATE_WRITING:
15445 **
15446 **   RECOVER_STATE_LOSTANDFOUND1:
15447 **    State to populate the bitmap of pages used by other tables or the
15448 **    database freelist.
15449 **
15450 **   RECOVER_STATE_LOSTANDFOUND2:
15451 **    Populate the recovery.map table - used to figure out a "root" page
15452 **    for each lost page from in the database from which records are
15453 **    extracted.
15454 **
15455 **   RECOVER_STATE_LOSTANDFOUND3:
15456 **    Populate the lost-and-found table itself.
15457 */
15458 #define RECOVER_STATE_INIT           0
15459 #define RECOVER_STATE_WRITING        1
15460 #define RECOVER_STATE_LOSTANDFOUND1  2
15461 #define RECOVER_STATE_LOSTANDFOUND2  3
15462 #define RECOVER_STATE_LOSTANDFOUND3  4
15463 #define RECOVER_STATE_SCHEMA2        5
15464 #define RECOVER_STATE_DONE           6
15465 
15466 
15467 /*
15468 ** Global variables used by this extension.
15469 */
15470 typedef struct RecoverGlobal RecoverGlobal;
15471 struct RecoverGlobal {
15472   const sqlite3_io_methods *pMethods;
15473   sqlite3_recover *p;
15474 };
15475 static RecoverGlobal recover_g;
15476 
15477 /*
15478 ** Use this static SQLite mutex to protect the globals during the
15479 ** first call to sqlite3_recover_step().
15480 */
15481 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
15482 
15483 
15484 /*
15485 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
15486 */
15487 #define RECOVER_ROWID_DEFAULT 1
15488 
15489 /*
15490 ** Mutex handling:
15491 **
15492 **    recoverEnterMutex()       -   Enter the recovery mutex
15493 **    recoverLeaveMutex()       -   Leave the recovery mutex
15494 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
15495 */
15496 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
15497 # define recoverEnterMutex()
15498 # define recoverLeaveMutex()
15499 #else
recoverEnterMutex(void)15500 static void recoverEnterMutex(void){
15501   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
15502 }
recoverLeaveMutex(void)15503 static void recoverLeaveMutex(void){
15504   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
15505 }
15506 #endif
15507 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
recoverAssertMutexHeld(void)15508 static void recoverAssertMutexHeld(void){
15509   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
15510 }
15511 #else
15512 # define recoverAssertMutexHeld()
15513 #endif
15514 
15515 
15516 /*
15517 ** Like strlen(). But handles NULL pointer arguments.
15518 */
recoverStrlen(const char * zStr)15519 static int recoverStrlen(const char *zStr){
15520   if( zStr==0 ) return 0;
15521   return (int)(strlen(zStr)&0x7fffffff);
15522 }
15523 
15524 /*
15525 ** This function is a no-op if the recover handle passed as the first
15526 ** argument already contains an error (if p->errCode!=SQLITE_OK).
15527 **
15528 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
15529 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
15530 ** if an OOM error occurs, NULL is returned and the handle error code
15531 ** (p->errCode) set to SQLITE_NOMEM.
15532 */
recoverMalloc(sqlite3_recover * p,i64 nByte)15533 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
15534   void *pRet = 0;
15535   assert( nByte>0 );
15536   if( p->errCode==SQLITE_OK ){
15537     pRet = sqlite3_malloc64(nByte);
15538     if( pRet ){
15539       memset(pRet, 0, nByte);
15540     }else{
15541       p->errCode = SQLITE_NOMEM;
15542     }
15543   }
15544   return pRet;
15545 }
15546 
15547 /*
15548 ** Set the error code and error message for the recover handle passed as
15549 ** the first argument. The error code is set to the value of parameter
15550 ** errCode.
15551 **
15552 ** Parameter zFmt must be a printf() style formatting string. The handle
15553 ** error message is set to the result of using any trailing arguments for
15554 ** parameter substitutions in the formatting string.
15555 **
15556 ** For example:
15557 **
15558 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
15559 */
recoverError(sqlite3_recover * p,int errCode,const char * zFmt,...)15560 static int recoverError(
15561   sqlite3_recover *p,
15562   int errCode,
15563   const char *zFmt, ...
15564 ){
15565   char *z = 0;
15566   va_list ap;
15567   va_start(ap, zFmt);
15568   if( zFmt ){
15569     z = sqlite3_vmprintf(zFmt, ap);
15570     va_end(ap);
15571   }
15572   sqlite3_free(p->zErrMsg);
15573   p->zErrMsg = z;
15574   p->errCode = errCode;
15575   return errCode;
15576 }
15577 
15578 
15579 /*
15580 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
15581 ** In this case it returns NULL.
15582 **
15583 ** Otherwise, an attempt is made to allocate and return a bitmap object
15584 ** large enough to store a bit for all page numbers between 1 and nPg,
15585 ** inclusive. The bitmap is initially zeroed.
15586 */
recoverBitmapAlloc(sqlite3_recover * p,i64 nPg)15587 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
15588   int nElem = (nPg+1+31) / 32;
15589   int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
15590   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
15591 
15592   if( pRet ){
15593     pRet->nPg = nPg;
15594   }
15595   return pRet;
15596 }
15597 
15598 /*
15599 ** Free a bitmap object allocated by recoverBitmapAlloc().
15600 */
recoverBitmapFree(RecoverBitmap * pMap)15601 static void recoverBitmapFree(RecoverBitmap *pMap){
15602   sqlite3_free(pMap);
15603 }
15604 
15605 /*
15606 ** Set the bit associated with page iPg in bitvec pMap.
15607 */
recoverBitmapSet(RecoverBitmap * pMap,i64 iPg)15608 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
15609   if( iPg<=pMap->nPg ){
15610     int iElem = (iPg / 32);
15611     int iBit = (iPg % 32);
15612     pMap->aElem[iElem] |= (((u32)1) << iBit);
15613   }
15614 }
15615 
15616 /*
15617 ** Query bitmap object pMap for the state of the bit associated with page
15618 ** iPg. Return 1 if it is set, or 0 otherwise.
15619 */
recoverBitmapQuery(RecoverBitmap * pMap,i64 iPg)15620 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
15621   int ret = 1;
15622   if( iPg<=pMap->nPg && iPg>0 ){
15623     int iElem = (iPg / 32);
15624     int iBit = (iPg % 32);
15625     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
15626   }
15627   return ret;
15628 }
15629 
15630 /*
15631 ** Set the recover handle error to the error code and message returned by
15632 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
15633 ** handle db.
15634 */
recoverDbError(sqlite3_recover * p,sqlite3 * db)15635 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
15636   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
15637 }
15638 
15639 /*
15640 ** This function is a no-op if recover handle p already contains an error
15641 ** (if p->errCode!=SQLITE_OK).
15642 **
15643 ** Otherwise, it attempts to prepare the SQL statement in zSql against
15644 ** database handle db. If successful, the statement handle is returned.
15645 ** Or, if an error occurs, NULL is returned and an error left in the
15646 ** recover handle.
15647 */
recoverPrepare(sqlite3_recover * p,sqlite3 * db,const char * zSql)15648 static sqlite3_stmt *recoverPrepare(
15649   sqlite3_recover *p,
15650   sqlite3 *db,
15651   const char *zSql
15652 ){
15653   sqlite3_stmt *pStmt = 0;
15654   if( p->errCode==SQLITE_OK ){
15655     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
15656       recoverDbError(p, db);
15657     }
15658   }
15659   return pStmt;
15660 }
15661 
15662 /*
15663 ** This function is a no-op if recover handle p already contains an error
15664 ** (if p->errCode!=SQLITE_OK).
15665 **
15666 ** Otherwise, argument zFmt is used as a printf() style format string,
15667 ** along with any trailing arguments, to create an SQL statement. This
15668 ** SQL statement is prepared against database handle db and, if successful,
15669 ** the statment handle returned. Or, if an error occurs - either during
15670 ** the printf() formatting or when preparing the resulting SQL - an
15671 ** error code and message are left in the recover handle.
15672 */
recoverPreparePrintf(sqlite3_recover * p,sqlite3 * db,const char * zFmt,...)15673 static sqlite3_stmt *recoverPreparePrintf(
15674   sqlite3_recover *p,
15675   sqlite3 *db,
15676   const char *zFmt, ...
15677 ){
15678   sqlite3_stmt *pStmt = 0;
15679   if( p->errCode==SQLITE_OK ){
15680     va_list ap;
15681     char *z;
15682     va_start(ap, zFmt);
15683     z = sqlite3_vmprintf(zFmt, ap);
15684     va_end(ap);
15685     if( z==0 ){
15686       p->errCode = SQLITE_NOMEM;
15687     }else{
15688       pStmt = recoverPrepare(p, db, z);
15689       sqlite3_free(z);
15690     }
15691   }
15692   return pStmt;
15693 }
15694 
15695 /*
15696 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
15697 ** indicates that an error occurred, and there is not already an error
15698 ** in the recover handle passed as the first argument, set the error
15699 ** code and error message appropriately.
15700 **
15701 ** This function returns a copy of the statement handle pointer passed
15702 ** as the second argument.
15703 */
recoverReset(sqlite3_recover * p,sqlite3_stmt * pStmt)15704 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
15705   int rc = sqlite3_reset(pStmt);
15706   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
15707     recoverDbError(p, sqlite3_db_handle(pStmt));
15708   }
15709   return pStmt;
15710 }
15711 
15712 /*
15713 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
15714 ** indicates that an error occurred, and there is not already an error
15715 ** in the recover handle passed as the first argument, set the error
15716 ** code and error message appropriately.
15717 */
recoverFinalize(sqlite3_recover * p,sqlite3_stmt * pStmt)15718 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
15719   sqlite3 *db = sqlite3_db_handle(pStmt);
15720   int rc = sqlite3_finalize(pStmt);
15721   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
15722     recoverDbError(p, db);
15723   }
15724 }
15725 
15726 /*
15727 ** This function is a no-op if recover handle p already contains an error
15728 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
15729 ** case.
15730 **
15731 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
15732 ** Or, if an error occurs, leave an error code and message in the recover
15733 ** handle and return a copy of the error code.
15734 */
recoverExec(sqlite3_recover * p,sqlite3 * db,const char * zSql)15735 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
15736   if( p->errCode==SQLITE_OK ){
15737     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
15738     if( rc ){
15739       recoverDbError(p, db);
15740     }
15741   }
15742   return p->errCode;
15743 }
15744 
15745 /*
15746 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
15747 ** error in the recover handle passed as the first argument if an error
15748 ** (e.g. an OOM) occurs.
15749 */
recoverBindValue(sqlite3_recover * p,sqlite3_stmt * pStmt,int iBind,sqlite3_value * pVal)15750 static void recoverBindValue(
15751   sqlite3_recover *p,
15752   sqlite3_stmt *pStmt,
15753   int iBind,
15754   sqlite3_value *pVal
15755 ){
15756   if( p->errCode==SQLITE_OK ){
15757     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
15758     if( rc ) recoverError(p, rc, 0);
15759   }
15760 }
15761 
15762 /*
15763 ** This function is a no-op if recover handle p already contains an error
15764 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
15765 **
15766 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
15767 ** formatting string and the result of using the trailing arguments for
15768 ** parameter substitution with it written into a buffer obtained from
15769 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
15770 ** It is the responsibility of the caller to eventually free the buffer
15771 ** using sqlite3_free().
15772 **
15773 ** Or, if an error occurs, an error code and message is left in the recover
15774 ** handle and NULL returned.
15775 */
recoverMPrintf(sqlite3_recover * p,const char * zFmt,...)15776 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
15777   va_list ap;
15778   char *z;
15779   va_start(ap, zFmt);
15780   z = sqlite3_vmprintf(zFmt, ap);
15781   va_end(ap);
15782   if( p->errCode==SQLITE_OK ){
15783     if( z==0 ) p->errCode = SQLITE_NOMEM;
15784   }else{
15785     sqlite3_free(z);
15786     z = 0;
15787   }
15788   return z;
15789 }
15790 
15791 /*
15792 ** This function is a no-op if recover handle p already contains an error
15793 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
15794 **
15795 ** Otherwise, execute "PRAGMA page_count" against the input database. If
15796 ** successful, return the integer result. Or, if an error occurs, leave an
15797 ** error code and error message in the sqlite3_recover handle and return
15798 ** zero.
15799 */
recoverPageCount(sqlite3_recover * p)15800 static i64 recoverPageCount(sqlite3_recover *p){
15801   i64 nPg = 0;
15802   if( p->errCode==SQLITE_OK ){
15803     sqlite3_stmt *pStmt = 0;
15804     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
15805     if( pStmt ){
15806       sqlite3_step(pStmt);
15807       nPg = sqlite3_column_int64(pStmt, 0);
15808     }
15809     recoverFinalize(p, pStmt);
15810   }
15811   return nPg;
15812 }
15813 
15814 /*
15815 ** Implementation of SQL scalar function "read_i32". The first argument to
15816 ** this function must be a blob. The second a non-negative integer. This
15817 ** function reads and returns a 32-bit big-endian integer from byte
15818 ** offset (4*<arg2>) of the blob.
15819 **
15820 **     SELECT read_i32(<blob>, <idx>)
15821 */
recoverReadI32(sqlite3_context * context,int argc,sqlite3_value ** argv)15822 static void recoverReadI32(
15823   sqlite3_context *context,
15824   int argc,
15825   sqlite3_value **argv
15826 ){
15827   const unsigned char *pBlob;
15828   int nBlob;
15829   int iInt;
15830 
15831   assert( argc==2 );
15832   nBlob = sqlite3_value_bytes(argv[0]);
15833   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
15834   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
15835 
15836   if( (iInt+1)*4<=nBlob ){
15837     const unsigned char *a = &pBlob[iInt*4];
15838     i64 iVal = ((i64)a[0]<<24)
15839              + ((i64)a[1]<<16)
15840              + ((i64)a[2]<< 8)
15841              + ((i64)a[3]<< 0);
15842     sqlite3_result_int64(context, iVal);
15843   }
15844 }
15845 
15846 /*
15847 ** Implementation of SQL scalar function "page_is_used". This function
15848 ** is used as part of the procedure for locating orphan rows for the
15849 ** lost-and-found table, and it depends on those routines having populated
15850 ** the sqlite3_recover.laf.pUsed variable.
15851 **
15852 ** The only argument to this function is a page-number. It returns true
15853 ** if the page has already been used somehow during data recovery, or false
15854 ** otherwise.
15855 **
15856 **     SELECT page_is_used(<pgno>);
15857 */
recoverPageIsUsed(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)15858 static void recoverPageIsUsed(
15859   sqlite3_context *pCtx,
15860   int nArg,
15861   sqlite3_value **apArg
15862 ){
15863   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15864   i64 pgno = sqlite3_value_int64(apArg[0]);
15865   assert( nArg==1 );
15866   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
15867 }
15868 
15869 /*
15870 ** The implementation of a user-defined SQL function invoked by the
15871 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
15872 ** of the database being recovered.
15873 **
15874 ** This function always takes a single integer argument. If the argument
15875 ** is zero, then the value returned is the number of pages in the db being
15876 ** recovered. If the argument is greater than zero, it is a page number.
15877 ** The value returned in this case is an SQL blob containing the data for
15878 ** the identified page of the db being recovered. e.g.
15879 **
15880 **     SELECT getpage(0);       -- return number of pages in db
15881 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
15882 */
recoverGetPage(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)15883 static void recoverGetPage(
15884   sqlite3_context *pCtx,
15885   int nArg,
15886   sqlite3_value **apArg
15887 ){
15888   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15889   i64 pgno = sqlite3_value_int64(apArg[0]);
15890   sqlite3_stmt *pStmt = 0;
15891 
15892   assert( nArg==1 );
15893   if( pgno==0 ){
15894     i64 nPg = recoverPageCount(p);
15895     sqlite3_result_int64(pCtx, nPg);
15896     return;
15897   }else{
15898     if( p->pGetPage==0 ){
15899       pStmt = p->pGetPage = recoverPreparePrintf(
15900           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
15901       );
15902     }else if( p->errCode==SQLITE_OK ){
15903       pStmt = p->pGetPage;
15904     }
15905 
15906     if( pStmt ){
15907       sqlite3_bind_int64(pStmt, 1, pgno);
15908       if( SQLITE_ROW==sqlite3_step(pStmt) ){
15909         const u8 *aPg;
15910         int nPg;
15911         assert( p->errCode==SQLITE_OK );
15912         aPg = sqlite3_column_blob(pStmt, 0);
15913         nPg = sqlite3_column_bytes(pStmt, 0);
15914         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
15915           aPg = p->pPage1Disk;
15916         }
15917         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
15918       }
15919       recoverReset(p, pStmt);
15920     }
15921   }
15922 
15923   if( p->errCode ){
15924     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
15925     sqlite3_result_error_code(pCtx, p->errCode);
15926   }
15927 }
15928 
15929 /*
15930 ** Find a string that is not found anywhere in z[].  Return a pointer
15931 ** to that string.
15932 **
15933 ** Try to use zA and zB first.  If both of those are already found in z[]
15934 ** then make up some string and store it in the buffer zBuf.
15935 */
recoverUnusedString(const char * z,const char * zA,const char * zB,char * zBuf)15936 static const char *recoverUnusedString(
15937   const char *z,                    /* Result must not appear anywhere in z */
15938   const char *zA, const char *zB,   /* Try these first */
15939   char *zBuf                        /* Space to store a generated string */
15940 ){
15941   unsigned i = 0;
15942   if( strstr(z, zA)==0 ) return zA;
15943   if( strstr(z, zB)==0 ) return zB;
15944   do{
15945     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
15946   }while( strstr(z,zBuf)!=0 );
15947   return zBuf;
15948 }
15949 
15950 /*
15951 ** Implementation of scalar SQL function "escape_crnl".  The argument passed to
15952 ** this function is the output of built-in function quote(). If the first
15953 ** character of the input is "'", indicating that the value passed to quote()
15954 ** was a text value, then this function searches the input for "\n" and "\r"
15955 ** characters and adds a wrapper similar to the following:
15956 **
15957 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
15958 **
15959 ** Or, if the first character of the input is not "'", then a copy of the input
15960 ** is returned.
15961 */
recoverEscapeCrnl(sqlite3_context * context,int argc,sqlite3_value ** argv)15962 static void recoverEscapeCrnl(
15963   sqlite3_context *context,
15964   int argc,
15965   sqlite3_value **argv
15966 ){
15967   const char *zText = (const char*)sqlite3_value_text(argv[0]);
15968   (void)argc;
15969   if( zText && zText[0]=='\'' ){
15970     int nText = sqlite3_value_bytes(argv[0]);
15971     int i;
15972     char zBuf1[20];
15973     char zBuf2[20];
15974     const char *zNL = 0;
15975     const char *zCR = 0;
15976     int nCR = 0;
15977     int nNL = 0;
15978 
15979     for(i=0; zText[i]; i++){
15980       if( zNL==0 && zText[i]=='\n' ){
15981         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
15982         nNL = (int)strlen(zNL);
15983       }
15984       if( zCR==0 && zText[i]=='\r' ){
15985         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
15986         nCR = (int)strlen(zCR);
15987       }
15988     }
15989 
15990     if( zNL || zCR ){
15991       int iOut = 0;
15992       i64 nMax = (nNL > nCR) ? nNL : nCR;
15993       i64 nAlloc = nMax * nText + (nMax+64)*2;
15994       char *zOut = (char*)sqlite3_malloc64(nAlloc);
15995       if( zOut==0 ){
15996         sqlite3_result_error_nomem(context);
15997         return;
15998       }
15999 
16000       if( zNL && zCR ){
16001         memcpy(&zOut[iOut], "replace(replace(", 16);
16002         iOut += 16;
16003       }else{
16004         memcpy(&zOut[iOut], "replace(", 8);
16005         iOut += 8;
16006       }
16007       for(i=0; zText[i]; i++){
16008         if( zText[i]=='\n' ){
16009           memcpy(&zOut[iOut], zNL, nNL);
16010           iOut += nNL;
16011         }else if( zText[i]=='\r' ){
16012           memcpy(&zOut[iOut], zCR, nCR);
16013           iOut += nCR;
16014         }else{
16015           zOut[iOut] = zText[i];
16016           iOut++;
16017         }
16018       }
16019 
16020       if( zNL ){
16021         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16022         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
16023         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
16024       }
16025       if( zCR ){
16026         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16027         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
16028         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
16029       }
16030 
16031       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
16032       sqlite3_free(zOut);
16033       return;
16034     }
16035   }
16036 
16037   sqlite3_result_value(context, argv[0]);
16038 }
16039 
16040 /*
16041 ** This function is a no-op if recover handle p already contains an error
16042 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16043 ** this case.
16044 **
16045 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
16046 ** parts of the database schema that can be extracted from the input database.
16047 **
16048 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
16049 ** and error message are left in the recover handle and a copy of the
16050 ** error code returned. It is not considered an error if part of all of
16051 ** the database schema cannot be recovered due to corruption.
16052 */
recoverCacheSchema(sqlite3_recover * p)16053 static int recoverCacheSchema(sqlite3_recover *p){
16054   return recoverExec(p, p->dbOut,
16055     "WITH RECURSIVE pages(p) AS ("
16056     "  SELECT 1"
16057     "    UNION"
16058     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
16059     ")"
16060     "INSERT INTO recovery.schema SELECT"
16061     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
16062     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
16063     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
16064     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
16065     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
16066     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
16067     "  SELECT p FROM pages"
16068     ") GROUP BY pgno, cell"
16069   );
16070 }
16071 
16072 /*
16073 ** If this recover handle is not in SQL callback mode (i.e. was not created
16074 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
16075 ** this function is a no-op. Otherwise, issue a callback with SQL statement
16076 ** zSql as the parameter.
16077 **
16078 ** If the callback returns non-zero, set the recover handle error code to
16079 ** the value returned (so that the caller will abandon processing).
16080 */
recoverSqlCallback(sqlite3_recover * p,const char * zSql)16081 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
16082   if( p->errCode==SQLITE_OK && p->xSql ){
16083     int res = p->xSql(p->pSqlCtx, zSql);
16084     if( res ){
16085       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
16086     }
16087   }
16088 }
16089 
16090 /*
16091 ** Transfer the following settings from the input database to the output
16092 ** database:
16093 **
16094 **   + page-size,
16095 **   + auto-vacuum settings,
16096 **   + database encoding,
16097 **   + user-version (PRAGMA user_version), and
16098 **   + application-id (PRAGMA application_id), and
16099 */
recoverTransferSettings(sqlite3_recover * p)16100 static void recoverTransferSettings(sqlite3_recover *p){
16101   const char *aPragma[] = {
16102     "encoding",
16103     "page_size",
16104     "auto_vacuum",
16105     "user_version",
16106     "application_id"
16107   };
16108   int ii;
16109 
16110   /* Truncate the output database to 0 pages in size. This is done by
16111   ** opening a new, empty, temp db, then using the backup API to clobber
16112   ** any existing output db with a copy of it. */
16113   if( p->errCode==SQLITE_OK ){
16114     sqlite3 *db2 = 0;
16115     int rc = sqlite3_open("", &db2);
16116     if( rc!=SQLITE_OK ){
16117       recoverDbError(p, db2);
16118       return;
16119     }
16120 
16121     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
16122       const char *zPrag = aPragma[ii];
16123       sqlite3_stmt *p1 = 0;
16124       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
16125       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
16126         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
16127         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
16128         recoverSqlCallback(p, z2);
16129         recoverExec(p, db2, z2);
16130         sqlite3_free(z2);
16131         if( zArg==0 ){
16132           recoverError(p, SQLITE_NOMEM, 0);
16133         }
16134       }
16135       recoverFinalize(p, p1);
16136     }
16137     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
16138 
16139     if( p->errCode==SQLITE_OK ){
16140       sqlite3 *db = p->dbOut;
16141       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
16142       if( pBackup ){
16143         sqlite3_backup_step(pBackup, -1);
16144         p->errCode = sqlite3_backup_finish(pBackup);
16145       }else{
16146         recoverDbError(p, db);
16147       }
16148     }
16149 
16150     sqlite3_close(db2);
16151   }
16152 }
16153 
16154 /*
16155 ** This function is a no-op if recover handle p already contains an error
16156 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16157 ** this case.
16158 **
16159 ** Otherwise, an attempt is made to open the output database, attach
16160 ** and create the schema of the temporary database used to store
16161 ** intermediate data, and to register all required user functions and
16162 ** virtual table modules with the output handle.
16163 **
16164 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
16165 ** and error message are left in the recover handle and a copy of the
16166 ** error code returned.
16167 */
recoverOpenOutput(sqlite3_recover * p)16168 static int recoverOpenOutput(sqlite3_recover *p){
16169   struct Func {
16170     const char *zName;
16171     int nArg;
16172     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
16173   } aFunc[] = {
16174     { "getpage", 1, recoverGetPage },
16175     { "page_is_used", 1, recoverPageIsUsed },
16176     { "read_i32", 2, recoverReadI32 },
16177     { "escape_crnl", 1, recoverEscapeCrnl },
16178   };
16179 
16180   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
16181   sqlite3 *db = 0;                /* New database handle */
16182   int ii;                         /* For iterating through aFunc[] */
16183 
16184   assert( p->dbOut==0 );
16185 
16186   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
16187     recoverDbError(p, db);
16188   }
16189 
16190   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
16191   ** These two are registered with the output database handle - this
16192   ** module depends on the input handle supporting the sqlite_dbpage
16193   ** virtual table only.  */
16194   if( p->errCode==SQLITE_OK ){
16195     p->errCode = sqlite3_dbdata_init(db, 0, 0);
16196   }
16197 
16198   /* Register the custom user-functions with the output handle. */
16199   for(ii=0;
16200       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
16201       ii++){
16202     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
16203         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
16204     );
16205   }
16206 
16207   p->dbOut = db;
16208   return p->errCode;
16209 }
16210 
16211 /*
16212 ** Attach the auxiliary database 'recovery' to the output database handle.
16213 ** This temporary database is used during the recovery process and then
16214 ** discarded.
16215 */
recoverOpenRecovery(sqlite3_recover * p)16216 static void recoverOpenRecovery(sqlite3_recover *p){
16217   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
16218   recoverExec(p, p->dbOut, zSql);
16219   recoverExec(p, p->dbOut,
16220       "PRAGMA writable_schema = 1;"
16221       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
16222       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
16223   );
16224   sqlite3_free(zSql);
16225 }
16226 
16227 
16228 /*
16229 ** This function is a no-op if recover handle p already contains an error
16230 ** (if p->errCode!=SQLITE_OK).
16231 **
16232 ** Otherwise, argument zName must be the name of a table that has just been
16233 ** created in the output database. This function queries the output db
16234 ** for the schema of said table, and creates a RecoverTable object to
16235 ** store the schema in memory. The new RecoverTable object is linked into
16236 ** the list at sqlite3_recover.pTblList.
16237 **
16238 ** Parameter iRoot must be the root page of table zName in the INPUT
16239 ** database.
16240 */
recoverAddTable(sqlite3_recover * p,const char * zName,i64 iRoot)16241 static void recoverAddTable(
16242   sqlite3_recover *p,
16243   const char *zName,              /* Name of table created in output db */
16244   i64 iRoot                       /* Root page of same table in INPUT db */
16245 ){
16246   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
16247       "PRAGMA table_xinfo(%Q)", zName
16248   );
16249 
16250   if( pStmt ){
16251     int iPk = -1;
16252     int iBind = 1;
16253     RecoverTable *pNew = 0;
16254     int nCol = 0;
16255     int nName = recoverStrlen(zName);
16256     int nByte = 0;
16257     while( sqlite3_step(pStmt)==SQLITE_ROW ){
16258       nCol++;
16259       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
16260     }
16261     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
16262     recoverReset(p, pStmt);
16263 
16264     pNew = recoverMalloc(p, nByte);
16265     if( pNew ){
16266       int i = 0;
16267       int iField = 0;
16268       char *csr = 0;
16269       pNew->aCol = (RecoverColumn*)&pNew[1];
16270       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
16271       pNew->nCol = nCol;
16272       pNew->iRoot = iRoot;
16273       memcpy(csr, zName, nName);
16274       csr += nName+1;
16275 
16276       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
16277         int iPKF = sqlite3_column_int(pStmt, 5);
16278         int n = sqlite3_column_bytes(pStmt, 1);
16279         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
16280         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
16281         int eHidden = sqlite3_column_int(pStmt, 6);
16282 
16283         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
16284         if( iPKF>1 ) iPk = -2;
16285         pNew->aCol[i].zCol = csr;
16286         pNew->aCol[i].eHidden = eHidden;
16287         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
16288           pNew->aCol[i].iField = -1;
16289         }else{
16290           pNew->aCol[i].iField = iField++;
16291         }
16292         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
16293          && eHidden!=RECOVER_EHIDDEN_STORED
16294         ){
16295           pNew->aCol[i].iBind = iBind++;
16296         }
16297         memcpy(csr, z, n);
16298         csr += (n+1);
16299       }
16300 
16301       pNew->pNext = p->pTblList;
16302       p->pTblList = pNew;
16303       pNew->bIntkey = 1;
16304     }
16305 
16306     recoverFinalize(p, pStmt);
16307 
16308     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
16309     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
16310       int iField = sqlite3_column_int(pStmt, 0);
16311       int iCol = sqlite3_column_int(pStmt, 1);
16312 
16313       assert( iCol<pNew->nCol );
16314       pNew->aCol[iCol].iField = iField;
16315 
16316       pNew->bIntkey = 0;
16317       iPk = -2;
16318     }
16319     recoverFinalize(p, pStmt);
16320 
16321     if( p->errCode==SQLITE_OK ){
16322       if( iPk>=0 ){
16323         pNew->aCol[iPk].bIPK = 1;
16324       }else if( pNew->bIntkey ){
16325         pNew->iRowidBind = iBind++;
16326       }
16327     }
16328   }
16329 }
16330 
16331 /*
16332 ** This function is called after recoverCacheSchema() has cached those parts
16333 ** of the input database schema that could be recovered in temporary table
16334 ** "recovery.schema". This function creates in the output database copies
16335 ** of all parts of that schema that must be created before the tables can
16336 ** be populated. Specifically, this means:
16337 **
16338 **     * all tables that are not VIRTUAL, and
16339 **     * UNIQUE indexes.
16340 **
16341 ** If the recovery handle uses SQL callbacks, then callbacks containing
16342 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
16343 **
16344 ** Additionally, records are added to the sqlite_schema table of the
16345 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
16346 ** records are written directly to sqlite_schema, not actually executed.
16347 ** If the handle is in SQL callback mode, then callbacks are invoked
16348 ** with equivalent SQL statements.
16349 */
recoverWriteSchema1(sqlite3_recover * p)16350 static int recoverWriteSchema1(sqlite3_recover *p){
16351   sqlite3_stmt *pSelect = 0;
16352   sqlite3_stmt *pTblname = 0;
16353 
16354   pSelect = recoverPrepare(p, p->dbOut,
16355       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
16356       "  SELECT rootpage, name, sql, "
16357       "    type='table', "
16358       "    sql LIKE 'create virtual%',"
16359       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
16360       "  FROM recovery.schema"
16361       ")"
16362       "SELECT rootpage, tbl, isVirtual, name, sql"
16363       " FROM dbschema "
16364       "  WHERE tbl OR isIndex"
16365       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
16366   );
16367 
16368   pTblname = recoverPrepare(p, p->dbOut,
16369       "SELECT name FROM sqlite_schema "
16370       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
16371   );
16372 
16373   if( pSelect ){
16374     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
16375     while( sqlite3_step(pSelect)==SQLITE_ROW ){
16376       i64 iRoot = sqlite3_column_int64(pSelect, 0);
16377       int bTable = sqlite3_column_int(pSelect, 1);
16378       int bVirtual = sqlite3_column_int(pSelect, 2);
16379       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
16380       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
16381       char *zFree = 0;
16382       int rc = SQLITE_OK;
16383 
16384       if( bVirtual ){
16385         zSql = (const char*)(zFree = recoverMPrintf(p,
16386             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
16387             zName, zName, zSql
16388         ));
16389       }
16390       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
16391       if( rc==SQLITE_OK ){
16392         recoverSqlCallback(p, zSql);
16393         if( bTable && !bVirtual ){
16394           if( SQLITE_ROW==sqlite3_step(pTblname) ){
16395             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
16396             recoverAddTable(p, zTbl, iRoot);
16397           }
16398           recoverReset(p, pTblname);
16399         }
16400       }else if( rc!=SQLITE_ERROR ){
16401         recoverDbError(p, p->dbOut);
16402       }
16403       sqlite3_free(zFree);
16404     }
16405   }
16406   recoverFinalize(p, pSelect);
16407   recoverFinalize(p, pTblname);
16408 
16409   return p->errCode;
16410 }
16411 
16412 /*
16413 ** This function is called after the output database has been populated. It
16414 ** adds all recovered schema elements that were not created in the output
16415 ** database by recoverWriteSchema1() - everything except for tables and
16416 ** UNIQUE indexes. Specifically:
16417 **
16418 **     * views,
16419 **     * triggers,
16420 **     * non-UNIQUE indexes.
16421 **
16422 ** If the recover handle is in SQL callback mode, then equivalent callbacks
16423 ** are issued to create the schema elements.
16424 */
recoverWriteSchema2(sqlite3_recover * p)16425 static int recoverWriteSchema2(sqlite3_recover *p){
16426   sqlite3_stmt *pSelect = 0;
16427 
16428   pSelect = recoverPrepare(p, p->dbOut,
16429       p->bSlowIndexes ?
16430       "SELECT rootpage, sql FROM recovery.schema "
16431       "  WHERE type!='table' AND type!='index'"
16432       :
16433       "SELECT rootpage, sql FROM recovery.schema "
16434       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
16435   );
16436 
16437   if( pSelect ){
16438     while( sqlite3_step(pSelect)==SQLITE_ROW ){
16439       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
16440       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
16441       if( rc==SQLITE_OK ){
16442         recoverSqlCallback(p, zSql);
16443       }else if( rc!=SQLITE_ERROR ){
16444         recoverDbError(p, p->dbOut);
16445       }
16446     }
16447   }
16448   recoverFinalize(p, pSelect);
16449 
16450   return p->errCode;
16451 }
16452 
16453 /*
16454 ** This function is a no-op if recover handle p already contains an error
16455 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
16456 **
16457 ** Otherwise, if the recover handle is configured to create an output
16458 ** database (was created by sqlite3_recover_init()), then this function
16459 ** prepares and returns an SQL statement to INSERT a new record into table
16460 ** pTab, assuming the first nField fields of a record extracted from disk
16461 ** are valid.
16462 **
16463 ** For example, if table pTab is:
16464 **
16465 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
16466 **
16467 ** And nField is 4, then the SQL statement prepared and returned is:
16468 **
16469 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
16470 **
16471 ** In this case even though 4 values were extracted from the input db,
16472 ** only 3 are written to the output, as the generated STORED column
16473 ** cannot be written.
16474 **
16475 ** If the recover handle is in SQL callback mode, then the SQL statement
16476 ** prepared is such that evaluating it returns a single row containing
16477 ** a single text value - itself an SQL statement similar to the above,
16478 ** except with SQL literals in place of the variables. For example:
16479 **
16480 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
16481 **          || quote(?1) || ', '
16482 **          || quote(?2) || ', '
16483 **          || quote(?3) || ')';
16484 **
16485 ** In either case, it is the responsibility of the caller to eventually
16486 ** free the statement handle using sqlite3_finalize().
16487 */
recoverInsertStmt(sqlite3_recover * p,RecoverTable * pTab,int nField)16488 static sqlite3_stmt *recoverInsertStmt(
16489   sqlite3_recover *p,
16490   RecoverTable *pTab,
16491   int nField
16492 ){
16493   sqlite3_stmt *pRet = 0;
16494   const char *zSep = "";
16495   const char *zSqlSep = "";
16496   char *zSql = 0;
16497   char *zFinal = 0;
16498   char *zBind = 0;
16499   int ii;
16500   int bSql = p->xSql ? 1 : 0;
16501 
16502   if( nField<=0 ) return 0;
16503 
16504   assert( nField<=pTab->nCol );
16505 
16506   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
16507 
16508   if( pTab->iRowidBind ){
16509     assert( pTab->bIntkey );
16510     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
16511     if( bSql ){
16512       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
16513     }else{
16514       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
16515     }
16516     zSqlSep = "||', '||";
16517     zSep = ", ";
16518   }
16519 
16520   for(ii=0; ii<nField; ii++){
16521     int eHidden = pTab->aCol[ii].eHidden;
16522     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
16523      && eHidden!=RECOVER_EHIDDEN_STORED
16524     ){
16525       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
16526       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
16527 
16528       if( bSql ){
16529         zBind = recoverMPrintf(p,
16530             "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
16531         );
16532         zSqlSep = "||', '||";
16533       }else{
16534         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
16535       }
16536       zSep = ", ";
16537     }
16538   }
16539 
16540   if( bSql ){
16541     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
16542         zSql, zBind
16543     );
16544   }else{
16545     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
16546   }
16547 
16548   pRet = recoverPrepare(p, p->dbOut, zFinal);
16549   sqlite3_free(zSql);
16550   sqlite3_free(zBind);
16551   sqlite3_free(zFinal);
16552 
16553   return pRet;
16554 }
16555 
16556 
16557 /*
16558 ** Search the list of RecoverTable objects at p->pTblList for one that
16559 ** has root page iRoot in the input database. If such an object is found,
16560 ** return a pointer to it. Otherwise, return NULL.
16561 */
recoverFindTable(sqlite3_recover * p,u32 iRoot)16562 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
16563   RecoverTable *pRet = 0;
16564   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
16565   return pRet;
16566 }
16567 
16568 /*
16569 ** This function attempts to create a lost and found table within the
16570 ** output db. If successful, it returns a pointer to a buffer containing
16571 ** the name of the new table. It is the responsibility of the caller to
16572 ** eventually free this buffer using sqlite3_free().
16573 **
16574 ** If an error occurs, NULL is returned and an error code and error
16575 ** message left in the recover handle.
16576 */
recoverLostAndFoundCreate(sqlite3_recover * p,int nField)16577 static char *recoverLostAndFoundCreate(
16578   sqlite3_recover *p,             /* Recover object */
16579   int nField                      /* Number of column fields in new table */
16580 ){
16581   char *zTbl = 0;
16582   sqlite3_stmt *pProbe = 0;
16583   int ii = 0;
16584 
16585   pProbe = recoverPrepare(p, p->dbOut,
16586     "SELECT 1 FROM sqlite_schema WHERE name=?"
16587   );
16588   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
16589     int bFail = 0;
16590     if( ii<0 ){
16591       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
16592     }else{
16593       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
16594     }
16595 
16596     if( p->errCode==SQLITE_OK ){
16597       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
16598       if( SQLITE_ROW==sqlite3_step(pProbe) ){
16599         bFail = 1;
16600       }
16601       recoverReset(p, pProbe);
16602     }
16603 
16604     if( bFail ){
16605       sqlite3_clear_bindings(pProbe);
16606       sqlite3_free(zTbl);
16607       zTbl = 0;
16608     }
16609   }
16610   recoverFinalize(p, pProbe);
16611 
16612   if( zTbl ){
16613     const char *zSep = 0;
16614     char *zField = 0;
16615     char *zSql = 0;
16616 
16617     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
16618     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
16619       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
16620       zSep = ", ";
16621     }
16622 
16623     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
16624     sqlite3_free(zField);
16625 
16626     recoverExec(p, p->dbOut, zSql);
16627     recoverSqlCallback(p, zSql);
16628     sqlite3_free(zSql);
16629   }else if( p->errCode==SQLITE_OK ){
16630     recoverError(
16631         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
16632     );
16633   }
16634 
16635   return zTbl;
16636 }
16637 
16638 /*
16639 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
16640 ** table in the output database. The name of the table is zTab, and it has
16641 ** nField c* fields.
16642 */
recoverLostAndFoundInsert(sqlite3_recover * p,const char * zTab,int nField)16643 static sqlite3_stmt *recoverLostAndFoundInsert(
16644   sqlite3_recover *p,
16645   const char *zTab,
16646   int nField
16647 ){
16648   int nTotal = nField + 4;
16649   int ii;
16650   char *zBind = 0;
16651   sqlite3_stmt *pRet = 0;
16652 
16653   if( p->xSql==0 ){
16654     for(ii=0; ii<nTotal; ii++){
16655       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
16656     }
16657     pRet = recoverPreparePrintf(
16658         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
16659     );
16660   }else{
16661     const char *zSep = "";
16662     for(ii=0; ii<nTotal; ii++){
16663       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
16664       zSep = "|| ', ' ||";
16665     }
16666     pRet = recoverPreparePrintf(
16667         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
16668     );
16669   }
16670 
16671   sqlite3_free(zBind);
16672   return pRet;
16673 }
16674 
16675 /*
16676 ** Input database page iPg contains data that will be written to the
16677 ** lost-and-found table of the output database. This function attempts
16678 ** to identify the root page of the tree that page iPg belonged to.
16679 ** If successful, it sets output variable (*piRoot) to the page number
16680 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
16681 ** an SQLite error code is returned and the final value of *piRoot
16682 ** undefined.
16683 */
recoverLostAndFoundFindRoot(sqlite3_recover * p,i64 iPg,i64 * piRoot)16684 static int recoverLostAndFoundFindRoot(
16685   sqlite3_recover *p,
16686   i64 iPg,
16687   i64 *piRoot
16688 ){
16689   RecoverStateLAF *pLaf = &p->laf;
16690 
16691   if( pLaf->pFindRoot==0 ){
16692     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
16693         "WITH RECURSIVE p(pgno) AS ("
16694         "  SELECT ?"
16695         "    UNION"
16696         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
16697         ") "
16698         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
16699         "    AND m.parent IS NULL"
16700     );
16701   }
16702   if( p->errCode==SQLITE_OK ){
16703     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
16704     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
16705       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
16706     }else{
16707       *piRoot = iPg;
16708     }
16709     recoverReset(p, pLaf->pFindRoot);
16710   }
16711   return p->errCode;
16712 }
16713 
16714 /*
16715 ** Recover data from page iPage of the input database and write it to
16716 ** the lost-and-found table in the output database.
16717 */
recoverLostAndFoundOnePage(sqlite3_recover * p,i64 iPage)16718 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
16719   RecoverStateLAF *pLaf = &p->laf;
16720   sqlite3_value **apVal = pLaf->apVal;
16721   sqlite3_stmt *pPageData = pLaf->pPageData;
16722   sqlite3_stmt *pInsert = pLaf->pInsert;
16723 
16724   int nVal = -1;
16725   int iPrevCell = 0;
16726   i64 iRoot = 0;
16727   int bHaveRowid = 0;
16728   i64 iRowid = 0;
16729   int ii = 0;
16730 
16731   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
16732   sqlite3_bind_int64(pPageData, 1, iPage);
16733   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
16734     int iCell = sqlite3_column_int64(pPageData, 0);
16735     int iField = sqlite3_column_int64(pPageData, 1);
16736 
16737     if( iPrevCell!=iCell && nVal>=0 ){
16738       /* Insert the new row */
16739       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
16740       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
16741       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
16742       if( bHaveRowid ){
16743         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
16744       }
16745       for(ii=0; ii<nVal; ii++){
16746         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
16747       }
16748       if( sqlite3_step(pInsert)==SQLITE_ROW ){
16749         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
16750       }
16751       recoverReset(p, pInsert);
16752 
16753       /* Discard the accumulated row data */
16754       for(ii=0; ii<nVal; ii++){
16755         sqlite3_value_free(apVal[ii]);
16756         apVal[ii] = 0;
16757       }
16758       sqlite3_clear_bindings(pInsert);
16759       bHaveRowid = 0;
16760       nVal = -1;
16761     }
16762 
16763     if( iCell<0 ) break;
16764 
16765     if( iField<0 ){
16766       assert( nVal==-1 );
16767       iRowid = sqlite3_column_int64(pPageData, 2);
16768       bHaveRowid = 1;
16769       nVal = 0;
16770     }else if( iField<pLaf->nMaxField ){
16771       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
16772       apVal[iField] = sqlite3_value_dup(pVal);
16773       assert( iField==nVal || (nVal==-1 && iField==0) );
16774       nVal = iField+1;
16775       if( apVal[iField]==0 ){
16776         recoverError(p, SQLITE_NOMEM, 0);
16777       }
16778     }
16779 
16780     iPrevCell = iCell;
16781   }
16782   recoverReset(p, pPageData);
16783 
16784   for(ii=0; ii<nVal; ii++){
16785     sqlite3_value_free(apVal[ii]);
16786     apVal[ii] = 0;
16787   }
16788 }
16789 
16790 /*
16791 ** Perform one step (sqlite3_recover_step()) of work for the connection
16792 ** passed as the only argument, which is guaranteed to be in
16793 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
16794 ** table of the output database is populated with recovered data that can
16795 ** not be assigned to any recovered schema object.
16796 */
recoverLostAndFound3Step(sqlite3_recover * p)16797 static int recoverLostAndFound3Step(sqlite3_recover *p){
16798   RecoverStateLAF *pLaf = &p->laf;
16799   if( p->errCode==SQLITE_OK ){
16800     if( pLaf->pInsert==0 ){
16801       return SQLITE_DONE;
16802     }else{
16803       if( p->errCode==SQLITE_OK ){
16804         int res = sqlite3_step(pLaf->pAllPage);
16805         if( res==SQLITE_ROW ){
16806           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
16807           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
16808             recoverLostAndFoundOnePage(p, iPage);
16809           }
16810         }else{
16811           recoverReset(p, pLaf->pAllPage);
16812           return SQLITE_DONE;
16813         }
16814       }
16815     }
16816   }
16817   return SQLITE_OK;
16818 }
16819 
16820 /*
16821 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
16822 ** state - during which the lost-and-found table of the output database
16823 ** is populated with recovered data that can not be assigned to any
16824 ** recovered schema object.
16825 */
recoverLostAndFound3Init(sqlite3_recover * p)16826 static void recoverLostAndFound3Init(sqlite3_recover *p){
16827   RecoverStateLAF *pLaf = &p->laf;
16828 
16829   if( pLaf->nMaxField>0 ){
16830     char *zTab = 0;               /* Name of lost_and_found table */
16831 
16832     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
16833     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
16834     sqlite3_free(zTab);
16835 
16836     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
16837         "WITH RECURSIVE seq(ii) AS ("
16838         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
16839         ")"
16840         "SELECT ii FROM seq" , p->laf.nPg
16841     );
16842     pLaf->pPageData = recoverPrepare(p, p->dbOut,
16843         "SELECT cell, field, value "
16844         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
16845         "UNION ALL "
16846         "SELECT -1, -1, -1"
16847     );
16848 
16849     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
16850         pLaf->nMaxField*sizeof(sqlite3_value*)
16851     );
16852   }
16853 }
16854 
16855 /*
16856 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
16857 ** tables recovered from the schema of the input database are populated with
16858 ** recovered data.
16859 */
recoverWriteDataInit(sqlite3_recover * p)16860 static int recoverWriteDataInit(sqlite3_recover *p){
16861   RecoverStateW1 *p1 = &p->w1;
16862   RecoverTable *pTbl = 0;
16863   int nByte = 0;
16864 
16865   /* Figure out the maximum number of columns for any table in the schema */
16866   assert( p1->nMax==0 );
16867   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
16868     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
16869   }
16870 
16871   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
16872   ** that will be written to the output database in a single row. */
16873   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
16874   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
16875   if( p1->apVal==0 ) return p->errCode;
16876 
16877   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
16878   ** to loop through cells that appear to belong to a single table (pSel). */
16879   p1->pTbls = recoverPrepare(p, p->dbOut,
16880       "SELECT rootpage FROM recovery.schema "
16881       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
16882       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
16883   );
16884   p1->pSel = recoverPrepare(p, p->dbOut,
16885       "WITH RECURSIVE pages(page) AS ("
16886       "  SELECT ?1"
16887       "    UNION"
16888       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
16889       "    WHERE pgno=page"
16890       ") "
16891       "SELECT page, cell, field, value "
16892       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
16893       "UNION ALL "
16894       "SELECT 0, 0, 0, 0"
16895   );
16896 
16897   return p->errCode;
16898 }
16899 
16900 /*
16901 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
16902 ** sqlite3_recover.w1).
16903 */
recoverWriteDataCleanup(sqlite3_recover * p)16904 static void recoverWriteDataCleanup(sqlite3_recover *p){
16905   RecoverStateW1 *p1 = &p->w1;
16906   int ii;
16907   for(ii=0; ii<p1->nVal; ii++){
16908     sqlite3_value_free(p1->apVal[ii]);
16909   }
16910   sqlite3_free(p1->apVal);
16911   recoverFinalize(p, p1->pInsert);
16912   recoverFinalize(p, p1->pTbls);
16913   recoverFinalize(p, p1->pSel);
16914   memset(p1, 0, sizeof(*p1));
16915 }
16916 
16917 /*
16918 ** Perform one step (sqlite3_recover_step()) of work for the connection
16919 ** passed as the only argument, which is guaranteed to be in
16920 ** RECOVER_STATE_WRITING state - during which tables recovered from the
16921 ** schema of the input database are populated with recovered data.
16922 */
recoverWriteDataStep(sqlite3_recover * p)16923 static int recoverWriteDataStep(sqlite3_recover *p){
16924   RecoverStateW1 *p1 = &p->w1;
16925   sqlite3_stmt *pSel = p1->pSel;
16926   sqlite3_value **apVal = p1->apVal;
16927 
16928   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
16929     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
16930       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
16931       p1->pTab = recoverFindTable(p, iRoot);
16932 
16933       recoverFinalize(p, p1->pInsert);
16934       p1->pInsert = 0;
16935 
16936       /* If this table is unknown, return early. The caller will invoke this
16937       ** function again and it will move on to the next table.  */
16938       if( p1->pTab==0 ) return p->errCode;
16939 
16940       /* If this is the sqlite_sequence table, delete any rows added by
16941       ** earlier INSERT statements on tables with AUTOINCREMENT primary
16942       ** keys before recovering its contents. The p1->pTbls SELECT statement
16943       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
16944       ** worry about it being modified after it is recovered. */
16945       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
16946         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
16947         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
16948       }
16949 
16950       /* Bind the root page of this table within the original database to
16951       ** SELECT statement p1->pSel. The SELECT statement will then iterate
16952       ** through cells that look like they belong to table pTab.  */
16953       sqlite3_bind_int64(pSel, 1, iRoot);
16954 
16955       p1->nVal = 0;
16956       p1->bHaveRowid = 0;
16957       p1->iPrevPage = -1;
16958       p1->iPrevCell = -1;
16959     }else{
16960       return SQLITE_DONE;
16961     }
16962   }
16963   assert( p->errCode!=SQLITE_OK || p1->pTab );
16964 
16965   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
16966     RecoverTable *pTab = p1->pTab;
16967 
16968     i64 iPage = sqlite3_column_int64(pSel, 0);
16969     int iCell = sqlite3_column_int(pSel, 1);
16970     int iField = sqlite3_column_int(pSel, 2);
16971     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
16972     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
16973 
16974     assert( bNewCell==0 || (iField==-1 || iField==0) );
16975     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
16976 
16977     if( bNewCell ){
16978       int ii = 0;
16979       if( p1->nVal>=0 ){
16980         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
16981           recoverFinalize(p, p1->pInsert);
16982           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
16983           p1->nInsert = p1->nVal;
16984         }
16985         if( p1->nVal>0 ){
16986           sqlite3_stmt *pInsert = p1->pInsert;
16987           for(ii=0; ii<pTab->nCol; ii++){
16988             RecoverColumn *pCol = &pTab->aCol[ii];
16989             int iBind = pCol->iBind;
16990             if( iBind>0 ){
16991               if( pCol->bIPK ){
16992                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
16993               }else if( pCol->iField<p1->nVal ){
16994                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
16995               }
16996             }
16997           }
16998           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
16999             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
17000           }
17001           if( SQLITE_ROW==sqlite3_step(pInsert) ){
17002             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
17003             recoverSqlCallback(p, z);
17004           }
17005           recoverReset(p, pInsert);
17006           assert( p->errCode || pInsert );
17007           if( pInsert ) sqlite3_clear_bindings(pInsert);
17008         }
17009       }
17010 
17011       for(ii=0; ii<p1->nVal; ii++){
17012         sqlite3_value_free(apVal[ii]);
17013         apVal[ii] = 0;
17014       }
17015       p1->nVal = -1;
17016       p1->bHaveRowid = 0;
17017     }
17018 
17019     if( iPage!=0 ){
17020       if( iField<0 ){
17021         p1->iRowid = sqlite3_column_int64(pSel, 3);
17022         assert( p1->nVal==-1 );
17023         p1->nVal = 0;
17024         p1->bHaveRowid = 1;
17025       }else if( iField<pTab->nCol ){
17026         assert( apVal[iField]==0 );
17027         apVal[iField] = sqlite3_value_dup( pVal );
17028         if( apVal[iField]==0 ){
17029           recoverError(p, SQLITE_NOMEM, 0);
17030         }
17031         p1->nVal = iField+1;
17032       }
17033       p1->iPrevCell = iCell;
17034       p1->iPrevPage = iPage;
17035     }
17036   }else{
17037     recoverReset(p, pSel);
17038     p1->pTab = 0;
17039   }
17040 
17041   return p->errCode;
17042 }
17043 
17044 /*
17045 ** Initialize resources required by sqlite3_recover_step() in
17046 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17047 ** already allocated to a recovered schema element is determined.
17048 */
recoverLostAndFound1Init(sqlite3_recover * p)17049 static void recoverLostAndFound1Init(sqlite3_recover *p){
17050   RecoverStateLAF *pLaf = &p->laf;
17051   sqlite3_stmt *pStmt = 0;
17052 
17053   assert( p->laf.pUsed==0 );
17054   pLaf->nPg = recoverPageCount(p);
17055   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
17056 
17057   /* Prepare a statement to iterate through all pages that are part of any tree
17058   ** in the recoverable part of the input database schema to the bitmap. And,
17059   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
17060   ** freelist.  */
17061   pStmt = recoverPrepare(
17062       p, p->dbOut,
17063       "WITH trunk(pgno) AS ("
17064       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
17065       "    UNION"
17066       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
17067       "),"
17068       "trunkdata(pgno, data) AS ("
17069       "  SELECT pgno, getpage(pgno) FROM trunk"
17070       "),"
17071       "freelist(data, n, freepgno) AS ("
17072       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
17073       "    UNION ALL"
17074       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
17075       "),"
17076       ""
17077       "roots(r) AS ("
17078       "  SELECT 1 UNION ALL"
17079       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
17080       "),"
17081       "used(page) AS ("
17082       "  SELECT r FROM roots"
17083       "    UNION"
17084       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
17085       "    WHERE pgno=page"
17086       ") "
17087       "SELECT page FROM used"
17088       " UNION ALL "
17089       "SELECT freepgno FROM freelist WHERE NOT ?"
17090   );
17091   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
17092   pLaf->pUsedPages = pStmt;
17093 }
17094 
17095 /*
17096 ** Perform one step (sqlite3_recover_step()) of work for the connection
17097 ** passed as the only argument, which is guaranteed to be in
17098 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17099 ** already allocated to a recovered schema element is determined.
17100 */
recoverLostAndFound1Step(sqlite3_recover * p)17101 static int recoverLostAndFound1Step(sqlite3_recover *p){
17102   RecoverStateLAF *pLaf = &p->laf;
17103   int rc = p->errCode;
17104   if( rc==SQLITE_OK ){
17105     rc = sqlite3_step(pLaf->pUsedPages);
17106     if( rc==SQLITE_ROW ){
17107       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
17108       recoverBitmapSet(pLaf->pUsed, iPg);
17109       rc = SQLITE_OK;
17110     }else{
17111       recoverFinalize(p, pLaf->pUsedPages);
17112       pLaf->pUsedPages = 0;
17113     }
17114   }
17115   return rc;
17116 }
17117 
17118 /*
17119 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
17120 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
17121 ** are sorted into sets that likely belonged to the same database tree.
17122 */
recoverLostAndFound2Init(sqlite3_recover * p)17123 static void recoverLostAndFound2Init(sqlite3_recover *p){
17124   RecoverStateLAF *pLaf = &p->laf;
17125 
17126   assert( p->laf.pAllAndParent==0 );
17127   assert( p->laf.pMapInsert==0 );
17128   assert( p->laf.pMaxField==0 );
17129   assert( p->laf.nMaxField==0 );
17130 
17131   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
17132       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
17133   );
17134   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
17135       "WITH RECURSIVE seq(ii) AS ("
17136       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
17137       ")"
17138       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
17139       " UNION ALL "
17140       "SELECT NULL, ii FROM seq", p->laf.nPg
17141   );
17142   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
17143       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
17144   );
17145 }
17146 
17147 /*
17148 ** Perform one step (sqlite3_recover_step()) of work for the connection
17149 ** passed as the only argument, which is guaranteed to be in
17150 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
17151 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
17152 ** to the same database tree.
17153 */
recoverLostAndFound2Step(sqlite3_recover * p)17154 static int recoverLostAndFound2Step(sqlite3_recover *p){
17155   RecoverStateLAF *pLaf = &p->laf;
17156   if( p->errCode==SQLITE_OK ){
17157     int res = sqlite3_step(pLaf->pAllAndParent);
17158     if( res==SQLITE_ROW ){
17159       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
17160       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
17161         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
17162         sqlite3_bind_value(pLaf->pMapInsert, 2,
17163             sqlite3_column_value(pLaf->pAllAndParent, 0)
17164         );
17165         sqlite3_step(pLaf->pMapInsert);
17166         recoverReset(p, pLaf->pMapInsert);
17167         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
17168         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
17169           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
17170           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
17171         }
17172         recoverReset(p, pLaf->pMaxField);
17173       }
17174     }else{
17175       recoverFinalize(p, pLaf->pAllAndParent);
17176       pLaf->pAllAndParent =0;
17177       return SQLITE_DONE;
17178     }
17179   }
17180   return p->errCode;
17181 }
17182 
17183 /*
17184 ** Free all resources allocated as part of sqlite3_recover_step() calls
17185 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
17186 */
recoverLostAndFoundCleanup(sqlite3_recover * p)17187 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
17188   recoverBitmapFree(p->laf.pUsed);
17189   p->laf.pUsed = 0;
17190   sqlite3_finalize(p->laf.pUsedPages);
17191   sqlite3_finalize(p->laf.pAllAndParent);
17192   sqlite3_finalize(p->laf.pMapInsert);
17193   sqlite3_finalize(p->laf.pMaxField);
17194   sqlite3_finalize(p->laf.pFindRoot);
17195   sqlite3_finalize(p->laf.pInsert);
17196   sqlite3_finalize(p->laf.pAllPage);
17197   sqlite3_finalize(p->laf.pPageData);
17198   p->laf.pUsedPages = 0;
17199   p->laf.pAllAndParent = 0;
17200   p->laf.pMapInsert = 0;
17201   p->laf.pMaxField = 0;
17202   p->laf.pFindRoot = 0;
17203   p->laf.pInsert = 0;
17204   p->laf.pAllPage = 0;
17205   p->laf.pPageData = 0;
17206   sqlite3_free(p->laf.apVal);
17207   p->laf.apVal = 0;
17208 }
17209 
17210 /*
17211 ** Free all resources allocated as part of sqlite3_recover_step() calls.
17212 */
recoverFinalCleanup(sqlite3_recover * p)17213 static void recoverFinalCleanup(sqlite3_recover *p){
17214   RecoverTable *pTab = 0;
17215   RecoverTable *pNext = 0;
17216 
17217   recoverWriteDataCleanup(p);
17218   recoverLostAndFoundCleanup(p);
17219 
17220   for(pTab=p->pTblList; pTab; pTab=pNext){
17221     pNext = pTab->pNext;
17222     sqlite3_free(pTab);
17223   }
17224   p->pTblList = 0;
17225   sqlite3_finalize(p->pGetPage);
17226   p->pGetPage = 0;
17227   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
17228 
17229   {
17230 #ifndef NDEBUG
17231     int res =
17232 #endif
17233        sqlite3_close(p->dbOut);
17234     assert( res==SQLITE_OK );
17235   }
17236   p->dbOut = 0;
17237 }
17238 
17239 /*
17240 ** Decode and return an unsigned 16-bit big-endian integer value from
17241 ** buffer a[].
17242 */
recoverGetU16(const u8 * a)17243 static u32 recoverGetU16(const u8 *a){
17244   return (((u32)a[0])<<8) + ((u32)a[1]);
17245 }
17246 
17247 /*
17248 ** Decode and return an unsigned 32-bit big-endian integer value from
17249 ** buffer a[].
17250 */
recoverGetU32(const u8 * a)17251 static u32 recoverGetU32(const u8 *a){
17252   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
17253 }
17254 
17255 /*
17256 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
17257 ** and return the number of bytes consumed.
17258 */
recoverGetVarint(const u8 * a,i64 * pVal)17259 static int recoverGetVarint(const u8 *a, i64 *pVal){
17260   sqlite3_uint64 u = 0;
17261   int i;
17262   for(i=0; i<8; i++){
17263     u = (u<<7) + (a[i]&0x7f);
17264     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
17265   }
17266   u = (u<<8) + (a[i]&0xff);
17267   *pVal = (sqlite3_int64)u;
17268   return 9;
17269 }
17270 
17271 /*
17272 ** The second argument points to a buffer n bytes in size. If this buffer
17273 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
17274 ** return the page-size in bytes. Otherwise, if the buffer does not
17275 ** appear to contain a well-formed b-tree page, return 0.
17276 */
recoverIsValidPage(u8 * aTmp,const u8 * a,int n)17277 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
17278   u8 *aUsed = aTmp;
17279   int nFrag = 0;
17280   int nActual = 0;
17281   int iFree = 0;
17282   int nCell = 0;                  /* Number of cells on page */
17283   int iCellOff = 0;               /* Offset of cell array in page */
17284   int iContent = 0;
17285   int eType = 0;
17286   int ii = 0;
17287 
17288   eType = (int)a[0];
17289   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
17290 
17291   iFree = (int)recoverGetU16(&a[1]);
17292   nCell = (int)recoverGetU16(&a[3]);
17293   iContent = (int)recoverGetU16(&a[5]);
17294   if( iContent==0 ) iContent = 65536;
17295   nFrag = (int)a[7];
17296 
17297   if( iContent>n ) return 0;
17298 
17299   memset(aUsed, 0, n);
17300   memset(aUsed, 0xFF, iContent);
17301 
17302   /* Follow the free-list. This is the same format for all b-tree pages. */
17303   if( iFree && iFree<=iContent ) return 0;
17304   while( iFree ){
17305     int iNext = 0;
17306     int nByte = 0;
17307     if( iFree>(n-4) ) return 0;
17308     iNext = recoverGetU16(&a[iFree]);
17309     nByte = recoverGetU16(&a[iFree+2]);
17310     if( iFree+nByte>n || nByte<4 ) return 0;
17311     if( iNext && iNext<iFree+nByte ) return 0;
17312     memset(&aUsed[iFree], 0xFF, nByte);
17313     iFree = iNext;
17314   }
17315 
17316   /* Run through the cells */
17317   if( eType==0x02 || eType==0x05 ){
17318     iCellOff = 12;
17319   }else{
17320     iCellOff = 8;
17321   }
17322   if( (iCellOff + 2*nCell)>iContent ) return 0;
17323   for(ii=0; ii<nCell; ii++){
17324     int iByte;
17325     i64 nPayload = 0;
17326     int nByte = 0;
17327     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
17328     if( iOff<iContent || iOff>n ){
17329       return 0;
17330     }
17331     if( eType==0x05 || eType==0x02 ) nByte += 4;
17332     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
17333     if( eType==0x0D ){
17334       i64 dummy = 0;
17335       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
17336     }
17337     if( eType!=0x05 ){
17338       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
17339       int M = ((n-12)*32/255)-23;
17340       int K = M+((nPayload-M)%(n-4));
17341 
17342       if( nPayload<X ){
17343         nByte += nPayload;
17344       }else if( K<=X ){
17345         nByte += K+4;
17346       }else{
17347         nByte += M+4;
17348       }
17349     }
17350 
17351     if( iOff+nByte>n ){
17352       return 0;
17353     }
17354     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
17355       if( aUsed[iByte]!=0 ){
17356         return 0;
17357       }
17358       aUsed[iByte] = 0xFF;
17359     }
17360   }
17361 
17362   nActual = 0;
17363   for(ii=0; ii<n; ii++){
17364     if( aUsed[ii]==0 ) nActual++;
17365   }
17366   return (nActual==nFrag);
17367 }
17368 
17369 
17370 static int recoverVfsClose(sqlite3_file*);
17371 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
17372 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
17373 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
17374 static int recoverVfsSync(sqlite3_file*, int flags);
17375 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
17376 static int recoverVfsLock(sqlite3_file*, int);
17377 static int recoverVfsUnlock(sqlite3_file*, int);
17378 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
17379 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
17380 static int recoverVfsSectorSize(sqlite3_file*);
17381 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
17382 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
17383 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
17384 static void recoverVfsShmBarrier(sqlite3_file*);
17385 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
17386 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
17387 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
17388 
17389 static sqlite3_io_methods recover_methods = {
17390   2, /* iVersion */
17391   recoverVfsClose,
17392   recoverVfsRead,
17393   recoverVfsWrite,
17394   recoverVfsTruncate,
17395   recoverVfsSync,
17396   recoverVfsFileSize,
17397   recoverVfsLock,
17398   recoverVfsUnlock,
17399   recoverVfsCheckReservedLock,
17400   recoverVfsFileControl,
17401   recoverVfsSectorSize,
17402   recoverVfsDeviceCharacteristics,
17403   recoverVfsShmMap,
17404   recoverVfsShmLock,
17405   recoverVfsShmBarrier,
17406   recoverVfsShmUnmap,
17407   recoverVfsFetch,
17408   recoverVfsUnfetch
17409 };
17410 
recoverVfsClose(sqlite3_file * pFd)17411 static int recoverVfsClose(sqlite3_file *pFd){
17412   assert( pFd->pMethods!=&recover_methods );
17413   return pFd->pMethods->xClose(pFd);
17414 }
17415 
17416 /*
17417 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
17418 */
recoverPutU16(u8 * a,u32 v)17419 static void recoverPutU16(u8 *a, u32 v){
17420   a[0] = (v>>8) & 0x00FF;
17421   a[1] = (v>>0) & 0x00FF;
17422 }
17423 
17424 /*
17425 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
17426 */
recoverPutU32(u8 * a,u32 v)17427 static void recoverPutU32(u8 *a, u32 v){
17428   a[0] = (v>>24) & 0x00FF;
17429   a[1] = (v>>16) & 0x00FF;
17430   a[2] = (v>>8) & 0x00FF;
17431   a[3] = (v>>0) & 0x00FF;
17432 }
17433 
17434 /*
17435 ** Detect the page-size of the database opened by file-handle pFd by
17436 ** searching the first part of the file for a well-formed SQLite b-tree
17437 ** page. If parameter nReserve is non-zero, then as well as searching for
17438 ** a b-tree page with zero reserved bytes, this function searches for one
17439 ** with nReserve reserved bytes at the end of it.
17440 **
17441 ** If successful, set variable p->detected_pgsz to the detected page-size
17442 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
17443 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
17444 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
17445 ** is returned. The final value of p->detected_pgsz is undefined in this
17446 ** case.
17447 */
recoverVfsDetectPagesize(sqlite3_recover * p,sqlite3_file * pFd,u32 nReserve,i64 nSz)17448 static int recoverVfsDetectPagesize(
17449   sqlite3_recover *p,             /* Recover handle */
17450   sqlite3_file *pFd,              /* File-handle open on input database */
17451   u32 nReserve,                   /* Possible nReserve value */
17452   i64 nSz                         /* Size of database file in bytes */
17453 ){
17454   int rc = SQLITE_OK;
17455   const int nMin = 512;
17456   const int nMax = 65536;
17457   const int nMaxBlk = 4;
17458   u32 pgsz = 0;
17459   int iBlk = 0;
17460   u8 *aPg = 0;
17461   u8 *aTmp = 0;
17462   int nBlk = 0;
17463 
17464   aPg = (u8*)sqlite3_malloc(2*nMax);
17465   if( aPg==0 ) return SQLITE_NOMEM;
17466   aTmp = &aPg[nMax];
17467 
17468   nBlk = (nSz+nMax-1)/nMax;
17469   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
17470 
17471   do {
17472     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
17473       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
17474       memset(aPg, 0, nMax);
17475       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
17476       if( rc==SQLITE_OK ){
17477         int pgsz2;
17478         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
17479           int iOff;
17480           for(iOff=0; iOff<nMax; iOff+=pgsz2){
17481             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
17482               pgsz = pgsz2;
17483               break;
17484             }
17485           }
17486         }
17487       }
17488     }
17489     if( pgsz>(u32)p->detected_pgsz ){
17490       p->detected_pgsz = pgsz;
17491       p->nReserve = nReserve;
17492     }
17493     if( nReserve==0 ) break;
17494     nReserve = 0;
17495   }while( 1 );
17496 
17497   p->detected_pgsz = pgsz;
17498   sqlite3_free(aPg);
17499   return rc;
17500 }
17501 
17502 /*
17503 ** The xRead() method of the wrapper VFS. This is used to intercept calls
17504 ** to read page 1 of the input database.
17505 */
recoverVfsRead(sqlite3_file * pFd,void * aBuf,int nByte,i64 iOff)17506 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
17507   int rc = SQLITE_OK;
17508   if( pFd->pMethods==&recover_methods ){
17509     pFd->pMethods = recover_g.pMethods;
17510     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
17511     if( nByte==16 ){
17512       sqlite3_randomness(16, aBuf);
17513     }else
17514     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
17515       /* Ensure that the database has a valid header file. The only fields
17516       ** that really matter to recovery are:
17517       **
17518       **   + Database page size (16-bits at offset 16)
17519       **   + Size of db in pages (32-bits at offset 28)
17520       **   + Database encoding (32-bits at offset 56)
17521       **
17522       ** Also preserved are:
17523       **
17524       **   + first freelist page (32-bits at offset 32)
17525       **   + size of freelist (32-bits at offset 36)
17526       **   + the wal-mode flags (16-bits at offset 18)
17527       **
17528       ** We also try to preserve the auto-vacuum, incr-value, user-version
17529       ** and application-id fields - all 32 bit quantities at offsets
17530       ** 52, 60, 64 and 68. All other fields are set to known good values.
17531       **
17532       ** Byte offset 105 should also contain the page-size as a 16-bit
17533       ** integer.
17534       */
17535       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
17536       u8 aHdr[108] = {
17537         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
17538         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
17539         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
17540         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
17541         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17542         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
17543         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
17544         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17545         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17546         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17547         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17548         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17549         0x00, 0x2e, 0x5b, 0x30,
17550 
17551         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
17552       };
17553       u8 *a = (u8*)aBuf;
17554 
17555       u32 pgsz = recoverGetU16(&a[16]);
17556       u32 nReserve = a[20];
17557       u32 enc = recoverGetU32(&a[56]);
17558       u32 dbsz = 0;
17559       i64 dbFileSize = 0;
17560       int ii;
17561       sqlite3_recover *p = recover_g.p;
17562 
17563       if( pgsz==0x01 ) pgsz = 65536;
17564       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
17565 
17566       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
17567         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
17568       }
17569       if( p->detected_pgsz ){
17570         pgsz = p->detected_pgsz;
17571         nReserve = p->nReserve;
17572       }
17573 
17574       if( pgsz ){
17575         dbsz = dbFileSize / pgsz;
17576       }
17577       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
17578         enc = SQLITE_UTF8;
17579       }
17580 
17581       sqlite3_free(p->pPage1Cache);
17582       p->pPage1Cache = 0;
17583       p->pPage1Disk = 0;
17584 
17585       p->pgsz = nByte;
17586       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
17587       if( p->pPage1Cache ){
17588         p->pPage1Disk = &p->pPage1Cache[nByte];
17589         memcpy(p->pPage1Disk, aBuf, nByte);
17590         aHdr[18] = a[18];
17591         aHdr[19] = a[19];
17592         recoverPutU32(&aHdr[28], dbsz);
17593         recoverPutU32(&aHdr[56], enc);
17594         recoverPutU16(&aHdr[105], pgsz-nReserve);
17595         if( pgsz==65536 ) pgsz = 1;
17596         recoverPutU16(&aHdr[16], pgsz);
17597         aHdr[20] = nReserve;
17598         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
17599           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
17600         }
17601         memcpy(aBuf, aHdr, sizeof(aHdr));
17602         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
17603 
17604         memcpy(p->pPage1Cache, aBuf, nByte);
17605       }else{
17606         rc = p->errCode;
17607       }
17608 
17609     }
17610     pFd->pMethods = &recover_methods;
17611   }else{
17612     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
17613   }
17614   return rc;
17615 }
17616 
17617 /*
17618 ** Used to make sqlite3_io_methods wrapper methods less verbose.
17619 */
17620 #define RECOVER_VFS_WRAPPER(code)                         \
17621   int rc = SQLITE_OK;                                     \
17622   if( pFd->pMethods==&recover_methods ){                  \
17623     pFd->pMethods = recover_g.pMethods;                   \
17624     rc = code;                                            \
17625     pFd->pMethods = &recover_methods;                     \
17626   }else{                                                  \
17627     rc = code;                                            \
17628   }                                                       \
17629   return rc;
17630 
17631 /*
17632 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
17633 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
17634 ** method on the lower level VFS, then reinstall the wrapper before returning.
17635 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
17636 */
recoverVfsWrite(sqlite3_file * pFd,const void * aBuf,int nByte,i64 iOff)17637 static int recoverVfsWrite(
17638   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
17639 ){
17640   RECOVER_VFS_WRAPPER (
17641       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
17642   );
17643 }
recoverVfsTruncate(sqlite3_file * pFd,sqlite3_int64 size)17644 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
17645   RECOVER_VFS_WRAPPER (
17646       pFd->pMethods->xTruncate(pFd, size)
17647   );
17648 }
recoverVfsSync(sqlite3_file * pFd,int flags)17649 static int recoverVfsSync(sqlite3_file *pFd, int flags){
17650   RECOVER_VFS_WRAPPER (
17651       pFd->pMethods->xSync(pFd, flags)
17652   );
17653 }
recoverVfsFileSize(sqlite3_file * pFd,sqlite3_int64 * pSize)17654 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
17655   RECOVER_VFS_WRAPPER (
17656       pFd->pMethods->xFileSize(pFd, pSize)
17657   );
17658 }
recoverVfsLock(sqlite3_file * pFd,int eLock)17659 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
17660   RECOVER_VFS_WRAPPER (
17661       pFd->pMethods->xLock(pFd, eLock)
17662   );
17663 }
recoverVfsUnlock(sqlite3_file * pFd,int eLock)17664 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
17665   RECOVER_VFS_WRAPPER (
17666       pFd->pMethods->xUnlock(pFd, eLock)
17667   );
17668 }
recoverVfsCheckReservedLock(sqlite3_file * pFd,int * pResOut)17669 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
17670   RECOVER_VFS_WRAPPER (
17671       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
17672   );
17673 }
recoverVfsFileControl(sqlite3_file * pFd,int op,void * pArg)17674 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
17675   RECOVER_VFS_WRAPPER (
17676     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
17677   );
17678 }
recoverVfsSectorSize(sqlite3_file * pFd)17679 static int recoverVfsSectorSize(sqlite3_file *pFd){
17680   RECOVER_VFS_WRAPPER (
17681       pFd->pMethods->xSectorSize(pFd)
17682   );
17683 }
recoverVfsDeviceCharacteristics(sqlite3_file * pFd)17684 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
17685   RECOVER_VFS_WRAPPER (
17686       pFd->pMethods->xDeviceCharacteristics(pFd)
17687   );
17688 }
recoverVfsShmMap(sqlite3_file * pFd,int iPg,int pgsz,int bExtend,void volatile ** pp)17689 static int recoverVfsShmMap(
17690   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
17691 ){
17692   RECOVER_VFS_WRAPPER (
17693       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
17694   );
17695 }
recoverVfsShmLock(sqlite3_file * pFd,int offset,int n,int flags)17696 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
17697   RECOVER_VFS_WRAPPER (
17698       pFd->pMethods->xShmLock(pFd, offset, n, flags)
17699   );
17700 }
recoverVfsShmBarrier(sqlite3_file * pFd)17701 static void recoverVfsShmBarrier(sqlite3_file *pFd){
17702   if( pFd->pMethods==&recover_methods ){
17703     pFd->pMethods = recover_g.pMethods;
17704     pFd->pMethods->xShmBarrier(pFd);
17705     pFd->pMethods = &recover_methods;
17706   }else{
17707     pFd->pMethods->xShmBarrier(pFd);
17708   }
17709 }
recoverVfsShmUnmap(sqlite3_file * pFd,int deleteFlag)17710 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
17711   RECOVER_VFS_WRAPPER (
17712       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
17713   );
17714 }
17715 
recoverVfsFetch(sqlite3_file * pFd,sqlite3_int64 iOff,int iAmt,void ** pp)17716 static int recoverVfsFetch(
17717   sqlite3_file *pFd,
17718   sqlite3_int64 iOff,
17719   int iAmt,
17720   void **pp
17721 ){
17722   (void)pFd;
17723   (void)iOff;
17724   (void)iAmt;
17725   *pp = 0;
17726   return SQLITE_OK;
17727 }
recoverVfsUnfetch(sqlite3_file * pFd,sqlite3_int64 iOff,void * p)17728 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
17729   (void)pFd;
17730   (void)iOff;
17731   (void)p;
17732   return SQLITE_OK;
17733 }
17734 
17735 /*
17736 ** Install the VFS wrapper around the file-descriptor open on the input
17737 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
17738 ** when this function is called.
17739 */
recoverInstallWrapper(sqlite3_recover * p)17740 static void recoverInstallWrapper(sqlite3_recover *p){
17741   sqlite3_file *pFd = 0;
17742   assert( recover_g.pMethods==0 );
17743   recoverAssertMutexHeld();
17744   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
17745   assert( pFd==0 || pFd->pMethods!=&recover_methods );
17746   if( pFd && pFd->pMethods ){
17747     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
17748     recover_g.pMethods = pFd->pMethods;
17749     recover_g.p = p;
17750     recover_methods.iVersion = iVersion;
17751     pFd->pMethods = &recover_methods;
17752   }
17753 }
17754 
17755 /*
17756 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
17757 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
17758 ** held when this function is called.
17759 */
recoverUninstallWrapper(sqlite3_recover * p)17760 static void recoverUninstallWrapper(sqlite3_recover *p){
17761   sqlite3_file *pFd = 0;
17762   recoverAssertMutexHeld();
17763   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
17764   if( pFd && pFd->pMethods ){
17765     pFd->pMethods = recover_g.pMethods;
17766     recover_g.pMethods = 0;
17767     recover_g.p = 0;
17768   }
17769 }
17770 
17771 /*
17772 ** This function does the work of a single sqlite3_recover_step() call. It
17773 ** is guaranteed that the handle is not in an error state when this
17774 ** function is called.
17775 */
recoverStep(sqlite3_recover * p)17776 static void recoverStep(sqlite3_recover *p){
17777   assert( p && p->errCode==SQLITE_OK );
17778   switch( p->eState ){
17779     case RECOVER_STATE_INIT:
17780       /* This is the very first call to sqlite3_recover_step() on this object.
17781       */
17782       recoverSqlCallback(p, "BEGIN");
17783       recoverSqlCallback(p, "PRAGMA writable_schema = on");
17784 
17785       recoverEnterMutex();
17786       recoverInstallWrapper(p);
17787 
17788       /* Open the output database. And register required virtual tables and
17789       ** user functions with the new handle. */
17790       recoverOpenOutput(p);
17791 
17792       /* Open transactions on both the input and output databases. */
17793       sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
17794       recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
17795       recoverExec(p, p->dbIn, "BEGIN");
17796       if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
17797       recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
17798       recoverTransferSettings(p);
17799       recoverOpenRecovery(p);
17800       recoverCacheSchema(p);
17801 
17802       recoverUninstallWrapper(p);
17803       recoverLeaveMutex();
17804 
17805       recoverExec(p, p->dbOut, "BEGIN");
17806 
17807       recoverWriteSchema1(p);
17808       p->eState = RECOVER_STATE_WRITING;
17809       break;
17810 
17811     case RECOVER_STATE_WRITING: {
17812       if( p->w1.pTbls==0 ){
17813         recoverWriteDataInit(p);
17814       }
17815       if( SQLITE_DONE==recoverWriteDataStep(p) ){
17816         recoverWriteDataCleanup(p);
17817         if( p->zLostAndFound ){
17818           p->eState = RECOVER_STATE_LOSTANDFOUND1;
17819         }else{
17820           p->eState = RECOVER_STATE_SCHEMA2;
17821         }
17822       }
17823       break;
17824     }
17825 
17826     case RECOVER_STATE_LOSTANDFOUND1: {
17827       if( p->laf.pUsed==0 ){
17828         recoverLostAndFound1Init(p);
17829       }
17830       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
17831         p->eState = RECOVER_STATE_LOSTANDFOUND2;
17832       }
17833       break;
17834     }
17835     case RECOVER_STATE_LOSTANDFOUND2: {
17836       if( p->laf.pAllAndParent==0 ){
17837         recoverLostAndFound2Init(p);
17838       }
17839       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
17840         p->eState = RECOVER_STATE_LOSTANDFOUND3;
17841       }
17842       break;
17843     }
17844 
17845     case RECOVER_STATE_LOSTANDFOUND3: {
17846       if( p->laf.pInsert==0 ){
17847         recoverLostAndFound3Init(p);
17848       }
17849       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
17850         p->eState = RECOVER_STATE_SCHEMA2;
17851       }
17852       break;
17853     }
17854 
17855     case RECOVER_STATE_SCHEMA2: {
17856       int rc = SQLITE_OK;
17857 
17858       recoverWriteSchema2(p);
17859       p->eState = RECOVER_STATE_DONE;
17860 
17861       /* If no error has occurred, commit the write transaction on the output
17862       ** database. Regardless of whether or not an error has occurred, make
17863       ** an attempt to end the read transaction on the input database.  */
17864       recoverExec(p, p->dbOut, "COMMIT");
17865       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
17866       if( p->errCode==SQLITE_OK ) p->errCode = rc;
17867 
17868       recoverSqlCallback(p, "PRAGMA writable_schema = off");
17869       recoverSqlCallback(p, "COMMIT");
17870       p->eState = RECOVER_STATE_DONE;
17871       recoverFinalCleanup(p);
17872       break;
17873     };
17874 
17875     case RECOVER_STATE_DONE: {
17876       /* no-op */
17877       break;
17878     };
17879   }
17880 }
17881 
17882 
17883 /*
17884 ** This is a worker function that does the heavy lifting for both init
17885 ** functions:
17886 **
17887 **     sqlite3_recover_init()
17888 **     sqlite3_recover_init_sql()
17889 **
17890 ** All this function does is allocate space for the recover handle and
17891 ** take copies of the input parameters. All the real work is done within
17892 ** sqlite3_recover_run().
17893 */
recoverInit(sqlite3 * db,const char * zDb,const char * zUri,int (* xSql)(void *,const char *),void * pSqlCtx)17894 sqlite3_recover *recoverInit(
17895   sqlite3* db,
17896   const char *zDb,
17897   const char *zUri,               /* Output URI for _recover_init() */
17898   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
17899   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
17900 ){
17901   sqlite3_recover *pRet = 0;
17902   int nDb = 0;
17903   int nUri = 0;
17904   int nByte = 0;
17905 
17906   if( zDb==0 ){ zDb = "main"; }
17907 
17908   nDb = recoverStrlen(zDb);
17909   nUri = recoverStrlen(zUri);
17910 
17911   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
17912   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
17913   if( pRet ){
17914     memset(pRet, 0, nByte);
17915     pRet->dbIn = db;
17916     pRet->zDb = (char*)&pRet[1];
17917     pRet->zUri = &pRet->zDb[nDb+1];
17918     memcpy(pRet->zDb, zDb, nDb);
17919     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
17920     pRet->xSql = xSql;
17921     pRet->pSqlCtx = pSqlCtx;
17922     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
17923   }
17924 
17925   return pRet;
17926 }
17927 
17928 /*
17929 ** Initialize a recovery handle that creates a new database containing
17930 ** the recovered data.
17931 */
sqlite3_recover_init(sqlite3 * db,const char * zDb,const char * zUri)17932 sqlite3_recover *sqlite3_recover_init(
17933   sqlite3* db,
17934   const char *zDb,
17935   const char *zUri
17936 ){
17937   return recoverInit(db, zDb, zUri, 0, 0);
17938 }
17939 
17940 /*
17941 ** Initialize a recovery handle that returns recovered data in the
17942 ** form of SQL statements via a callback.
17943 */
sqlite3_recover_init_sql(sqlite3 * db,const char * zDb,int (* xSql)(void *,const char *),void * pSqlCtx)17944 sqlite3_recover *sqlite3_recover_init_sql(
17945   sqlite3* db,
17946   const char *zDb,
17947   int (*xSql)(void*, const char*),
17948   void *pSqlCtx
17949 ){
17950   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
17951 }
17952 
17953 /*
17954 ** Return the handle error message, if any.
17955 */
sqlite3_recover_errmsg(sqlite3_recover * p)17956 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
17957   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
17958 }
17959 
17960 /*
17961 ** Return the handle error code.
17962 */
sqlite3_recover_errcode(sqlite3_recover * p)17963 int sqlite3_recover_errcode(sqlite3_recover *p){
17964   return p ? p->errCode : SQLITE_NOMEM;
17965 }
17966 
17967 /*
17968 ** Configure the handle.
17969 */
sqlite3_recover_config(sqlite3_recover * p,int op,void * pArg)17970 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
17971   int rc = SQLITE_OK;
17972   if( p==0 ){
17973     rc = SQLITE_NOMEM;
17974   }else if( p->eState!=RECOVER_STATE_INIT ){
17975     rc = SQLITE_MISUSE;
17976   }else{
17977     switch( op ){
17978       case 789:
17979         /* This undocumented magic configuration option is used to set the
17980         ** name of the auxiliary database that is ATTACH-ed to the database
17981         ** connection and used to hold state information during the
17982         ** recovery process.  This option is for debugging use only and
17983         ** is subject to change or removal at any time. */
17984         sqlite3_free(p->zStateDb);
17985         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
17986         break;
17987 
17988       case SQLITE_RECOVER_LOST_AND_FOUND: {
17989         const char *zArg = (const char*)pArg;
17990         sqlite3_free(p->zLostAndFound);
17991         if( zArg ){
17992           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
17993         }else{
17994           p->zLostAndFound = 0;
17995         }
17996         break;
17997       }
17998 
17999       case SQLITE_RECOVER_FREELIST_CORRUPT:
18000         p->bFreelistCorrupt = *(int*)pArg;
18001         break;
18002 
18003       case SQLITE_RECOVER_ROWIDS:
18004         p->bRecoverRowid = *(int*)pArg;
18005         break;
18006 
18007       case SQLITE_RECOVER_SLOWINDEXES:
18008         p->bSlowIndexes = *(int*)pArg;
18009         break;
18010 
18011       default:
18012         rc = SQLITE_NOTFOUND;
18013         break;
18014     }
18015   }
18016 
18017   return rc;
18018 }
18019 
18020 /*
18021 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
18022 ** no error has occurred but database recovery is not finished, SQLITE_DONE
18023 ** if database recovery has been successfully completed, or an SQLite
18024 ** error code if an error has occurred.
18025 */
sqlite3_recover_step(sqlite3_recover * p)18026 int sqlite3_recover_step(sqlite3_recover *p){
18027   if( p==0 ) return SQLITE_NOMEM;
18028   if( p->errCode==SQLITE_OK ) recoverStep(p);
18029   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
18030     return SQLITE_DONE;
18031   }
18032   return p->errCode;
18033 }
18034 
18035 /*
18036 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
18037 ** else an SQLite error code.
18038 */
sqlite3_recover_run(sqlite3_recover * p)18039 int sqlite3_recover_run(sqlite3_recover *p){
18040   while( SQLITE_OK==sqlite3_recover_step(p) );
18041   return sqlite3_recover_errcode(p);
18042 }
18043 
18044 
18045 /*
18046 ** Free all resources associated with the recover handle passed as the only
18047 ** argument. The results of using a handle with any sqlite3_recover_**
18048 ** API function after it has been passed to this function are undefined.
18049 **
18050 ** A copy of the value returned by the first call made to sqlite3_recover_run()
18051 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
18052 ** not been called on this handle.
18053 */
sqlite3_recover_finish(sqlite3_recover * p)18054 int sqlite3_recover_finish(sqlite3_recover *p){
18055   int rc;
18056   if( p==0 ){
18057     rc = SQLITE_NOMEM;
18058   }else{
18059     recoverFinalCleanup(p);
18060     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
18061       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
18062       if( p->errCode==SQLITE_OK ) p->errCode = rc;
18063     }
18064     rc = p->errCode;
18065     sqlite3_free(p->zErrMsg);
18066     sqlite3_free(p->zStateDb);
18067     sqlite3_free(p->zLostAndFound);
18068     sqlite3_free(p->pPage1Cache);
18069     sqlite3_free(p);
18070   }
18071   return rc;
18072 }
18073 
18074 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
18075 
18076 /************************* End ../ext/recover/sqlite3recover.c ********************/
18077 # endif /* SQLITE_HAVE_SQLITE3R */
18078 #endif
18079 #ifdef SQLITE_SHELL_EXTSRC
18080 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
18081 #endif
18082 
18083 #if defined(SQLITE_ENABLE_SESSION)
18084 /*
18085 ** State information for a single open session
18086 */
18087 typedef struct OpenSession OpenSession;
18088 struct OpenSession {
18089   char *zName;             /* Symbolic name for this session */
18090   int nFilter;             /* Number of xFilter rejection GLOB patterns */
18091   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
18092   sqlite3_session *p;      /* The open session */
18093 };
18094 #endif
18095 
18096 typedef struct ExpertInfo ExpertInfo;
18097 struct ExpertInfo {
18098   sqlite3expert *pExpert;
18099   int bVerbose;
18100 };
18101 
18102 /* A single line in the EQP output */
18103 typedef struct EQPGraphRow EQPGraphRow;
18104 struct EQPGraphRow {
18105   int iEqpId;           /* ID for this row */
18106   int iParentId;        /* ID of the parent row */
18107   EQPGraphRow *pNext;   /* Next row in sequence */
18108   char zText[1];        /* Text to display for this row */
18109 };
18110 
18111 /* All EQP output is collected into an instance of the following */
18112 typedef struct EQPGraph EQPGraph;
18113 struct EQPGraph {
18114   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
18115   EQPGraphRow *pLast;   /* Last element of the pRow list */
18116   char zPrefix[100];    /* Graph prefix */
18117 };
18118 
18119 /* Parameters affecting columnar mode result display (defaulting together) */
18120 typedef struct ColModeOpts {
18121   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
18122   u8 bQuote;            /* Quote results for .mode box and table */
18123   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
18124 } ColModeOpts;
18125 #define ColModeOpts_default { 60, 0, 0 }
18126 #define ColModeOpts_default_qbox { 60, 1, 0 }
18127 
18128 /*
18129 ** State information about the database connection is contained in an
18130 ** instance of the following structure.
18131 */
18132 typedef struct ShellState ShellState;
18133 struct ShellState {
18134   sqlite3 *db;           /* The database */
18135   u8 autoExplain;        /* Automatically turn on .explain mode */
18136   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
18137   u8 autoEQPtest;        /* autoEQP is in test mode */
18138   u8 autoEQPtrace;       /* autoEQP is in trace mode */
18139   u8 scanstatsOn;        /* True to display scan stats before each finalize */
18140   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
18141   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
18142   u8 nEqpLevel;          /* Depth of the EQP output graph */
18143   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
18144   u8 bSafeMode;          /* True to prohibit unsafe operations */
18145   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
18146   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
18147   unsigned statsOn;      /* True to display memory stats before each finalize */
18148   unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
18149   int inputNesting;      /* Track nesting level of .read and other redirects */
18150   int outCount;          /* Revert to stdout when reaching zero */
18151   int cnt;               /* Number of records displayed so far */
18152   int lineno;            /* Line number of last line read from in */
18153   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
18154   FILE *in;              /* Read commands from this stream */
18155   FILE *out;             /* Write results here */
18156   FILE *traceOut;        /* Output for sqlite3_trace() */
18157   int nErr;              /* Number of errors seen */
18158   int mode;              /* An output mode setting */
18159   int modePrior;         /* Saved mode */
18160   int cMode;             /* temporary output mode for the current query */
18161   int normalMode;        /* Output mode before ".explain on" */
18162   int writableSchema;    /* True if PRAGMA writable_schema=ON */
18163   int showHeader;        /* True to show column names in List or Column mode */
18164   int nCheck;            /* Number of ".check" commands run */
18165   unsigned nProgress;    /* Number of progress callbacks encountered */
18166   unsigned mxProgress;   /* Maximum progress callbacks before failing */
18167   unsigned flgProgress;  /* Flags for the progress callback */
18168   unsigned shellFlgs;    /* Various flags */
18169   unsigned priorShFlgs;  /* Saved copy of flags */
18170   sqlite3_int64 szMax;   /* --maxsize argument to .open */
18171   char *zDestTable;      /* Name of destination table when MODE_Insert */
18172   char *zTempFile;       /* Temporary file that might need deleting */
18173   char zTestcase[30];    /* Name of current test case */
18174   char colSeparator[20]; /* Column separator character for several modes */
18175   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
18176   char colSepPrior[20];  /* Saved column separator */
18177   char rowSepPrior[20];  /* Saved row separator */
18178   int *colWidth;         /* Requested width of each column in columnar modes */
18179   int *actualWidth;      /* Actual width of each column */
18180   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
18181   char nullValue[20];    /* The text to print when a NULL comes back from
18182                          ** the database */
18183   char outfile[FILENAME_MAX]; /* Filename for *out */
18184   sqlite3_stmt *pStmt;   /* Current statement if any. */
18185   FILE *pLog;            /* Write log output here */
18186   struct AuxDb {         /* Storage space for auxiliary database connections */
18187     sqlite3 *db;               /* Connection pointer */
18188     const char *zDbFilename;   /* Filename used to open the connection */
18189     char *zFreeOnClose;        /* Free this memory allocation on close */
18190 #if defined(SQLITE_ENABLE_SESSION)
18191     int nSession;              /* Number of active sessions */
18192     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
18193 #endif
18194   } aAuxDb[5],           /* Array of all database connections */
18195     *pAuxDb;             /* Currently active database connection */
18196   int *aiIndent;         /* Array of indents used in MODE_Explain */
18197   int nIndent;           /* Size of array aiIndent[] */
18198   int iIndent;           /* Index of current op in aiIndent[] */
18199   char *zNonce;          /* Nonce for temporary safe-mode escapes */
18200   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
18201   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
18202 #ifdef SQLITE_SHELL_FIDDLE
18203   struct {
18204     const char * zInput; /* Input string from wasm/JS proxy */
18205     const char * zPos;   /* Cursor pos into zInput */
18206     const char * zDefaultDbName; /* Default name for db file */
18207   } wasm;
18208 #endif
18209 };
18210 
18211 #ifdef SQLITE_SHELL_FIDDLE
18212 static ShellState shellState;
18213 #endif
18214 
18215 
18216 /* Allowed values for ShellState.autoEQP
18217 */
18218 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
18219 #define AUTOEQP_on       1           /* Automatic EQP is on */
18220 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
18221 #define AUTOEQP_full     3           /* Show full EXPLAIN */
18222 
18223 /* Allowed values for ShellState.openMode
18224 */
18225 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
18226 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
18227 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
18228 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
18229 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
18230 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
18231 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
18232 
18233 /* Allowed values for ShellState.eTraceType
18234 */
18235 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
18236 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
18237 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
18238 
18239 /* Bits in the ShellState.flgProgress variable */
18240 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
18241 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
18242                                    ** callback limit is reached, and for each
18243                                    ** top-level SQL statement */
18244 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
18245 
18246 /*
18247 ** These are the allowed shellFlgs values
18248 */
18249 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
18250 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
18251 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
18252 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
18253 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
18254 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
18255 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
18256 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
18257 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
18258 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
18259 #define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
18260 
18261 /*
18262 ** Macros for testing and setting shellFlgs
18263 */
18264 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
18265 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
18266 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
18267 
18268 /*
18269 ** These are the allowed modes.
18270 */
18271 #define MODE_Line     0  /* One column per line.  Blank line between records */
18272 #define MODE_Column   1  /* One record per line in neat columns */
18273 #define MODE_List     2  /* One record per line with a separator */
18274 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
18275 #define MODE_Html     4  /* Generate an XHTML table */
18276 #define MODE_Insert   5  /* Generate SQL "insert" statements */
18277 #define MODE_Quote    6  /* Quote values as for SQL */
18278 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
18279 #define MODE_Csv      8  /* Quote strings, numbers are plain */
18280 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
18281 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
18282 #define MODE_Pretty  11  /* Pretty-print schemas */
18283 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
18284 #define MODE_Json    13  /* Output JSON */
18285 #define MODE_Markdown 14 /* Markdown formatting */
18286 #define MODE_Table   15  /* MySQL-style table formatting */
18287 #define MODE_Box     16  /* Unicode box-drawing characters */
18288 #define MODE_Count   17  /* Output only a count of the rows of output */
18289 #define MODE_Off     18  /* No query output shown */
18290 #define MODE_ScanExp 19  /* Like MODE_Explain, but for ".scanstats vm" */
18291 
18292 static const char *modeDescr[] = {
18293   "line",
18294   "column",
18295   "list",
18296   "semi",
18297   "html",
18298   "insert",
18299   "quote",
18300   "tcl",
18301   "csv",
18302   "explain",
18303   "ascii",
18304   "prettyprint",
18305   "eqp",
18306   "json",
18307   "markdown",
18308   "table",
18309   "box",
18310   "count",
18311   "off"
18312 };
18313 
18314 /*
18315 ** These are the column/row/line separators used by the various
18316 ** import/export modes.
18317 */
18318 #define SEP_Column    "|"
18319 #define SEP_Row       "\n"
18320 #define SEP_Tab       "\t"
18321 #define SEP_Space     " "
18322 #define SEP_Comma     ","
18323 #define SEP_CrLf      "\r\n"
18324 #define SEP_Unit      "\x1F"
18325 #define SEP_Record    "\x1E"
18326 
18327 /*
18328 ** Limit input nesting via .read or any other input redirect.
18329 ** It's not too expensive, so a generous allowance can be made.
18330 */
18331 #define MAX_INPUT_NESTING 25
18332 
18333 /*
18334 ** A callback for the sqlite3_log() interface.
18335 */
shellLog(void * pArg,int iErrCode,const char * zMsg)18336 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
18337   ShellState *p = (ShellState*)pArg;
18338   if( p->pLog==0 ) return;
18339   sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
18340   fflush(p->pLog);
18341 }
18342 
18343 /*
18344 ** SQL function:  shell_putsnl(X)
18345 **
18346 ** Write the text X to the screen (or whatever output is being directed)
18347 ** adding a newline at the end, and then return X.
18348 */
shellPutsFunc(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)18349 static void shellPutsFunc(
18350   sqlite3_context *pCtx,
18351   int nVal,
18352   sqlite3_value **apVal
18353 ){
18354   /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
18355   (void)nVal;
18356   oputf("%s\n", sqlite3_value_text(apVal[0]));
18357   sqlite3_result_value(pCtx, apVal[0]);
18358 }
18359 
18360 /*
18361 ** If in safe mode, print an error message described by the arguments
18362 ** and exit immediately.
18363 */
failIfSafeMode(ShellState * p,const char * zErrMsg,...)18364 static void failIfSafeMode(
18365   ShellState *p,
18366   const char *zErrMsg,
18367   ...
18368 ){
18369   if( p->bSafeMode ){
18370     va_list ap;
18371     char *zMsg;
18372     va_start(ap, zErrMsg);
18373     zMsg = sqlite3_vmprintf(zErrMsg, ap);
18374     va_end(ap);
18375     eputf("line %d: %s\n", p->lineno, zMsg);
18376     exit(1);
18377   }
18378 }
18379 
18380 /*
18381 ** SQL function:   edit(VALUE)
18382 **                 edit(VALUE,EDITOR)
18383 **
18384 ** These steps:
18385 **
18386 **     (1) Write VALUE into a temporary file.
18387 **     (2) Run program EDITOR on that temporary file.
18388 **     (3) Read the temporary file back and return its content as the result.
18389 **     (4) Delete the temporary file
18390 **
18391 ** If the EDITOR argument is omitted, use the value in the VISUAL
18392 ** environment variable.  If still there is no EDITOR, through an error.
18393 **
18394 ** Also throw an error if the EDITOR program returns a non-zero exit code.
18395 */
18396 #ifndef SQLITE_NOHAVE_SYSTEM
editFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)18397 static void editFunc(
18398   sqlite3_context *context,
18399   int argc,
18400   sqlite3_value **argv
18401 ){
18402   const char *zEditor;
18403   char *zTempFile = 0;
18404   sqlite3 *db;
18405   char *zCmd = 0;
18406   int bBin;
18407   int rc;
18408   int hasCRNL = 0;
18409   FILE *f = 0;
18410   sqlite3_int64 sz;
18411   sqlite3_int64 x;
18412   unsigned char *p = 0;
18413 
18414   if( argc==2 ){
18415     zEditor = (const char*)sqlite3_value_text(argv[1]);
18416   }else{
18417     zEditor = getenv("VISUAL");
18418   }
18419   if( zEditor==0 ){
18420     sqlite3_result_error(context, "no editor for edit()", -1);
18421     return;
18422   }
18423   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
18424     sqlite3_result_error(context, "NULL input to edit()", -1);
18425     return;
18426   }
18427   db = sqlite3_context_db_handle(context);
18428   zTempFile = 0;
18429   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
18430   if( zTempFile==0 ){
18431     sqlite3_uint64 r = 0;
18432     sqlite3_randomness(sizeof(r), &r);
18433     zTempFile = sqlite3_mprintf("temp%llx", r);
18434     if( zTempFile==0 ){
18435       sqlite3_result_error_nomem(context);
18436       return;
18437     }
18438   }
18439   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
18440   /* When writing the file to be edited, do \n to \r\n conversions on systems
18441   ** that want \r\n line endings */
18442   f = fopen(zTempFile, bBin ? "wb" : "w");
18443   if( f==0 ){
18444     sqlite3_result_error(context, "edit() cannot open temp file", -1);
18445     goto edit_func_end;
18446   }
18447   sz = sqlite3_value_bytes(argv[0]);
18448   if( bBin ){
18449     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
18450   }else{
18451     const char *z = (const char*)sqlite3_value_text(argv[0]);
18452     /* Remember whether or not the value originally contained \r\n */
18453     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
18454     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
18455   }
18456   fclose(f);
18457   f = 0;
18458   if( x!=sz ){
18459     sqlite3_result_error(context, "edit() could not write the whole file", -1);
18460     goto edit_func_end;
18461   }
18462   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
18463   if( zCmd==0 ){
18464     sqlite3_result_error_nomem(context);
18465     goto edit_func_end;
18466   }
18467   rc = system(zCmd);
18468   sqlite3_free(zCmd);
18469   if( rc ){
18470     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
18471     goto edit_func_end;
18472   }
18473   f = fopen(zTempFile, "rb");
18474   if( f==0 ){
18475     sqlite3_result_error(context,
18476       "edit() cannot reopen temp file after edit", -1);
18477     goto edit_func_end;
18478   }
18479   fseek(f, 0, SEEK_END);
18480   sz = ftell(f);
18481   rewind(f);
18482   p = sqlite3_malloc64( sz+1 );
18483   if( p==0 ){
18484     sqlite3_result_error_nomem(context);
18485     goto edit_func_end;
18486   }
18487   x = fread(p, 1, (size_t)sz, f);
18488   fclose(f);
18489   f = 0;
18490   if( x!=sz ){
18491     sqlite3_result_error(context, "could not read back the whole file", -1);
18492     goto edit_func_end;
18493   }
18494   if( bBin ){
18495     sqlite3_result_blob64(context, p, sz, sqlite3_free);
18496   }else{
18497     sqlite3_int64 i, j;
18498     if( hasCRNL ){
18499       /* If the original contains \r\n then do no conversions back to \n */
18500     }else{
18501       /* If the file did not originally contain \r\n then convert any new
18502       ** \r\n back into \n */
18503       p[sz] = 0;
18504       for(i=j=0; i<sz; i++){
18505         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
18506         p[j++] = p[i];
18507       }
18508       sz = j;
18509       p[sz] = 0;
18510     }
18511     sqlite3_result_text64(context, (const char*)p, sz,
18512                           sqlite3_free, SQLITE_UTF8);
18513   }
18514   p = 0;
18515 
18516 edit_func_end:
18517   if( f ) fclose(f);
18518   unlink(zTempFile);
18519   sqlite3_free(zTempFile);
18520   sqlite3_free(p);
18521 }
18522 #endif /* SQLITE_NOHAVE_SYSTEM */
18523 
18524 /*
18525 ** Save or restore the current output mode
18526 */
outputModePush(ShellState * p)18527 static void outputModePush(ShellState *p){
18528   p->modePrior = p->mode;
18529   p->priorShFlgs = p->shellFlgs;
18530   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
18531   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
18532 }
outputModePop(ShellState * p)18533 static void outputModePop(ShellState *p){
18534   p->mode = p->modePrior;
18535   p->shellFlgs = p->priorShFlgs;
18536   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
18537   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
18538 }
18539 
18540 /*
18541 ** Output the given string as a hex-encoded blob (eg. X'1234' )
18542 */
output_hex_blob(const void * pBlob,int nBlob)18543 static void output_hex_blob(const void *pBlob, int nBlob){
18544   int i;
18545   unsigned char *aBlob = (unsigned char*)pBlob;
18546 
18547   char *zStr = sqlite3_malloc(nBlob*2 + 1);
18548   shell_check_oom(zStr);
18549 
18550   for(i=0; i<nBlob; i++){
18551     static const char aHex[] = {
18552         '0', '1', '2', '3', '4', '5', '6', '7',
18553         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
18554     };
18555     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
18556     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
18557   }
18558   zStr[i*2] = '\0';
18559 
18560   oputf("X'%s'", zStr);
18561   sqlite3_free(zStr);
18562 }
18563 
18564 /*
18565 ** Find a string that is not found anywhere in z[].  Return a pointer
18566 ** to that string.
18567 **
18568 ** Try to use zA and zB first.  If both of those are already found in z[]
18569 ** then make up some string and store it in the buffer zBuf.
18570 */
unused_string(const char * z,const char * zA,const char * zB,char * zBuf)18571 static const char *unused_string(
18572   const char *z,                    /* Result must not appear anywhere in z */
18573   const char *zA, const char *zB,   /* Try these first */
18574   char *zBuf                        /* Space to store a generated string */
18575 ){
18576   unsigned i = 0;
18577   if( strstr(z, zA)==0 ) return zA;
18578   if( strstr(z, zB)==0 ) return zB;
18579   do{
18580     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
18581   }while( strstr(z,zBuf)!=0 );
18582   return zBuf;
18583 }
18584 
18585 /*
18586 ** Output the given string as a quoted string using SQL quoting conventions.
18587 **
18588 ** See also: output_quoted_escaped_string()
18589 */
output_quoted_string(const char * z)18590 static void output_quoted_string(const char *z){
18591   int i;
18592   char c;
18593 #ifndef SQLITE_SHELL_FIDDLE
18594   FILE *pfO = setOutputStream(invalidFileStream);
18595   setBinaryMode(pfO, 1);
18596 #endif
18597   if( z==0 ) return;
18598   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
18599   if( c==0 ){
18600     oputf("'%s'",z);
18601   }else{
18602     oputz("'");
18603     while( *z ){
18604       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
18605       if( c=='\'' ) i++;
18606       if( i ){
18607         oputf("%.*s", i, z);
18608         z += i;
18609       }
18610       if( c=='\'' ){
18611         oputz("'");
18612         continue;
18613       }
18614       if( c==0 ){
18615         break;
18616       }
18617       z++;
18618     }
18619     oputz("'");
18620   }
18621 #ifndef SQLITE_SHELL_FIDDLE
18622   setTextMode(pfO, 1);
18623 #else
18624   setTextMode(stdout, 1);
18625 #endif
18626 }
18627 
18628 /*
18629 ** Output the given string as a quoted string using SQL quoting conventions.
18630 ** Additionallly , escape the "\n" and "\r" characters so that they do not
18631 ** get corrupted by end-of-line translation facilities in some operating
18632 ** systems.
18633 **
18634 ** This is like output_quoted_string() but with the addition of the \r\n
18635 ** escape mechanism.
18636 */
output_quoted_escaped_string(const char * z)18637 static void output_quoted_escaped_string(const char *z){
18638   int i;
18639   char c;
18640 #ifndef SQLITE_SHELL_FIDDLE
18641   FILE *pfO = setOutputStream(invalidFileStream);
18642   setBinaryMode(pfO, 1);
18643 #endif
18644   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
18645   if( c==0 ){
18646     oputf("'%s'",z);
18647   }else{
18648     const char *zNL = 0;
18649     const char *zCR = 0;
18650     int nNL = 0;
18651     int nCR = 0;
18652     char zBuf1[20], zBuf2[20];
18653     for(i=0; z[i]; i++){
18654       if( z[i]=='\n' ) nNL++;
18655       if( z[i]=='\r' ) nCR++;
18656     }
18657     if( nNL ){
18658       oputz("replace(");
18659       zNL = unused_string(z, "\\n", "\\012", zBuf1);
18660     }
18661     if( nCR ){
18662       oputz("replace(");
18663       zCR = unused_string(z, "\\r", "\\015", zBuf2);
18664     }
18665     oputz("'");
18666     while( *z ){
18667       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
18668       if( c=='\'' ) i++;
18669       if( i ){
18670         oputf("%.*s", i, z);
18671         z += i;
18672       }
18673       if( c=='\'' ){
18674         oputz("'");
18675         continue;
18676       }
18677       if( c==0 ){
18678         break;
18679       }
18680       z++;
18681       if( c=='\n' ){
18682         oputz(zNL);
18683         continue;
18684       }
18685       oputz(zCR);
18686     }
18687     oputz("'");
18688     if( nCR ){
18689       oputf(",'%s',char(13))", zCR);
18690     }
18691     if( nNL ){
18692       oputf(",'%s',char(10))", zNL);
18693     }
18694   }
18695 #ifndef SQLITE_SHELL_FIDDLE
18696   setTextMode(pfO, 1);
18697 #else
18698   setTextMode(stdout, 1);
18699 #endif
18700 }
18701 
18702 /*
18703 ** Find earliest of chars within s specified in zAny.
18704 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
18705 */
anyOfInStr(const char * s,const char * zAny,size_t ns)18706 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
18707   const char *pcFirst = 0;
18708   if( ns == ~(size_t)0 ) ns = strlen(s);
18709   while(*zAny){
18710     const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
18711     if( pc ){
18712       pcFirst = pc;
18713       ns = pcFirst - s;
18714     }
18715     ++zAny;
18716   }
18717   return pcFirst;
18718 }
18719 /*
18720 ** Output the given string as a quoted according to C or TCL quoting rules.
18721 */
output_c_string(const char * z)18722 static void output_c_string(const char *z){
18723   char c;
18724   static const char *zq = "\"";
18725   static long ctrlMask = ~0L;
18726   static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
18727   char ace[3] = "\\?";
18728   char cbsSay;
18729   oputz(zq);
18730   while( *z!=0 ){
18731     const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
18732     const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
18733     const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
18734     if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
18735     if( (c = *pcEnd)==0 ) break;
18736     ++pcEnd;
18737     switch( c ){
18738     case '\\': case '"':
18739       cbsSay = (char)c;
18740       break;
18741     case '\t': cbsSay = 't'; break;
18742     case '\n': cbsSay = 'n'; break;
18743     case '\r': cbsSay = 'r'; break;
18744     case '\f': cbsSay = 'f'; break;
18745     default: cbsSay = 0; break;
18746     }
18747     if( cbsSay ){
18748       ace[1] = cbsSay;
18749       oputz(ace);
18750     }else if( !isprint(c&0xff) ){
18751       oputf("\\%03o", c&0xff);
18752     }else{
18753       ace[1] = (char)c;
18754       oputz(ace+1);
18755     }
18756     z = pcEnd;
18757   }
18758   oputz(zq);
18759 }
18760 
18761 /*
18762 ** Output the given string as a quoted according to JSON quoting rules.
18763 */
output_json_string(const char * z,i64 n)18764 static void output_json_string(const char *z, i64 n){
18765   char c;
18766   static const char *zq = "\"";
18767   static long ctrlMask = ~0L;
18768   static const char *zDQBS = "\"\\";
18769   const char *pcLimit;
18770   char ace[3] = "\\?";
18771   char cbsSay;
18772 
18773   if( z==0 ) z = "";
18774   pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
18775   oputz(zq);
18776   while( z < pcLimit ){
18777     const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
18778     const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
18779     const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
18780     if( pcEnd > z ){
18781       oputb(z, (int)(pcEnd-z));
18782       z = pcEnd;
18783     }
18784     if( z >= pcLimit ) break;
18785     c = *(z++);
18786     switch( c ){
18787     case '"': case '\\':
18788       cbsSay = (char)c;
18789       break;
18790     case '\b': cbsSay = 'b'; break;
18791     case '\f': cbsSay = 'f'; break;
18792     case '\n': cbsSay = 'n'; break;
18793     case '\r': cbsSay = 'r'; break;
18794     case '\t': cbsSay = 't'; break;
18795     default: cbsSay = 0; break;
18796     }
18797     if( cbsSay ){
18798       ace[1] = cbsSay;
18799       oputz(ace);
18800     }else if( c<=0x1f ){
18801       oputf("u%04x", c);
18802     }else{
18803       ace[1] = (char)c;
18804       oputz(ace+1);
18805     }
18806   }
18807   oputz(zq);
18808 }
18809 
18810 /*
18811 ** Output the given string with characters that are special to
18812 ** HTML escaped.
18813 */
output_html_string(const char * z)18814 static void output_html_string(const char *z){
18815   int i;
18816   if( z==0 ) z = "";
18817   while( *z ){
18818     for(i=0;   z[i]
18819             && z[i]!='<'
18820             && z[i]!='&'
18821             && z[i]!='>'
18822             && z[i]!='\"'
18823             && z[i]!='\'';
18824         i++){}
18825     if( i>0 ){
18826       oputf("%.*s",i,z);
18827     }
18828     if( z[i]=='<' ){
18829       oputz("&lt;");
18830     }else if( z[i]=='&' ){
18831       oputz("&amp;");
18832     }else if( z[i]=='>' ){
18833       oputz("&gt;");
18834     }else if( z[i]=='\"' ){
18835       oputz("&quot;");
18836     }else if( z[i]=='\'' ){
18837       oputz("&#39;");
18838     }else{
18839       break;
18840     }
18841     z += i + 1;
18842   }
18843 }
18844 
18845 /*
18846 ** If a field contains any character identified by a 1 in the following
18847 ** array, then the string must be quoted for CSV.
18848 */
18849 static const char needCsvQuote[] = {
18850   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18851   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18852   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
18853   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18854   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18855   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18856   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18857   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
18858   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18859   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18860   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18861   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18862   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18863   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18864   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18865   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18866 };
18867 
18868 /*
18869 ** Output a single term of CSV.  Actually, p->colSeparator is used for
18870 ** the separator, which may or may not be a comma.  p->nullValue is
18871 ** the null value.  Strings are quoted if necessary.  The separator
18872 ** is only issued if bSep is true.
18873 */
output_csv(ShellState * p,const char * z,int bSep)18874 static void output_csv(ShellState *p, const char *z, int bSep){
18875   if( z==0 ){
18876     oputf("%s",p->nullValue);
18877   }else{
18878     unsigned i;
18879     for(i=0; z[i]; i++){
18880       if( needCsvQuote[((unsigned char*)z)[i]] ){
18881         i = 0;
18882         break;
18883       }
18884     }
18885     if( i==0 || strstr(z, p->colSeparator)!=0 ){
18886       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
18887       shell_check_oom(zQuoted);
18888       oputz(zQuoted);
18889       sqlite3_free(zQuoted);
18890     }else{
18891       oputz(z);
18892     }
18893   }
18894   if( bSep ){
18895     oputz(p->colSeparator);
18896   }
18897 }
18898 
18899 /*
18900 ** This routine runs when the user presses Ctrl-C
18901 */
interrupt_handler(int NotUsed)18902 static void interrupt_handler(int NotUsed){
18903   UNUSED_PARAMETER(NotUsed);
18904   if( ++seenInterrupt>1 ) exit(1);
18905   if( globalDb ) sqlite3_interrupt(globalDb);
18906 }
18907 
18908 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
18909 /*
18910 ** This routine runs for console events (e.g. Ctrl-C) on Win32
18911 */
ConsoleCtrlHandler(DWORD dwCtrlType)18912 static BOOL WINAPI ConsoleCtrlHandler(
18913   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
18914 ){
18915   if( dwCtrlType==CTRL_C_EVENT ){
18916     interrupt_handler(0);
18917     return TRUE;
18918   }
18919   return FALSE;
18920 }
18921 #endif
18922 
18923 #ifndef SQLITE_OMIT_AUTHORIZATION
18924 /*
18925 ** This authorizer runs in safe mode.
18926 */
safeModeAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)18927 static int safeModeAuth(
18928   void *pClientData,
18929   int op,
18930   const char *zA1,
18931   const char *zA2,
18932   const char *zA3,
18933   const char *zA4
18934 ){
18935   ShellState *p = (ShellState*)pClientData;
18936   static const char *azProhibitedFunctions[] = {
18937     "edit",
18938     "fts3_tokenizer",
18939     "load_extension",
18940     "readfile",
18941     "writefile",
18942     "zipfile",
18943     "zipfile_cds",
18944   };
18945   UNUSED_PARAMETER(zA1);
18946   UNUSED_PARAMETER(zA3);
18947   UNUSED_PARAMETER(zA4);
18948   switch( op ){
18949     case SQLITE_ATTACH: {
18950 #ifndef SQLITE_SHELL_FIDDLE
18951       /* In WASM builds the filesystem is a virtual sandbox, so
18952       ** there's no harm in using ATTACH. */
18953       failIfSafeMode(p, "cannot run ATTACH in safe mode");
18954 #endif
18955       break;
18956     }
18957     case SQLITE_FUNCTION: {
18958       int i;
18959       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
18960         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
18961           failIfSafeMode(p, "cannot use the %s() function in safe mode",
18962                          azProhibitedFunctions[i]);
18963         }
18964       }
18965       break;
18966     }
18967   }
18968   return SQLITE_OK;
18969 }
18970 
18971 /*
18972 ** When the ".auth ON" is set, the following authorizer callback is
18973 ** invoked.  It always returns SQLITE_OK.
18974 */
shellAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)18975 static int shellAuth(
18976   void *pClientData,
18977   int op,
18978   const char *zA1,
18979   const char *zA2,
18980   const char *zA3,
18981   const char *zA4
18982 ){
18983   ShellState *p = (ShellState*)pClientData;
18984   static const char *azAction[] = { 0,
18985      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
18986      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
18987      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
18988      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
18989      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
18990      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
18991      "PRAGMA",               "READ",                 "SELECT",
18992      "TRANSACTION",          "UPDATE",               "ATTACH",
18993      "DETACH",               "ALTER_TABLE",          "REINDEX",
18994      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
18995      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
18996   };
18997   int i;
18998   const char *az[4];
18999   az[0] = zA1;
19000   az[1] = zA2;
19001   az[2] = zA3;
19002   az[3] = zA4;
19003   oputf("authorizer: %s", azAction[op]);
19004   for(i=0; i<4; i++){
19005     oputz(" ");
19006     if( az[i] ){
19007       output_c_string(az[i]);
19008     }else{
19009       oputz("NULL");
19010     }
19011   }
19012   oputz("\n");
19013   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
19014   return SQLITE_OK;
19015 }
19016 #endif
19017 
19018 /*
19019 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
19020 **
19021 ** This routine converts some CREATE TABLE statements for shadow tables
19022 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
19023 **
19024 ** If the schema statement in z[] contains a start-of-comment and if
19025 ** sqlite3_complete() returns false, try to terminate the comment before
19026 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
19027 */
printSchemaLine(const char * z,const char * zTail)19028 static void printSchemaLine(const char *z, const char *zTail){
19029   char *zToFree = 0;
19030   if( z==0 ) return;
19031   if( zTail==0 ) return;
19032   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
19033     const char *zOrig = z;
19034     static const char *azTerm[] = { "", "*/", "\n" };
19035     int i;
19036     for(i=0; i<ArraySize(azTerm); i++){
19037       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
19038       shell_check_oom(zNew);
19039       if( sqlite3_complete(zNew) ){
19040         size_t n = strlen(zNew);
19041         zNew[n-1] = 0;
19042         zToFree = zNew;
19043         z = zNew;
19044         break;
19045       }
19046       sqlite3_free(zNew);
19047     }
19048   }
19049   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
19050     oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
19051   }else{
19052     oputf("%s%s", z, zTail);
19053   }
19054   sqlite3_free(zToFree);
19055 }
printSchemaLineN(char * z,int n,const char * zTail)19056 static void printSchemaLineN(char *z, int n, const char *zTail){
19057   char c = z[n];
19058   z[n] = 0;
19059   printSchemaLine(z, zTail);
19060   z[n] = c;
19061 }
19062 
19063 /*
19064 ** Return true if string z[] has nothing but whitespace and comments to the
19065 ** end of the first line.
19066 */
wsToEol(const char * z)19067 static int wsToEol(const char *z){
19068   int i;
19069   for(i=0; z[i]; i++){
19070     if( z[i]=='\n' ) return 1;
19071     if( IsSpace(z[i]) ) continue;
19072     if( z[i]=='-' && z[i+1]=='-' ) return 1;
19073     return 0;
19074   }
19075   return 1;
19076 }
19077 
19078 /*
19079 ** Add a new entry to the EXPLAIN QUERY PLAN data
19080 */
eqp_append(ShellState * p,int iEqpId,int p2,const char * zText)19081 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
19082   EQPGraphRow *pNew;
19083   i64 nText;
19084   if( zText==0 ) return;
19085   nText = strlen(zText);
19086   if( p->autoEQPtest ){
19087     oputf("%d,%d,%s\n", iEqpId, p2, zText);
19088   }
19089   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
19090   shell_check_oom(pNew);
19091   pNew->iEqpId = iEqpId;
19092   pNew->iParentId = p2;
19093   memcpy(pNew->zText, zText, nText+1);
19094   pNew->pNext = 0;
19095   if( p->sGraph.pLast ){
19096     p->sGraph.pLast->pNext = pNew;
19097   }else{
19098     p->sGraph.pRow = pNew;
19099   }
19100   p->sGraph.pLast = pNew;
19101 }
19102 
19103 /*
19104 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
19105 ** in p->sGraph.
19106 */
eqp_reset(ShellState * p)19107 static void eqp_reset(ShellState *p){
19108   EQPGraphRow *pRow, *pNext;
19109   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
19110     pNext = pRow->pNext;
19111     sqlite3_free(pRow);
19112   }
19113   memset(&p->sGraph, 0, sizeof(p->sGraph));
19114 }
19115 
19116 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
19117 ** pOld, or return the first such line if pOld is NULL
19118 */
eqp_next_row(ShellState * p,int iEqpId,EQPGraphRow * pOld)19119 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
19120   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
19121   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
19122   return pRow;
19123 }
19124 
19125 /* Render a single level of the graph that has iEqpId as its parent.  Called
19126 ** recursively to render sublevels.
19127 */
eqp_render_level(ShellState * p,int iEqpId)19128 static void eqp_render_level(ShellState *p, int iEqpId){
19129   EQPGraphRow *pRow, *pNext;
19130   i64 n = strlen(p->sGraph.zPrefix);
19131   char *z;
19132   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
19133     pNext = eqp_next_row(p, iEqpId, pRow);
19134     z = pRow->zText;
19135     oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
19136     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
19137       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
19138       eqp_render_level(p, pRow->iEqpId);
19139       p->sGraph.zPrefix[n] = 0;
19140     }
19141   }
19142 }
19143 
19144 /*
19145 ** Display and reset the EXPLAIN QUERY PLAN data
19146 */
eqp_render(ShellState * p,i64 nCycle)19147 static void eqp_render(ShellState *p, i64 nCycle){
19148   EQPGraphRow *pRow = p->sGraph.pRow;
19149   if( pRow ){
19150     if( pRow->zText[0]=='-' ){
19151       if( pRow->pNext==0 ){
19152         eqp_reset(p);
19153         return;
19154       }
19155       oputf("%s\n", pRow->zText+3);
19156       p->sGraph.pRow = pRow->pNext;
19157       sqlite3_free(pRow);
19158     }else if( nCycle>0 ){
19159       oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
19160     }else{
19161       oputz("QUERY PLAN\n");
19162     }
19163     p->sGraph.zPrefix[0] = 0;
19164     eqp_render_level(p, 0);
19165     eqp_reset(p);
19166   }
19167 }
19168 
19169 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19170 /*
19171 ** Progress handler callback.
19172 */
progress_handler(void * pClientData)19173 static int progress_handler(void *pClientData) {
19174   ShellState *p = (ShellState*)pClientData;
19175   p->nProgress++;
19176   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
19177     oputf("Progress limit reached (%u)\n", p->nProgress);
19178     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
19179     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
19180     return 1;
19181   }
19182   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
19183     oputf("Progress %u\n", p->nProgress);
19184   }
19185   return 0;
19186 }
19187 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
19188 
19189 /*
19190 ** Print N dashes
19191 */
print_dashes(int N)19192 static void print_dashes(int N){
19193   const char zDash[] = "--------------------------------------------------";
19194   const int nDash = sizeof(zDash) - 1;
19195   while( N>nDash ){
19196     oputz(zDash);
19197     N -= nDash;
19198   }
19199   oputf("%.*s", N, zDash);
19200 }
19201 
19202 /*
19203 ** Print a markdown or table-style row separator using ascii-art
19204 */
print_row_separator(ShellState * p,int nArg,const char * zSep)19205 static void print_row_separator(
19206   ShellState *p,
19207   int nArg,
19208   const char *zSep
19209 ){
19210   int i;
19211   if( nArg>0 ){
19212     oputz(zSep);
19213     print_dashes(p->actualWidth[0]+2);
19214     for(i=1; i<nArg; i++){
19215       oputz(zSep);
19216       print_dashes(p->actualWidth[i]+2);
19217     }
19218     oputz(zSep);
19219   }
19220   oputz("\n");
19221 }
19222 
19223 /*
19224 ** This is the callback routine that the shell
19225 ** invokes for each row of a query result.
19226 */
shell_callback(void * pArg,int nArg,char ** azArg,char ** azCol,int * aiType)19227 static int shell_callback(
19228   void *pArg,
19229   int nArg,        /* Number of result columns */
19230   char **azArg,    /* Text of each result column */
19231   char **azCol,    /* Column names */
19232   int *aiType      /* Column types.  Might be NULL */
19233 ){
19234   int i;
19235   ShellState *p = (ShellState*)pArg;
19236 
19237   if( azArg==0 ) return 0;
19238   switch( p->cMode ){
19239     case MODE_Count:
19240     case MODE_Off: {
19241       break;
19242     }
19243     case MODE_Line: {
19244       int w = 5;
19245       if( azArg==0 ) break;
19246       for(i=0; i<nArg; i++){
19247         int len = strlen30(azCol[i] ? azCol[i] : "");
19248         if( len>w ) w = len;
19249       }
19250       if( p->cnt++>0 ) oputz(p->rowSeparator);
19251       for(i=0; i<nArg; i++){
19252         oputf("%*s = %s%s", w, azCol[i],
19253               azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
19254       }
19255       break;
19256     }
19257     case MODE_ScanExp:
19258     case MODE_Explain: {
19259       static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
19260       static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
19261       static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
19262       static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
19263 
19264       const int *aWidth = aExplainWidth;
19265       const int *aMap = aExplainMap;
19266       int nWidth = ArraySize(aExplainWidth);
19267       int iIndent = 1;
19268 
19269       if( p->cMode==MODE_ScanExp ){
19270         aWidth = aScanExpWidth;
19271         aMap = aScanExpMap;
19272         nWidth = ArraySize(aScanExpWidth);
19273         iIndent = 3;
19274       }
19275       if( nArg>nWidth ) nArg = nWidth;
19276 
19277       /* If this is the first row seen, print out the headers */
19278       if( p->cnt++==0 ){
19279         for(i=0; i<nArg; i++){
19280           utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
19281           oputz(i==nArg-1 ? "\n" : "  ");
19282         }
19283         for(i=0; i<nArg; i++){
19284           print_dashes(aWidth[i]);
19285           oputz(i==nArg-1 ? "\n" : "  ");
19286         }
19287       }
19288 
19289       /* If there is no data, exit early. */
19290       if( azArg==0 ) break;
19291 
19292       for(i=0; i<nArg; i++){
19293         const char *zSep = "  ";
19294         int w = aWidth[i];
19295         const char *zVal = azArg[ aMap[i] ];
19296         if( i==nArg-1 ) w = 0;
19297         if( zVal && strlenChar(zVal)>w ){
19298           w = strlenChar(zVal);
19299           zSep = " ";
19300         }
19301         if( i==iIndent && p->aiIndent && p->pStmt ){
19302           if( p->iIndent<p->nIndent ){
19303             oputf("%*.s", p->aiIndent[p->iIndent], "");
19304           }
19305           p->iIndent++;
19306         }
19307         utf8_width_print(w, zVal ? zVal : p->nullValue);
19308         oputz(i==nArg-1 ? "\n" : zSep);
19309       }
19310       break;
19311     }
19312     case MODE_Semi: {   /* .schema and .fullschema output */
19313       printSchemaLine(azArg[0], ";\n");
19314       break;
19315     }
19316     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
19317       char *z;
19318       int j;
19319       int nParen = 0;
19320       char cEnd = 0;
19321       char c;
19322       int nLine = 0;
19323       assert( nArg==1 );
19324       if( azArg[0]==0 ) break;
19325       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
19326        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
19327       ){
19328         oputf("%s;\n", azArg[0]);
19329         break;
19330       }
19331       z = sqlite3_mprintf("%s", azArg[0]);
19332       shell_check_oom(z);
19333       j = 0;
19334       for(i=0; IsSpace(z[i]); i++){}
19335       for(; (c = z[i])!=0; i++){
19336         if( IsSpace(c) ){
19337           if( z[j-1]=='\r' ) z[j-1] = '\n';
19338           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
19339         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
19340           j--;
19341         }
19342         z[j++] = c;
19343       }
19344       while( j>0 && IsSpace(z[j-1]) ){ j--; }
19345       z[j] = 0;
19346       if( strlen30(z)>=79 ){
19347         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
19348           if( c==cEnd ){
19349             cEnd = 0;
19350           }else if( c=='"' || c=='\'' || c=='`' ){
19351             cEnd = c;
19352           }else if( c=='[' ){
19353             cEnd = ']';
19354           }else if( c=='-' && z[i+1]=='-' ){
19355             cEnd = '\n';
19356           }else if( c=='(' ){
19357             nParen++;
19358           }else if( c==')' ){
19359             nParen--;
19360             if( nLine>0 && nParen==0 && j>0 ){
19361               printSchemaLineN(z, j, "\n");
19362               j = 0;
19363             }
19364           }
19365           z[j++] = c;
19366           if( nParen==1 && cEnd==0
19367            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
19368           ){
19369             if( c=='\n' ) j--;
19370             printSchemaLineN(z, j, "\n  ");
19371             j = 0;
19372             nLine++;
19373             while( IsSpace(z[i+1]) ){ i++; }
19374           }
19375         }
19376         z[j] = 0;
19377       }
19378       printSchemaLine(z, ";\n");
19379       sqlite3_free(z);
19380       break;
19381     }
19382     case MODE_List: {
19383       if( p->cnt++==0 && p->showHeader ){
19384         for(i=0; i<nArg; i++){
19385           oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
19386         }
19387       }
19388       if( azArg==0 ) break;
19389       for(i=0; i<nArg; i++){
19390         char *z = azArg[i];
19391         if( z==0 ) z = p->nullValue;
19392         oputz(z);
19393         oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
19394       }
19395       break;
19396     }
19397     case MODE_Html: {
19398       if( p->cnt++==0 && p->showHeader ){
19399         oputz("<TR>");
19400         for(i=0; i<nArg; i++){
19401           oputz("<TH>");
19402           output_html_string(azCol[i]);
19403           oputz("</TH>\n");
19404         }
19405         oputz("</TR>\n");
19406       }
19407       if( azArg==0 ) break;
19408       oputz("<TR>");
19409       for(i=0; i<nArg; i++){
19410         oputz("<TD>");
19411         output_html_string(azArg[i] ? azArg[i] : p->nullValue);
19412         oputz("</TD>\n");
19413       }
19414       oputz("</TR>\n");
19415       break;
19416     }
19417     case MODE_Tcl: {
19418       if( p->cnt++==0 && p->showHeader ){
19419         for(i=0; i<nArg; i++){
19420           output_c_string(azCol[i] ? azCol[i] : "");
19421           if(i<nArg-1) oputz(p->colSeparator);
19422         }
19423         oputz(p->rowSeparator);
19424       }
19425       if( azArg==0 ) break;
19426       for(i=0; i<nArg; i++){
19427         output_c_string(azArg[i] ? azArg[i] : p->nullValue);
19428         if(i<nArg-1) oputz(p->colSeparator);
19429       }
19430       oputz(p->rowSeparator);
19431       break;
19432     }
19433     case MODE_Csv: {
19434       setBinaryMode(p->out, 1);
19435       if( p->cnt++==0 && p->showHeader ){
19436         for(i=0; i<nArg; i++){
19437           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
19438         }
19439         oputz(p->rowSeparator);
19440       }
19441       if( nArg>0 ){
19442         for(i=0; i<nArg; i++){
19443           output_csv(p, azArg[i], i<nArg-1);
19444         }
19445         oputz(p->rowSeparator);
19446       }
19447       setTextMode(p->out, 1);
19448       break;
19449     }
19450     case MODE_Insert: {
19451       if( azArg==0 ) break;
19452       oputf("INSERT INTO %s",p->zDestTable);
19453       if( p->showHeader ){
19454         oputz("(");
19455         for(i=0; i<nArg; i++){
19456           if( i>0 ) oputz(",");
19457           if( quoteChar(azCol[i]) ){
19458             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
19459             shell_check_oom(z);
19460             oputz(z);
19461             sqlite3_free(z);
19462           }else{
19463             oputf("%s", azCol[i]);
19464           }
19465         }
19466         oputz(")");
19467       }
19468       p->cnt++;
19469       for(i=0; i<nArg; i++){
19470         oputz(i>0 ? "," : " VALUES(");
19471         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19472           oputz("NULL");
19473         }else if( aiType && aiType[i]==SQLITE_TEXT ){
19474           if( ShellHasFlag(p, SHFLG_Newlines) ){
19475             output_quoted_string(azArg[i]);
19476           }else{
19477             output_quoted_escaped_string(azArg[i]);
19478           }
19479         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
19480           oputz(azArg[i]);
19481         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19482           char z[50];
19483           double r = sqlite3_column_double(p->pStmt, i);
19484           sqlite3_uint64 ur;
19485           memcpy(&ur,&r,sizeof(r));
19486           if( ur==0x7ff0000000000000LL ){
19487             oputz("9.0e+999");
19488           }else if( ur==0xfff0000000000000LL ){
19489             oputz("-9.0e+999");
19490           }else{
19491             sqlite3_int64 ir = (sqlite3_int64)r;
19492             if( r==(double)ir ){
19493               sqlite3_snprintf(50,z,"%lld.0", ir);
19494             }else{
19495               sqlite3_snprintf(50,z,"%!.20g", r);
19496             }
19497             oputz(z);
19498           }
19499         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19500           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19501           int nBlob = sqlite3_column_bytes(p->pStmt, i);
19502           output_hex_blob(pBlob, nBlob);
19503         }else if( isNumber(azArg[i], 0) ){
19504           oputz(azArg[i]);
19505         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
19506           output_quoted_string(azArg[i]);
19507         }else{
19508           output_quoted_escaped_string(azArg[i]);
19509         }
19510       }
19511       oputz(");\n");
19512       break;
19513     }
19514     case MODE_Json: {
19515       if( azArg==0 ) break;
19516       if( p->cnt==0 ){
19517         fputs("[{", p->out);
19518       }else{
19519         fputs(",\n{", p->out);
19520       }
19521       p->cnt++;
19522       for(i=0; i<nArg; i++){
19523         output_json_string(azCol[i], -1);
19524         oputz(":");
19525         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19526           oputz("null");
19527         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19528           char z[50];
19529           double r = sqlite3_column_double(p->pStmt, i);
19530           sqlite3_uint64 ur;
19531           memcpy(&ur,&r,sizeof(r));
19532           if( ur==0x7ff0000000000000LL ){
19533             oputz("9.0e+999");
19534           }else if( ur==0xfff0000000000000LL ){
19535             oputz("-9.0e+999");
19536           }else{
19537             sqlite3_snprintf(50,z,"%!.20g", r);
19538             oputz(z);
19539           }
19540         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19541           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19542           int nBlob = sqlite3_column_bytes(p->pStmt, i);
19543           output_json_string(pBlob, nBlob);
19544         }else if( aiType && aiType[i]==SQLITE_TEXT ){
19545           output_json_string(azArg[i], -1);
19546         }else{
19547           oputz(azArg[i]);
19548         }
19549         if( i<nArg-1 ){
19550           oputz(",");
19551         }
19552       }
19553       oputz("}");
19554       break;
19555     }
19556     case MODE_Quote: {
19557       if( azArg==0 ) break;
19558       if( p->cnt==0 && p->showHeader ){
19559         for(i=0; i<nArg; i++){
19560           if( i>0 ) fputs(p->colSeparator, p->out);
19561           output_quoted_string(azCol[i]);
19562         }
19563         fputs(p->rowSeparator, p->out);
19564       }
19565       p->cnt++;
19566       for(i=0; i<nArg; i++){
19567         if( i>0 ) fputs(p->colSeparator, p->out);
19568         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19569           oputz("NULL");
19570         }else if( aiType && aiType[i]==SQLITE_TEXT ){
19571           output_quoted_string(azArg[i]);
19572         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
19573           oputz(azArg[i]);
19574         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19575           char z[50];
19576           double r = sqlite3_column_double(p->pStmt, i);
19577           sqlite3_snprintf(50,z,"%!.20g", r);
19578           oputz(z);
19579         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19580           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19581           int nBlob = sqlite3_column_bytes(p->pStmt, i);
19582           output_hex_blob(pBlob, nBlob);
19583         }else if( isNumber(azArg[i], 0) ){
19584           oputz(azArg[i]);
19585         }else{
19586           output_quoted_string(azArg[i]);
19587         }
19588       }
19589       fputs(p->rowSeparator, p->out);
19590       break;
19591     }
19592     case MODE_Ascii: {
19593       if( p->cnt++==0 && p->showHeader ){
19594         for(i=0; i<nArg; i++){
19595           if( i>0 ) oputz(p->colSeparator);
19596           oputz(azCol[i] ? azCol[i] : "");
19597         }
19598         oputz(p->rowSeparator);
19599       }
19600       if( azArg==0 ) break;
19601       for(i=0; i<nArg; i++){
19602         if( i>0 ) oputz(p->colSeparator);
19603         oputz(azArg[i] ? azArg[i] : p->nullValue);
19604       }
19605       oputz(p->rowSeparator);
19606       break;
19607     }
19608     case MODE_EQP: {
19609       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
19610       break;
19611     }
19612   }
19613   return 0;
19614 }
19615 
19616 /*
19617 ** This is the callback routine that the SQLite library
19618 ** invokes for each row of a query result.
19619 */
callback(void * pArg,int nArg,char ** azArg,char ** azCol)19620 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
19621   /* since we don't have type info, call the shell_callback with a NULL value */
19622   return shell_callback(pArg, nArg, azArg, azCol, NULL);
19623 }
19624 
19625 /*
19626 ** This is the callback routine from sqlite3_exec() that appends all
19627 ** output onto the end of a ShellText object.
19628 */
captureOutputCallback(void * pArg,int nArg,char ** azArg,char ** az)19629 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
19630   ShellText *p = (ShellText*)pArg;
19631   int i;
19632   UNUSED_PARAMETER(az);
19633   if( azArg==0 ) return 0;
19634   if( p->n ) appendText(p, "|", 0);
19635   for(i=0; i<nArg; i++){
19636     if( i ) appendText(p, ",", 0);
19637     if( azArg[i] ) appendText(p, azArg[i], 0);
19638   }
19639   return 0;
19640 }
19641 
19642 /*
19643 ** Generate an appropriate SELFTEST table in the main database.
19644 */
createSelftestTable(ShellState * p)19645 static void createSelftestTable(ShellState *p){
19646   char *zErrMsg = 0;
19647   sqlite3_exec(p->db,
19648     "SAVEPOINT selftest_init;\n"
19649     "CREATE TABLE IF NOT EXISTS selftest(\n"
19650     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
19651     "  op TEXT,\n"                   /* Operator:  memo run */
19652     "  cmd TEXT,\n"                  /* Command text */
19653     "  ans TEXT\n"                   /* Desired answer */
19654     ");"
19655     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
19656     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
19657     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
19658     "         'memo','Tests generated by --init');\n"
19659     "INSERT INTO [_shell$self]\n"
19660     "  SELECT 'run',\n"
19661     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
19662                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
19663     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
19664                           "FROM sqlite_schema ORDER BY 2',224));\n"
19665     "INSERT INTO [_shell$self]\n"
19666     "  SELECT 'run',"
19667     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
19668     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
19669     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
19670     "  FROM (\n"
19671     "    SELECT name FROM sqlite_schema\n"
19672     "     WHERE type='table'\n"
19673     "       AND name<>'selftest'\n"
19674     "       AND coalesce(rootpage,0)>0\n"
19675     "  )\n"
19676     " ORDER BY name;\n"
19677     "INSERT INTO [_shell$self]\n"
19678     "  VALUES('run','PRAGMA integrity_check','ok');\n"
19679     "INSERT INTO selftest(tno,op,cmd,ans)"
19680     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
19681     "DROP TABLE [_shell$self];"
19682     ,0,0,&zErrMsg);
19683   if( zErrMsg ){
19684     eputf("SELFTEST initialization failure: %s\n", zErrMsg);
19685     sqlite3_free(zErrMsg);
19686   }
19687   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
19688 }
19689 
19690 
19691 /*
19692 ** Set the destination table field of the ShellState structure to
19693 ** the name of the table given.  Escape any quote characters in the
19694 ** table name.
19695 */
set_table_name(ShellState * p,const char * zName)19696 static void set_table_name(ShellState *p, const char *zName){
19697   int i, n;
19698   char cQuote;
19699   char *z;
19700 
19701   if( p->zDestTable ){
19702     free(p->zDestTable);
19703     p->zDestTable = 0;
19704   }
19705   if( zName==0 ) return;
19706   cQuote = quoteChar(zName);
19707   n = strlen30(zName);
19708   if( cQuote ) n += n+2;
19709   z = p->zDestTable = malloc( n+1 );
19710   shell_check_oom(z);
19711   n = 0;
19712   if( cQuote ) z[n++] = cQuote;
19713   for(i=0; zName[i]; i++){
19714     z[n++] = zName[i];
19715     if( zName[i]==cQuote ) z[n++] = cQuote;
19716   }
19717   if( cQuote ) z[n++] = cQuote;
19718   z[n] = 0;
19719 }
19720 
19721 /*
19722 ** Maybe construct two lines of text that point out the position of a
19723 ** syntax error.  Return a pointer to the text, in memory obtained from
19724 ** sqlite3_malloc().  Or, if the most recent error does not involve a
19725 ** specific token that we can point to, return an empty string.
19726 **
19727 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
19728 ** and should be released by the caller invoking sqlite3_free().
19729 */
shell_error_context(const char * zSql,sqlite3 * db)19730 static char *shell_error_context(const char *zSql, sqlite3 *db){
19731   int iOffset;
19732   size_t len;
19733   char *zCode;
19734   char *zMsg;
19735   int i;
19736   if( db==0
19737    || zSql==0
19738    || (iOffset = sqlite3_error_offset(db))<0
19739    || iOffset>=(int)strlen(zSql)
19740   ){
19741     return sqlite3_mprintf("");
19742   }
19743   while( iOffset>50 ){
19744     iOffset--;
19745     zSql++;
19746     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
19747   }
19748   len = strlen(zSql);
19749   if( len>78 ){
19750     len = 78;
19751     while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
19752   }
19753   zCode = sqlite3_mprintf("%.*s", len, zSql);
19754   shell_check_oom(zCode);
19755   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
19756   if( iOffset<25 ){
19757     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
19758   }else{
19759     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
19760   }
19761   return zMsg;
19762 }
19763 
19764 
19765 /*
19766 ** Execute a query statement that will generate SQL output.  Print
19767 ** the result columns, comma-separated, on a line and then add a
19768 ** semicolon terminator to the end of that line.
19769 **
19770 ** If the number of columns is 1 and that column contains text "--"
19771 ** then write the semicolon on a separate line.  That way, if a
19772 ** "--" comment occurs at the end of the statement, the comment
19773 ** won't consume the semicolon terminator.
19774 */
run_table_dump_query(ShellState * p,const char * zSelect)19775 static int run_table_dump_query(
19776   ShellState *p,           /* Query context */
19777   const char *zSelect      /* SELECT statement to extract content */
19778 ){
19779   sqlite3_stmt *pSelect;
19780   int rc;
19781   int nResult;
19782   int i;
19783   const char *z;
19784   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
19785   if( rc!=SQLITE_OK || !pSelect ){
19786     char *zContext = shell_error_context(zSelect, p->db);
19787     oputf("/**** ERROR: (%d) %s *****/\n%s",
19788           rc, sqlite3_errmsg(p->db), zContext);
19789     sqlite3_free(zContext);
19790     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19791     return rc;
19792   }
19793   rc = sqlite3_step(pSelect);
19794   nResult = sqlite3_column_count(pSelect);
19795   while( rc==SQLITE_ROW ){
19796     z = (const char*)sqlite3_column_text(pSelect, 0);
19797     oputf("%s", z);
19798     for(i=1; i<nResult; i++){
19799       oputf(",%s", sqlite3_column_text(pSelect, i));
19800     }
19801     if( z==0 ) z = "";
19802     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
19803     if( z[0] ){
19804       oputz("\n;\n");
19805     }else{
19806       oputz(";\n");
19807     }
19808     rc = sqlite3_step(pSelect);
19809   }
19810   rc = sqlite3_finalize(pSelect);
19811   if( rc!=SQLITE_OK ){
19812     oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
19813     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19814   }
19815   return rc;
19816 }
19817 
19818 /*
19819 ** Allocate space and save off string indicating current error.
19820 */
save_err_msg(sqlite3 * db,const char * zPhase,int rc,const char * zSql)19821 static char *save_err_msg(
19822   sqlite3 *db,           /* Database to query */
19823   const char *zPhase,    /* When the error occurs */
19824   int rc,                /* Error code returned from API */
19825   const char *zSql       /* SQL string, or NULL */
19826 ){
19827   char *zErr;
19828   char *zContext;
19829   sqlite3_str *pStr = sqlite3_str_new(0);
19830   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
19831   if( rc>1 ){
19832     sqlite3_str_appendf(pStr, " (%d)", rc);
19833   }
19834   zContext = shell_error_context(zSql, db);
19835   if( zContext ){
19836     sqlite3_str_appendall(pStr, zContext);
19837     sqlite3_free(zContext);
19838   }
19839   zErr = sqlite3_str_finish(pStr);
19840   shell_check_oom(zErr);
19841   return zErr;
19842 }
19843 
19844 #ifdef __linux__
19845 /*
19846 ** Attempt to display I/O stats on Linux using /proc/PID/io
19847 */
displayLinuxIoStats(void)19848 static void displayLinuxIoStats(void){
19849   FILE *in;
19850   char z[200];
19851   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
19852   in = fopen(z, "rb");
19853   if( in==0 ) return;
19854   while( fgets(z, sizeof(z), in)!=0 ){
19855     static const struct {
19856       const char *zPattern;
19857       const char *zDesc;
19858     } aTrans[] = {
19859       { "rchar: ",                  "Bytes received by read():" },
19860       { "wchar: ",                  "Bytes sent to write():"    },
19861       { "syscr: ",                  "Read() system calls:"      },
19862       { "syscw: ",                  "Write() system calls:"     },
19863       { "read_bytes: ",             "Bytes read from storage:"  },
19864       { "write_bytes: ",            "Bytes written to storage:" },
19865       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
19866     };
19867     int i;
19868     for(i=0; i<ArraySize(aTrans); i++){
19869       int n = strlen30(aTrans[i].zPattern);
19870       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
19871         oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
19872         break;
19873       }
19874     }
19875   }
19876   fclose(in);
19877 }
19878 #endif
19879 
19880 /*
19881 ** Display a single line of status using 64-bit values.
19882 */
displayStatLine(char * zLabel,char * zFormat,int iStatusCtrl,int bReset)19883 static void displayStatLine(
19884   char *zLabel,             /* Label for this one line */
19885   char *zFormat,            /* Format for the result */
19886   int iStatusCtrl,          /* Which status to display */
19887   int bReset                /* True to reset the stats */
19888 ){
19889   sqlite3_int64 iCur = -1;
19890   sqlite3_int64 iHiwtr = -1;
19891   int i, nPercent;
19892   char zLine[200];
19893   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
19894   for(i=0, nPercent=0; zFormat[i]; i++){
19895     if( zFormat[i]=='%' ) nPercent++;
19896   }
19897   if( nPercent>1 ){
19898     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
19899   }else{
19900     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
19901   }
19902   oputf("%-36s %s\n", zLabel, zLine);
19903 }
19904 
19905 /*
19906 ** Display memory stats.
19907 */
display_stats(sqlite3 * db,ShellState * pArg,int bReset)19908 static int display_stats(
19909   sqlite3 *db,                /* Database to query */
19910   ShellState *pArg,           /* Pointer to ShellState */
19911   int bReset                  /* True to reset the stats */
19912 ){
19913   int iCur;
19914   int iHiwtr;
19915   if( pArg==0 || pArg->out==0 ) return 0;
19916 
19917   if( pArg->pStmt && pArg->statsOn==2 ){
19918     int nCol, i, x;
19919     sqlite3_stmt *pStmt = pArg->pStmt;
19920     char z[100];
19921     nCol = sqlite3_column_count(pStmt);
19922     oputf("%-36s %d\n", "Number of output columns:", nCol);
19923     for(i=0; i<nCol; i++){
19924       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
19925       oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
19926 #ifndef SQLITE_OMIT_DECLTYPE
19927       sqlite3_snprintf(30, z+x, "declared type:");
19928       oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
19929 #endif
19930 #ifdef SQLITE_ENABLE_COLUMN_METADATA
19931       sqlite3_snprintf(30, z+x, "database name:");
19932       oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
19933       sqlite3_snprintf(30, z+x, "table name:");
19934       oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
19935       sqlite3_snprintf(30, z+x, "origin name:");
19936       oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
19937 #endif
19938     }
19939   }
19940 
19941   if( pArg->statsOn==3 ){
19942     if( pArg->pStmt ){
19943       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
19944       oputf("VM-steps: %d\n", iCur);
19945     }
19946     return 0;
19947   }
19948 
19949   displayStatLine("Memory Used:",
19950      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
19951   displayStatLine("Number of Outstanding Allocations:",
19952      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
19953   if( pArg->shellFlgs & SHFLG_Pagecache ){
19954     displayStatLine("Number of Pcache Pages Used:",
19955        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
19956   }
19957   displayStatLine("Number of Pcache Overflow Bytes:",
19958      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
19959   displayStatLine("Largest Allocation:",
19960      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
19961   displayStatLine("Largest Pcache Allocation:",
19962      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
19963 #ifdef YYTRACKMAXSTACKDEPTH
19964   displayStatLine("Deepest Parser Stack:",
19965      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
19966 #endif
19967 
19968   if( db ){
19969     if( pArg->shellFlgs & SHFLG_Lookaside ){
19970       iHiwtr = iCur = -1;
19971       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
19972                         &iCur, &iHiwtr, bReset);
19973       oputf("Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
19974       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
19975                         &iCur, &iHiwtr, bReset);
19976       oputf("Successful lookaside attempts:       %d\n", iHiwtr);
19977       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
19978                         &iCur, &iHiwtr, bReset);
19979       oputf("Lookaside failures due to size:      %d\n", iHiwtr);
19980       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
19981                         &iCur, &iHiwtr, bReset);
19982       oputf("Lookaside failures due to OOM:       %d\n", iHiwtr);
19983     }
19984     iHiwtr = iCur = -1;
19985     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
19986     oputf("Pager Heap Usage:                    %d bytes\n", iCur);
19987     iHiwtr = iCur = -1;
19988     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
19989     oputf("Page cache hits:                     %d\n", iCur);
19990     iHiwtr = iCur = -1;
19991     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
19992     oputf("Page cache misses:                   %d\n", iCur);
19993     iHiwtr = iCur = -1;
19994     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
19995     oputf("Page cache writes:                   %d\n", iCur);
19996     iHiwtr = iCur = -1;
19997     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
19998     oputf("Page cache spills:                   %d\n", iCur);
19999     iHiwtr = iCur = -1;
20000     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
20001     oputf("Schema Heap Usage:                   %d bytes\n", iCur);
20002     iHiwtr = iCur = -1;
20003     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
20004     oputf("Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
20005   }
20006 
20007   if( pArg->pStmt ){
20008     int iHit, iMiss;
20009     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
20010                                bReset);
20011     oputf("Fullscan Steps:                      %d\n", iCur);
20012     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
20013     oputf("Sort Operations:                     %d\n", iCur);
20014     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
20015     oputf("Autoindex Inserts:                   %d\n", iCur);
20016     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
20017                                bReset);
20018     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
20019                                 bReset);
20020     if( iHit || iMiss ){
20021       oputf("Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
20022     }
20023     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
20024     oputf("Virtual Machine Steps:               %d\n", iCur);
20025     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
20026     oputf("Reprepare operations:                %d\n", iCur);
20027     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
20028     oputf("Number of times run:                 %d\n", iCur);
20029     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
20030     oputf("Memory used by prepared stmt:        %d\n", iCur);
20031   }
20032 
20033 #ifdef __linux__
20034   displayLinuxIoStats();
20035 #endif
20036 
20037   /* Do not remove this machine readable comment: extra-stats-output-here */
20038 
20039   return 0;
20040 }
20041 
20042 
20043 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
scanStatsHeight(sqlite3_stmt * p,int iEntry)20044 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
20045   int iPid = 0;
20046   int ret = 1;
20047   sqlite3_stmt_scanstatus_v2(p, iEntry,
20048       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
20049   );
20050   while( iPid!=0 ){
20051     int ii;
20052     for(ii=0; 1; ii++){
20053       int iId;
20054       int res;
20055       res = sqlite3_stmt_scanstatus_v2(p, ii,
20056           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
20057       );
20058       if( res ) break;
20059       if( iId==iPid ){
20060         sqlite3_stmt_scanstatus_v2(p, ii,
20061             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
20062         );
20063       }
20064     }
20065     ret++;
20066   }
20067   return ret;
20068 }
20069 #endif
20070 
20071 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
display_explain_scanstats(sqlite3 * db,ShellState * pArg)20072 static void display_explain_scanstats(
20073   sqlite3 *db,                    /* Database to query */
20074   ShellState *pArg                /* Pointer to ShellState */
20075 ){
20076   static const int f = SQLITE_SCANSTAT_COMPLEX;
20077   sqlite3_stmt *p = pArg->pStmt;
20078   int ii = 0;
20079   i64 nTotal = 0;
20080   int nWidth = 0;
20081   eqp_reset(pArg);
20082 
20083   for(ii=0; 1; ii++){
20084     const char *z = 0;
20085     int n = 0;
20086     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
20087       break;
20088     }
20089     n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
20090     if( n>nWidth ) nWidth = n;
20091   }
20092   nWidth += 4;
20093 
20094   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
20095   for(ii=0; 1; ii++){
20096     i64 nLoop = 0;
20097     i64 nRow = 0;
20098     i64 nCycle = 0;
20099     int iId = 0;
20100     int iPid = 0;
20101     const char *zo = 0;
20102     const char *zName = 0;
20103     char *zText = 0;
20104     double rEst = 0.0;
20105 
20106     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
20107       break;
20108     }
20109     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
20110     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
20111     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
20112     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
20113     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
20114     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
20115     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
20116 
20117     zText = sqlite3_mprintf("%s", zo);
20118     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
20119       char *z = 0;
20120       if( nCycle>=0 && nTotal>0 ){
20121         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
20122             nCycle, ((nCycle*100)+nTotal/2) / nTotal
20123         );
20124       }
20125       if( nLoop>=0 ){
20126         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
20127       }
20128       if( nRow>=0 ){
20129         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
20130       }
20131 
20132       if( zName && pArg->scanstatsOn>1 ){
20133         double rpl = (double)nRow / (double)nLoop;
20134         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
20135       }
20136 
20137       zText = sqlite3_mprintf(
20138           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
20139       );
20140     }
20141 
20142     eqp_append(pArg, iId, iPid, zText);
20143     sqlite3_free(zText);
20144   }
20145 
20146   eqp_render(pArg, nTotal);
20147 }
20148 #endif
20149 
20150 
20151 /*
20152 ** Parameter azArray points to a zero-terminated array of strings. zStr
20153 ** points to a single nul-terminated string. Return non-zero if zStr
20154 ** is equal, according to strcmp(), to any of the strings in the array.
20155 ** Otherwise, return zero.
20156 */
str_in_array(const char * zStr,const char ** azArray)20157 static int str_in_array(const char *zStr, const char **azArray){
20158   int i;
20159   for(i=0; azArray[i]; i++){
20160     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
20161   }
20162   return 0;
20163 }
20164 
20165 /*
20166 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
20167 ** and populate the ShellState.aiIndent[] array with the number of
20168 ** spaces each opcode should be indented before it is output.
20169 **
20170 ** The indenting rules are:
20171 **
20172 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
20173 **       all opcodes that occur between the p2 jump destination and the opcode
20174 **       itself by 2 spaces.
20175 **
20176 **     * Do the previous for "Return" instructions for when P2 is positive.
20177 **       See tag-20220407a in wherecode.c and vdbe.c.
20178 **
20179 **     * For each "Goto", if the jump destination is earlier in the program
20180 **       and ends on one of:
20181 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
20182 **       or if the P1 parameter is one instead of zero,
20183 **       then indent all opcodes between the earlier instruction
20184 **       and "Goto" by 2 spaces.
20185 */
explain_data_prepare(ShellState * p,sqlite3_stmt * pSql)20186 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
20187   int *abYield = 0;               /* True if op is an OP_Yield */
20188   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
20189   int iOp;                        /* Index of operation in p->aiIndent[] */
20190 
20191   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
20192                            "Return", 0 };
20193   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
20194                             "Rewind", 0 };
20195   const char *azGoto[] = { "Goto", 0 };
20196 
20197   /* The caller guarantees that the leftmost 4 columns of the statement
20198   ** passed to this function are equivalent to the leftmost 4 columns
20199   ** of EXPLAIN statement output. In practice the statement may be
20200   ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
20201   assert( sqlite3_column_count(pSql)>=4 );
20202   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
20203   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
20204   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
20205   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
20206 
20207   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
20208     int i;
20209     int iAddr = sqlite3_column_int(pSql, 0);
20210     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
20211     int p1 = sqlite3_column_int(pSql, 2);
20212     int p2 = sqlite3_column_int(pSql, 3);
20213 
20214     /* Assuming that p2 is an instruction address, set variable p2op to the
20215     ** index of that instruction in the aiIndent[] array. p2 and p2op may be
20216     ** different if the current instruction is part of a sub-program generated
20217     ** by an SQL trigger or foreign key.  */
20218     int p2op = (p2 + (iOp-iAddr));
20219 
20220     /* Grow the p->aiIndent array as required */
20221     if( iOp>=nAlloc ){
20222       nAlloc += 100;
20223       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
20224       shell_check_oom(p->aiIndent);
20225       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
20226       shell_check_oom(abYield);
20227     }
20228 
20229     abYield[iOp] = str_in_array(zOp, azYield);
20230     p->aiIndent[iOp] = 0;
20231     p->nIndent = iOp+1;
20232     if( str_in_array(zOp, azNext) && p2op>0 ){
20233       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
20234     }
20235     if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
20236       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
20237     }
20238   }
20239 
20240   p->iIndent = 0;
20241   sqlite3_free(abYield);
20242   sqlite3_reset(pSql);
20243 }
20244 
20245 /*
20246 ** Free the array allocated by explain_data_prepare().
20247 */
explain_data_delete(ShellState * p)20248 static void explain_data_delete(ShellState *p){
20249   sqlite3_free(p->aiIndent);
20250   p->aiIndent = 0;
20251   p->nIndent = 0;
20252   p->iIndent = 0;
20253 }
20254 
20255 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
20256 
20257 /*
20258 ** Display scan stats.
20259 */
display_scanstats(sqlite3 * db,ShellState * pArg)20260 static void display_scanstats(
20261   sqlite3 *db,                    /* Database to query */
20262   ShellState *pArg                /* Pointer to ShellState */
20263 ){
20264 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
20265   UNUSED_PARAMETER(db);
20266   UNUSED_PARAMETER(pArg);
20267 #else
20268   if( pArg->scanstatsOn==3 ){
20269     const char *zSql =
20270       "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
20271       "   round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
20272       "   FROM bytecode(?)";
20273 
20274     int rc = SQLITE_OK;
20275     sqlite3_stmt *pStmt = 0;
20276     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
20277     if( rc==SQLITE_OK ){
20278       sqlite3_stmt *pSave = pArg->pStmt;
20279       pArg->pStmt = pStmt;
20280       sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
20281 
20282       pArg->cnt = 0;
20283       pArg->cMode = MODE_ScanExp;
20284       explain_data_prepare(pArg, pStmt);
20285       exec_prepared_stmt(pArg, pStmt);
20286       explain_data_delete(pArg);
20287 
20288       sqlite3_finalize(pStmt);
20289       pArg->pStmt = pSave;
20290     }
20291   }else{
20292     display_explain_scanstats(db, pArg);
20293   }
20294 #endif
20295 }
20296 
20297 /*
20298 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
20299 */
20300 static unsigned int savedSelectTrace;
20301 static unsigned int savedWhereTrace;
disable_debug_trace_modes(void)20302 static void disable_debug_trace_modes(void){
20303   unsigned int zero = 0;
20304   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
20305   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
20306   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
20307   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
20308 }
restore_debug_trace_modes(void)20309 static void restore_debug_trace_modes(void){
20310   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
20311   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
20312 }
20313 
20314 /* Create the TEMP table used to store parameter bindings */
bind_table_init(ShellState * p)20315 static void bind_table_init(ShellState *p){
20316   int wrSchema = 0;
20317   int defensiveMode = 0;
20318   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
20319   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
20320   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
20321   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
20322   sqlite3_exec(p->db,
20323     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
20324     "  key TEXT PRIMARY KEY,\n"
20325     "  value\n"
20326     ") WITHOUT ROWID;",
20327     0, 0, 0);
20328   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
20329   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
20330 }
20331 
20332 /*
20333 ** Bind parameters on a prepared statement.
20334 **
20335 ** Parameter bindings are taken from a TEMP table of the form:
20336 **
20337 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
20338 **    WITHOUT ROWID;
20339 **
20340 ** No bindings occur if this table does not exist.  The name of the table
20341 ** begins with "sqlite_" so that it will not collide with ordinary application
20342 ** tables.  The table must be in the TEMP schema.
20343 */
bind_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)20344 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
20345   int nVar;
20346   int i;
20347   int rc;
20348   sqlite3_stmt *pQ = 0;
20349 
20350   nVar = sqlite3_bind_parameter_count(pStmt);
20351   if( nVar==0 ) return;  /* Nothing to do */
20352   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
20353                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
20354     rc = SQLITE_NOTFOUND;
20355     pQ = 0;
20356   }else{
20357     rc = sqlite3_prepare_v2(pArg->db,
20358             "SELECT value FROM temp.sqlite_parameters"
20359             " WHERE key=?1", -1, &pQ, 0);
20360   }
20361   for(i=1; i<=nVar; i++){
20362     char zNum[30];
20363     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
20364     if( zVar==0 ){
20365       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
20366       zVar = zNum;
20367     }
20368     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
20369     if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
20370       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
20371 #ifdef NAN
20372     }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
20373       sqlite3_bind_double(pStmt, i, NAN);
20374 #endif
20375 #ifdef INFINITY
20376     }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
20377       sqlite3_bind_double(pStmt, i, INFINITY);
20378 #endif
20379     }else{
20380       sqlite3_bind_null(pStmt, i);
20381     }
20382     sqlite3_reset(pQ);
20383   }
20384   sqlite3_finalize(pQ);
20385 }
20386 
20387 /*
20388 ** UTF8 box-drawing characters.  Imagine box lines like this:
20389 **
20390 **           1
20391 **           |
20392 **       4 --+-- 2
20393 **           |
20394 **           3
20395 **
20396 ** Each box characters has between 2 and 4 of the lines leading from
20397 ** the center.  The characters are here identified by the numbers of
20398 ** their corresponding lines.
20399 */
20400 #define BOX_24   "\342\224\200"  /* U+2500 --- */
20401 #define BOX_13   "\342\224\202"  /* U+2502  |  */
20402 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
20403 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
20404 #define BOX_12   "\342\224\224"  /* U+2514  '- */
20405 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
20406 #define BOX_123  "\342\224\234"  /* U+251c  |- */
20407 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
20408 #define BOX_234  "\342\224\254"  /* U+252c -,- */
20409 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
20410 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
20411 
20412 /* Draw horizontal line N characters long using unicode box
20413 ** characters
20414 */
print_box_line(int N)20415 static void print_box_line(int N){
20416   const char zDash[] =
20417       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
20418       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
20419   const int nDash = sizeof(zDash) - 1;
20420   N *= 3;
20421   while( N>nDash ){
20422     oputz(zDash);
20423     N -= nDash;
20424   }
20425   oputf("%.*s", N, zDash);
20426 }
20427 
20428 /*
20429 ** Draw a horizontal separator for a MODE_Box table.
20430 */
print_box_row_separator(ShellState * p,int nArg,const char * zSep1,const char * zSep2,const char * zSep3)20431 static void print_box_row_separator(
20432   ShellState *p,
20433   int nArg,
20434   const char *zSep1,
20435   const char *zSep2,
20436   const char *zSep3
20437 ){
20438   int i;
20439   if( nArg>0 ){
20440     oputz(zSep1);
20441     print_box_line(p->actualWidth[0]+2);
20442     for(i=1; i<nArg; i++){
20443       oputz(zSep2);
20444       print_box_line(p->actualWidth[i]+2);
20445     }
20446     oputz(zSep3);
20447   }
20448   oputz("\n");
20449 }
20450 
20451 /*
20452 ** z[] is a line of text that is to be displayed the .mode box or table or
20453 ** similar tabular formats.  z[] might contain control characters such
20454 ** as \n, \t, \f, or \r.
20455 **
20456 ** Compute characters to display on the first line of z[].  Stop at the
20457 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
20458 ** from malloc()) of that first line, which caller should free sometime.
20459 ** Write anything to display on the next line into *pzTail.  If this is
20460 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
20461 */
translateForDisplayAndDup(const unsigned char * z,const unsigned char ** pzTail,int mxWidth,u8 bWordWrap)20462 static char *translateForDisplayAndDup(
20463   const unsigned char *z,            /* Input text to be transformed */
20464   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
20465   int mxWidth,                       /* Max width.  0 means no limit */
20466   u8 bWordWrap                       /* If true, avoid breaking mid-word */
20467 ){
20468   int i;                 /* Input bytes consumed */
20469   int j;                 /* Output bytes generated */
20470   int k;                 /* Input bytes to be displayed */
20471   int n;                 /* Output column number */
20472   unsigned char *zOut;   /* Output text */
20473 
20474   if( z==0 ){
20475     *pzTail = 0;
20476     return 0;
20477   }
20478   if( mxWidth<0 ) mxWidth = -mxWidth;
20479   if( mxWidth==0 ) mxWidth = 1000000;
20480   i = j = n = 0;
20481   while( n<mxWidth ){
20482     if( z[i]>=' ' ){
20483       n++;
20484       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
20485       continue;
20486     }
20487     if( z[i]=='\t' ){
20488       do{
20489         n++;
20490         j++;
20491       }while( (n&7)!=0 && n<mxWidth );
20492       i++;
20493       continue;
20494     }
20495     break;
20496   }
20497   if( n>=mxWidth && bWordWrap  ){
20498     /* Perhaps try to back up to a better place to break the line */
20499     for(k=i; k>i/2; k--){
20500       if( isspace(z[k-1]) ) break;
20501     }
20502     if( k<=i/2 ){
20503       for(k=i; k>i/2; k--){
20504         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
20505       }
20506     }
20507     if( k<=i/2 ){
20508       k = i;
20509     }else{
20510       i = k;
20511       while( z[i]==' ' ) i++;
20512     }
20513   }else{
20514     k = i;
20515   }
20516   if( n>=mxWidth && z[i]>=' ' ){
20517    *pzTail = &z[i];
20518   }else if( z[i]=='\r' && z[i+1]=='\n' ){
20519     *pzTail = z[i+2] ? &z[i+2] : 0;
20520   }else if( z[i]==0 || z[i+1]==0 ){
20521     *pzTail = 0;
20522   }else{
20523     *pzTail = &z[i+1];
20524   }
20525   zOut = malloc( j+1 );
20526   shell_check_oom(zOut);
20527   i = j = n = 0;
20528   while( i<k ){
20529     if( z[i]>=' ' ){
20530       n++;
20531       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
20532       continue;
20533     }
20534     if( z[i]=='\t' ){
20535       do{
20536         n++;
20537         zOut[j++] = ' ';
20538       }while( (n&7)!=0 && n<mxWidth );
20539       i++;
20540       continue;
20541     }
20542     break;
20543   }
20544   zOut[j] = 0;
20545   return (char*)zOut;
20546 }
20547 
20548 /* Extract the value of the i-th current column for pStmt as an SQL literal
20549 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
20550 ** the caller.
20551 */
quoted_column(sqlite3_stmt * pStmt,int i)20552 static char *quoted_column(sqlite3_stmt *pStmt, int i){
20553   switch( sqlite3_column_type(pStmt, i) ){
20554     case SQLITE_NULL: {
20555       return sqlite3_mprintf("NULL");
20556     }
20557     case SQLITE_INTEGER:
20558     case SQLITE_FLOAT: {
20559       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
20560     }
20561     case SQLITE_TEXT: {
20562       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
20563     }
20564     case SQLITE_BLOB: {
20565       int j;
20566       sqlite3_str *pStr = sqlite3_str_new(0);
20567       const unsigned char *a = sqlite3_column_blob(pStmt,i);
20568       int n = sqlite3_column_bytes(pStmt,i);
20569       sqlite3_str_append(pStr, "x'", 2);
20570       for(j=0; j<n; j++){
20571         sqlite3_str_appendf(pStr, "%02x", a[j]);
20572       }
20573       sqlite3_str_append(pStr, "'", 1);
20574       return sqlite3_str_finish(pStr);
20575     }
20576   }
20577   return 0; /* Not reached */
20578 }
20579 
20580 /*
20581 ** Run a prepared statement and output the result in one of the
20582 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
20583 ** or MODE_Box.
20584 **
20585 ** This is different from ordinary exec_prepared_stmt() in that
20586 ** it has to run the entire query and gather the results into memory
20587 ** first, in order to determine column widths, before providing
20588 ** any output.
20589 */
exec_prepared_stmt_columnar(ShellState * p,sqlite3_stmt * pStmt)20590 static void exec_prepared_stmt_columnar(
20591   ShellState *p,                        /* Pointer to ShellState */
20592   sqlite3_stmt *pStmt                   /* Statement to run */
20593 ){
20594   sqlite3_int64 nRow = 0;
20595   int nColumn = 0;
20596   char **azData = 0;
20597   sqlite3_int64 nAlloc = 0;
20598   char *abRowDiv = 0;
20599   const unsigned char *uz;
20600   const char *z;
20601   char **azQuoted = 0;
20602   int rc;
20603   sqlite3_int64 i, nData;
20604   int j, nTotal, w, n;
20605   const char *colSep = 0;
20606   const char *rowSep = 0;
20607   const unsigned char **azNextLine = 0;
20608   int bNextLine = 0;
20609   int bMultiLineRowExists = 0;
20610   int bw = p->cmOpts.bWordWrap;
20611   const char *zEmpty = "";
20612   const char *zShowNull = p->nullValue;
20613 
20614   rc = sqlite3_step(pStmt);
20615   if( rc!=SQLITE_ROW ) return;
20616   nColumn = sqlite3_column_count(pStmt);
20617   nAlloc = nColumn*4;
20618   if( nAlloc<=0 ) nAlloc = 1;
20619   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
20620   shell_check_oom(azData);
20621   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
20622   shell_check_oom(azNextLine);
20623   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
20624   if( p->cmOpts.bQuote ){
20625     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
20626     shell_check_oom(azQuoted);
20627     memset(azQuoted, 0, nColumn*sizeof(char*) );
20628   }
20629   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
20630   shell_check_oom(abRowDiv);
20631   if( nColumn>p->nWidth ){
20632     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
20633     shell_check_oom(p->colWidth);
20634     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
20635     p->nWidth = nColumn;
20636     p->actualWidth = &p->colWidth[nColumn];
20637   }
20638   memset(p->actualWidth, 0, nColumn*sizeof(int));
20639   for(i=0; i<nColumn; i++){
20640     w = p->colWidth[i];
20641     if( w<0 ) w = -w;
20642     p->actualWidth[i] = w;
20643   }
20644   for(i=0; i<nColumn; i++){
20645     const unsigned char *zNotUsed;
20646     int wx = p->colWidth[i];
20647     if( wx==0 ){
20648       wx = p->cmOpts.iWrap;
20649     }
20650     if( wx<0 ) wx = -wx;
20651     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
20652     if( uz==0 ) uz = (u8*)"";
20653     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
20654   }
20655   do{
20656     int useNextLine = bNextLine;
20657     bNextLine = 0;
20658     if( (nRow+2)*nColumn >= nAlloc ){
20659       nAlloc *= 2;
20660       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
20661       shell_check_oom(azData);
20662       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
20663       shell_check_oom(abRowDiv);
20664     }
20665     abRowDiv[nRow] = 1;
20666     nRow++;
20667     for(i=0; i<nColumn; i++){
20668       int wx = p->colWidth[i];
20669       if( wx==0 ){
20670         wx = p->cmOpts.iWrap;
20671       }
20672       if( wx<0 ) wx = -wx;
20673       if( useNextLine ){
20674         uz = azNextLine[i];
20675         if( uz==0 ) uz = (u8*)zEmpty;
20676       }else if( p->cmOpts.bQuote ){
20677         sqlite3_free(azQuoted[i]);
20678         azQuoted[i] = quoted_column(pStmt,i);
20679         uz = (const unsigned char*)azQuoted[i];
20680       }else{
20681         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
20682         if( uz==0 ) uz = (u8*)zShowNull;
20683       }
20684       azData[nRow*nColumn + i]
20685         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
20686       if( azNextLine[i] ){
20687         bNextLine = 1;
20688         abRowDiv[nRow-1] = 0;
20689         bMultiLineRowExists = 1;
20690       }
20691     }
20692   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
20693   nTotal = nColumn*(nRow+1);
20694   for(i=0; i<nTotal; i++){
20695     z = azData[i];
20696     if( z==0 ) z = (char*)zEmpty;
20697     n = strlenChar(z);
20698     j = i%nColumn;
20699     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
20700   }
20701   if( seenInterrupt ) goto columnar_end;
20702   if( nColumn==0 ) goto columnar_end;
20703   switch( p->cMode ){
20704     case MODE_Column: {
20705       colSep = "  ";
20706       rowSep = "\n";
20707       if( p->showHeader ){
20708         for(i=0; i<nColumn; i++){
20709           w = p->actualWidth[i];
20710           if( p->colWidth[i]<0 ) w = -w;
20711           utf8_width_print(w, azData[i]);
20712           fputs(i==nColumn-1?"\n":"  ", p->out);
20713         }
20714         for(i=0; i<nColumn; i++){
20715           print_dashes(p->actualWidth[i]);
20716           fputs(i==nColumn-1?"\n":"  ", p->out);
20717         }
20718       }
20719       break;
20720     }
20721     case MODE_Table: {
20722       colSep = " | ";
20723       rowSep = " |\n";
20724       print_row_separator(p, nColumn, "+");
20725       fputs("| ", p->out);
20726       for(i=0; i<nColumn; i++){
20727         w = p->actualWidth[i];
20728         n = strlenChar(azData[i]);
20729         oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
20730         oputz(i==nColumn-1?" |\n":" | ");
20731       }
20732       print_row_separator(p, nColumn, "+");
20733       break;
20734     }
20735     case MODE_Markdown: {
20736       colSep = " | ";
20737       rowSep = " |\n";
20738       fputs("| ", p->out);
20739       for(i=0; i<nColumn; i++){
20740         w = p->actualWidth[i];
20741         n = strlenChar(azData[i]);
20742         oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
20743         oputz(i==nColumn-1?" |\n":" | ");
20744       }
20745       print_row_separator(p, nColumn, "|");
20746       break;
20747     }
20748     case MODE_Box: {
20749       colSep = " " BOX_13 " ";
20750       rowSep = " " BOX_13 "\n";
20751       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
20752       oputz(BOX_13 " ");
20753       for(i=0; i<nColumn; i++){
20754         w = p->actualWidth[i];
20755         n = strlenChar(azData[i]);
20756         oputf("%*s%s%*s%s",
20757               (w-n)/2, "", azData[i], (w-n+1)/2, "",
20758               i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
20759       }
20760       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20761       break;
20762     }
20763   }
20764   for(i=nColumn, j=0; i<nTotal; i++, j++){
20765     if( j==0 && p->cMode!=MODE_Column ){
20766       oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
20767     }
20768     z = azData[i];
20769     if( z==0 ) z = p->nullValue;
20770     w = p->actualWidth[j];
20771     if( p->colWidth[j]<0 ) w = -w;
20772     utf8_width_print(w, z);
20773     if( j==nColumn-1 ){
20774       oputz(rowSep);
20775       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
20776         if( p->cMode==MODE_Table ){
20777           print_row_separator(p, nColumn, "+");
20778         }else if( p->cMode==MODE_Box ){
20779           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20780         }else if( p->cMode==MODE_Column ){
20781           oputz("\n");
20782         }
20783       }
20784       j = -1;
20785       if( seenInterrupt ) goto columnar_end;
20786     }else{
20787       oputz(colSep);
20788     }
20789   }
20790   if( p->cMode==MODE_Table ){
20791     print_row_separator(p, nColumn, "+");
20792   }else if( p->cMode==MODE_Box ){
20793     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
20794   }
20795 columnar_end:
20796   if( seenInterrupt ){
20797     oputz("Interrupt\n");
20798   }
20799   nData = (nRow+1)*nColumn;
20800   for(i=0; i<nData; i++){
20801     z = azData[i];
20802     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
20803   }
20804   sqlite3_free(azData);
20805   sqlite3_free((void*)azNextLine);
20806   sqlite3_free(abRowDiv);
20807   if( azQuoted ){
20808     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
20809     sqlite3_free(azQuoted);
20810   }
20811 }
20812 
20813 /*
20814 ** Run a prepared statement
20815 */
exec_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)20816 static void exec_prepared_stmt(
20817   ShellState *pArg,                                /* Pointer to ShellState */
20818   sqlite3_stmt *pStmt                              /* Statement to run */
20819 ){
20820   int rc;
20821   sqlite3_uint64 nRow = 0;
20822 
20823   if( pArg->cMode==MODE_Column
20824    || pArg->cMode==MODE_Table
20825    || pArg->cMode==MODE_Box
20826    || pArg->cMode==MODE_Markdown
20827   ){
20828     exec_prepared_stmt_columnar(pArg, pStmt);
20829     return;
20830   }
20831 
20832   /* perform the first step.  this will tell us if we
20833   ** have a result set or not and how wide it is.
20834   */
20835   rc = sqlite3_step(pStmt);
20836   /* if we have a result set... */
20837   if( SQLITE_ROW == rc ){
20838     /* allocate space for col name ptr, value ptr, and type */
20839     int nCol = sqlite3_column_count(pStmt);
20840     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
20841     if( !pData ){
20842       shell_out_of_memory();
20843     }else{
20844       char **azCols = (char **)pData;      /* Names of result columns */
20845       char **azVals = &azCols[nCol];       /* Results */
20846       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
20847       int i, x;
20848       assert(sizeof(int) <= sizeof(char *));
20849       /* save off ptrs to column names */
20850       for(i=0; i<nCol; i++){
20851         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
20852       }
20853       do{
20854         nRow++;
20855         /* extract the data and data types */
20856         for(i=0; i<nCol; i++){
20857           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
20858           if( x==SQLITE_BLOB
20859            && pArg
20860            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
20861           ){
20862             azVals[i] = "";
20863           }else{
20864             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
20865           }
20866           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
20867             rc = SQLITE_NOMEM;
20868             break; /* from for */
20869           }
20870         } /* end for */
20871 
20872         /* if data and types extracted successfully... */
20873         if( SQLITE_ROW == rc ){
20874           /* call the supplied callback with the result row data */
20875           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
20876             rc = SQLITE_ABORT;
20877           }else{
20878             rc = sqlite3_step(pStmt);
20879           }
20880         }
20881       } while( SQLITE_ROW == rc );
20882       sqlite3_free(pData);
20883       if( pArg->cMode==MODE_Json ){
20884         fputs("]\n", pArg->out);
20885       }else if( pArg->cMode==MODE_Count ){
20886         char zBuf[200];
20887         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
20888                          nRow, nRow!=1 ? "s" : "");
20889         printf("%s", zBuf);
20890       }
20891     }
20892   }
20893 }
20894 
20895 #ifndef SQLITE_OMIT_VIRTUALTABLE
20896 /*
20897 ** This function is called to process SQL if the previous shell command
20898 ** was ".expert". It passes the SQL in the second argument directly to
20899 ** the sqlite3expert object.
20900 **
20901 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20902 ** code. In this case, (*pzErr) may be set to point to a buffer containing
20903 ** an English language error message. It is the responsibility of the
20904 ** caller to eventually free this buffer using sqlite3_free().
20905 */
expertHandleSQL(ShellState * pState,const char * zSql,char ** pzErr)20906 static int expertHandleSQL(
20907   ShellState *pState,
20908   const char *zSql,
20909   char **pzErr
20910 ){
20911   assert( pState->expert.pExpert );
20912   assert( pzErr==0 || *pzErr==0 );
20913   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
20914 }
20915 
20916 /*
20917 ** This function is called either to silently clean up the object
20918 ** created by the ".expert" command (if bCancel==1), or to generate a
20919 ** report from it and then clean it up (if bCancel==0).
20920 **
20921 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20922 ** code. In this case, (*pzErr) may be set to point to a buffer containing
20923 ** an English language error message. It is the responsibility of the
20924 ** caller to eventually free this buffer using sqlite3_free().
20925 */
expertFinish(ShellState * pState,int bCancel,char ** pzErr)20926 static int expertFinish(
20927   ShellState *pState,
20928   int bCancel,
20929   char **pzErr
20930 ){
20931   int rc = SQLITE_OK;
20932   sqlite3expert *p = pState->expert.pExpert;
20933   assert( p );
20934   assert( bCancel || pzErr==0 || *pzErr==0 );
20935   if( bCancel==0 ){
20936     int bVerbose = pState->expert.bVerbose;
20937 
20938     rc = sqlite3_expert_analyze(p, pzErr);
20939     if( rc==SQLITE_OK ){
20940       int nQuery = sqlite3_expert_count(p);
20941       int i;
20942 
20943       if( bVerbose ){
20944         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
20945         oputz("-- Candidates -----------------------------\n");
20946         oputf("%s\n", zCand);
20947       }
20948       for(i=0; i<nQuery; i++){
20949         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
20950         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
20951         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
20952         if( zIdx==0 ) zIdx = "(no new indexes)\n";
20953         if( bVerbose ){
20954           oputf("-- Query %d --------------------------------\n",i+1);
20955           oputf("%s\n\n", zSql);
20956         }
20957         oputf("%s\n", zIdx);
20958         oputf("%s\n", zEQP);
20959       }
20960     }
20961   }
20962   sqlite3_expert_destroy(p);
20963   pState->expert.pExpert = 0;
20964   return rc;
20965 }
20966 
20967 /*
20968 ** Implementation of ".expert" dot command.
20969 */
expertDotCommand(ShellState * pState,char ** azArg,int nArg)20970 static int expertDotCommand(
20971   ShellState *pState,             /* Current shell tool state */
20972   char **azArg,                   /* Array of arguments passed to dot command */
20973   int nArg                        /* Number of entries in azArg[] */
20974 ){
20975   int rc = SQLITE_OK;
20976   char *zErr = 0;
20977   int i;
20978   int iSample = 0;
20979 
20980   assert( pState->expert.pExpert==0 );
20981   memset(&pState->expert, 0, sizeof(ExpertInfo));
20982 
20983   for(i=1; rc==SQLITE_OK && i<nArg; i++){
20984     char *z = azArg[i];
20985     int n;
20986     if( z[0]=='-' && z[1]=='-' ) z++;
20987     n = strlen30(z);
20988     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
20989       pState->expert.bVerbose = 1;
20990     }
20991     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
20992       if( i==(nArg-1) ){
20993         eputf("option requires an argument: %s\n", z);
20994         rc = SQLITE_ERROR;
20995       }else{
20996         iSample = (int)integerValue(azArg[++i]);
20997         if( iSample<0 || iSample>100 ){
20998           eputf("value out of range: %s\n", azArg[i]);
20999           rc = SQLITE_ERROR;
21000         }
21001       }
21002     }
21003     else{
21004       eputf("unknown option: %s\n", z);
21005       rc = SQLITE_ERROR;
21006     }
21007   }
21008 
21009   if( rc==SQLITE_OK ){
21010     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
21011     if( pState->expert.pExpert==0 ){
21012       eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
21013       rc = SQLITE_ERROR;
21014     }else{
21015       sqlite3_expert_config(
21016           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
21017       );
21018     }
21019   }
21020   sqlite3_free(zErr);
21021 
21022   return rc;
21023 }
21024 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
21025 
21026 /*
21027 ** Execute a statement or set of statements.  Print
21028 ** any result rows/columns depending on the current mode
21029 ** set via the supplied callback.
21030 **
21031 ** This is very similar to SQLite's built-in sqlite3_exec()
21032 ** function except it takes a slightly different callback
21033 ** and callback data argument.
21034 */
shell_exec(ShellState * pArg,const char * zSql,char ** pzErrMsg)21035 static int shell_exec(
21036   ShellState *pArg,                         /* Pointer to ShellState */
21037   const char *zSql,                         /* SQL to be evaluated */
21038   char **pzErrMsg                           /* Error msg written here */
21039 ){
21040   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
21041   int rc = SQLITE_OK;             /* Return Code */
21042   int rc2;
21043   const char *zLeftover;          /* Tail of unprocessed SQL */
21044   sqlite3 *db = pArg->db;
21045 
21046   if( pzErrMsg ){
21047     *pzErrMsg = NULL;
21048   }
21049 
21050 #ifndef SQLITE_OMIT_VIRTUALTABLE
21051   if( pArg->expert.pExpert ){
21052     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
21053     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
21054   }
21055 #endif
21056 
21057   while( zSql[0] && (SQLITE_OK == rc) ){
21058     static const char *zStmtSql;
21059     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
21060     if( SQLITE_OK != rc ){
21061       if( pzErrMsg ){
21062         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
21063       }
21064     }else{
21065       if( !pStmt ){
21066         /* this happens for a comment or white-space */
21067         zSql = zLeftover;
21068         while( IsSpace(zSql[0]) ) zSql++;
21069         continue;
21070       }
21071       zStmtSql = sqlite3_sql(pStmt);
21072       if( zStmtSql==0 ) zStmtSql = "";
21073       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
21074 
21075       /* save off the prepared statement handle and reset row count */
21076       if( pArg ){
21077         pArg->pStmt = pStmt;
21078         pArg->cnt = 0;
21079       }
21080 
21081       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
21082       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
21083         sqlite3_stmt *pExplain;
21084         int triggerEQP = 0;
21085         disable_debug_trace_modes();
21086         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
21087         if( pArg->autoEQP>=AUTOEQP_trigger ){
21088           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
21089         }
21090         pExplain = pStmt;
21091         sqlite3_reset(pExplain);
21092         rc = sqlite3_stmt_explain(pExplain, 2);
21093         if( rc==SQLITE_OK ){
21094           while( sqlite3_step(pExplain)==SQLITE_ROW ){
21095             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
21096             int iEqpId = sqlite3_column_int(pExplain, 0);
21097             int iParentId = sqlite3_column_int(pExplain, 1);
21098             if( zEQPLine==0 ) zEQPLine = "";
21099             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
21100             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
21101           }
21102           eqp_render(pArg, 0);
21103         }
21104         if( pArg->autoEQP>=AUTOEQP_full ){
21105           /* Also do an EXPLAIN for ".eqp full" mode */
21106           sqlite3_reset(pExplain);
21107           rc = sqlite3_stmt_explain(pExplain, 1);
21108           if( rc==SQLITE_OK ){
21109             pArg->cMode = MODE_Explain;
21110             assert( sqlite3_stmt_isexplain(pExplain)==1 );
21111             explain_data_prepare(pArg, pExplain);
21112             exec_prepared_stmt(pArg, pExplain);
21113             explain_data_delete(pArg);
21114           }
21115         }
21116         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
21117           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
21118         }
21119         sqlite3_reset(pStmt);
21120         sqlite3_stmt_explain(pStmt, 0);
21121         restore_debug_trace_modes();
21122       }
21123 
21124       if( pArg ){
21125         int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
21126         pArg->cMode = pArg->mode;
21127         if( pArg->autoExplain ){
21128           if( bIsExplain ){
21129             pArg->cMode = MODE_Explain;
21130           }
21131           if( sqlite3_stmt_isexplain(pStmt)==2 ){
21132             pArg->cMode = MODE_EQP;
21133           }
21134         }
21135 
21136         /* If the shell is currently in ".explain" mode, gather the extra
21137         ** data required to add indents to the output.*/
21138         if( pArg->cMode==MODE_Explain && bIsExplain ){
21139           explain_data_prepare(pArg, pStmt);
21140         }
21141       }
21142 
21143       bind_prepared_stmt(pArg, pStmt);
21144       exec_prepared_stmt(pArg, pStmt);
21145       explain_data_delete(pArg);
21146       eqp_render(pArg, 0);
21147 
21148       /* print usage stats if stats on */
21149       if( pArg && pArg->statsOn ){
21150         display_stats(db, pArg, 0);
21151       }
21152 
21153       /* print loop-counters if required */
21154       if( pArg && pArg->scanstatsOn ){
21155         display_scanstats(db, pArg);
21156       }
21157 
21158       /* Finalize the statement just executed. If this fails, save a
21159       ** copy of the error message. Otherwise, set zSql to point to the
21160       ** next statement to execute. */
21161       rc2 = sqlite3_finalize(pStmt);
21162       if( rc!=SQLITE_NOMEM ) rc = rc2;
21163       if( rc==SQLITE_OK ){
21164         zSql = zLeftover;
21165         while( IsSpace(zSql[0]) ) zSql++;
21166       }else if( pzErrMsg ){
21167         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
21168       }
21169 
21170       /* clear saved stmt handle */
21171       if( pArg ){
21172         pArg->pStmt = NULL;
21173       }
21174     }
21175   } /* end while */
21176 
21177   return rc;
21178 }
21179 
21180 /*
21181 ** Release memory previously allocated by tableColumnList().
21182 */
freeColumnList(char ** azCol)21183 static void freeColumnList(char **azCol){
21184   int i;
21185   for(i=1; azCol[i]; i++){
21186     sqlite3_free(azCol[i]);
21187   }
21188   /* azCol[0] is a static string */
21189   sqlite3_free(azCol);
21190 }
21191 
21192 /*
21193 ** Return a list of pointers to strings which are the names of all
21194 ** columns in table zTab.   The memory to hold the names is dynamically
21195 ** allocated and must be released by the caller using a subsequent call
21196 ** to freeColumnList().
21197 **
21198 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
21199 ** value that needs to be preserved, then azCol[0] is filled in with the
21200 ** name of the rowid column.
21201 **
21202 ** The first regular column in the table is azCol[1].  The list is terminated
21203 ** by an entry with azCol[i]==0.
21204 */
tableColumnList(ShellState * p,const char * zTab)21205 static char **tableColumnList(ShellState *p, const char *zTab){
21206   char **azCol = 0;
21207   sqlite3_stmt *pStmt;
21208   char *zSql;
21209   int nCol = 0;
21210   int nAlloc = 0;
21211   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
21212   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
21213   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
21214   int rc;
21215 
21216   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
21217   shell_check_oom(zSql);
21218   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
21219   sqlite3_free(zSql);
21220   if( rc ) return 0;
21221   while( sqlite3_step(pStmt)==SQLITE_ROW ){
21222     if( nCol>=nAlloc-2 ){
21223       nAlloc = nAlloc*2 + nCol + 10;
21224       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
21225       shell_check_oom(azCol);
21226     }
21227     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
21228     shell_check_oom(azCol[nCol]);
21229     if( sqlite3_column_int(pStmt, 5) ){
21230       nPK++;
21231       if( nPK==1
21232        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
21233                           "INTEGER")==0
21234       ){
21235         isIPK = 1;
21236       }else{
21237         isIPK = 0;
21238       }
21239     }
21240   }
21241   sqlite3_finalize(pStmt);
21242   if( azCol==0 ) return 0;
21243   azCol[0] = 0;
21244   azCol[nCol+1] = 0;
21245 
21246   /* The decision of whether or not a rowid really needs to be preserved
21247   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
21248   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
21249   ** rowids on tables where the rowid is inaccessible because there are other
21250   ** columns in the table named "rowid", "_rowid_", and "oid".
21251   */
21252   if( preserveRowid && isIPK ){
21253     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
21254     ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
21255     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
21256     ** ROWID aliases.  To distinguish these cases, check to see if
21257     ** there is a "pk" entry in "PRAGMA index_list".  There will be
21258     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
21259     */
21260     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
21261                            " WHERE origin='pk'", zTab);
21262     shell_check_oom(zSql);
21263     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
21264     sqlite3_free(zSql);
21265     if( rc ){
21266       freeColumnList(azCol);
21267       return 0;
21268     }
21269     rc = sqlite3_step(pStmt);
21270     sqlite3_finalize(pStmt);
21271     preserveRowid = rc==SQLITE_ROW;
21272   }
21273   if( preserveRowid ){
21274     /* Only preserve the rowid if we can find a name to use for the
21275     ** rowid */
21276     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
21277     int i, j;
21278     for(j=0; j<3; j++){
21279       for(i=1; i<=nCol; i++){
21280         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
21281       }
21282       if( i>nCol ){
21283         /* At this point, we know that azRowid[j] is not the name of any
21284         ** ordinary column in the table.  Verify that azRowid[j] is a valid
21285         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
21286         ** tables will fail this last check */
21287         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
21288         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
21289         break;
21290       }
21291     }
21292   }
21293   return azCol;
21294 }
21295 
21296 /*
21297 ** Toggle the reverse_unordered_selects setting.
21298 */
toggleSelectOrder(sqlite3 * db)21299 static void toggleSelectOrder(sqlite3 *db){
21300   sqlite3_stmt *pStmt = 0;
21301   int iSetting = 0;
21302   char zStmt[100];
21303   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
21304   if( sqlite3_step(pStmt)==SQLITE_ROW ){
21305     iSetting = sqlite3_column_int(pStmt, 0);
21306   }
21307   sqlite3_finalize(pStmt);
21308   sqlite3_snprintf(sizeof(zStmt), zStmt,
21309        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
21310   sqlite3_exec(db, zStmt, 0, 0, 0);
21311 }
21312 
21313 /*
21314 ** This is a different callback routine used for dumping the database.
21315 ** Each row received by this callback consists of a table name,
21316 ** the table type ("index" or "table") and SQL to create the table.
21317 ** This routine should print text sufficient to recreate the table.
21318 */
dump_callback(void * pArg,int nArg,char ** azArg,char ** azNotUsed)21319 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
21320   int rc;
21321   const char *zTable;
21322   const char *zType;
21323   const char *zSql;
21324   ShellState *p = (ShellState *)pArg;
21325   int dataOnly;
21326   int noSys;
21327 
21328   UNUSED_PARAMETER(azNotUsed);
21329   if( nArg!=3 || azArg==0 ) return 0;
21330   zTable = azArg[0];
21331   zType = azArg[1];
21332   zSql = azArg[2];
21333   if( zTable==0 ) return 0;
21334   if( zType==0 ) return 0;
21335   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
21336   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
21337 
21338   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
21339     if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
21340   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
21341     if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
21342   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
21343     return 0;
21344   }else if( dataOnly ){
21345     /* no-op */
21346   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
21347     char *zIns;
21348     if( !p->writableSchema ){
21349       oputz("PRAGMA writable_schema=ON;\n");
21350       p->writableSchema = 1;
21351     }
21352     zIns = sqlite3_mprintf(
21353        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
21354        "VALUES('table','%q','%q',0,'%q');",
21355        zTable, zTable, zSql);
21356     shell_check_oom(zIns);
21357     oputf("%s\n", zIns);
21358     sqlite3_free(zIns);
21359     return 0;
21360   }else{
21361     printSchemaLine(zSql, ";\n");
21362   }
21363 
21364   if( cli_strcmp(zType, "table")==0 ){
21365     ShellText sSelect;
21366     ShellText sTable;
21367     char **azCol;
21368     int i;
21369     char *savedDestTable;
21370     int savedMode;
21371 
21372     azCol = tableColumnList(p, zTable);
21373     if( azCol==0 ){
21374       p->nErr++;
21375       return 0;
21376     }
21377 
21378     /* Always quote the table name, even if it appears to be pure ascii,
21379     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
21380     initText(&sTable);
21381     appendText(&sTable, zTable, quoteChar(zTable));
21382     /* If preserving the rowid, add a column list after the table name.
21383     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
21384     ** instead of the usual "INSERT INTO tab VALUES(...)".
21385     */
21386     if( azCol[0] ){
21387       appendText(&sTable, "(", 0);
21388       appendText(&sTable, azCol[0], 0);
21389       for(i=1; azCol[i]; i++){
21390         appendText(&sTable, ",", 0);
21391         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
21392       }
21393       appendText(&sTable, ")", 0);
21394     }
21395 
21396     /* Build an appropriate SELECT statement */
21397     initText(&sSelect);
21398     appendText(&sSelect, "SELECT ", 0);
21399     if( azCol[0] ){
21400       appendText(&sSelect, azCol[0], 0);
21401       appendText(&sSelect, ",", 0);
21402     }
21403     for(i=1; azCol[i]; i++){
21404       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
21405       if( azCol[i+1] ){
21406         appendText(&sSelect, ",", 0);
21407       }
21408     }
21409     freeColumnList(azCol);
21410     appendText(&sSelect, " FROM ", 0);
21411     appendText(&sSelect, zTable, quoteChar(zTable));
21412 
21413     savedDestTable = p->zDestTable;
21414     savedMode = p->mode;
21415     p->zDestTable = sTable.z;
21416     p->mode = p->cMode = MODE_Insert;
21417     rc = shell_exec(p, sSelect.z, 0);
21418     if( (rc&0xff)==SQLITE_CORRUPT ){
21419       oputz("/****** CORRUPTION ERROR *******/\n");
21420       toggleSelectOrder(p->db);
21421       shell_exec(p, sSelect.z, 0);
21422       toggleSelectOrder(p->db);
21423     }
21424     p->zDestTable = savedDestTable;
21425     p->mode = savedMode;
21426     freeText(&sTable);
21427     freeText(&sSelect);
21428     if( rc ) p->nErr++;
21429   }
21430   return 0;
21431 }
21432 
21433 /*
21434 ** Run zQuery.  Use dump_callback() as the callback routine so that
21435 ** the contents of the query are output as SQL statements.
21436 **
21437 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
21438 ** "ORDER BY rowid DESC" to the end.
21439 */
run_schema_dump_query(ShellState * p,const char * zQuery)21440 static int run_schema_dump_query(
21441   ShellState *p,
21442   const char *zQuery
21443 ){
21444   int rc;
21445   char *zErr = 0;
21446   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
21447   if( rc==SQLITE_CORRUPT ){
21448     char *zQ2;
21449     int len = strlen30(zQuery);
21450     oputz("/****** CORRUPTION ERROR *******/\n");
21451     if( zErr ){
21452       oputf("/****** %s ******/\n", zErr);
21453       sqlite3_free(zErr);
21454       zErr = 0;
21455     }
21456     zQ2 = malloc( len+100 );
21457     if( zQ2==0 ) return rc;
21458     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
21459     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
21460     if( rc ){
21461       oputf("/****** ERROR: %s ******/\n", zErr);
21462     }else{
21463       rc = SQLITE_CORRUPT;
21464     }
21465     sqlite3_free(zErr);
21466     free(zQ2);
21467   }
21468   return rc;
21469 }
21470 
21471 /*
21472 ** Text of help messages.
21473 **
21474 ** The help text for each individual command begins with a line that starts
21475 ** with ".".  Subsequent lines are supplemental information.
21476 **
21477 ** There must be two or more spaces between the end of the command and the
21478 ** start of the description of what that command does.
21479 */
21480 static const char *(azHelp[]) = {
21481 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
21482   && !defined(SQLITE_SHELL_FIDDLE)
21483   ".archive ...             Manage SQL archives",
21484   "   Each command must have exactly one of the following options:",
21485   "     -c, --create               Create a new archive",
21486   "     -u, --update               Add or update files with changed mtime",
21487   "     -i, --insert               Like -u but always add even if unchanged",
21488   "     -r, --remove               Remove files from archive",
21489   "     -t, --list                 List contents of archive",
21490   "     -x, --extract              Extract files from archive",
21491   "   Optional arguments:",
21492   "     -v, --verbose              Print each filename as it is processed",
21493   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
21494   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
21495   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
21496   "     -g, --glob                 Use glob matching for names in archive",
21497   "     -n, --dryrun               Show the SQL that would have occurred",
21498   "   Examples:",
21499   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
21500   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
21501   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
21502   "   See also:",
21503   "      http://sqlite.org/cli.html#sqlite_archive_support",
21504 #endif
21505 #ifndef SQLITE_OMIT_AUTHORIZATION
21506   ".auth ON|OFF             Show authorizer callbacks",
21507 #endif
21508 #ifndef SQLITE_SHELL_FIDDLE
21509   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
21510   "   Options:",
21511   "       --append            Use the appendvfs",
21512   "       --async             Write to FILE without journal and fsync()",
21513 #endif
21514   ".bail on|off             Stop after hitting an error.  Default OFF",
21515 #ifndef SQLITE_SHELL_FIDDLE
21516   ".cd DIRECTORY            Change the working directory to DIRECTORY",
21517 #endif
21518   ".changes on|off          Show number of rows changed by SQL",
21519 #ifndef SQLITE_SHELL_FIDDLE
21520   ".check GLOB              Fail if output since .testcase does not match",
21521   ".clone NEWDB             Clone data into NEWDB from the existing database",
21522 #endif
21523   ".connection [close] [#]  Open or close an auxiliary database connection",
21524 #if defined(_WIN32) || defined(WIN32)
21525   ".crnl on|off             Translate \\n to \\r\\n.  Default ON",
21526 #endif
21527   ".databases               List names and files of attached databases",
21528   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
21529 #if SQLITE_SHELL_HAVE_RECOVER
21530   ".dbinfo ?DB?             Show status information about the database",
21531 #endif
21532   ".dump ?OBJECTS?          Render database content as SQL",
21533   "   Options:",
21534   "     --data-only            Output only INSERT statements",
21535   "     --newlines             Allow unescaped newline characters in output",
21536   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
21537   "     --preserve-rowids      Include ROWID values in the output",
21538   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
21539   "   Additional LIKE patterns can be given in subsequent arguments",
21540   ".echo on|off             Turn command echo on or off",
21541   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
21542   "   Other Modes:",
21543 #ifdef SQLITE_DEBUG
21544   "      test                  Show raw EXPLAIN QUERY PLAN output",
21545   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
21546 #endif
21547   "      trigger               Like \"full\" but also show trigger bytecode",
21548 #ifndef SQLITE_SHELL_FIDDLE
21549   ".excel                   Display the output of next command in spreadsheet",
21550   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
21551 #endif
21552 #ifndef SQLITE_SHELL_FIDDLE
21553   ".exit ?CODE?             Exit this program with return-code CODE",
21554 #endif
21555   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
21556   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
21557   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
21558   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
21559   "   --help                  Show CMD details",
21560   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
21561   ".headers on|off          Turn display of headers on or off",
21562   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
21563 #ifndef SQLITE_SHELL_FIDDLE
21564   ".import FILE TABLE       Import data from FILE into TABLE",
21565   "   Options:",
21566   "     --ascii               Use \\037 and \\036 as column and row separators",
21567   "     --csv                 Use , and \\n as column and row separators",
21568   "     --skip N              Skip the first N rows of input",
21569   "     --schema S            Target table to be S.TABLE",
21570   "     -v                    \"Verbose\" - increase auxiliary output",
21571   "   Notes:",
21572   "     *  If TABLE does not exist, it is created.  The first row of input",
21573   "        determines the column names.",
21574   "     *  If neither --csv or --ascii are used, the input mode is derived",
21575   "        from the \".mode\" output mode",
21576   "     *  If FILE begins with \"|\" then it is a command that generates the",
21577   "        input text.",
21578 #endif
21579 #ifndef SQLITE_OMIT_TEST_CONTROL
21580   ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
21581 #endif
21582   ".indexes ?TABLE?         Show names of indexes",
21583   "                           If TABLE is specified, only show indexes for",
21584   "                           tables matching TABLE using the LIKE operator.",
21585 #ifdef SQLITE_ENABLE_IOTRACE
21586   ",iotrace FILE            Enable I/O diagnostic logging to FILE",
21587 #endif
21588   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
21589   ".lint OPTIONS            Report potential schema issues.",
21590   "     Options:",
21591   "        fkey-indexes     Find missing foreign key indexes",
21592 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
21593   ".load FILE ?ENTRY?       Load an extension library",
21594 #endif
21595 #if !defined(SQLITE_SHELL_FIDDLE)
21596   ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
21597 #else
21598   ".log on|off              Turn logging on or off.",
21599 #endif
21600   ".mode MODE ?OPTIONS?     Set output mode",
21601   "   MODE is one of:",
21602   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
21603   "     box         Tables using unicode box-drawing characters",
21604   "     csv         Comma-separated values",
21605   "     column      Output in columns.  (See .width)",
21606   "     html        HTML <table> code",
21607   "     insert      SQL insert statements for TABLE",
21608   "     json        Results in a JSON array",
21609   "     line        One value per line",
21610   "     list        Values delimited by \"|\"",
21611   "     markdown    Markdown table format",
21612   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
21613   "     quote       Escape answers as for SQL",
21614   "     table       ASCII-art table",
21615   "     tabs        Tab-separated values",
21616   "     tcl         TCL list elements",
21617   "   OPTIONS: (for columnar modes or insert mode):",
21618   "     --wrap N       Wrap output lines to no longer than N characters",
21619   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
21620   "     --ww           Shorthand for \"--wordwrap 1\"",
21621   "     --quote        Quote output text as SQL literals",
21622   "     --noquote      Do not quote output text",
21623   "     TABLE          The name of SQL table used for \"insert\" mode",
21624 #ifndef SQLITE_SHELL_FIDDLE
21625   ".nonce STRING            Suspend safe mode for one command if nonce matches",
21626 #endif
21627   ".nullvalue STRING        Use STRING in place of NULL values",
21628 #ifndef SQLITE_SHELL_FIDDLE
21629   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
21630   "     If FILE begins with '|' then open as a pipe",
21631   "       --bom  Put a UTF8 byte-order mark at the beginning",
21632   "       -e     Send output to the system text editor",
21633   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
21634   /* Note that .open is (partially) available in WASM builds but is
21635   ** currently only intended to be used by the fiddle tool, not
21636   ** end users, so is "undocumented." */
21637   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
21638   "     Options:",
21639   "        --append        Use appendvfs to append database to the end of FILE",
21640 #endif
21641 #ifndef SQLITE_OMIT_DESERIALIZE
21642   "        --deserialize   Load into memory using sqlite3_deserialize()",
21643   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
21644   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
21645 #endif
21646   "        --new           Initialize FILE to an empty database",
21647   "        --nofollow      Do not follow symbolic links",
21648   "        --readonly      Open FILE readonly",
21649   "        --zip           FILE is a ZIP archive",
21650 #ifndef SQLITE_SHELL_FIDDLE
21651   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
21652   "   If FILE begins with '|' then open it as a pipe.",
21653   "   Options:",
21654   "     --bom                 Prefix output with a UTF8 byte-order mark",
21655   "     -e                    Send output to the system text editor",
21656   "     -x                    Send output as CSV to a spreadsheet",
21657 #endif
21658   ".parameter CMD ...       Manage SQL parameter bindings",
21659   "   clear                   Erase all bindings",
21660   "   init                    Initialize the TEMP table that holds bindings",
21661   "   list                    List the current parameter bindings",
21662   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
21663   "                           PARAMETER should start with one of: $ : @ ?",
21664   "   unset PARAMETER         Remove PARAMETER from the binding table",
21665   ".print STRING...         Print literal STRING",
21666 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
21667   ".progress N              Invoke progress handler after every N opcodes",
21668   "   --limit N                 Interrupt after N progress callbacks",
21669   "   --once                    Do no more than one progress interrupt",
21670   "   --quiet|-q                No output except at interrupts",
21671   "   --reset                   Reset the count for each input and interrupt",
21672 #endif
21673   ".prompt MAIN CONTINUE    Replace the standard prompts",
21674 #ifndef SQLITE_SHELL_FIDDLE
21675   ".quit                    Stop interpreting input stream, exit if primary.",
21676   ".read FILE               Read input from FILE or command output",
21677   "    If FILE begins with \"|\", it is a command that generates the input.",
21678 #endif
21679 #if SQLITE_SHELL_HAVE_RECOVER
21680   ".recover                 Recover as much data as possible from corrupt db.",
21681   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
21682   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
21683   "   --no-rowids              Do not attempt to recover rowid values",
21684   "                            that are not also INTEGER PRIMARY KEYs",
21685 #endif
21686 #ifndef SQLITE_SHELL_FIDDLE
21687   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
21688   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
21689 #endif
21690   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
21691   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
21692   "   Options:",
21693   "      --indent             Try to pretty-print the schema",
21694   "      --nosys              Omit objects whose names start with \"sqlite_\"",
21695   ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
21696   "    Options:",
21697   "       --init               Create a new SELFTEST table",
21698   "       -v                   Verbose output",
21699   ".separator COL ?ROW?     Change the column and row separators",
21700 #if defined(SQLITE_ENABLE_SESSION)
21701   ".session ?NAME? CMD ...  Create or control sessions",
21702   "   Subcommands:",
21703   "     attach TABLE             Attach TABLE",
21704   "     changeset FILE           Write a changeset into FILE",
21705   "     close                    Close one session",
21706   "     enable ?BOOLEAN?         Set or query the enable bit",
21707   "     filter GLOB...           Reject tables matching GLOBs",
21708   "     indirect ?BOOLEAN?       Mark or query the indirect status",
21709   "     isempty                  Query whether the session is empty",
21710   "     list                     List currently open session names",
21711   "     open DB NAME             Open a new session on DB",
21712   "     patchset FILE            Write a patchset into FILE",
21713   "   If ?NAME? is omitted, the first defined session is used.",
21714 #endif
21715   ".sha3sum ...             Compute a SHA3 hash of database content",
21716   "    Options:",
21717   "      --schema              Also hash the sqlite_schema table",
21718   "      --sha3-224            Use the sha3-224 algorithm",
21719   "      --sha3-256            Use the sha3-256 algorithm (default)",
21720   "      --sha3-384            Use the sha3-384 algorithm",
21721   "      --sha3-512            Use the sha3-512 algorithm",
21722   "    Any other argument is a LIKE pattern for tables to hash",
21723 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
21724   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
21725 #endif
21726   ".show                    Show the current values for various settings",
21727   ".stats ?ARG?             Show stats or turn stats on or off",
21728   "   off                      Turn off automatic stat display",
21729   "   on                       Turn on automatic stat display",
21730   "   stmt                     Show statement stats",
21731   "   vmstep                   Show the virtual machine step count only",
21732 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
21733   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
21734 #endif
21735   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
21736 #ifndef SQLITE_SHELL_FIDDLE
21737   ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
21738 #endif
21739   ",testctrl CMD ...        Run various sqlite3_test_control() operations",
21740   "                           Run \".testctrl\" with no arguments for details",
21741   ".timeout MS              Try opening locked tables for MS milliseconds",
21742   ".timer on|off            Turn SQL timer on or off",
21743 #ifndef SQLITE_OMIT_TRACE
21744   ".trace ?OPTIONS?         Output each SQL statement as it is run",
21745   "    FILE                    Send output to FILE",
21746   "    stdout                  Send output to stdout",
21747   "    stderr                  Send output to stderr",
21748   "    off                     Disable tracing",
21749   "    --expanded              Expand query parameters",
21750 #ifdef SQLITE_ENABLE_NORMALIZE
21751   "    --normalized            Normal the SQL statements",
21752 #endif
21753   "    --plain                 Show SQL as it is input",
21754   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
21755   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
21756   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
21757   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
21758 #endif /* SQLITE_OMIT_TRACE */
21759 #ifdef SQLITE_DEBUG
21760   ".unmodule NAME ...       Unregister virtual table modules",
21761   "    --allexcept             Unregister everything except those named",
21762 #endif
21763   ".version                 Show source, library and compiler versions",
21764   ".vfsinfo ?AUX?           Information about the top-level VFS",
21765   ".vfslist                 List all available VFSes",
21766   ".vfsname ?AUX?           Print the name of the VFS stack",
21767   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
21768   "     Negative values right-justify",
21769 };
21770 
21771 /*
21772 ** Output help text.
21773 **
21774 ** zPattern describes the set of commands for which help text is provided.
21775 ** If zPattern is NULL, then show all commands, but only give a one-line
21776 ** description of each.
21777 **
21778 ** Return the number of matches.
21779 */
showHelp(FILE * out,const char * zPattern)21780 static int showHelp(FILE *out, const char *zPattern){
21781   int i = 0;
21782   int j = 0;
21783   int n = 0;
21784   char *zPat;
21785   if( zPattern==0
21786    || zPattern[0]=='0'
21787    || cli_strcmp(zPattern,"-a")==0
21788    || cli_strcmp(zPattern,"-all")==0
21789    || cli_strcmp(zPattern,"--all")==0
21790   ){
21791     enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
21792     enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
21793     /* Show all or most commands
21794     ** *zPattern==0   => summary of documented commands only
21795     ** *zPattern=='0' => whole help for undocumented commands
21796     ** Otherwise      => whole help for documented commands
21797     */
21798     enum HelpWanted hw = HW_SummaryOnly;
21799     enum HelpHave hh = HH_More;
21800     if( zPattern!=0 ){
21801       hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
21802     }
21803     for(i=0; i<ArraySize(azHelp); i++){
21804       switch( azHelp[i][0] ){
21805       case ',':
21806         hh = HH_Summary|HH_Undoc;
21807         break;
21808       case '.':
21809         hh = HH_Summary;
21810         break;
21811       default:
21812         hh &= ~HH_Summary;
21813         break;
21814       }
21815       if( ((hw^hh)&HH_Undoc)==0 ){
21816         if( (hh&HH_Summary)!=0 ){
21817           sputf(out, ".%s\n", azHelp[i]+1);
21818           ++n;
21819         }else if( (hw&HW_SummaryOnly)==0 ){
21820           sputf(out, "%s\n", azHelp[i]);
21821         }
21822       }
21823     }
21824   }else{
21825     /* Seek documented commands for which zPattern is an exact prefix */
21826     zPat = sqlite3_mprintf(".%s*", zPattern);
21827     shell_check_oom(zPat);
21828     for(i=0; i<ArraySize(azHelp); i++){
21829       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
21830         sputf(out, "%s\n", azHelp[i]);
21831         j = i+1;
21832         n++;
21833       }
21834     }
21835     sqlite3_free(zPat);
21836     if( n ){
21837       if( n==1 ){
21838         /* when zPattern is a prefix of exactly one command, then include
21839         ** the details of that command, which should begin at offset j */
21840         while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
21841           sputf(out, "%s\n", azHelp[j]);
21842           j++;
21843         }
21844       }
21845       return n;
21846     }
21847     /* Look for documented commands that contain zPattern anywhere.
21848     ** Show complete text of all documented commands that match. */
21849     zPat = sqlite3_mprintf("%%%s%%", zPattern);
21850     shell_check_oom(zPat);
21851     for(i=0; i<ArraySize(azHelp); i++){
21852       if( azHelp[i][0]==',' ){
21853         while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
21854         continue;
21855       }
21856       if( azHelp[i][0]=='.' ) j = i;
21857       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
21858         sputf(out, "%s\n", azHelp[j]);
21859         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
21860           j++;
21861           sputf(out, "%s\n", azHelp[j]);
21862         }
21863         i = j;
21864         n++;
21865       }
21866     }
21867     sqlite3_free(zPat);
21868   }
21869   return n;
21870 }
21871 
21872 /* Forward reference */
21873 static int process_input(ShellState *p);
21874 
21875 /*
21876 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
21877 ** and return a pointer to the buffer. The caller is responsible for freeing
21878 ** the memory.
21879 **
21880 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
21881 ** read.
21882 **
21883 ** For convenience, a nul-terminator byte is always appended to the data read
21884 ** from the file before the buffer is returned. This byte is not included in
21885 ** the final value of (*pnByte), if applicable.
21886 **
21887 ** NULL is returned if any error is encountered. The final value of *pnByte
21888 ** is undefined in this case.
21889 */
readFile(const char * zName,int * pnByte)21890 static char *readFile(const char *zName, int *pnByte){
21891   FILE *in = fopen(zName, "rb");
21892   long nIn;
21893   size_t nRead;
21894   char *pBuf;
21895   int rc;
21896   if( in==0 ) return 0;
21897   rc = fseek(in, 0, SEEK_END);
21898   if( rc!=0 ){
21899     eputf("Error: '%s' not seekable\n", zName);
21900     fclose(in);
21901     return 0;
21902   }
21903   nIn = ftell(in);
21904   rewind(in);
21905   pBuf = sqlite3_malloc64( nIn+1 );
21906   if( pBuf==0 ){
21907     eputz("Error: out of memory\n");
21908     fclose(in);
21909     return 0;
21910   }
21911   nRead = fread(pBuf, nIn, 1, in);
21912   fclose(in);
21913   if( nRead!=1 ){
21914     sqlite3_free(pBuf);
21915     eputf("Error: cannot read '%s'\n", zName);
21916     return 0;
21917   }
21918   pBuf[nIn] = 0;
21919   if( pnByte ) *pnByte = nIn;
21920   return pBuf;
21921 }
21922 
21923 #if defined(SQLITE_ENABLE_SESSION)
21924 /*
21925 ** Close a single OpenSession object and release all of its associated
21926 ** resources.
21927 */
session_close(OpenSession * pSession)21928 static void session_close(OpenSession *pSession){
21929   int i;
21930   sqlite3session_delete(pSession->p);
21931   sqlite3_free(pSession->zName);
21932   for(i=0; i<pSession->nFilter; i++){
21933     sqlite3_free(pSession->azFilter[i]);
21934   }
21935   sqlite3_free(pSession->azFilter);
21936   memset(pSession, 0, sizeof(OpenSession));
21937 }
21938 #endif
21939 
21940 /*
21941 ** Close all OpenSession objects and release all associated resources.
21942 */
21943 #if defined(SQLITE_ENABLE_SESSION)
session_close_all(ShellState * p,int i)21944 static void session_close_all(ShellState *p, int i){
21945   int j;
21946   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
21947   for(j=0; j<pAuxDb->nSession; j++){
21948     session_close(&pAuxDb->aSession[j]);
21949   }
21950   pAuxDb->nSession = 0;
21951 }
21952 #else
21953 # define session_close_all(X,Y)
21954 #endif
21955 
21956 /*
21957 ** Implementation of the xFilter function for an open session.  Omit
21958 ** any tables named by ".session filter" but let all other table through.
21959 */
21960 #if defined(SQLITE_ENABLE_SESSION)
session_filter(void * pCtx,const char * zTab)21961 static int session_filter(void *pCtx, const char *zTab){
21962   OpenSession *pSession = (OpenSession*)pCtx;
21963   int i;
21964   for(i=0; i<pSession->nFilter; i++){
21965     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
21966   }
21967   return 1;
21968 }
21969 #endif
21970 
21971 /*
21972 ** Try to deduce the type of file for zName based on its content.  Return
21973 ** one of the SHELL_OPEN_* constants.
21974 **
21975 ** If the file does not exist or is empty but its name looks like a ZIP
21976 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
21977 ** Otherwise, assume an ordinary database regardless of the filename if
21978 ** the type cannot be determined from content.
21979 */
deduceDatabaseType(const char * zName,int dfltZip)21980 int deduceDatabaseType(const char *zName, int dfltZip){
21981   FILE *f = fopen(zName, "rb");
21982   size_t n;
21983   int rc = SHELL_OPEN_UNSPEC;
21984   char zBuf[100];
21985   if( f==0 ){
21986     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
21987        return SHELL_OPEN_ZIPFILE;
21988     }else{
21989        return SHELL_OPEN_NORMAL;
21990     }
21991   }
21992   n = fread(zBuf, 16, 1, f);
21993   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
21994     fclose(f);
21995     return SHELL_OPEN_NORMAL;
21996   }
21997   fseek(f, -25, SEEK_END);
21998   n = fread(zBuf, 25, 1, f);
21999   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
22000     rc = SHELL_OPEN_APPENDVFS;
22001   }else{
22002     fseek(f, -22, SEEK_END);
22003     n = fread(zBuf, 22, 1, f);
22004     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
22005        && zBuf[3]==0x06 ){
22006       rc = SHELL_OPEN_ZIPFILE;
22007     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
22008       rc = SHELL_OPEN_ZIPFILE;
22009     }
22010   }
22011   fclose(f);
22012   return rc;
22013 }
22014 
22015 #ifndef SQLITE_OMIT_DESERIALIZE
22016 /*
22017 ** Reconstruct an in-memory database using the output from the "dbtotxt"
22018 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
22019 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
22020 */
readHexDb(ShellState * p,int * pnData)22021 static unsigned char *readHexDb(ShellState *p, int *pnData){
22022   unsigned char *a = 0;
22023   int nLine;
22024   int n = 0;
22025   int pgsz = 0;
22026   int iOffset = 0;
22027   int j, k;
22028   int rc;
22029   FILE *in;
22030   const char *zDbFilename = p->pAuxDb->zDbFilename;
22031   unsigned int x[16];
22032   char zLine[1000];
22033   if( zDbFilename ){
22034     in = fopen(zDbFilename, "r");
22035     if( in==0 ){
22036       eputf("cannot open \"%s\" for reading\n", zDbFilename);
22037       return 0;
22038     }
22039     nLine = 0;
22040   }else{
22041     in = p->in;
22042     nLine = p->lineno;
22043     if( in==0 ) in = stdin;
22044   }
22045   *pnData = 0;
22046   nLine++;
22047   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
22048   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
22049   if( rc!=2 ) goto readHexDb_error;
22050   if( n<0 ) goto readHexDb_error;
22051   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
22052   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
22053   a = sqlite3_malloc( n ? n : 1 );
22054   shell_check_oom(a);
22055   memset(a, 0, n);
22056   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
22057     eputz("invalid pagesize\n");
22058     goto readHexDb_error;
22059   }
22060   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
22061     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
22062     if( rc==2 ){
22063       iOffset = k;
22064       continue;
22065     }
22066     if( cli_strncmp(zLine, "| end ", 6)==0 ){
22067       break;
22068     }
22069     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
22070                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
22071                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
22072     if( rc==17 ){
22073       k = iOffset+j;
22074       if( k+16<=n && k>=0 ){
22075         int ii;
22076         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
22077       }
22078     }
22079   }
22080   *pnData = n;
22081   if( in!=p->in ){
22082     fclose(in);
22083   }else{
22084     p->lineno = nLine;
22085   }
22086   return a;
22087 
22088 readHexDb_error:
22089   if( in!=p->in ){
22090     fclose(in);
22091   }else{
22092     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
22093       nLine++;
22094       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
22095     }
22096     p->lineno = nLine;
22097   }
22098   sqlite3_free(a);
22099   eputf("Error on line %d of --hexdb input\n", nLine);
22100   return 0;
22101 }
22102 #endif /* SQLITE_OMIT_DESERIALIZE */
22103 
22104 /*
22105 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
22106 */
shellUSleepFunc(sqlite3_context * context,int argcUnused,sqlite3_value ** argv)22107 static void shellUSleepFunc(
22108   sqlite3_context *context,
22109   int argcUnused,
22110   sqlite3_value **argv
22111 ){
22112   int sleep = sqlite3_value_int(argv[0]);
22113   (void)argcUnused;
22114   sqlite3_sleep(sleep/1000);
22115   sqlite3_result_int(context, sleep);
22116 }
22117 
22118 /* Flags for open_db().
22119 **
22120 ** The default behavior of open_db() is to exit(1) if the database fails to
22121 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
22122 ** but still returns without calling exit.
22123 **
22124 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
22125 ** ZIP archive if the file does not exist or is empty and its name matches
22126 ** the *.zip pattern.
22127 */
22128 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
22129 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
22130 
22131 /*
22132 ** Make sure the database is open.  If it is not, then open it.  If
22133 ** the database fails to open, print an error message and exit.
22134 */
open_db(ShellState * p,int openFlags)22135 static void open_db(ShellState *p, int openFlags){
22136   if( p->db==0 ){
22137     const char *zDbFilename = p->pAuxDb->zDbFilename;
22138     if( p->openMode==SHELL_OPEN_UNSPEC ){
22139       if( zDbFilename==0 || zDbFilename[0]==0 ){
22140         p->openMode = SHELL_OPEN_NORMAL;
22141       }else{
22142         p->openMode = (u8)deduceDatabaseType(zDbFilename,
22143                              (openFlags & OPEN_DB_ZIPFILE)!=0);
22144       }
22145     }
22146     switch( p->openMode ){
22147       case SHELL_OPEN_APPENDVFS: {
22148         sqlite3_open_v2(zDbFilename, &p->db,
22149            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
22150         break;
22151       }
22152       case SHELL_OPEN_HEXDB:
22153       case SHELL_OPEN_DESERIALIZE: {
22154         sqlite3_open(0, &p->db);
22155         break;
22156       }
22157       case SHELL_OPEN_ZIPFILE: {
22158         sqlite3_open(":memory:", &p->db);
22159         break;
22160       }
22161       case SHELL_OPEN_READONLY: {
22162         sqlite3_open_v2(zDbFilename, &p->db,
22163             SQLITE_OPEN_READONLY|p->openFlags, 0);
22164         break;
22165       }
22166       case SHELL_OPEN_UNSPEC:
22167       case SHELL_OPEN_NORMAL: {
22168         sqlite3_open_v2(zDbFilename, &p->db,
22169            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
22170         break;
22171       }
22172     }
22173     globalDb = p->db;
22174     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22175       eputf("Error: unable to open database \"%s\": %s\n",
22176             zDbFilename, sqlite3_errmsg(p->db));
22177       if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
22178         exit(1);
22179       }
22180       sqlite3_close(p->db);
22181       sqlite3_open(":memory:", &p->db);
22182       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22183         eputz("Also: unable to open substitute in-memory database.\n");
22184         exit(1);
22185       }else{
22186         eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
22187               zDbFilename);
22188       }
22189     }
22190     sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
22191 
22192     /* Reflect the use or absence of --unsafe-testing invocation. */
22193     {
22194       int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
22195       sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
22196       sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
22197     }
22198 
22199 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22200     sqlite3_enable_load_extension(p->db, 1);
22201 #endif
22202     sqlite3_shathree_init(p->db, 0, 0);
22203     sqlite3_uint_init(p->db, 0, 0);
22204     sqlite3_decimal_init(p->db, 0, 0);
22205     sqlite3_base64_init(p->db, 0, 0);
22206     sqlite3_base85_init(p->db, 0, 0);
22207     sqlite3_regexp_init(p->db, 0, 0);
22208     sqlite3_ieee_init(p->db, 0, 0);
22209     sqlite3_series_init(p->db, 0, 0);
22210 #ifndef SQLITE_SHELL_FIDDLE
22211     sqlite3_fileio_init(p->db, 0, 0);
22212     sqlite3_completion_init(p->db, 0, 0);
22213 #endif
22214 #ifdef SQLITE_HAVE_ZLIB
22215     if( !p->bSafeModePersist ){
22216       sqlite3_zipfile_init(p->db, 0, 0);
22217       sqlite3_sqlar_init(p->db, 0, 0);
22218     }
22219 #endif
22220 #ifdef SQLITE_SHELL_EXTFUNCS
22221     /* Create a preprocessing mechanism for extensions to make
22222      * their own provisions for being built into the shell.
22223      * This is a short-span macro. See further below for usage.
22224      */
22225 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
22226 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
22227     /* Let custom-included extensions get their ..._init() called.
22228      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
22229      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
22230      * initialization routine to be called.
22231      */
22232     {
22233       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
22234     /* Let custom-included extensions expose their functionality.
22235      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
22236      * the SQL functions, virtual tables, collating sequences or
22237      * VFS's implemented by the extension to be registered.
22238      */
22239       if( irc==SQLITE_OK
22240           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
22241         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
22242       }
22243 #undef SHELL_SUB_MACRO
22244 #undef SHELL_SUBMACRO
22245     }
22246 #endif
22247 
22248     sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
22249                             shellStrtod, 0, 0);
22250     sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
22251                             shellDtostr, 0, 0);
22252     sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
22253                             shellDtostr, 0, 0);
22254     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
22255                             shellAddSchemaName, 0, 0);
22256     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
22257                             shellModuleSchema, 0, 0);
22258     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
22259                             shellPutsFunc, 0, 0);
22260     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
22261                             shellUSleepFunc, 0, 0);
22262 #ifndef SQLITE_NOHAVE_SYSTEM
22263     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
22264                             editFunc, 0, 0);
22265     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
22266                             editFunc, 0, 0);
22267 #endif
22268 
22269     if( p->openMode==SHELL_OPEN_ZIPFILE ){
22270       char *zSql = sqlite3_mprintf(
22271          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
22272       shell_check_oom(zSql);
22273       sqlite3_exec(p->db, zSql, 0, 0, 0);
22274       sqlite3_free(zSql);
22275     }
22276 #ifndef SQLITE_OMIT_DESERIALIZE
22277     else
22278     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
22279       int rc;
22280       int nData = 0;
22281       unsigned char *aData;
22282       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
22283         aData = (unsigned char*)readFile(zDbFilename, &nData);
22284       }else{
22285         aData = readHexDb(p, &nData);
22286       }
22287       if( aData==0 ){
22288         return;
22289       }
22290       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
22291                    SQLITE_DESERIALIZE_RESIZEABLE |
22292                    SQLITE_DESERIALIZE_FREEONCLOSE);
22293       if( rc ){
22294         eputf("Error: sqlite3_deserialize() returns %d\n", rc);
22295       }
22296       if( p->szMax>0 ){
22297         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
22298       }
22299     }
22300 #endif
22301   }
22302   if( p->db!=0 ){
22303     if( p->bSafeModePersist ){
22304       sqlite3_set_authorizer(p->db, safeModeAuth, p);
22305     }
22306     sqlite3_db_config(
22307         p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
22308     );
22309   }
22310 }
22311 
22312 /*
22313 ** Attempt to close the database connection.  Report errors.
22314 */
close_db(sqlite3 * db)22315 void close_db(sqlite3 *db){
22316   int rc = sqlite3_close(db);
22317   if( rc ){
22318     eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
22319   }
22320 }
22321 
22322 #if HAVE_READLINE || HAVE_EDITLINE
22323 /*
22324 ** Readline completion callbacks
22325 */
readline_completion_generator(const char * text,int state)22326 static char *readline_completion_generator(const char *text, int state){
22327   static sqlite3_stmt *pStmt = 0;
22328   char *zRet;
22329   if( state==0 ){
22330     char *zSql;
22331     sqlite3_finalize(pStmt);
22332     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
22333                            "  FROM completion(%Q) ORDER BY 1", text);
22334     shell_check_oom(zSql);
22335     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
22336     sqlite3_free(zSql);
22337   }
22338   if( sqlite3_step(pStmt)==SQLITE_ROW ){
22339     const char *z = (const char*)sqlite3_column_text(pStmt,0);
22340     zRet = z ? strdup(z) : 0;
22341   }else{
22342     sqlite3_finalize(pStmt);
22343     pStmt = 0;
22344     zRet = 0;
22345   }
22346   return zRet;
22347 }
readline_completion(const char * zText,int iStart,int iEnd)22348 static char **readline_completion(const char *zText, int iStart, int iEnd){
22349   (void)iStart;
22350   (void)iEnd;
22351   rl_attempted_completion_over = 1;
22352   return rl_completion_matches(zText, readline_completion_generator);
22353 }
22354 
22355 #elif HAVE_LINENOISE
22356 /*
22357 ** Linenoise completion callback
22358 */
linenoise_completion(const char * zLine,linenoiseCompletions * lc)22359 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
22360   i64 nLine = strlen(zLine);
22361   i64 i, iStart;
22362   sqlite3_stmt *pStmt = 0;
22363   char *zSql;
22364   char zBuf[1000];
22365 
22366   if( nLine>(i64)sizeof(zBuf)-30 ) return;
22367   if( zLine[0]=='.' || zLine[0]=='#') return;
22368   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
22369   if( i==nLine-1 ) return;
22370   iStart = i+1;
22371   memcpy(zBuf, zLine, iStart);
22372   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
22373                          "  FROM completion(%Q,%Q) ORDER BY 1",
22374                          &zLine[iStart], zLine);
22375   shell_check_oom(zSql);
22376   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
22377   sqlite3_free(zSql);
22378   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
22379   while( sqlite3_step(pStmt)==SQLITE_ROW ){
22380     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
22381     int nCompletion = sqlite3_column_bytes(pStmt, 0);
22382     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
22383       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
22384       linenoiseAddCompletion(lc, zBuf);
22385     }
22386   }
22387   sqlite3_finalize(pStmt);
22388 }
22389 #endif
22390 
22391 /*
22392 ** Do C-language style dequoting.
22393 **
22394 **    \a    -> alarm
22395 **    \b    -> backspace
22396 **    \t    -> tab
22397 **    \n    -> newline
22398 **    \v    -> vertical tab
22399 **    \f    -> form feed
22400 **    \r    -> carriage return
22401 **    \s    -> space
22402 **    \"    -> "
22403 **    \'    -> '
22404 **    \\    -> backslash
22405 **    \NNN  -> ascii character NNN in octal
22406 **    \xHH  -> ascii character HH in hexadecimal
22407 */
resolve_backslashes(char * z)22408 static void resolve_backslashes(char *z){
22409   int i, j;
22410   char c;
22411   while( *z && *z!='\\' ) z++;
22412   for(i=j=0; (c = z[i])!=0; i++, j++){
22413     if( c=='\\' && z[i+1]!=0 ){
22414       c = z[++i];
22415       if( c=='a' ){
22416         c = '\a';
22417       }else if( c=='b' ){
22418         c = '\b';
22419       }else if( c=='t' ){
22420         c = '\t';
22421       }else if( c=='n' ){
22422         c = '\n';
22423       }else if( c=='v' ){
22424         c = '\v';
22425       }else if( c=='f' ){
22426         c = '\f';
22427       }else if( c=='r' ){
22428         c = '\r';
22429       }else if( c=='"' ){
22430         c = '"';
22431       }else if( c=='\'' ){
22432         c = '\'';
22433       }else if( c=='\\' ){
22434         c = '\\';
22435       }else if( c=='x' ){
22436         int nhd = 0, hdv;
22437         u8 hv = 0;
22438         while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
22439           hv = (u8)((hv<<4)|hdv);
22440           ++nhd;
22441         }
22442         i += nhd;
22443         c = (u8)hv;
22444       }else if( c>='0' && c<='7' ){
22445         c -= '0';
22446         if( z[i+1]>='0' && z[i+1]<='7' ){
22447           i++;
22448           c = (c<<3) + z[i] - '0';
22449           if( z[i+1]>='0' && z[i+1]<='7' ){
22450             i++;
22451             c = (c<<3) + z[i] - '0';
22452           }
22453         }
22454       }
22455     }
22456     z[j] = c;
22457   }
22458   if( j<i ) z[j] = 0;
22459 }
22460 
22461 /*
22462 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
22463 ** for TRUE and FALSE.  Return the integer value if appropriate.
22464 */
booleanValue(const char * zArg)22465 static int booleanValue(const char *zArg){
22466   int i;
22467   if( zArg[0]=='0' && zArg[1]=='x' ){
22468     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
22469   }else{
22470     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
22471   }
22472   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
22473   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
22474     return 1;
22475   }
22476   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
22477     return 0;
22478   }
22479   eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
22480   return 0;
22481 }
22482 
22483 /*
22484 ** Set or clear a shell flag according to a boolean value.
22485 */
setOrClearFlag(ShellState * p,unsigned mFlag,const char * zArg)22486 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
22487   if( booleanValue(zArg) ){
22488     ShellSetFlag(p, mFlag);
22489   }else{
22490     ShellClearFlag(p, mFlag);
22491   }
22492 }
22493 
22494 /*
22495 ** Close an output file, assuming it is not stderr or stdout
22496 */
output_file_close(FILE * f)22497 static void output_file_close(FILE *f){
22498   if( f && f!=stdout && f!=stderr ) fclose(f);
22499 }
22500 
22501 /*
22502 ** Try to open an output file.   The names "stdout" and "stderr" are
22503 ** recognized and do the right thing.  NULL is returned if the output
22504 ** filename is "off".
22505 */
output_file_open(const char * zFile,int bTextMode)22506 static FILE *output_file_open(const char *zFile, int bTextMode){
22507   FILE *f;
22508   if( cli_strcmp(zFile,"stdout")==0 ){
22509     f = stdout;
22510   }else if( cli_strcmp(zFile, "stderr")==0 ){
22511     f = stderr;
22512   }else if( cli_strcmp(zFile, "off")==0 ){
22513     f = 0;
22514   }else{
22515     f = fopen(zFile, bTextMode ? "w" : "wb");
22516     if( f==0 ){
22517       eputf("Error: cannot open \"%s\"\n", zFile);
22518     }
22519   }
22520   return f;
22521 }
22522 
22523 #ifndef SQLITE_OMIT_TRACE
22524 /*
22525 ** A routine for handling output from sqlite3_trace().
22526 */
sql_trace_callback(unsigned mType,void * pArg,void * pP,void * pX)22527 static int sql_trace_callback(
22528   unsigned mType,         /* The trace type */
22529   void *pArg,             /* The ShellState pointer */
22530   void *pP,               /* Usually a pointer to sqlite_stmt */
22531   void *pX                /* Auxiliary output */
22532 ){
22533   ShellState *p = (ShellState*)pArg;
22534   sqlite3_stmt *pStmt;
22535   const char *zSql;
22536   i64 nSql;
22537   if( p->traceOut==0 ) return 0;
22538   if( mType==SQLITE_TRACE_CLOSE ){
22539     sputz(p->traceOut, "-- closing database connection\n");
22540     return 0;
22541   }
22542   if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
22543     zSql = (const char*)pX;
22544   }else{
22545     pStmt = (sqlite3_stmt*)pP;
22546     switch( p->eTraceType ){
22547       case SHELL_TRACE_EXPANDED: {
22548         zSql = sqlite3_expanded_sql(pStmt);
22549         break;
22550       }
22551 #ifdef SQLITE_ENABLE_NORMALIZE
22552       case SHELL_TRACE_NORMALIZED: {
22553         zSql = sqlite3_normalized_sql(pStmt);
22554         break;
22555       }
22556 #endif
22557       default: {
22558         zSql = sqlite3_sql(pStmt);
22559         break;
22560       }
22561     }
22562   }
22563   if( zSql==0 ) return 0;
22564   nSql = strlen(zSql);
22565   if( nSql>1000000000 ) nSql = 1000000000;
22566   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
22567   switch( mType ){
22568     case SQLITE_TRACE_ROW:
22569     case SQLITE_TRACE_STMT: {
22570       sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
22571       break;
22572     }
22573     case SQLITE_TRACE_PROFILE: {
22574       sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
22575       sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
22576       break;
22577     }
22578   }
22579   return 0;
22580 }
22581 #endif
22582 
22583 /*
22584 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
22585 ** a useful spot to set a debugger breakpoint.
22586 **
22587 ** This routine does not do anything practical.  The code are there simply
22588 ** to prevent the compiler from optimizing this routine out.
22589 */
test_breakpoint(void)22590 static void test_breakpoint(void){
22591   static unsigned int nCall = 0;
22592   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
22593 }
22594 
22595 /*
22596 ** An object used to read a CSV and other files for import.
22597 */
22598 typedef struct ImportCtx ImportCtx;
22599 struct ImportCtx {
22600   const char *zFile;  /* Name of the input file */
22601   FILE *in;           /* Read the CSV text from this input stream */
22602   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
22603   char *z;            /* Accumulated text for a field */
22604   int n;              /* Number of bytes in z */
22605   int nAlloc;         /* Space allocated for z[] */
22606   int nLine;          /* Current line number */
22607   int nRow;           /* Number of rows imported */
22608   int nErr;           /* Number of errors encountered */
22609   int bNotFirst;      /* True if one or more bytes already read */
22610   int cTerm;          /* Character that terminated the most recent field */
22611   int cColSep;        /* The column separator character.  (Usually ",") */
22612   int cRowSep;        /* The row separator character.  (Usually "\n") */
22613 };
22614 
22615 /* Clean up resourced used by an ImportCtx */
import_cleanup(ImportCtx * p)22616 static void import_cleanup(ImportCtx *p){
22617   if( p->in!=0 && p->xCloser!=0 ){
22618     p->xCloser(p->in);
22619     p->in = 0;
22620   }
22621   sqlite3_free(p->z);
22622   p->z = 0;
22623 }
22624 
22625 /* Append a single byte to z[] */
import_append_char(ImportCtx * p,int c)22626 static void import_append_char(ImportCtx *p, int c){
22627   if( p->n+1>=p->nAlloc ){
22628     p->nAlloc += p->nAlloc + 100;
22629     p->z = sqlite3_realloc64(p->z, p->nAlloc);
22630     shell_check_oom(p->z);
22631   }
22632   p->z[p->n++] = (char)c;
22633 }
22634 
22635 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
22636 ** with the option of having a separator other than ",".
22637 **
22638 **   +  Input comes from p->in.
22639 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
22640 **      from sqlite3_malloc64().
22641 **   +  Use p->cSep as the column separator.  The default is ",".
22642 **   +  Use p->rSep as the row separator.  The default is "\n".
22643 **   +  Keep track of the line number in p->nLine.
22644 **   +  Store the character that terminates the field in p->cTerm.  Store
22645 **      EOF on end-of-file.
22646 **   +  Report syntax errors on stderr
22647 */
csv_read_one_field(ImportCtx * p)22648 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
22649   int c;
22650   int cSep = (u8)p->cColSep;
22651   int rSep = (u8)p->cRowSep;
22652   p->n = 0;
22653   c = fgetc(p->in);
22654   if( c==EOF || seenInterrupt ){
22655     p->cTerm = EOF;
22656     return 0;
22657   }
22658   if( c=='"' ){
22659     int pc, ppc;
22660     int startLine = p->nLine;
22661     int cQuote = c;
22662     pc = ppc = 0;
22663     while( 1 ){
22664       c = fgetc(p->in);
22665       if( c==rSep ) p->nLine++;
22666       if( c==cQuote ){
22667         if( pc==cQuote ){
22668           pc = 0;
22669           continue;
22670         }
22671       }
22672       if( (c==cSep && pc==cQuote)
22673        || (c==rSep && pc==cQuote)
22674        || (c==rSep && pc=='\r' && ppc==cQuote)
22675        || (c==EOF && pc==cQuote)
22676       ){
22677         do{ p->n--; }while( p->z[p->n]!=cQuote );
22678         p->cTerm = c;
22679         break;
22680       }
22681       if( pc==cQuote && c!='\r' ){
22682         eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
22683       }
22684       if( c==EOF ){
22685         eputf("%s:%d: unterminated %c-quoted field\n",
22686               p->zFile, startLine, cQuote);
22687         p->cTerm = c;
22688         break;
22689       }
22690       import_append_char(p, c);
22691       ppc = pc;
22692       pc = c;
22693     }
22694   }else{
22695     /* If this is the first field being parsed and it begins with the
22696     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
22697     if( (c&0xff)==0xef && p->bNotFirst==0 ){
22698       import_append_char(p, c);
22699       c = fgetc(p->in);
22700       if( (c&0xff)==0xbb ){
22701         import_append_char(p, c);
22702         c = fgetc(p->in);
22703         if( (c&0xff)==0xbf ){
22704           p->bNotFirst = 1;
22705           p->n = 0;
22706           return csv_read_one_field(p);
22707         }
22708       }
22709     }
22710     while( c!=EOF && c!=cSep && c!=rSep ){
22711       import_append_char(p, c);
22712       c = fgetc(p->in);
22713     }
22714     if( c==rSep ){
22715       p->nLine++;
22716       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
22717     }
22718     p->cTerm = c;
22719   }
22720   if( p->z ) p->z[p->n] = 0;
22721   p->bNotFirst = 1;
22722   return p->z;
22723 }
22724 
22725 /* Read a single field of ASCII delimited text.
22726 **
22727 **   +  Input comes from p->in.
22728 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
22729 **      from sqlite3_malloc64().
22730 **   +  Use p->cSep as the column separator.  The default is "\x1F".
22731 **   +  Use p->rSep as the row separator.  The default is "\x1E".
22732 **   +  Keep track of the row number in p->nLine.
22733 **   +  Store the character that terminates the field in p->cTerm.  Store
22734 **      EOF on end-of-file.
22735 **   +  Report syntax errors on stderr
22736 */
ascii_read_one_field(ImportCtx * p)22737 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
22738   int c;
22739   int cSep = (u8)p->cColSep;
22740   int rSep = (u8)p->cRowSep;
22741   p->n = 0;
22742   c = fgetc(p->in);
22743   if( c==EOF || seenInterrupt ){
22744     p->cTerm = EOF;
22745     return 0;
22746   }
22747   while( c!=EOF && c!=cSep && c!=rSep ){
22748     import_append_char(p, c);
22749     c = fgetc(p->in);
22750   }
22751   if( c==rSep ){
22752     p->nLine++;
22753   }
22754   p->cTerm = c;
22755   if( p->z ) p->z[p->n] = 0;
22756   return p->z;
22757 }
22758 
22759 /*
22760 ** Try to transfer data for table zTable.  If an error is seen while
22761 ** moving forward, try to go backwards.  The backwards movement won't
22762 ** work for WITHOUT ROWID tables.
22763 */
tryToCloneData(ShellState * p,sqlite3 * newDb,const char * zTable)22764 static void tryToCloneData(
22765   ShellState *p,
22766   sqlite3 *newDb,
22767   const char *zTable
22768 ){
22769   sqlite3_stmt *pQuery = 0;
22770   sqlite3_stmt *pInsert = 0;
22771   char *zQuery = 0;
22772   char *zInsert = 0;
22773   int rc;
22774   int i, j, n;
22775   int nTable = strlen30(zTable);
22776   int k = 0;
22777   int cnt = 0;
22778   const int spinRate = 10000;
22779 
22780   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
22781   shell_check_oom(zQuery);
22782   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22783   if( rc ){
22784     eputf("Error %d: %s on [%s]\n",
22785           sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
22786     goto end_data_xfer;
22787   }
22788   n = sqlite3_column_count(pQuery);
22789   zInsert = sqlite3_malloc64(200 + nTable + n*3);
22790   shell_check_oom(zInsert);
22791   sqlite3_snprintf(200+nTable,zInsert,
22792                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
22793   i = strlen30(zInsert);
22794   for(j=1; j<n; j++){
22795     memcpy(zInsert+i, ",?", 2);
22796     i += 2;
22797   }
22798   memcpy(zInsert+i, ");", 3);
22799   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
22800   if( rc ){
22801     eputf("Error %d: %s on [%s]\n",
22802           sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
22803     goto end_data_xfer;
22804   }
22805   for(k=0; k<2; k++){
22806     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22807       for(i=0; i<n; i++){
22808         switch( sqlite3_column_type(pQuery, i) ){
22809           case SQLITE_NULL: {
22810             sqlite3_bind_null(pInsert, i+1);
22811             break;
22812           }
22813           case SQLITE_INTEGER: {
22814             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
22815             break;
22816           }
22817           case SQLITE_FLOAT: {
22818             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
22819             break;
22820           }
22821           case SQLITE_TEXT: {
22822             sqlite3_bind_text(pInsert, i+1,
22823                              (const char*)sqlite3_column_text(pQuery,i),
22824                              -1, SQLITE_STATIC);
22825             break;
22826           }
22827           case SQLITE_BLOB: {
22828             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
22829                                             sqlite3_column_bytes(pQuery,i),
22830                                             SQLITE_STATIC);
22831             break;
22832           }
22833         }
22834       } /* End for */
22835       rc = sqlite3_step(pInsert);
22836       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
22837         eputf("Error %d: %s\n",
22838               sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
22839       }
22840       sqlite3_reset(pInsert);
22841       cnt++;
22842       if( (cnt%spinRate)==0 ){
22843         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
22844         fflush(stdout);
22845       }
22846     } /* End while */
22847     if( rc==SQLITE_DONE ) break;
22848     sqlite3_finalize(pQuery);
22849     sqlite3_free(zQuery);
22850     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
22851                              zTable);
22852     shell_check_oom(zQuery);
22853     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22854     if( rc ){
22855       eputf("Warning: cannot step \"%s\" backwards", zTable);
22856       break;
22857     }
22858   } /* End for(k=0...) */
22859 
22860 end_data_xfer:
22861   sqlite3_finalize(pQuery);
22862   sqlite3_finalize(pInsert);
22863   sqlite3_free(zQuery);
22864   sqlite3_free(zInsert);
22865 }
22866 
22867 
22868 /*
22869 ** Try to transfer all rows of the schema that match zWhere.  For
22870 ** each row, invoke xForEach() on the object defined by that row.
22871 ** If an error is encountered while moving forward through the
22872 ** sqlite_schema table, try again moving backwards.
22873 */
tryToCloneSchema(ShellState * p,sqlite3 * newDb,const char * zWhere,void (* xForEach)(ShellState *,sqlite3 *,const char *))22874 static void tryToCloneSchema(
22875   ShellState *p,
22876   sqlite3 *newDb,
22877   const char *zWhere,
22878   void (*xForEach)(ShellState*,sqlite3*,const char*)
22879 ){
22880   sqlite3_stmt *pQuery = 0;
22881   char *zQuery = 0;
22882   int rc;
22883   const unsigned char *zName;
22884   const unsigned char *zSql;
22885   char *zErrMsg = 0;
22886 
22887   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22888                            " WHERE %s ORDER BY rowid ASC", zWhere);
22889   shell_check_oom(zQuery);
22890   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22891   if( rc ){
22892     eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
22893           sqlite3_errmsg(p->db), zQuery);
22894     goto end_schema_xfer;
22895   }
22896   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22897     zName = sqlite3_column_text(pQuery, 0);
22898     zSql = sqlite3_column_text(pQuery, 1);
22899     if( zName==0 || zSql==0 ) continue;
22900     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
22901       sputf(stdout, "%s... ", zName); fflush(stdout);
22902       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22903       if( zErrMsg ){
22904         eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22905         sqlite3_free(zErrMsg);
22906         zErrMsg = 0;
22907       }
22908     }
22909     if( xForEach ){
22910       xForEach(p, newDb, (const char*)zName);
22911     }
22912     sputz(stdout, "done\n");
22913   }
22914   if( rc!=SQLITE_DONE ){
22915     sqlite3_finalize(pQuery);
22916     sqlite3_free(zQuery);
22917     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22918                              " WHERE %s ORDER BY rowid DESC", zWhere);
22919     shell_check_oom(zQuery);
22920     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22921     if( rc ){
22922       eputf("Error: (%d) %s on [%s]\n",
22923             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
22924       goto end_schema_xfer;
22925     }
22926     while( sqlite3_step(pQuery)==SQLITE_ROW ){
22927       zName = sqlite3_column_text(pQuery, 0);
22928       zSql = sqlite3_column_text(pQuery, 1);
22929       if( zName==0 || zSql==0 ) continue;
22930       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
22931       sputf(stdout, "%s... ", zName); fflush(stdout);
22932       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22933       if( zErrMsg ){
22934         eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22935         sqlite3_free(zErrMsg);
22936         zErrMsg = 0;
22937       }
22938       if( xForEach ){
22939         xForEach(p, newDb, (const char*)zName);
22940       }
22941       sputz(stdout, "done\n");
22942     }
22943   }
22944 end_schema_xfer:
22945   sqlite3_finalize(pQuery);
22946   sqlite3_free(zQuery);
22947 }
22948 
22949 /*
22950 ** Open a new database file named "zNewDb".  Try to recover as much information
22951 ** as possible out of the main database (which might be corrupt) and write it
22952 ** into zNewDb.
22953 */
tryToClone(ShellState * p,const char * zNewDb)22954 static void tryToClone(ShellState *p, const char *zNewDb){
22955   int rc;
22956   sqlite3 *newDb = 0;
22957   if( access(zNewDb,0)==0 ){
22958     eputf("File \"%s\" already exists.\n", zNewDb);
22959     return;
22960   }
22961   rc = sqlite3_open(zNewDb, &newDb);
22962   if( rc ){
22963     eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
22964   }else{
22965     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
22966     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
22967     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
22968     tryToCloneSchema(p, newDb, "type!='table'", 0);
22969     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
22970     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
22971   }
22972   close_db(newDb);
22973 }
22974 
22975 #ifndef SQLITE_SHELL_FIDDLE
22976 /*
22977 ** Change the output stream (file or pipe or console) to something else.
22978 */
output_redir(ShellState * p,FILE * pfNew)22979 static void output_redir(ShellState *p, FILE *pfNew){
22980   if( p->out != stdout ) eputz("Output already redirected.\n");
22981   else{
22982     p->out = pfNew;
22983     setOutputStream(pfNew);
22984   }
22985 }
22986 
22987 /*
22988 ** Change the output file back to stdout.
22989 **
22990 ** If the p->doXdgOpen flag is set, that means the output was being
22991 ** redirected to a temporary file named by p->zTempFile.  In that case,
22992 ** launch start/open/xdg-open on that temporary file.
22993 */
output_reset(ShellState * p)22994 static void output_reset(ShellState *p){
22995   if( p->outfile[0]=='|' ){
22996 #ifndef SQLITE_OMIT_POPEN
22997     pclose(p->out);
22998 #endif
22999   }else{
23000     output_file_close(p->out);
23001 #ifndef SQLITE_NOHAVE_SYSTEM
23002     if( p->doXdgOpen ){
23003       const char *zXdgOpenCmd =
23004 #if defined(_WIN32)
23005       "start";
23006 #elif defined(__APPLE__)
23007       "open";
23008 #else
23009       "xdg-open";
23010 #endif
23011       char *zCmd;
23012       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
23013       if( system(zCmd) ){
23014         eputf("Failed: [%s]\n", zCmd);
23015       }else{
23016         /* Give the start/open/xdg-open command some time to get
23017         ** going before we continue, and potential delete the
23018         ** p->zTempFile data file out from under it */
23019         sqlite3_sleep(2000);
23020       }
23021       sqlite3_free(zCmd);
23022       outputModePop(p);
23023       p->doXdgOpen = 0;
23024     }
23025 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
23026   }
23027   p->outfile[0] = 0;
23028   p->out = stdout;
23029   setOutputStream(stdout);
23030 }
23031 #else
23032 # define output_redir(SS,pfO)
23033 # define output_reset(SS)
23034 #endif
23035 
23036 /*
23037 ** Run an SQL command and return the single integer result.
23038 */
db_int(sqlite3 * db,const char * zSql)23039 static int db_int(sqlite3 *db, const char *zSql){
23040   sqlite3_stmt *pStmt;
23041   int res = 0;
23042   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
23043   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
23044     res = sqlite3_column_int(pStmt,0);
23045   }
23046   sqlite3_finalize(pStmt);
23047   return res;
23048 }
23049 
23050 #if SQLITE_SHELL_HAVE_RECOVER
23051 /*
23052 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
23053 */
get2byteInt(unsigned char * a)23054 static unsigned int get2byteInt(unsigned char *a){
23055   return (a[0]<<8) + a[1];
23056 }
get4byteInt(unsigned char * a)23057 static unsigned int get4byteInt(unsigned char *a){
23058   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
23059 }
23060 
23061 /*
23062 ** Implementation of the ".dbinfo" command.
23063 **
23064 ** Return 1 on error, 2 to exit, and 0 otherwise.
23065 */
shell_dbinfo_command(ShellState * p,int nArg,char ** azArg)23066 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
23067   static const struct { const char *zName; int ofst; } aField[] = {
23068      { "file change counter:",  24  },
23069      { "database page count:",  28  },
23070      { "freelist page count:",  36  },
23071      { "schema cookie:",        40  },
23072      { "schema format:",        44  },
23073      { "default cache size:",   48  },
23074      { "autovacuum top root:",  52  },
23075      { "incremental vacuum:",   64  },
23076      { "text encoding:",        56  },
23077      { "user version:",         60  },
23078      { "application id:",       68  },
23079      { "software version:",     96  },
23080   };
23081   static const struct { const char *zName; const char *zSql; } aQuery[] = {
23082      { "number of tables:",
23083        "SELECT count(*) FROM %s WHERE type='table'" },
23084      { "number of indexes:",
23085        "SELECT count(*) FROM %s WHERE type='index'" },
23086      { "number of triggers:",
23087        "SELECT count(*) FROM %s WHERE type='trigger'" },
23088      { "number of views:",
23089        "SELECT count(*) FROM %s WHERE type='view'" },
23090      { "schema size:",
23091        "SELECT total(length(sql)) FROM %s" },
23092   };
23093   int i, rc;
23094   unsigned iDataVersion;
23095   char *zSchemaTab;
23096   char *zDb = nArg>=2 ? azArg[1] : "main";
23097   sqlite3_stmt *pStmt = 0;
23098   unsigned char aHdr[100];
23099   open_db(p, 0);
23100   if( p->db==0 ) return 1;
23101   rc = sqlite3_prepare_v2(p->db,
23102              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
23103              -1, &pStmt, 0);
23104   if( rc ){
23105     eputf("error: %s\n", sqlite3_errmsg(p->db));
23106     sqlite3_finalize(pStmt);
23107     return 1;
23108   }
23109   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
23110   if( sqlite3_step(pStmt)==SQLITE_ROW
23111    && sqlite3_column_bytes(pStmt,0)>100
23112   ){
23113     const u8 *pb = sqlite3_column_blob(pStmt,0);
23114     shell_check_oom(pb);
23115     memcpy(aHdr, pb, 100);
23116     sqlite3_finalize(pStmt);
23117   }else{
23118     eputz("unable to read database header\n");
23119     sqlite3_finalize(pStmt);
23120     return 1;
23121   }
23122   i = get2byteInt(aHdr+16);
23123   if( i==1 ) i = 65536;
23124   oputf("%-20s %d\n", "database page size:", i);
23125   oputf("%-20s %d\n", "write format:", aHdr[18]);
23126   oputf("%-20s %d\n", "read format:", aHdr[19]);
23127   oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
23128   for(i=0; i<ArraySize(aField); i++){
23129     int ofst = aField[i].ofst;
23130     unsigned int val = get4byteInt(aHdr + ofst);
23131     oputf("%-20s %u", aField[i].zName, val);
23132     switch( ofst ){
23133       case 56: {
23134         if( val==1 ) oputz(" (utf8)");
23135         if( val==2 ) oputz(" (utf16le)");
23136         if( val==3 ) oputz(" (utf16be)");
23137       }
23138     }
23139     oputz("\n");
23140   }
23141   if( zDb==0 ){
23142     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
23143   }else if( cli_strcmp(zDb,"temp")==0 ){
23144     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
23145   }else{
23146     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
23147   }
23148   for(i=0; i<ArraySize(aQuery); i++){
23149     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
23150     int val = db_int(p->db, zSql);
23151     sqlite3_free(zSql);
23152     oputf("%-20s %d\n", aQuery[i].zName, val);
23153   }
23154   sqlite3_free(zSchemaTab);
23155   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
23156   oputf("%-20s %u\n", "data version", iDataVersion);
23157   return 0;
23158 }
23159 #endif /* SQLITE_SHELL_HAVE_RECOVER */
23160 
23161 /*
23162 ** Print the current sqlite3_errmsg() value to stderr and return 1.
23163 */
shellDatabaseError(sqlite3 * db)23164 static int shellDatabaseError(sqlite3 *db){
23165   const char *zErr = sqlite3_errmsg(db);
23166   eputf("Error: %s\n", zErr);
23167   return 1;
23168 }
23169 
23170 /*
23171 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
23172 ** if they match and FALSE (0) if they do not match.
23173 **
23174 ** Globbing rules:
23175 **
23176 **      '*'       Matches any sequence of zero or more characters.
23177 **
23178 **      '?'       Matches exactly one character.
23179 **
23180 **     [...]      Matches one character from the enclosed list of
23181 **                characters.
23182 **
23183 **     [^...]     Matches one character not in the enclosed list.
23184 **
23185 **      '#'       Matches any sequence of one or more digits with an
23186 **                optional + or - sign in front
23187 **
23188 **      ' '       Any span of whitespace matches any other span of
23189 **                whitespace.
23190 **
23191 ** Extra whitespace at the end of z[] is ignored.
23192 */
testcase_glob(const char * zGlob,const char * z)23193 static int testcase_glob(const char *zGlob, const char *z){
23194   int c, c2;
23195   int invert;
23196   int seen;
23197 
23198   while( (c = (*(zGlob++)))!=0 ){
23199     if( IsSpace(c) ){
23200       if( !IsSpace(*z) ) return 0;
23201       while( IsSpace(*zGlob) ) zGlob++;
23202       while( IsSpace(*z) ) z++;
23203     }else if( c=='*' ){
23204       while( (c=(*(zGlob++))) == '*' || c=='?' ){
23205         if( c=='?' && (*(z++))==0 ) return 0;
23206       }
23207       if( c==0 ){
23208         return 1;
23209       }else if( c=='[' ){
23210         while( *z && testcase_glob(zGlob-1,z)==0 ){
23211           z++;
23212         }
23213         return (*z)!=0;
23214       }
23215       while( (c2 = (*(z++)))!=0 ){
23216         while( c2!=c ){
23217           c2 = *(z++);
23218           if( c2==0 ) return 0;
23219         }
23220         if( testcase_glob(zGlob,z) ) return 1;
23221       }
23222       return 0;
23223     }else if( c=='?' ){
23224       if( (*(z++))==0 ) return 0;
23225     }else if( c=='[' ){
23226       int prior_c = 0;
23227       seen = 0;
23228       invert = 0;
23229       c = *(z++);
23230       if( c==0 ) return 0;
23231       c2 = *(zGlob++);
23232       if( c2=='^' ){
23233         invert = 1;
23234         c2 = *(zGlob++);
23235       }
23236       if( c2==']' ){
23237         if( c==']' ) seen = 1;
23238         c2 = *(zGlob++);
23239       }
23240       while( c2 && c2!=']' ){
23241         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
23242           c2 = *(zGlob++);
23243           if( c>=prior_c && c<=c2 ) seen = 1;
23244           prior_c = 0;
23245         }else{
23246           if( c==c2 ){
23247             seen = 1;
23248           }
23249           prior_c = c2;
23250         }
23251         c2 = *(zGlob++);
23252       }
23253       if( c2==0 || (seen ^ invert)==0 ) return 0;
23254     }else if( c=='#' ){
23255       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
23256       if( !IsDigit(z[0]) ) return 0;
23257       z++;
23258       while( IsDigit(z[0]) ){ z++; }
23259     }else{
23260       if( c!=(*(z++)) ) return 0;
23261     }
23262   }
23263   while( IsSpace(*z) ){ z++; }
23264   return *z==0;
23265 }
23266 
23267 
23268 /*
23269 ** Compare the string as a command-line option with either one or two
23270 ** initial "-" characters.
23271 */
optionMatch(const char * zStr,const char * zOpt)23272 static int optionMatch(const char *zStr, const char *zOpt){
23273   if( zStr[0]!='-' ) return 0;
23274   zStr++;
23275   if( zStr[0]=='-' ) zStr++;
23276   return cli_strcmp(zStr, zOpt)==0;
23277 }
23278 
23279 /*
23280 ** Delete a file.
23281 */
shellDeleteFile(const char * zFilename)23282 int shellDeleteFile(const char *zFilename){
23283   int rc;
23284 #ifdef _WIN32
23285   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
23286   rc = _wunlink(z);
23287   sqlite3_free(z);
23288 #else
23289   rc = unlink(zFilename);
23290 #endif
23291   return rc;
23292 }
23293 
23294 /*
23295 ** Try to delete the temporary file (if there is one) and free the
23296 ** memory used to hold the name of the temp file.
23297 */
clearTempFile(ShellState * p)23298 static void clearTempFile(ShellState *p){
23299   if( p->zTempFile==0 ) return;
23300   if( p->doXdgOpen ) return;
23301   if( shellDeleteFile(p->zTempFile) ) return;
23302   sqlite3_free(p->zTempFile);
23303   p->zTempFile = 0;
23304 }
23305 
23306 /*
23307 ** Create a new temp file name with the given suffix.
23308 */
newTempFile(ShellState * p,const char * zSuffix)23309 static void newTempFile(ShellState *p, const char *zSuffix){
23310   clearTempFile(p);
23311   sqlite3_free(p->zTempFile);
23312   p->zTempFile = 0;
23313   if( p->db ){
23314     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
23315   }
23316   if( p->zTempFile==0 ){
23317     /* If p->db is an in-memory database then the TEMPFILENAME file-control
23318     ** will not work and we will need to fallback to guessing */
23319     char *zTemp;
23320     sqlite3_uint64 r;
23321     sqlite3_randomness(sizeof(r), &r);
23322     zTemp = getenv("TEMP");
23323     if( zTemp==0 ) zTemp = getenv("TMP");
23324     if( zTemp==0 ){
23325 #ifdef _WIN32
23326       zTemp = "\\tmp";
23327 #else
23328       zTemp = "/tmp";
23329 #endif
23330     }
23331     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
23332   }else{
23333     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
23334   }
23335   shell_check_oom(p->zTempFile);
23336 }
23337 
23338 
23339 /*
23340 ** The implementation of SQL scalar function fkey_collate_clause(), used
23341 ** by the ".lint fkey-indexes" command. This scalar function is always
23342 ** called with four arguments - the parent table name, the parent column name,
23343 ** the child table name and the child column name.
23344 **
23345 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
23346 **
23347 ** If either of the named tables or columns do not exist, this function
23348 ** returns an empty string. An empty string is also returned if both tables
23349 ** and columns exist but have the same default collation sequence. Or,
23350 ** if both exist but the default collation sequences are different, this
23351 ** function returns the string " COLLATE <parent-collation>", where
23352 ** <parent-collation> is the default collation sequence of the parent column.
23353 */
shellFkeyCollateClause(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)23354 static void shellFkeyCollateClause(
23355   sqlite3_context *pCtx,
23356   int nVal,
23357   sqlite3_value **apVal
23358 ){
23359   sqlite3 *db = sqlite3_context_db_handle(pCtx);
23360   const char *zParent;
23361   const char *zParentCol;
23362   const char *zParentSeq;
23363   const char *zChild;
23364   const char *zChildCol;
23365   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
23366   int rc;
23367 
23368   assert( nVal==4 );
23369   zParent = (const char*)sqlite3_value_text(apVal[0]);
23370   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
23371   zChild = (const char*)sqlite3_value_text(apVal[2]);
23372   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
23373 
23374   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
23375   rc = sqlite3_table_column_metadata(
23376       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
23377   );
23378   if( rc==SQLITE_OK ){
23379     rc = sqlite3_table_column_metadata(
23380         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
23381     );
23382   }
23383 
23384   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
23385     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
23386     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
23387     sqlite3_free(z);
23388   }
23389 }
23390 
23391 
23392 /*
23393 ** The implementation of dot-command ".lint fkey-indexes".
23394 */
lintFkeyIndexes(ShellState * pState,char ** azArg,int nArg)23395 static int lintFkeyIndexes(
23396   ShellState *pState,             /* Current shell tool state */
23397   char **azArg,                   /* Array of arguments passed to dot command */
23398   int nArg                        /* Number of entries in azArg[] */
23399 ){
23400   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
23401   int bVerbose = 0;               /* If -verbose is present */
23402   int bGroupByParent = 0;         /* If -groupbyparent is present */
23403   int i;                          /* To iterate through azArg[] */
23404   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
23405   int rc;                         /* Return code */
23406   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
23407 
23408   /*
23409   ** This SELECT statement returns one row for each foreign key constraint
23410   ** in the schema of the main database. The column values are:
23411   **
23412   ** 0. The text of an SQL statement similar to:
23413   **
23414   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
23415   **
23416   **    This SELECT is similar to the one that the foreign keys implementation
23417   **    needs to run internally on child tables. If there is an index that can
23418   **    be used to optimize this query, then it can also be used by the FK
23419   **    implementation to optimize DELETE or UPDATE statements on the parent
23420   **    table.
23421   **
23422   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
23423   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
23424   **    contains an index that can be used to optimize the query.
23425   **
23426   ** 2. Human readable text that describes the child table and columns. e.g.
23427   **
23428   **       "child_table(child_key1, child_key2)"
23429   **
23430   ** 3. Human readable text that describes the parent table and columns. e.g.
23431   **
23432   **       "parent_table(parent_key1, parent_key2)"
23433   **
23434   ** 4. A full CREATE INDEX statement for an index that could be used to
23435   **    optimize DELETE or UPDATE statements on the parent table. e.g.
23436   **
23437   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
23438   **
23439   ** 5. The name of the parent table.
23440   **
23441   ** These six values are used by the C logic below to generate the report.
23442   */
23443   const char *zSql =
23444   "SELECT "
23445     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
23446     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
23447     "  || fkey_collate_clause("
23448     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
23449     ", "
23450     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
23451     "  || group_concat('*=?', ' AND ') || ')'"
23452     ", "
23453     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
23454     ", "
23455     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
23456     ", "
23457     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
23458     "  || ' ON ' || quote(s.name) || '('"
23459     "  || group_concat(quote(f.[from]) ||"
23460     "        fkey_collate_clause("
23461     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
23462     "  || ');'"
23463     ", "
23464     "     f.[table] "
23465     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
23466     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
23467     "GROUP BY s.name, f.id "
23468     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
23469   ;
23470   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
23471 
23472   for(i=2; i<nArg; i++){
23473     int n = strlen30(azArg[i]);
23474     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
23475       bVerbose = 1;
23476     }
23477     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
23478       bGroupByParent = 1;
23479       zIndent = "    ";
23480     }
23481     else{
23482       eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
23483       return SQLITE_ERROR;
23484     }
23485   }
23486 
23487   /* Register the fkey_collate_clause() SQL function */
23488   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
23489       0, shellFkeyCollateClause, 0, 0
23490   );
23491 
23492 
23493   if( rc==SQLITE_OK ){
23494     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
23495   }
23496   if( rc==SQLITE_OK ){
23497     sqlite3_bind_int(pSql, 1, bGroupByParent);
23498   }
23499 
23500   if( rc==SQLITE_OK ){
23501     int rc2;
23502     char *zPrev = 0;
23503     while( SQLITE_ROW==sqlite3_step(pSql) ){
23504       int res = -1;
23505       sqlite3_stmt *pExplain = 0;
23506       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
23507       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
23508       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
23509       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
23510       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
23511       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
23512 
23513       if( zEQP==0 ) continue;
23514       if( zGlob==0 ) continue;
23515       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
23516       if( rc!=SQLITE_OK ) break;
23517       if( SQLITE_ROW==sqlite3_step(pExplain) ){
23518         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
23519         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
23520                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
23521       }
23522       rc = sqlite3_finalize(pExplain);
23523       if( rc!=SQLITE_OK ) break;
23524 
23525       if( res<0 ){
23526         eputz("Error: internal error");
23527         break;
23528       }else{
23529         if( bGroupByParent
23530         && (bVerbose || res==0)
23531         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
23532         ){
23533           oputf("-- Parent table %s\n", zParent);
23534           sqlite3_free(zPrev);
23535           zPrev = sqlite3_mprintf("%s", zParent);
23536         }
23537 
23538         if( res==0 ){
23539           oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
23540         }else if( bVerbose ){
23541           oputf("%s/* no extra indexes required for %s -> %s */\n",
23542                 zIndent, zFrom, zTarget
23543           );
23544         }
23545       }
23546     }
23547     sqlite3_free(zPrev);
23548 
23549     if( rc!=SQLITE_OK ){
23550       eputf("%s\n", sqlite3_errmsg(db));
23551     }
23552 
23553     rc2 = sqlite3_finalize(pSql);
23554     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
23555       rc = rc2;
23556       eputf("%s\n", sqlite3_errmsg(db));
23557     }
23558   }else{
23559     eputf("%s\n", sqlite3_errmsg(db));
23560   }
23561 
23562   return rc;
23563 }
23564 
23565 /*
23566 ** Implementation of ".lint" dot command.
23567 */
lintDotCommand(ShellState * pState,char ** azArg,int nArg)23568 static int lintDotCommand(
23569   ShellState *pState,             /* Current shell tool state */
23570   char **azArg,                   /* Array of arguments passed to dot command */
23571   int nArg                        /* Number of entries in azArg[] */
23572 ){
23573   int n;
23574   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
23575   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
23576   return lintFkeyIndexes(pState, azArg, nArg);
23577 
23578  usage:
23579   eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
23580   eputz("Where sub-commands are:\n");
23581   eputz("    fkey-indexes\n");
23582   return SQLITE_ERROR;
23583 }
23584 
23585 #if !defined SQLITE_OMIT_VIRTUALTABLE
shellPrepare(sqlite3 * db,int * pRc,const char * zSql,sqlite3_stmt ** ppStmt)23586 static void shellPrepare(
23587   sqlite3 *db,
23588   int *pRc,
23589   const char *zSql,
23590   sqlite3_stmt **ppStmt
23591 ){
23592   *ppStmt = 0;
23593   if( *pRc==SQLITE_OK ){
23594     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
23595     if( rc!=SQLITE_OK ){
23596       eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
23597       *pRc = rc;
23598     }
23599   }
23600 }
23601 
23602 /*
23603 ** Create a prepared statement using printf-style arguments for the SQL.
23604 **
23605 ** This routine is could be marked "static".  But it is not always used,
23606 ** depending on compile-time options.  By omitting the "static", we avoid
23607 ** nuisance compiler warnings about "defined but not used".
23608 */
shellPreparePrintf(sqlite3 * db,int * pRc,sqlite3_stmt ** ppStmt,const char * zFmt,...)23609 void shellPreparePrintf(
23610   sqlite3 *db,
23611   int *pRc,
23612   sqlite3_stmt **ppStmt,
23613   const char *zFmt,
23614   ...
23615 ){
23616   *ppStmt = 0;
23617   if( *pRc==SQLITE_OK ){
23618     va_list ap;
23619     char *z;
23620     va_start(ap, zFmt);
23621     z = sqlite3_vmprintf(zFmt, ap);
23622     va_end(ap);
23623     if( z==0 ){
23624       *pRc = SQLITE_NOMEM;
23625     }else{
23626       shellPrepare(db, pRc, z, ppStmt);
23627       sqlite3_free(z);
23628     }
23629   }
23630 }
23631 
23632 /* Finalize the prepared statement created using shellPreparePrintf().
23633 **
23634 ** This routine is could be marked "static".  But it is not always used,
23635 ** depending on compile-time options.  By omitting the "static", we avoid
23636 ** nuisance compiler warnings about "defined but not used".
23637 */
shellFinalize(int * pRc,sqlite3_stmt * pStmt)23638 void shellFinalize(
23639   int *pRc,
23640   sqlite3_stmt *pStmt
23641 ){
23642   if( pStmt ){
23643     sqlite3 *db = sqlite3_db_handle(pStmt);
23644     int rc = sqlite3_finalize(pStmt);
23645     if( *pRc==SQLITE_OK ){
23646       if( rc!=SQLITE_OK ){
23647         eputf("SQL error: %s\n", sqlite3_errmsg(db));
23648       }
23649       *pRc = rc;
23650     }
23651   }
23652 }
23653 
23654 /* Reset the prepared statement created using shellPreparePrintf().
23655 **
23656 ** This routine is could be marked "static".  But it is not always used,
23657 ** depending on compile-time options.  By omitting the "static", we avoid
23658 ** nuisance compiler warnings about "defined but not used".
23659 */
shellReset(int * pRc,sqlite3_stmt * pStmt)23660 void shellReset(
23661   int *pRc,
23662   sqlite3_stmt *pStmt
23663 ){
23664   int rc = sqlite3_reset(pStmt);
23665   if( *pRc==SQLITE_OK ){
23666     if( rc!=SQLITE_OK ){
23667       sqlite3 *db = sqlite3_db_handle(pStmt);
23668       eputf("SQL error: %s\n", sqlite3_errmsg(db));
23669     }
23670     *pRc = rc;
23671   }
23672 }
23673 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
23674 
23675 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
23676 /******************************************************************************
23677 ** The ".archive" or ".ar" command.
23678 */
23679 /*
23680 ** Structure representing a single ".ar" command.
23681 */
23682 typedef struct ArCommand ArCommand;
23683 struct ArCommand {
23684   u8 eCmd;                        /* An AR_CMD_* value */
23685   u8 bVerbose;                    /* True if --verbose */
23686   u8 bZip;                        /* True if the archive is a ZIP */
23687   u8 bDryRun;                     /* True if --dry-run */
23688   u8 bAppend;                     /* True if --append */
23689   u8 bGlob;                       /* True if --glob */
23690   u8 fromCmdLine;                 /* Run from -A instead of .archive */
23691   int nArg;                       /* Number of command arguments */
23692   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
23693   const char *zFile;              /* --file argument, or NULL */
23694   const char *zDir;               /* --directory argument, or NULL */
23695   char **azArg;                   /* Array of command arguments */
23696   ShellState *p;                  /* Shell state */
23697   sqlite3 *db;                    /* Database containing the archive */
23698 };
23699 
23700 /*
23701 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
23702 */
arUsage(FILE * f)23703 static int arUsage(FILE *f){
23704   showHelp(f,"archive");
23705   return SQLITE_ERROR;
23706 }
23707 
23708 /*
23709 ** Print an error message for the .ar command to stderr and return
23710 ** SQLITE_ERROR.
23711 */
arErrorMsg(ArCommand * pAr,const char * zFmt,...)23712 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
23713   va_list ap;
23714   char *z;
23715   va_start(ap, zFmt);
23716   z = sqlite3_vmprintf(zFmt, ap);
23717   va_end(ap);
23718   eputf("Error: %s\n", z);
23719   if( pAr->fromCmdLine ){
23720     eputz("Use \"-A\" for more help\n");
23721   }else{
23722     eputz("Use \".archive --help\" for more help\n");
23723   }
23724   sqlite3_free(z);
23725   return SQLITE_ERROR;
23726 }
23727 
23728 /*
23729 ** Values for ArCommand.eCmd.
23730 */
23731 #define AR_CMD_CREATE       1
23732 #define AR_CMD_UPDATE       2
23733 #define AR_CMD_INSERT       3
23734 #define AR_CMD_EXTRACT      4
23735 #define AR_CMD_LIST         5
23736 #define AR_CMD_HELP         6
23737 #define AR_CMD_REMOVE       7
23738 
23739 /*
23740 ** Other (non-command) switches.
23741 */
23742 #define AR_SWITCH_VERBOSE     8
23743 #define AR_SWITCH_FILE        9
23744 #define AR_SWITCH_DIRECTORY  10
23745 #define AR_SWITCH_APPEND     11
23746 #define AR_SWITCH_DRYRUN     12
23747 #define AR_SWITCH_GLOB       13
23748 
arProcessSwitch(ArCommand * pAr,int eSwitch,const char * zArg)23749 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
23750   switch( eSwitch ){
23751     case AR_CMD_CREATE:
23752     case AR_CMD_EXTRACT:
23753     case AR_CMD_LIST:
23754     case AR_CMD_REMOVE:
23755     case AR_CMD_UPDATE:
23756     case AR_CMD_INSERT:
23757     case AR_CMD_HELP:
23758       if( pAr->eCmd ){
23759         return arErrorMsg(pAr, "multiple command options");
23760       }
23761       pAr->eCmd = eSwitch;
23762       break;
23763 
23764     case AR_SWITCH_DRYRUN:
23765       pAr->bDryRun = 1;
23766       break;
23767     case AR_SWITCH_GLOB:
23768       pAr->bGlob = 1;
23769       break;
23770     case AR_SWITCH_VERBOSE:
23771       pAr->bVerbose = 1;
23772       break;
23773     case AR_SWITCH_APPEND:
23774       pAr->bAppend = 1;
23775       deliberate_fall_through;
23776     case AR_SWITCH_FILE:
23777       pAr->zFile = zArg;
23778       break;
23779     case AR_SWITCH_DIRECTORY:
23780       pAr->zDir = zArg;
23781       break;
23782   }
23783 
23784   return SQLITE_OK;
23785 }
23786 
23787 /*
23788 ** Parse the command line for an ".ar" command. The results are written into
23789 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
23790 ** successfully, otherwise an error message is written to stderr and
23791 ** SQLITE_ERROR returned.
23792 */
arParseCommand(char ** azArg,int nArg,ArCommand * pAr)23793 static int arParseCommand(
23794   char **azArg,                   /* Array of arguments passed to dot command */
23795   int nArg,                       /* Number of entries in azArg[] */
23796   ArCommand *pAr                  /* Populate this object */
23797 ){
23798   struct ArSwitch {
23799     const char *zLong;
23800     char cShort;
23801     u8 eSwitch;
23802     u8 bArg;
23803   } aSwitch[] = {
23804     { "create",    'c', AR_CMD_CREATE,       0 },
23805     { "extract",   'x', AR_CMD_EXTRACT,      0 },
23806     { "insert",    'i', AR_CMD_INSERT,       0 },
23807     { "list",      't', AR_CMD_LIST,         0 },
23808     { "remove",    'r', AR_CMD_REMOVE,       0 },
23809     { "update",    'u', AR_CMD_UPDATE,       0 },
23810     { "help",      'h', AR_CMD_HELP,         0 },
23811     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
23812     { "file",      'f', AR_SWITCH_FILE,      1 },
23813     { "append",    'a', AR_SWITCH_APPEND,    1 },
23814     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
23815     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
23816     { "glob",      'g', AR_SWITCH_GLOB,      0 },
23817   };
23818   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
23819   struct ArSwitch *pEnd = &aSwitch[nSwitch];
23820 
23821   if( nArg<=1 ){
23822     eputz("Wrong number of arguments.  Usage:\n");
23823     return arUsage(stderr);
23824   }else{
23825     char *z = azArg[1];
23826     if( z[0]!='-' ){
23827       /* Traditional style [tar] invocation */
23828       int i;
23829       int iArg = 2;
23830       for(i=0; z[i]; i++){
23831         const char *zArg = 0;
23832         struct ArSwitch *pOpt;
23833         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23834           if( z[i]==pOpt->cShort ) break;
23835         }
23836         if( pOpt==pEnd ){
23837           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23838         }
23839         if( pOpt->bArg ){
23840           if( iArg>=nArg ){
23841             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
23842           }
23843           zArg = azArg[iArg++];
23844         }
23845         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23846       }
23847       pAr->nArg = nArg-iArg;
23848       if( pAr->nArg>0 ){
23849         pAr->azArg = &azArg[iArg];
23850       }
23851     }else{
23852       /* Non-traditional invocation */
23853       int iArg;
23854       for(iArg=1; iArg<nArg; iArg++){
23855         int n;
23856         z = azArg[iArg];
23857         if( z[0]!='-' ){
23858           /* All remaining command line words are command arguments. */
23859           pAr->azArg = &azArg[iArg];
23860           pAr->nArg = nArg-iArg;
23861           break;
23862         }
23863         n = strlen30(z);
23864 
23865         if( z[1]!='-' ){
23866           int i;
23867           /* One or more short options */
23868           for(i=1; i<n; i++){
23869             const char *zArg = 0;
23870             struct ArSwitch *pOpt;
23871             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23872               if( z[i]==pOpt->cShort ) break;
23873             }
23874             if( pOpt==pEnd ){
23875               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23876             }
23877             if( pOpt->bArg ){
23878               if( i<(n-1) ){
23879                 zArg = &z[i+1];
23880                 i = n;
23881               }else{
23882                 if( iArg>=(nArg-1) ){
23883                   return arErrorMsg(pAr, "option requires an argument: %c",
23884                                     z[i]);
23885                 }
23886                 zArg = azArg[++iArg];
23887               }
23888             }
23889             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23890           }
23891         }else if( z[2]=='\0' ){
23892           /* A -- option, indicating that all remaining command line words
23893           ** are command arguments.  */
23894           pAr->azArg = &azArg[iArg+1];
23895           pAr->nArg = nArg-iArg-1;
23896           break;
23897         }else{
23898           /* A long option */
23899           const char *zArg = 0;             /* Argument for option, if any */
23900           struct ArSwitch *pMatch = 0;      /* Matching option */
23901           struct ArSwitch *pOpt;            /* Iterator */
23902           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23903             const char *zLong = pOpt->zLong;
23904             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
23905               if( pMatch ){
23906                 return arErrorMsg(pAr, "ambiguous option: %s",z);
23907               }else{
23908                 pMatch = pOpt;
23909               }
23910             }
23911           }
23912 
23913           if( pMatch==0 ){
23914             return arErrorMsg(pAr, "unrecognized option: %s", z);
23915           }
23916           if( pMatch->bArg ){
23917             if( iArg>=(nArg-1) ){
23918               return arErrorMsg(pAr, "option requires an argument: %s", z);
23919             }
23920             zArg = azArg[++iArg];
23921           }
23922           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
23923         }
23924       }
23925     }
23926   }
23927   if( pAr->eCmd==0 ){
23928     eputz("Required argument missing.  Usage:\n");
23929     return arUsage(stderr);
23930   }
23931   return SQLITE_OK;
23932 }
23933 
23934 /*
23935 ** This function assumes that all arguments within the ArCommand.azArg[]
23936 ** array refer to archive members, as for the --extract, --list or --remove
23937 ** commands. It checks that each of them are "present". If any specified
23938 ** file is not present in the archive, an error is printed to stderr and an
23939 ** error code returned. Otherwise, if all specified arguments are present
23940 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
23941 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
23942 ** when pAr->bGlob is true.
23943 **
23944 ** This function strips any trailing '/' characters from each argument.
23945 ** This is consistent with the way the [tar] command seems to work on
23946 ** Linux.
23947 */
arCheckEntries(ArCommand * pAr)23948 static int arCheckEntries(ArCommand *pAr){
23949   int rc = SQLITE_OK;
23950   if( pAr->nArg ){
23951     int i, j;
23952     sqlite3_stmt *pTest = 0;
23953     const char *zSel = (pAr->bGlob)
23954       ? "SELECT name FROM %s WHERE glob($name,name)"
23955       : "SELECT name FROM %s WHERE name=$name";
23956 
23957     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
23958     j = sqlite3_bind_parameter_index(pTest, "$name");
23959     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
23960       char *z = pAr->azArg[i];
23961       int n = strlen30(z);
23962       int bOk = 0;
23963       while( n>0 && z[n-1]=='/' ) n--;
23964       z[n] = '\0';
23965       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
23966       if( SQLITE_ROW==sqlite3_step(pTest) ){
23967         bOk = 1;
23968       }
23969       shellReset(&rc, pTest);
23970       if( rc==SQLITE_OK && bOk==0 ){
23971         eputf("not found in archive: %s\n", z);
23972         rc = SQLITE_ERROR;
23973       }
23974     }
23975     shellFinalize(&rc, pTest);
23976   }
23977   return rc;
23978 }
23979 
23980 /*
23981 ** Format a WHERE clause that can be used against the "sqlar" table to
23982 ** identify all archive members that match the command arguments held
23983 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
23984 ** The caller is responsible for eventually calling sqlite3_free() on
23985 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
23986 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
23987 */
arWhereClause(int * pRc,ArCommand * pAr,char ** pzWhere)23988 static void arWhereClause(
23989   int *pRc,
23990   ArCommand *pAr,
23991   char **pzWhere                  /* OUT: New WHERE clause */
23992 ){
23993   char *zWhere = 0;
23994   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
23995   if( *pRc==SQLITE_OK ){
23996     if( pAr->nArg==0 ){
23997       zWhere = sqlite3_mprintf("1");
23998     }else{
23999       int i;
24000       const char *zSep = "";
24001       for(i=0; i<pAr->nArg; i++){
24002         const char *z = pAr->azArg[i];
24003         zWhere = sqlite3_mprintf(
24004           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
24005           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
24006         );
24007         if( zWhere==0 ){
24008           *pRc = SQLITE_NOMEM;
24009           break;
24010         }
24011         zSep = " OR ";
24012       }
24013     }
24014   }
24015   *pzWhere = zWhere;
24016 }
24017 
24018 /*
24019 ** Implementation of .ar "lisT" command.
24020 */
arListCommand(ArCommand * pAr)24021 static int arListCommand(ArCommand *pAr){
24022   const char *zSql = "SELECT %s FROM %s WHERE %s";
24023   const char *azCols[] = {
24024     "name",
24025     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
24026   };
24027 
24028   char *zWhere = 0;
24029   sqlite3_stmt *pSql = 0;
24030   int rc;
24031 
24032   rc = arCheckEntries(pAr);
24033   arWhereClause(&rc, pAr, &zWhere);
24034 
24035   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
24036                      pAr->zSrcTable, zWhere);
24037   if( pAr->bDryRun ){
24038     oputf("%s\n", sqlite3_sql(pSql));
24039   }else{
24040     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
24041       if( pAr->bVerbose ){
24042         oputf("%s % 10d  %s  %s\n",
24043               sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
24044               sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
24045       }else{
24046         oputf("%s\n", sqlite3_column_text(pSql, 0));
24047       }
24048     }
24049   }
24050   shellFinalize(&rc, pSql);
24051   sqlite3_free(zWhere);
24052   return rc;
24053 }
24054 
24055 /*
24056 ** Implementation of .ar "Remove" command.
24057 */
arRemoveCommand(ArCommand * pAr)24058 static int arRemoveCommand(ArCommand *pAr){
24059   int rc = 0;
24060   char *zSql = 0;
24061   char *zWhere = 0;
24062 
24063   if( pAr->nArg ){
24064     /* Verify that args actually exist within the archive before proceeding.
24065     ** And formulate a WHERE clause to match them.  */
24066     rc = arCheckEntries(pAr);
24067     arWhereClause(&rc, pAr, &zWhere);
24068   }
24069   if( rc==SQLITE_OK ){
24070     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
24071                            pAr->zSrcTable, zWhere);
24072     if( pAr->bDryRun ){
24073       oputf("%s\n", zSql);
24074     }else{
24075       char *zErr = 0;
24076       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
24077       if( rc==SQLITE_OK ){
24078         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
24079         if( rc!=SQLITE_OK ){
24080           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
24081         }else{
24082           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
24083         }
24084       }
24085       if( zErr ){
24086         sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
24087         sqlite3_free(zErr);
24088       }
24089     }
24090   }
24091   sqlite3_free(zWhere);
24092   sqlite3_free(zSql);
24093   return rc;
24094 }
24095 
24096 /*
24097 ** Implementation of .ar "eXtract" command.
24098 */
arExtractCommand(ArCommand * pAr)24099 static int arExtractCommand(ArCommand *pAr){
24100   const char *zSql1 =
24101     "SELECT "
24102     " ($dir || name),"
24103     " writefile(($dir || name), %s, mode, mtime) "
24104     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
24105     " AND name NOT GLOB '*..[/\\]*'";
24106 
24107   const char *azExtraArg[] = {
24108     "sqlar_uncompress(data, sz)",
24109     "data"
24110   };
24111 
24112   sqlite3_stmt *pSql = 0;
24113   int rc = SQLITE_OK;
24114   char *zDir = 0;
24115   char *zWhere = 0;
24116   int i, j;
24117 
24118   /* If arguments are specified, check that they actually exist within
24119   ** the archive before proceeding. And formulate a WHERE clause to
24120   ** match them.  */
24121   rc = arCheckEntries(pAr);
24122   arWhereClause(&rc, pAr, &zWhere);
24123 
24124   if( rc==SQLITE_OK ){
24125     if( pAr->zDir ){
24126       zDir = sqlite3_mprintf("%s/", pAr->zDir);
24127     }else{
24128       zDir = sqlite3_mprintf("");
24129     }
24130     if( zDir==0 ) rc = SQLITE_NOMEM;
24131   }
24132 
24133   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
24134       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
24135   );
24136 
24137   if( rc==SQLITE_OK ){
24138     j = sqlite3_bind_parameter_index(pSql, "$dir");
24139     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
24140 
24141     /* Run the SELECT statement twice. The first time, writefile() is called
24142     ** for all archive members that should be extracted. The second time,
24143     ** only for the directories. This is because the timestamps for
24144     ** extracted directories must be reset after they are populated (as
24145     ** populating them changes the timestamp).  */
24146     for(i=0; i<2; i++){
24147       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
24148       sqlite3_bind_int(pSql, j, i);
24149       if( pAr->bDryRun ){
24150         oputf("%s\n", sqlite3_sql(pSql));
24151       }else{
24152         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
24153           if( i==0 && pAr->bVerbose ){
24154             oputf("%s\n", sqlite3_column_text(pSql, 0));
24155           }
24156         }
24157       }
24158       shellReset(&rc, pSql);
24159     }
24160     shellFinalize(&rc, pSql);
24161   }
24162 
24163   sqlite3_free(zDir);
24164   sqlite3_free(zWhere);
24165   return rc;
24166 }
24167 
24168 /*
24169 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
24170 */
arExecSql(ArCommand * pAr,const char * zSql)24171 static int arExecSql(ArCommand *pAr, const char *zSql){
24172   int rc;
24173   if( pAr->bDryRun ){
24174     oputf("%s\n", zSql);
24175     rc = SQLITE_OK;
24176   }else{
24177     char *zErr = 0;
24178     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
24179     if( zErr ){
24180       sputf(stdout, "ERROR: %s\n", zErr);
24181       sqlite3_free(zErr);
24182     }
24183   }
24184   return rc;
24185 }
24186 
24187 
24188 /*
24189 ** Implementation of .ar "create", "insert", and "update" commands.
24190 **
24191 **     create    ->     Create a new SQL archive
24192 **     insert    ->     Insert or reinsert all files listed
24193 **     update    ->     Insert files that have changed or that were not
24194 **                      previously in the archive
24195 **
24196 ** Create the "sqlar" table in the database if it does not already exist.
24197 ** Then add each file in the azFile[] array to the archive. Directories
24198 ** are added recursively. If argument bVerbose is non-zero, a message is
24199 ** printed on stdout for each file archived.
24200 **
24201 ** The create command is the same as update, except that it drops
24202 ** any existing "sqlar" table before beginning.  The "insert" command
24203 ** always overwrites every file named on the command-line, where as
24204 ** "update" only overwrites if the size or mtime or mode has changed.
24205 */
arCreateOrUpdateCommand(ArCommand * pAr,int bUpdate,int bOnlyIfChanged)24206 static int arCreateOrUpdateCommand(
24207   ArCommand *pAr,                 /* Command arguments and options */
24208   int bUpdate,                    /* true for a --create. */
24209   int bOnlyIfChanged              /* Only update if file has changed */
24210 ){
24211   const char *zCreate =
24212       "CREATE TABLE IF NOT EXISTS sqlar(\n"
24213       "  name TEXT PRIMARY KEY,  -- name of the file\n"
24214       "  mode INT,               -- access permissions\n"
24215       "  mtime INT,              -- last modification time\n"
24216       "  sz INT,                 -- original file size\n"
24217       "  data BLOB               -- compressed content\n"
24218       ")";
24219   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
24220   const char *zInsertFmt[2] = {
24221      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
24222      "  SELECT\n"
24223      "    %s,\n"
24224      "    mode,\n"
24225      "    mtime,\n"
24226      "    CASE substr(lsmode(mode),1,1)\n"
24227      "      WHEN '-' THEN length(data)\n"
24228      "      WHEN 'd' THEN 0\n"
24229      "      ELSE -1 END,\n"
24230      "    sqlar_compress(data)\n"
24231      "  FROM fsdir(%Q,%Q) AS disk\n"
24232      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
24233      ,
24234      "REPLACE INTO %s(name,mode,mtime,data)\n"
24235      "  SELECT\n"
24236      "    %s,\n"
24237      "    mode,\n"
24238      "    mtime,\n"
24239      "    data\n"
24240      "  FROM fsdir(%Q,%Q) AS disk\n"
24241      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
24242   };
24243   int i;                          /* For iterating through azFile[] */
24244   int rc;                         /* Return code */
24245   const char *zTab = 0;           /* SQL table into which to insert */
24246   char *zSql;
24247   char zTemp[50];
24248   char *zExists = 0;
24249 
24250   arExecSql(pAr, "PRAGMA page_size=512");
24251   rc = arExecSql(pAr, "SAVEPOINT ar;");
24252   if( rc!=SQLITE_OK ) return rc;
24253   zTemp[0] = 0;
24254   if( pAr->bZip ){
24255     /* Initialize the zipfile virtual table, if necessary */
24256     if( pAr->zFile ){
24257       sqlite3_uint64 r;
24258       sqlite3_randomness(sizeof(r),&r);
24259       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
24260       zTab = zTemp;
24261       zSql = sqlite3_mprintf(
24262          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
24263          zTab, pAr->zFile
24264       );
24265       rc = arExecSql(pAr, zSql);
24266       sqlite3_free(zSql);
24267     }else{
24268       zTab = "zip";
24269     }
24270   }else{
24271     /* Initialize the table for an SQLAR */
24272     zTab = "sqlar";
24273     if( bUpdate==0 ){
24274       rc = arExecSql(pAr, zDrop);
24275       if( rc!=SQLITE_OK ) goto end_ar_transaction;
24276     }
24277     rc = arExecSql(pAr, zCreate);
24278   }
24279   if( bOnlyIfChanged ){
24280     zExists = sqlite3_mprintf(
24281       " AND NOT EXISTS("
24282           "SELECT 1 FROM %s AS mem"
24283           " WHERE mem.name=disk.name"
24284           " AND mem.mtime=disk.mtime"
24285           " AND mem.mode=disk.mode)", zTab);
24286   }else{
24287     zExists = sqlite3_mprintf("");
24288   }
24289   if( zExists==0 ) rc = SQLITE_NOMEM;
24290   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
24291     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
24292         pAr->bVerbose ? "shell_putsnl(name)" : "name",
24293         pAr->azArg[i], pAr->zDir, zExists);
24294     rc = arExecSql(pAr, zSql2);
24295     sqlite3_free(zSql2);
24296   }
24297 end_ar_transaction:
24298   if( rc!=SQLITE_OK ){
24299     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
24300   }else{
24301     rc = arExecSql(pAr, "RELEASE ar;");
24302     if( pAr->bZip && pAr->zFile ){
24303       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
24304       arExecSql(pAr, zSql);
24305       sqlite3_free(zSql);
24306     }
24307   }
24308   sqlite3_free(zExists);
24309   return rc;
24310 }
24311 
24312 /*
24313 ** Implementation of ".ar" dot command.
24314 */
arDotCommand(ShellState * pState,int fromCmdLine,char ** azArg,int nArg)24315 static int arDotCommand(
24316   ShellState *pState,          /* Current shell tool state */
24317   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
24318   char **azArg,                /* Array of arguments passed to dot command */
24319   int nArg                     /* Number of entries in azArg[] */
24320 ){
24321   ArCommand cmd;
24322   int rc;
24323   memset(&cmd, 0, sizeof(cmd));
24324   cmd.fromCmdLine = fromCmdLine;
24325   rc = arParseCommand(azArg, nArg, &cmd);
24326   if( rc==SQLITE_OK ){
24327     int eDbType = SHELL_OPEN_UNSPEC;
24328     cmd.p = pState;
24329     cmd.db = pState->db;
24330     if( cmd.zFile ){
24331       eDbType = deduceDatabaseType(cmd.zFile, 1);
24332     }else{
24333       eDbType = pState->openMode;
24334     }
24335     if( eDbType==SHELL_OPEN_ZIPFILE ){
24336       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
24337         if( cmd.zFile==0 ){
24338           cmd.zSrcTable = sqlite3_mprintf("zip");
24339         }else{
24340           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
24341         }
24342       }
24343       cmd.bZip = 1;
24344     }else if( cmd.zFile ){
24345       int flags;
24346       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
24347       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
24348            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
24349         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
24350       }else{
24351         flags = SQLITE_OPEN_READONLY;
24352       }
24353       cmd.db = 0;
24354       if( cmd.bDryRun ){
24355         oputf("-- open database '%s'%s\n", cmd.zFile,
24356               eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
24357       }
24358       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
24359              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
24360       if( rc!=SQLITE_OK ){
24361         eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
24362         goto end_ar_command;
24363       }
24364       sqlite3_fileio_init(cmd.db, 0, 0);
24365       sqlite3_sqlar_init(cmd.db, 0, 0);
24366       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
24367                               shellPutsFunc, 0, 0);
24368 
24369     }
24370     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
24371       if( cmd.eCmd!=AR_CMD_CREATE
24372        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
24373       ){
24374         eputz("database does not contain an 'sqlar' table\n");
24375         rc = SQLITE_ERROR;
24376         goto end_ar_command;
24377       }
24378       cmd.zSrcTable = sqlite3_mprintf("sqlar");
24379     }
24380 
24381     switch( cmd.eCmd ){
24382       case AR_CMD_CREATE:
24383         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
24384         break;
24385 
24386       case AR_CMD_EXTRACT:
24387         rc = arExtractCommand(&cmd);
24388         break;
24389 
24390       case AR_CMD_LIST:
24391         rc = arListCommand(&cmd);
24392         break;
24393 
24394       case AR_CMD_HELP:
24395         arUsage(pState->out);
24396         break;
24397 
24398       case AR_CMD_INSERT:
24399         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
24400         break;
24401 
24402       case AR_CMD_REMOVE:
24403         rc = arRemoveCommand(&cmd);
24404         break;
24405 
24406       default:
24407         assert( cmd.eCmd==AR_CMD_UPDATE );
24408         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
24409         break;
24410     }
24411   }
24412 end_ar_command:
24413   if( cmd.db!=pState->db ){
24414     close_db(cmd.db);
24415   }
24416   sqlite3_free(cmd.zSrcTable);
24417 
24418   return rc;
24419 }
24420 /* End of the ".archive" or ".ar" command logic
24421 *******************************************************************************/
24422 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
24423 
24424 #if SQLITE_SHELL_HAVE_RECOVER
24425 
24426 /*
24427 ** This function is used as a callback by the recover extension. Simply
24428 ** print the supplied SQL statement to stdout.
24429 */
recoverSqlCb(void * pCtx,const char * zSql)24430 static int recoverSqlCb(void *pCtx, const char *zSql){
24431   ShellState *pState = (ShellState*)pCtx;
24432   sputf(pState->out, "%s;\n", zSql);
24433   return SQLITE_OK;
24434 }
24435 
24436 /*
24437 ** This function is called to recover data from the database. A script
24438 ** to construct a new database containing all recovered data is output
24439 ** on stream pState->out.
24440 */
recoverDatabaseCmd(ShellState * pState,int nArg,char ** azArg)24441 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
24442   int rc = SQLITE_OK;
24443   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
24444   const char *zLAF = "lost_and_found";
24445   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
24446   int bRowids = 1;                /* 0 if --no-rowids */
24447   sqlite3_recover *p = 0;
24448   int i = 0;
24449 
24450   for(i=1; i<nArg; i++){
24451     char *z = azArg[i];
24452     int n;
24453     if( z[0]=='-' && z[1]=='-' ) z++;
24454     n = strlen30(z);
24455     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
24456       bFreelist = 0;
24457     }else
24458     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
24459       /* This option determines the name of the ATTACH-ed database used
24460       ** internally by the recovery extension.  The default is "" which
24461       ** means to use a temporary database that is automatically deleted
24462       ** when closed.  This option is undocumented and might disappear at
24463       ** any moment. */
24464       i++;
24465       zRecoveryDb = azArg[i];
24466     }else
24467     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
24468       i++;
24469       zLAF = azArg[i];
24470     }else
24471     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
24472       bRowids = 0;
24473     }
24474     else{
24475       eputf("unexpected option: %s\n", azArg[i]);
24476       showHelp(pState->out, azArg[0]);
24477       return 1;
24478     }
24479   }
24480 
24481   p = sqlite3_recover_init_sql(
24482       pState->db, "main", recoverSqlCb, (void*)pState
24483   );
24484 
24485   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
24486   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
24487   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
24488   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
24489 
24490   sqlite3_recover_run(p);
24491   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
24492     const char *zErr = sqlite3_recover_errmsg(p);
24493     int errCode = sqlite3_recover_errcode(p);
24494     eputf("sql error: %s (%d)\n", zErr, errCode);
24495   }
24496   rc = sqlite3_recover_finish(p);
24497   return rc;
24498 }
24499 #endif /* SQLITE_SHELL_HAVE_RECOVER */
24500 
24501 
24502 /*
24503  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
24504  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
24505  *   close db and set it to 0, and return the columns spec, to later
24506  *   be sqlite3_free()'ed by the caller.
24507  * The return is 0 when either:
24508  *   (a) The db was not initialized and zCol==0 (There are no columns.)
24509  *   (b) zCol!=0  (Column was added, db initialized as needed.)
24510  * The 3rd argument, pRenamed, references an out parameter. If the
24511  * pointer is non-zero, its referent will be set to a summary of renames
24512  * done if renaming was necessary, or set to 0 if none was done. The out
24513  * string (if any) must be sqlite3_free()'ed by the caller.
24514  */
24515 #ifdef SHELL_DEBUG
24516 #define rc_err_oom_die(rc) \
24517   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
24518   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
24519     eputf("E:%d\n",rc), assert(0)
24520 #else
rc_err_oom_die(int rc)24521 static void rc_err_oom_die(int rc){
24522   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
24523   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
24524 }
24525 #endif
24526 
24527 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
24528 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
24529 #else  /* Otherwise, memory is faster/better for the transient DB. */
24530 static const char *zCOL_DB = ":memory:";
24531 #endif
24532 
24533 /* Define character (as C string) to separate generated column ordinal
24534  * from protected part of incoming column names. This defaults to "_"
24535  * so that incoming column identifiers that did not need not be quoted
24536  * remain usable without being quoted. It must be one character.
24537  */
24538 #ifndef SHELL_AUTOCOLUMN_SEP
24539 # define AUTOCOLUMN_SEP "_"
24540 #else
24541 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
24542 #endif
24543 
zAutoColumn(const char * zColNew,sqlite3 ** pDb,char ** pzRenamed)24544 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
24545   /* Queries and D{D,M}L used here */
24546   static const char * const zTabMake = "\
24547 CREATE TABLE ColNames(\
24548  cpos INTEGER PRIMARY KEY,\
24549  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
24550 CREATE VIEW RepeatedNames AS \
24551 SELECT DISTINCT t.name FROM ColNames t \
24552 WHERE t.name COLLATE NOCASE IN (\
24553  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
24554 );\
24555 ";
24556   static const char * const zTabFill = "\
24557 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
24558  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
24559 ";
24560   static const char * const zHasDupes = "\
24561 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
24562  <count(name) FROM ColNames\
24563 ";
24564 #ifdef SHELL_COLUMN_RENAME_CLEAN
24565   static const char * const zDedoctor = "\
24566 UPDATE ColNames SET chop=iif(\
24567   (substring(name,nlen,1) BETWEEN '0' AND '9')\
24568   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
24569  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
24570  0\
24571 )\
24572 ";
24573 #endif
24574   static const char * const zSetReps = "\
24575 UPDATE ColNames AS t SET reps=\
24576 (SELECT count(*) FROM ColNames d \
24577  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
24578  COLLATE NOCASE\
24579 )\
24580 ";
24581 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
24582   static const char * const zColDigits = "\
24583 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
24584 ";
24585 #else
24586   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
24587   static const char * const zColDigits = "\
24588 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
24589  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
24590  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
24591 ";
24592 #endif
24593   static const char * const zRenameRank =
24594 #ifdef SHELL_COLUMN_RENAME_CLEAN
24595     "UPDATE ColNames AS t SET suff="
24596     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
24597 #else /* ...RENAME_MINIMAL_ONE_PASS */
24598 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
24599 "  SELECT 0 AS nlz"
24600 "  UNION"
24601 "  SELECT nlz+1 AS nlz FROM Lzn"
24602 "  WHERE EXISTS("
24603 "   SELECT 1"
24604 "   FROM ColNames t, ColNames o"
24605 "   WHERE"
24606 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
24607 "     printf('%s"AUTOCOLUMN_SEP"%s',"
24608 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
24609 "     t.name"
24610 "    )"
24611 "    ="
24612 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
24613 "     printf('%s"AUTOCOLUMN_SEP"%s',"
24614 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
24615 "     o.name"
24616 "    )"
24617 "    COLLATE NOCASE"
24618 "    AND o.cpos<>t.cpos"
24619 "   GROUP BY t.cpos"
24620 "  )"
24621 ") UPDATE Colnames AS t SET"
24622 " chop = 0," /* No chopping, never touch incoming names. */
24623 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
24624 "  printf('"AUTOCOLUMN_SEP"%s', substring("
24625 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
24626 "  ''"
24627 " )"
24628 #endif
24629     ;
24630   static const char * const zCollectVar = "\
24631 SELECT\
24632  '('||x'0a'\
24633  || group_concat(\
24634   cname||' TEXT',\
24635   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
24636  ||')' AS ColsSpec \
24637 FROM (\
24638  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
24639  FROM ColNames ORDER BY cpos\
24640 )";
24641   static const char * const zRenamesDone =
24642     "SELECT group_concat("
24643     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
24644     " ','||x'0a')"
24645     "FROM ColNames WHERE suff<>'' OR chop!=0"
24646     ;
24647   int rc;
24648   sqlite3_stmt *pStmt = 0;
24649   assert(pDb!=0);
24650   if( zColNew ){
24651     /* Add initial or additional column. Init db if necessary. */
24652     if( *pDb==0 ){
24653       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
24654 #ifdef SHELL_COLFIX_DB
24655       if(*zCOL_DB!=':')
24656         sqlite3_exec(*pDb,"drop table if exists ColNames;"
24657                      "drop view if exists RepeatedNames;",0,0,0);
24658 #endif
24659 #undef SHELL_COLFIX_DB
24660       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
24661       rc_err_oom_die(rc);
24662     }
24663     assert(*pDb!=0);
24664     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
24665     rc_err_oom_die(rc);
24666     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
24667     rc_err_oom_die(rc);
24668     rc = sqlite3_step(pStmt);
24669     rc_err_oom_die(rc);
24670     sqlite3_finalize(pStmt);
24671     return 0;
24672   }else if( *pDb==0 ){
24673     return 0;
24674   }else{
24675     /* Formulate the columns spec, close the DB, zero *pDb. */
24676     char *zColsSpec = 0;
24677     int hasDupes = db_int(*pDb, zHasDupes);
24678     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
24679     if( hasDupes ){
24680 #ifdef SHELL_COLUMN_RENAME_CLEAN
24681       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
24682       rc_err_oom_die(rc);
24683 #endif
24684       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
24685       rc_err_oom_die(rc);
24686       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
24687       rc_err_oom_die(rc);
24688       sqlite3_bind_int(pStmt, 1, nDigits);
24689       rc = sqlite3_step(pStmt);
24690       sqlite3_finalize(pStmt);
24691       if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
24692     }
24693     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
24694     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
24695     rc_err_oom_die(rc);
24696     rc = sqlite3_step(pStmt);
24697     if( rc==SQLITE_ROW ){
24698       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
24699     }else{
24700       zColsSpec = 0;
24701     }
24702     if( pzRenamed!=0 ){
24703       if( !hasDupes ) *pzRenamed = 0;
24704       else{
24705         sqlite3_finalize(pStmt);
24706         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
24707             && SQLITE_ROW==sqlite3_step(pStmt) ){
24708           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
24709         }else
24710           *pzRenamed = 0;
24711       }
24712     }
24713     sqlite3_finalize(pStmt);
24714     sqlite3_close(*pDb);
24715     *pDb = 0;
24716     return zColsSpec;
24717   }
24718 }
24719 
24720 /*
24721 ** If an input line begins with "." then invoke this routine to
24722 ** process that line.
24723 **
24724 ** Return 1 on error, 2 to exit, and 0 otherwise.
24725 */
do_meta_command(char * zLine,ShellState * p)24726 static int do_meta_command(char *zLine, ShellState *p){
24727   int h = 1;
24728   int nArg = 0;
24729   int n, c;
24730   int rc = 0;
24731   char *azArg[52];
24732 
24733 #ifndef SQLITE_OMIT_VIRTUALTABLE
24734   if( p->expert.pExpert ){
24735     expertFinish(p, 1, 0);
24736   }
24737 #endif
24738 
24739   /* Parse the input line into tokens.
24740   */
24741   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
24742     while( IsSpace(zLine[h]) ){ h++; }
24743     if( zLine[h]==0 ) break;
24744     if( zLine[h]=='\'' || zLine[h]=='"' ){
24745       int delim = zLine[h++];
24746       azArg[nArg++] = &zLine[h];
24747       while( zLine[h] && zLine[h]!=delim ){
24748         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
24749         h++;
24750       }
24751       if( zLine[h]==delim ){
24752         zLine[h++] = 0;
24753       }
24754       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
24755     }else{
24756       azArg[nArg++] = &zLine[h];
24757       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
24758       if( zLine[h] ) zLine[h++] = 0;
24759     }
24760   }
24761   azArg[nArg] = 0;
24762 
24763   /* Process the input line.
24764   */
24765   if( nArg==0 ) return 0; /* no tokens, no error */
24766   n = strlen30(azArg[0]);
24767   c = azArg[0][0];
24768   clearTempFile(p);
24769 
24770 #ifndef SQLITE_OMIT_AUTHORIZATION
24771   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
24772     if( nArg!=2 ){
24773       eputz("Usage: .auth ON|OFF\n");
24774       rc = 1;
24775       goto meta_command_exit;
24776     }
24777     open_db(p, 0);
24778     if( booleanValue(azArg[1]) ){
24779       sqlite3_set_authorizer(p->db, shellAuth, p);
24780     }else if( p->bSafeModePersist ){
24781       sqlite3_set_authorizer(p->db, safeModeAuth, p);
24782     }else{
24783       sqlite3_set_authorizer(p->db, 0, 0);
24784     }
24785   }else
24786 #endif
24787 
24788 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
24789   && !defined(SQLITE_SHELL_FIDDLE)
24790   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
24791     open_db(p, 0);
24792     failIfSafeMode(p, "cannot run .archive in safe mode");
24793     rc = arDotCommand(p, 0, azArg, nArg);
24794   }else
24795 #endif
24796 
24797 #ifndef SQLITE_SHELL_FIDDLE
24798   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
24799    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
24800   ){
24801     const char *zDestFile = 0;
24802     const char *zDb = 0;
24803     sqlite3 *pDest;
24804     sqlite3_backup *pBackup;
24805     int j;
24806     int bAsync = 0;
24807     const char *zVfs = 0;
24808     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
24809     for(j=1; j<nArg; j++){
24810       const char *z = azArg[j];
24811       if( z[0]=='-' ){
24812         if( z[1]=='-' ) z++;
24813         if( cli_strcmp(z, "-append")==0 ){
24814           zVfs = "apndvfs";
24815         }else
24816         if( cli_strcmp(z, "-async")==0 ){
24817           bAsync = 1;
24818         }else
24819         {
24820           eputf("unknown option: %s\n", azArg[j]);
24821           return 1;
24822         }
24823       }else if( zDestFile==0 ){
24824         zDestFile = azArg[j];
24825       }else if( zDb==0 ){
24826         zDb = zDestFile;
24827         zDestFile = azArg[j];
24828       }else{
24829         eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
24830         return 1;
24831       }
24832     }
24833     if( zDestFile==0 ){
24834       eputz("missing FILENAME argument on .backup\n");
24835       return 1;
24836     }
24837     if( zDb==0 ) zDb = "main";
24838     rc = sqlite3_open_v2(zDestFile, &pDest,
24839                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
24840     if( rc!=SQLITE_OK ){
24841       eputf("Error: cannot open \"%s\"\n", zDestFile);
24842       close_db(pDest);
24843       return 1;
24844     }
24845     if( bAsync ){
24846       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
24847                    0, 0, 0);
24848     }
24849     open_db(p, 0);
24850     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
24851     if( pBackup==0 ){
24852       eputf("Error: %s\n", sqlite3_errmsg(pDest));
24853       close_db(pDest);
24854       return 1;
24855     }
24856     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
24857     sqlite3_backup_finish(pBackup);
24858     if( rc==SQLITE_DONE ){
24859       rc = 0;
24860     }else{
24861       eputf("Error: %s\n", sqlite3_errmsg(pDest));
24862       rc = 1;
24863     }
24864     close_db(pDest);
24865   }else
24866 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24867 
24868   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
24869     if( nArg==2 ){
24870       bail_on_error = booleanValue(azArg[1]);
24871     }else{
24872       eputz("Usage: .bail on|off\n");
24873       rc = 1;
24874     }
24875   }else
24876 
24877   /* Undocumented.  Legacy only.  See "crnl" below */
24878   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
24879     if( nArg==2 ){
24880       if( booleanValue(azArg[1]) ){
24881         setBinaryMode(p->out, 1);
24882       }else{
24883         setTextMode(p->out, 1);
24884       }
24885     }else{
24886       eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
24887             "Usage: .binary on|off\n");
24888       rc = 1;
24889     }
24890   }else
24891 
24892   /* The undocumented ".breakpoint" command causes a call to the no-op
24893   ** routine named test_breakpoint().
24894   */
24895   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
24896     test_breakpoint();
24897   }else
24898 
24899 #ifndef SQLITE_SHELL_FIDDLE
24900   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
24901     failIfSafeMode(p, "cannot run .cd in safe mode");
24902     if( nArg==2 ){
24903 #if defined(_WIN32) || defined(WIN32)
24904       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
24905       rc = !SetCurrentDirectoryW(z);
24906       sqlite3_free(z);
24907 #else
24908       rc = chdir(azArg[1]);
24909 #endif
24910       if( rc ){
24911         eputf("Cannot change to directory \"%s\"\n", azArg[1]);
24912         rc = 1;
24913       }
24914     }else{
24915       eputz("Usage: .cd DIRECTORY\n");
24916       rc = 1;
24917     }
24918   }else
24919 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24920 
24921   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
24922     if( nArg==2 ){
24923       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
24924     }else{
24925       eputz("Usage: .changes on|off\n");
24926       rc = 1;
24927     }
24928   }else
24929 
24930 #ifndef SQLITE_SHELL_FIDDLE
24931   /* Cancel output redirection, if it is currently set (by .testcase)
24932   ** Then read the content of the testcase-out.txt file and compare against
24933   ** azArg[1].  If there are differences, report an error and exit.
24934   */
24935   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
24936     char *zRes = 0;
24937     output_reset(p);
24938     if( nArg!=2 ){
24939       eputz("Usage: .check GLOB-PATTERN\n");
24940       rc = 2;
24941     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
24942       rc = 2;
24943     }else if( testcase_glob(azArg[1],zRes)==0 ){
24944       eputf("testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
24945             p->zTestcase, azArg[1], zRes);
24946       rc = 1;
24947     }else{
24948       oputf("testcase-%s ok\n", p->zTestcase);
24949       p->nCheck++;
24950     }
24951     sqlite3_free(zRes);
24952   }else
24953 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24954 
24955 #ifndef SQLITE_SHELL_FIDDLE
24956   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
24957     failIfSafeMode(p, "cannot run .clone in safe mode");
24958     if( nArg==2 ){
24959       tryToClone(p, azArg[1]);
24960     }else{
24961       eputz("Usage: .clone FILENAME\n");
24962       rc = 1;
24963     }
24964   }else
24965 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24966 
24967   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
24968     if( nArg==1 ){
24969       /* List available connections */
24970       int i;
24971       for(i=0; i<ArraySize(p->aAuxDb); i++){
24972         const char *zFile = p->aAuxDb[i].zDbFilename;
24973         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
24974           zFile = "(not open)";
24975         }else if( zFile==0 ){
24976           zFile = "(memory)";
24977         }else if( zFile[0]==0 ){
24978           zFile = "(temporary-file)";
24979         }
24980         if( p->pAuxDb == &p->aAuxDb[i] ){
24981           sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
24982         }else if( p->aAuxDb[i].db!=0 ){
24983           sputf(stdout, "       %d: %s\n", i, zFile);
24984         }
24985       }
24986     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
24987       int i = azArg[1][0] - '0';
24988       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
24989         p->pAuxDb->db = p->db;
24990         p->pAuxDb = &p->aAuxDb[i];
24991         globalDb = p->db = p->pAuxDb->db;
24992         p->pAuxDb->db = 0;
24993       }
24994     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
24995            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
24996       int i = azArg[2][0] - '0';
24997       if( i<0 || i>=ArraySize(p->aAuxDb) ){
24998         /* No-op */
24999       }else if( p->pAuxDb == &p->aAuxDb[i] ){
25000         eputz("cannot close the active database connection\n");
25001         rc = 1;
25002       }else if( p->aAuxDb[i].db ){
25003         session_close_all(p, i);
25004         close_db(p->aAuxDb[i].db);
25005         p->aAuxDb[i].db = 0;
25006       }
25007     }else{
25008       eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
25009       rc = 1;
25010     }
25011   }else
25012 
25013   if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
25014     if( nArg==2 ){
25015       if( booleanValue(azArg[1]) ){
25016         setTextMode(p->out, 1);
25017       }else{
25018         setBinaryMode(p->out, 1);
25019       }
25020     }else{
25021 #if !defined(_WIN32) && !defined(WIN32)
25022       eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
25023 #endif
25024       eputz("Usage: .crnl on|off\n");
25025       rc = 1;
25026     }
25027   }else
25028 
25029   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
25030     char **azName = 0;
25031     int nName = 0;
25032     sqlite3_stmt *pStmt;
25033     int i;
25034     open_db(p, 0);
25035     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
25036     if( rc ){
25037       eputf("Error: %s\n", sqlite3_errmsg(p->db));
25038       rc = 1;
25039     }else{
25040       while( sqlite3_step(pStmt)==SQLITE_ROW ){
25041         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
25042         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
25043         if( zSchema==0 || zFile==0 ) continue;
25044         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
25045         shell_check_oom(azName);
25046         azName[nName*2] = strdup(zSchema);
25047         azName[nName*2+1] = strdup(zFile);
25048         nName++;
25049       }
25050     }
25051     sqlite3_finalize(pStmt);
25052     for(i=0; i<nName; i++){
25053       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
25054       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
25055       const char *z = azName[i*2+1];
25056       oputf("%s: %s %s%s\n",
25057             azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
25058             eTxn==SQLITE_TXN_NONE ? "" :
25059             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
25060       free(azName[i*2]);
25061       free(azName[i*2+1]);
25062     }
25063     sqlite3_free(azName);
25064   }else
25065 
25066   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
25067     static const struct DbConfigChoices {
25068       const char *zName;
25069       int op;
25070     } aDbConfig[] = {
25071         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
25072         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
25073         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
25074         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
25075         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
25076         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
25077         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
25078         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
25079         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
25080         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
25081         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
25082         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
25083         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
25084         { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
25085         { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
25086         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
25087         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
25088         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
25089     };
25090     int ii, v;
25091     open_db(p, 0);
25092     for(ii=0; ii<ArraySize(aDbConfig); ii++){
25093       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
25094       if( nArg>=3 ){
25095         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
25096       }
25097       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
25098       oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
25099       if( nArg>1 ) break;
25100     }
25101     if( nArg>1 && ii==ArraySize(aDbConfig) ){
25102       eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
25103       eputz("Enter \".dbconfig\" with no arguments for a list\n");
25104     }
25105   }else
25106 
25107 #if SQLITE_SHELL_HAVE_RECOVER
25108   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
25109     rc = shell_dbinfo_command(p, nArg, azArg);
25110   }else
25111 
25112   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
25113     open_db(p, 0);
25114     rc = recoverDatabaseCmd(p, nArg, azArg);
25115   }else
25116 #endif /* SQLITE_SHELL_HAVE_RECOVER */
25117 
25118   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
25119     char *zLike = 0;
25120     char *zSql;
25121     int i;
25122     int savedShowHeader = p->showHeader;
25123     int savedShellFlags = p->shellFlgs;
25124     ShellClearFlag(p,
25125        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
25126        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
25127     for(i=1; i<nArg; i++){
25128       if( azArg[i][0]=='-' ){
25129         const char *z = azArg[i]+1;
25130         if( z[0]=='-' ) z++;
25131         if( cli_strcmp(z,"preserve-rowids")==0 ){
25132 #ifdef SQLITE_OMIT_VIRTUALTABLE
25133           eputz("The --preserve-rowids option is not compatible"
25134                 " with SQLITE_OMIT_VIRTUALTABLE\n");
25135           rc = 1;
25136           sqlite3_free(zLike);
25137           goto meta_command_exit;
25138 #else
25139           ShellSetFlag(p, SHFLG_PreserveRowid);
25140 #endif
25141         }else
25142         if( cli_strcmp(z,"newlines")==0 ){
25143           ShellSetFlag(p, SHFLG_Newlines);
25144         }else
25145         if( cli_strcmp(z,"data-only")==0 ){
25146           ShellSetFlag(p, SHFLG_DumpDataOnly);
25147         }else
25148         if( cli_strcmp(z,"nosys")==0 ){
25149           ShellSetFlag(p, SHFLG_DumpNoSys);
25150         }else
25151         {
25152           eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
25153           rc = 1;
25154           sqlite3_free(zLike);
25155           goto meta_command_exit;
25156         }
25157       }else{
25158         /* azArg[i] contains a LIKE pattern. This ".dump" request should
25159         ** only dump data for tables for which either the table name matches
25160         ** the LIKE pattern, or the table appears to be a shadow table of
25161         ** a virtual table for which the name matches the LIKE pattern.
25162         */
25163         char *zExpr = sqlite3_mprintf(
25164             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
25165             "  SELECT 1 FROM sqlite_schema WHERE "
25166             "    name LIKE %Q ESCAPE '\\' AND"
25167             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
25168             "    substr(o.name, 1, length(name)+1) == (name||'_')"
25169             ")", azArg[i], azArg[i]
25170         );
25171 
25172         if( zLike ){
25173           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
25174         }else{
25175           zLike = zExpr;
25176         }
25177       }
25178     }
25179 
25180     open_db(p, 0);
25181 
25182     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25183       /* When playing back a "dump", the content might appear in an order
25184       ** which causes immediate foreign key constraints to be violated.
25185       ** So disable foreign-key constraint enforcement to prevent problems. */
25186       oputz("PRAGMA foreign_keys=OFF;\n");
25187       oputz("BEGIN TRANSACTION;\n");
25188     }
25189     p->writableSchema = 0;
25190     p->showHeader = 0;
25191     /* Set writable_schema=ON since doing so forces SQLite to initialize
25192     ** as much of the schema as it can even if the sqlite_schema table is
25193     ** corrupt. */
25194     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
25195     p->nErr = 0;
25196     if( zLike==0 ) zLike = sqlite3_mprintf("true");
25197     zSql = sqlite3_mprintf(
25198       "SELECT name, type, sql FROM sqlite_schema AS o "
25199       "WHERE (%s) AND type=='table'"
25200       "  AND sql NOT NULL"
25201       " ORDER BY tbl_name='sqlite_sequence', rowid",
25202       zLike
25203     );
25204     run_schema_dump_query(p,zSql);
25205     sqlite3_free(zSql);
25206     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25207       zSql = sqlite3_mprintf(
25208         "SELECT sql FROM sqlite_schema AS o "
25209         "WHERE (%s) AND sql NOT NULL"
25210         "  AND type IN ('index','trigger','view')",
25211         zLike
25212       );
25213       run_table_dump_query(p, zSql);
25214       sqlite3_free(zSql);
25215     }
25216     sqlite3_free(zLike);
25217     if( p->writableSchema ){
25218       oputz("PRAGMA writable_schema=OFF;\n");
25219       p->writableSchema = 0;
25220     }
25221     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
25222     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
25223     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25224       oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
25225     }
25226     p->showHeader = savedShowHeader;
25227     p->shellFlgs = savedShellFlags;
25228   }else
25229 
25230   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
25231     if( nArg==2 ){
25232       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
25233     }else{
25234       eputz("Usage: .echo on|off\n");
25235       rc = 1;
25236     }
25237   }else
25238 
25239   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
25240     if( nArg==2 ){
25241       p->autoEQPtest = 0;
25242       if( p->autoEQPtrace ){
25243         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
25244         p->autoEQPtrace = 0;
25245       }
25246       if( cli_strcmp(azArg[1],"full")==0 ){
25247         p->autoEQP = AUTOEQP_full;
25248       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
25249         p->autoEQP = AUTOEQP_trigger;
25250 #ifdef SQLITE_DEBUG
25251       }else if( cli_strcmp(azArg[1],"test")==0 ){
25252         p->autoEQP = AUTOEQP_on;
25253         p->autoEQPtest = 1;
25254       }else if( cli_strcmp(azArg[1],"trace")==0 ){
25255         p->autoEQP = AUTOEQP_full;
25256         p->autoEQPtrace = 1;
25257         open_db(p, 0);
25258         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
25259         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
25260 #endif
25261       }else{
25262         p->autoEQP = (u8)booleanValue(azArg[1]);
25263       }
25264     }else{
25265       eputz("Usage: .eqp off|on|trace|trigger|full\n");
25266       rc = 1;
25267     }
25268   }else
25269 
25270 #ifndef SQLITE_SHELL_FIDDLE
25271   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
25272     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
25273     rc = 2;
25274   }else
25275 #endif
25276 
25277   /* The ".explain" command is automatic now.  It is largely pointless.  It
25278   ** retained purely for backwards compatibility */
25279   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
25280     int val = 1;
25281     if( nArg>=2 ){
25282       if( cli_strcmp(azArg[1],"auto")==0 ){
25283         val = 99;
25284       }else{
25285         val =  booleanValue(azArg[1]);
25286       }
25287     }
25288     if( val==1 && p->mode!=MODE_Explain ){
25289       p->normalMode = p->mode;
25290       p->mode = MODE_Explain;
25291       p->autoExplain = 0;
25292     }else if( val==0 ){
25293       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
25294       p->autoExplain = 0;
25295     }else if( val==99 ){
25296       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
25297       p->autoExplain = 1;
25298     }
25299   }else
25300 
25301 #ifndef SQLITE_OMIT_VIRTUALTABLE
25302   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
25303     if( p->bSafeMode ){
25304       eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
25305             azArg[0]);
25306       rc = 1;
25307     }else{
25308       open_db(p, 0);
25309       expertDotCommand(p, azArg, nArg);
25310     }
25311   }else
25312 #endif
25313 
25314   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
25315     static const struct {
25316        const char *zCtrlName;   /* Name of a test-control option */
25317        int ctrlCode;            /* Integer code for that option */
25318        const char *zUsage;      /* Usage notes */
25319     } aCtrl[] = {
25320       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
25321       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
25322       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
25323       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
25324       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
25325    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
25326       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
25327       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
25328       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
25329       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
25330    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
25331     };
25332     int filectrl = -1;
25333     int iCtrl = -1;
25334     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
25335     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
25336     int n2, i;
25337     const char *zCmd = 0;
25338     const char *zSchema = 0;
25339 
25340     open_db(p, 0);
25341     zCmd = nArg>=2 ? azArg[1] : "help";
25342 
25343     if( zCmd[0]=='-'
25344      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
25345      && nArg>=4
25346     ){
25347       zSchema = azArg[2];
25348       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
25349       nArg -= 2;
25350       zCmd = azArg[1];
25351     }
25352 
25353     /* The argument can optionally begin with "-" or "--" */
25354     if( zCmd[0]=='-' && zCmd[1] ){
25355       zCmd++;
25356       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
25357     }
25358 
25359     /* --help lists all file-controls */
25360     if( cli_strcmp(zCmd,"help")==0 ){
25361       oputz("Available file-controls:\n");
25362       for(i=0; i<ArraySize(aCtrl); i++){
25363         oputf("  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
25364       }
25365       rc = 1;
25366       goto meta_command_exit;
25367     }
25368 
25369     /* convert filectrl text option to value. allow any unique prefix
25370     ** of the option name, or a numerical value. */
25371     n2 = strlen30(zCmd);
25372     for(i=0; i<ArraySize(aCtrl); i++){
25373       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
25374         if( filectrl<0 ){
25375           filectrl = aCtrl[i].ctrlCode;
25376           iCtrl = i;
25377         }else{
25378           eputf("Error: ambiguous file-control: \"%s\"\n"
25379                 "Use \".filectrl --help\" for help\n", zCmd);
25380           rc = 1;
25381           goto meta_command_exit;
25382         }
25383       }
25384     }
25385     if( filectrl<0 ){
25386       eputf("Error: unknown file-control: %s\n"
25387             "Use \".filectrl --help\" for help\n", zCmd);
25388     }else{
25389       switch(filectrl){
25390         case SQLITE_FCNTL_SIZE_LIMIT: {
25391           if( nArg!=2 && nArg!=3 ) break;
25392           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
25393           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
25394           isOk = 1;
25395           break;
25396         }
25397         case SQLITE_FCNTL_LOCK_TIMEOUT:
25398         case SQLITE_FCNTL_CHUNK_SIZE: {
25399           int x;
25400           if( nArg!=3 ) break;
25401           x = (int)integerValue(azArg[2]);
25402           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25403           isOk = 2;
25404           break;
25405         }
25406         case SQLITE_FCNTL_PERSIST_WAL:
25407         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
25408           int x;
25409           if( nArg!=2 && nArg!=3 ) break;
25410           x = nArg==3 ? booleanValue(azArg[2]) : -1;
25411           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25412           iRes = x;
25413           isOk = 1;
25414           break;
25415         }
25416         case SQLITE_FCNTL_DATA_VERSION:
25417         case SQLITE_FCNTL_HAS_MOVED: {
25418           int x;
25419           if( nArg!=2 ) break;
25420           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25421           iRes = x;
25422           isOk = 1;
25423           break;
25424         }
25425         case SQLITE_FCNTL_TEMPFILENAME: {
25426           char *z = 0;
25427           if( nArg!=2 ) break;
25428           sqlite3_file_control(p->db, zSchema, filectrl, &z);
25429           if( z ){
25430             oputf("%s\n", z);
25431             sqlite3_free(z);
25432           }
25433           isOk = 2;
25434           break;
25435         }
25436         case SQLITE_FCNTL_RESERVE_BYTES: {
25437           int x;
25438           if( nArg>=3 ){
25439             x = atoi(azArg[2]);
25440             sqlite3_file_control(p->db, zSchema, filectrl, &x);
25441           }
25442           x = -1;
25443           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25444           oputf("%d\n", x);
25445           isOk = 2;
25446           break;
25447         }
25448       }
25449     }
25450     if( isOk==0 && iCtrl>=0 ){
25451       oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
25452       rc = 1;
25453     }else if( isOk==1 ){
25454       char zBuf[100];
25455       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
25456       oputf("%s\n", zBuf);
25457     }
25458   }else
25459 
25460   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
25461     ShellState data;
25462     int doStats = 0;
25463     memcpy(&data, p, sizeof(data));
25464     data.showHeader = 0;
25465     data.cMode = data.mode = MODE_Semi;
25466     if( nArg==2 && optionMatch(azArg[1], "indent") ){
25467       data.cMode = data.mode = MODE_Pretty;
25468       nArg = 1;
25469     }
25470     if( nArg!=1 ){
25471       eputz("Usage: .fullschema ?--indent?\n");
25472       rc = 1;
25473       goto meta_command_exit;
25474     }
25475     open_db(p, 0);
25476     rc = sqlite3_exec(p->db,
25477        "SELECT sql FROM"
25478        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
25479        "     FROM sqlite_schema UNION ALL"
25480        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
25481        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
25482        "ORDER BY x",
25483        callback, &data, 0
25484     );
25485     if( rc==SQLITE_OK ){
25486       sqlite3_stmt *pStmt;
25487       rc = sqlite3_prepare_v2(p->db,
25488                "SELECT rowid FROM sqlite_schema"
25489                " WHERE name GLOB 'sqlite_stat[134]'",
25490                -1, &pStmt, 0);
25491       if( rc==SQLITE_OK ){
25492         doStats = sqlite3_step(pStmt)==SQLITE_ROW;
25493         sqlite3_finalize(pStmt);
25494       }
25495     }
25496     if( doStats==0 ){
25497       oputz("/* No STAT tables available */\n");
25498     }else{
25499       oputz("ANALYZE sqlite_schema;\n");
25500       data.cMode = data.mode = MODE_Insert;
25501       data.zDestTable = "sqlite_stat1";
25502       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
25503       data.zDestTable = "sqlite_stat4";
25504       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
25505       oputz("ANALYZE sqlite_schema;\n");
25506     }
25507   }else
25508 
25509   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
25510     if( nArg==2 ){
25511       p->showHeader = booleanValue(azArg[1]);
25512       p->shellFlgs |= SHFLG_HeaderSet;
25513     }else{
25514       eputz("Usage: .headers on|off\n");
25515       rc = 1;
25516     }
25517   }else
25518 
25519   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
25520     if( nArg>=2 ){
25521       n = showHelp(p->out, azArg[1]);
25522       if( n==0 ){
25523         oputf("Nothing matches '%s'\n", azArg[1]);
25524       }
25525     }else{
25526       showHelp(p->out, 0);
25527     }
25528   }else
25529 
25530 #ifndef SQLITE_SHELL_FIDDLE
25531   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
25532     char *zTable = 0;           /* Insert data into this table */
25533     char *zSchema = 0;          /* within this schema (may default to "main") */
25534     char *zFile = 0;            /* Name of file to extra content from */
25535     sqlite3_stmt *pStmt = NULL; /* A statement */
25536     int nCol;                   /* Number of columns in the table */
25537     int nByte;                  /* Number of bytes in an SQL string */
25538     int i, j;                   /* Loop counters */
25539     int needCommit;             /* True to COMMIT or ROLLBACK at end */
25540     int nSep;                   /* Number of bytes in p->colSeparator[] */
25541     char *zSql;                 /* An SQL statement */
25542     char *zFullTabName;         /* Table name with schema if applicable */
25543     ImportCtx sCtx;             /* Reader context */
25544     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
25545     int eVerbose = 0;           /* Larger for more console output */
25546     int nSkip = 0;              /* Initial lines to skip */
25547     int useOutputMode = 1;      /* Use output mode to determine separators */
25548     char *zCreate = 0;          /* CREATE TABLE statement text */
25549 
25550     failIfSafeMode(p, "cannot run .import in safe mode");
25551     memset(&sCtx, 0, sizeof(sCtx));
25552     if( p->mode==MODE_Ascii ){
25553       xRead = ascii_read_one_field;
25554     }else{
25555       xRead = csv_read_one_field;
25556     }
25557     rc = 1;
25558     for(i=1; i<nArg; i++){
25559       char *z = azArg[i];
25560       if( z[0]=='-' && z[1]=='-' ) z++;
25561       if( z[0]!='-' ){
25562         if( zFile==0 ){
25563           zFile = z;
25564         }else if( zTable==0 ){
25565           zTable = z;
25566         }else{
25567           oputf("ERROR: extra argument: \"%s\".  Usage:\n", z);
25568           showHelp(p->out, "import");
25569           goto meta_command_exit;
25570         }
25571       }else if( cli_strcmp(z,"-v")==0 ){
25572         eVerbose++;
25573       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
25574         zSchema = azArg[++i];
25575       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
25576         nSkip = integerValue(azArg[++i]);
25577       }else if( cli_strcmp(z,"-ascii")==0 ){
25578         sCtx.cColSep = SEP_Unit[0];
25579         sCtx.cRowSep = SEP_Record[0];
25580         xRead = ascii_read_one_field;
25581         useOutputMode = 0;
25582       }else if( cli_strcmp(z,"-csv")==0 ){
25583         sCtx.cColSep = ',';
25584         sCtx.cRowSep = '\n';
25585         xRead = csv_read_one_field;
25586         useOutputMode = 0;
25587       }else{
25588         oputf("ERROR: unknown option: \"%s\".  Usage:\n", z);
25589         showHelp(p->out, "import");
25590         goto meta_command_exit;
25591       }
25592     }
25593     if( zTable==0 ){
25594       oputf("ERROR: missing %s argument. Usage:\n",
25595             zFile==0 ? "FILE" : "TABLE");
25596       showHelp(p->out, "import");
25597       goto meta_command_exit;
25598     }
25599     seenInterrupt = 0;
25600     open_db(p, 0);
25601     if( useOutputMode ){
25602       /* If neither the --csv or --ascii options are specified, then set
25603       ** the column and row separator characters from the output mode. */
25604       nSep = strlen30(p->colSeparator);
25605       if( nSep==0 ){
25606         eputz("Error: non-null column separator required for import\n");
25607         goto meta_command_exit;
25608       }
25609       if( nSep>1 ){
25610         eputz("Error: multi-character column separators not allowed"
25611               " for import\n");
25612         goto meta_command_exit;
25613       }
25614       nSep = strlen30(p->rowSeparator);
25615       if( nSep==0 ){
25616         eputz("Error: non-null row separator required for import\n");
25617         goto meta_command_exit;
25618       }
25619       if( nSep==2 && p->mode==MODE_Csv
25620        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
25621       ){
25622         /* When importing CSV (only), if the row separator is set to the
25623         ** default output row separator, change it to the default input
25624         ** row separator.  This avoids having to maintain different input
25625         ** and output row separators. */
25626         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25627         nSep = strlen30(p->rowSeparator);
25628       }
25629       if( nSep>1 ){
25630         eputz("Error: multi-character row separators not allowed"
25631               " for import\n");
25632         goto meta_command_exit;
25633       }
25634       sCtx.cColSep = (u8)p->colSeparator[0];
25635       sCtx.cRowSep = (u8)p->rowSeparator[0];
25636     }
25637     sCtx.zFile = zFile;
25638     sCtx.nLine = 1;
25639     if( sCtx.zFile[0]=='|' ){
25640 #ifdef SQLITE_OMIT_POPEN
25641       eputz("Error: pipes are not supported in this OS\n");
25642       goto meta_command_exit;
25643 #else
25644       sCtx.in = popen(sCtx.zFile+1, "r");
25645       sCtx.zFile = "<pipe>";
25646       sCtx.xCloser = pclose;
25647 #endif
25648     }else{
25649       sCtx.in = fopen(sCtx.zFile, "rb");
25650       sCtx.xCloser = fclose;
25651     }
25652     if( sCtx.in==0 ){
25653       eputf("Error: cannot open \"%s\"\n", zFile);
25654       goto meta_command_exit;
25655     }
25656     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
25657       char zSep[2];
25658       zSep[1] = 0;
25659       zSep[0] = sCtx.cColSep;
25660       oputz("Column separator ");
25661       output_c_string(zSep);
25662       oputz(", row separator ");
25663       zSep[0] = sCtx.cRowSep;
25664       output_c_string(zSep);
25665       oputz("\n");
25666     }
25667     sCtx.z = sqlite3_malloc64(120);
25668     if( sCtx.z==0 ){
25669       import_cleanup(&sCtx);
25670       shell_out_of_memory();
25671     }
25672     /* Below, resources must be freed before exit. */
25673     while( (nSkip--)>0 ){
25674       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
25675     }
25676     if( zSchema!=0 ){
25677       zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
25678     }else{
25679       zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
25680     }
25681     zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
25682     if( zSql==0 || zFullTabName==0 ){
25683       import_cleanup(&sCtx);
25684       shell_out_of_memory();
25685     }
25686     nByte = strlen30(zSql);
25687     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25688     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
25689     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
25690       sqlite3 *dbCols = 0;
25691       char *zRenames = 0;
25692       char *zColDefs;
25693       zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
25694       while( xRead(&sCtx) ){
25695         zAutoColumn(sCtx.z, &dbCols, 0);
25696         if( sCtx.cTerm!=sCtx.cColSep ) break;
25697       }
25698       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
25699       if( zRenames!=0 ){
25700         sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
25701               "Columns renamed during .import %s due to duplicates:\n"
25702               "%s\n", sCtx.zFile, zRenames);
25703         sqlite3_free(zRenames);
25704       }
25705       assert(dbCols==0);
25706       if( zColDefs==0 ){
25707         eputf("%s: empty file\n", sCtx.zFile);
25708       import_fail:
25709         sqlite3_free(zCreate);
25710         sqlite3_free(zSql);
25711         sqlite3_free(zFullTabName);
25712         import_cleanup(&sCtx);
25713         rc = 1;
25714         goto meta_command_exit;
25715       }
25716       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
25717       if( eVerbose>=1 ){
25718         oputf("%s\n", zCreate);
25719       }
25720       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
25721       if( rc ){
25722         eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
25723         goto import_fail;
25724       }
25725       sqlite3_free(zCreate);
25726       zCreate = 0;
25727       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25728     }
25729     if( rc ){
25730       if (pStmt) sqlite3_finalize(pStmt);
25731       eputf("Error: %s\n", sqlite3_errmsg(p->db));
25732       goto import_fail;
25733     }
25734     sqlite3_free(zSql);
25735     nCol = sqlite3_column_count(pStmt);
25736     sqlite3_finalize(pStmt);
25737     pStmt = 0;
25738     if( nCol==0 ) return 0; /* no columns, no error */
25739     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
25740     if( zSql==0 ){
25741       import_cleanup(&sCtx);
25742       shell_out_of_memory();
25743     }
25744     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
25745     j = strlen30(zSql);
25746     for(i=1; i<nCol; i++){
25747       zSql[j++] = ',';
25748       zSql[j++] = '?';
25749     }
25750     zSql[j++] = ')';
25751     zSql[j] = 0;
25752     if( eVerbose>=2 ){
25753       oputf("Insert using: %s\n", zSql);
25754     }
25755     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25756     if( rc ){
25757       eputf("Error: %s\n", sqlite3_errmsg(p->db));
25758       if (pStmt) sqlite3_finalize(pStmt);
25759       goto import_fail;
25760     }
25761     sqlite3_free(zSql);
25762     sqlite3_free(zFullTabName);
25763     needCommit = sqlite3_get_autocommit(p->db);
25764     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
25765     do{
25766       int startLine = sCtx.nLine;
25767       for(i=0; i<nCol; i++){
25768         char *z = xRead(&sCtx);
25769         /*
25770         ** Did we reach end-of-file before finding any columns?
25771         ** If so, stop instead of NULL filling the remaining columns.
25772         */
25773         if( z==0 && i==0 ) break;
25774         /*
25775         ** Did we reach end-of-file OR end-of-line before finding any
25776         ** columns in ASCII mode?  If so, stop instead of NULL filling
25777         ** the remaining columns.
25778         */
25779         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
25780         /*
25781         ** For CSV mode, per RFC 4180, accept EOF in lieu of final
25782         ** record terminator but only for last field of multi-field row.
25783         ** (If there are too few fields, it's not valid CSV anyway.)
25784         */
25785         if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
25786           z = "";
25787         }
25788         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
25789         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
25790           eputf("%s:%d: expected %d columns but found %d"
25791                 " - filling the rest with NULL\n",
25792                 sCtx.zFile, startLine, nCol, i+1);
25793           i += 2;
25794           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
25795         }
25796       }
25797       if( sCtx.cTerm==sCtx.cColSep ){
25798         do{
25799           xRead(&sCtx);
25800           i++;
25801         }while( sCtx.cTerm==sCtx.cColSep );
25802         eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
25803               sCtx.zFile, startLine, nCol, i);
25804       }
25805       if( i>=nCol ){
25806         sqlite3_step(pStmt);
25807         rc = sqlite3_reset(pStmt);
25808         if( rc!=SQLITE_OK ){
25809           eputf("%s:%d: INSERT failed: %s\n",
25810                 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
25811           sCtx.nErr++;
25812         }else{
25813           sCtx.nRow++;
25814         }
25815       }
25816     }while( sCtx.cTerm!=EOF );
25817 
25818     import_cleanup(&sCtx);
25819     sqlite3_finalize(pStmt);
25820     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
25821     if( eVerbose>0 ){
25822       oputf("Added %d rows with %d errors using %d lines of input\n",
25823             sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
25824     }
25825   }else
25826 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25827 
25828 #ifndef SQLITE_UNTESTABLE
25829   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
25830     char *zSql;
25831     char *zCollist = 0;
25832     sqlite3_stmt *pStmt;
25833     int tnum = 0;
25834     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
25835     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
25836     int i;
25837     if( !ShellHasFlag(p,SHFLG_TestingMode) ){
25838       eputf(".%s unavailable without --unsafe-testing\n",
25839             "imposter");
25840       rc = 1;
25841       goto meta_command_exit;
25842     }
25843     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
25844       eputz("Usage: .imposter INDEX IMPOSTER\n"
25845             "       .imposter off\n");
25846       /* Also allowed, but not documented:
25847       **
25848       **    .imposter TABLE IMPOSTER
25849       **
25850       ** where TABLE is a WITHOUT ROWID table.  In that case, the
25851       ** imposter is another WITHOUT ROWID table with the columns in
25852       ** storage order. */
25853       rc = 1;
25854       goto meta_command_exit;
25855     }
25856     open_db(p, 0);
25857     if( nArg==2 ){
25858       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
25859       goto meta_command_exit;
25860     }
25861     zSql = sqlite3_mprintf(
25862       "SELECT rootpage, 0 FROM sqlite_schema"
25863       " WHERE name='%q' AND type='index'"
25864       "UNION ALL "
25865       "SELECT rootpage, 1 FROM sqlite_schema"
25866       " WHERE name='%q' AND type='table'"
25867       "   AND sql LIKE '%%without%%rowid%%'",
25868       azArg[1], azArg[1]
25869     );
25870     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25871     sqlite3_free(zSql);
25872     if( sqlite3_step(pStmt)==SQLITE_ROW ){
25873       tnum = sqlite3_column_int(pStmt, 0);
25874       isWO = sqlite3_column_int(pStmt, 1);
25875     }
25876     sqlite3_finalize(pStmt);
25877     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
25878     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25879     sqlite3_free(zSql);
25880     i = 0;
25881     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
25882       char zLabel[20];
25883       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
25884       i++;
25885       if( zCol==0 ){
25886         if( sqlite3_column_int(pStmt,1)==-1 ){
25887           zCol = "_ROWID_";
25888         }else{
25889           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
25890           zCol = zLabel;
25891         }
25892       }
25893       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
25894         lenPK = (int)strlen(zCollist);
25895       }
25896       if( zCollist==0 ){
25897         zCollist = sqlite3_mprintf("\"%w\"", zCol);
25898       }else{
25899         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
25900       }
25901     }
25902     sqlite3_finalize(pStmt);
25903     if( i==0 || tnum==0 ){
25904       eputf("no such index: \"%s\"\n", azArg[1]);
25905       rc = 1;
25906       sqlite3_free(zCollist);
25907       goto meta_command_exit;
25908     }
25909     if( lenPK==0 ) lenPK = 100000;
25910     zSql = sqlite3_mprintf(
25911           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
25912           azArg[2], zCollist, lenPK, zCollist);
25913     sqlite3_free(zCollist);
25914     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
25915     if( rc==SQLITE_OK ){
25916       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
25917       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
25918       if( rc ){
25919         eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
25920       }else{
25921         sputf(stdout, "%s;\n", zSql);
25922         sputf(stdout, "WARNING: writing to an imposter table will corrupt"
25923               " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
25924       }
25925     }else{
25926       eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
25927       rc = 1;
25928     }
25929     sqlite3_free(zSql);
25930   }else
25931 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
25932 
25933 #ifdef SQLITE_ENABLE_IOTRACE
25934   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
25935     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
25936     if( iotrace && iotrace!=stdout ) fclose(iotrace);
25937     iotrace = 0;
25938     if( nArg<2 ){
25939       sqlite3IoTrace = 0;
25940     }else if( cli_strcmp(azArg[1], "-")==0 ){
25941       sqlite3IoTrace = iotracePrintf;
25942       iotrace = stdout;
25943     }else{
25944       iotrace = fopen(azArg[1], "w");
25945       if( iotrace==0 ){
25946         eputf("Error: cannot open \"%s\"\n", azArg[1]);
25947         sqlite3IoTrace = 0;
25948         rc = 1;
25949       }else{
25950         sqlite3IoTrace = iotracePrintf;
25951       }
25952     }
25953   }else
25954 #endif
25955 
25956   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
25957     static const struct {
25958        const char *zLimitName;   /* Name of a limit */
25959        int limitCode;            /* Integer code for that limit */
25960     } aLimit[] = {
25961       { "length",                SQLITE_LIMIT_LENGTH                    },
25962       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
25963       { "column",                SQLITE_LIMIT_COLUMN                    },
25964       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
25965       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
25966       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
25967       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
25968       { "attached",              SQLITE_LIMIT_ATTACHED                  },
25969       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
25970       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
25971       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
25972       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
25973     };
25974     int i, n2;
25975     open_db(p, 0);
25976     if( nArg==1 ){
25977       for(i=0; i<ArraySize(aLimit); i++){
25978         sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
25979               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
25980       }
25981     }else if( nArg>3 ){
25982       eputz("Usage: .limit NAME ?NEW-VALUE?\n");
25983       rc = 1;
25984       goto meta_command_exit;
25985     }else{
25986       int iLimit = -1;
25987       n2 = strlen30(azArg[1]);
25988       for(i=0; i<ArraySize(aLimit); i++){
25989         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
25990           if( iLimit<0 ){
25991             iLimit = i;
25992           }else{
25993             eputf("ambiguous limit: \"%s\"\n", azArg[1]);
25994             rc = 1;
25995             goto meta_command_exit;
25996           }
25997         }
25998       }
25999       if( iLimit<0 ){
26000         eputf("unknown limit: \"%s\"\n"
26001               "enter \".limits\" with no arguments for a list.\n",
26002               azArg[1]);
26003         rc = 1;
26004         goto meta_command_exit;
26005       }
26006       if( nArg==3 ){
26007         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
26008                       (int)integerValue(azArg[2]));
26009       }
26010       sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
26011             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
26012     }
26013   }else
26014 
26015   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
26016     open_db(p, 0);
26017     lintDotCommand(p, azArg, nArg);
26018   }else
26019 
26020 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
26021   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
26022     const char *zFile, *zProc;
26023     char *zErrMsg = 0;
26024     failIfSafeMode(p, "cannot run .load in safe mode");
26025     if( nArg<2 || azArg[1][0]==0 ){
26026       /* Must have a non-empty FILE. (Will not load self.) */
26027       eputz("Usage: .load FILE ?ENTRYPOINT?\n");
26028       rc = 1;
26029       goto meta_command_exit;
26030     }
26031     zFile = azArg[1];
26032     zProc = nArg>=3 ? azArg[2] : 0;
26033     open_db(p, 0);
26034     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
26035     if( rc!=SQLITE_OK ){
26036       eputf("Error: %s\n", zErrMsg);
26037       sqlite3_free(zErrMsg);
26038       rc = 1;
26039     }
26040   }else
26041 #endif
26042 
26043   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
26044     if( nArg!=2 ){
26045       eputz("Usage: .log FILENAME\n");
26046       rc = 1;
26047     }else{
26048       const char *zFile = azArg[1];
26049       if( p->bSafeMode
26050        && cli_strcmp(zFile,"on")!=0
26051        && cli_strcmp(zFile,"off")!=0
26052       ){
26053         sputz(stdout, "cannot set .log to anything other"
26054               " than \"on\" or \"off\"\n");
26055         zFile = "off";
26056       }
26057       output_file_close(p->pLog);
26058       if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
26059       p->pLog = output_file_open(zFile, 0);
26060     }
26061   }else
26062 
26063   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
26064     const char *zMode = 0;
26065     const char *zTabname = 0;
26066     int i, n2;
26067     ColModeOpts cmOpts = ColModeOpts_default;
26068     for(i=1; i<nArg; i++){
26069       const char *z = azArg[i];
26070       if( optionMatch(z,"wrap") && i+1<nArg ){
26071         cmOpts.iWrap = integerValue(azArg[++i]);
26072       }else if( optionMatch(z,"ww") ){
26073         cmOpts.bWordWrap = 1;
26074       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
26075         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
26076       }else if( optionMatch(z,"quote") ){
26077         cmOpts.bQuote = 1;
26078       }else if( optionMatch(z,"noquote") ){
26079         cmOpts.bQuote = 0;
26080       }else if( zMode==0 ){
26081         zMode = z;
26082         /* Apply defaults for qbox pseudo-mode.  If that
26083          * overwrites already-set values, user was informed of this.
26084          */
26085         if( cli_strcmp(z, "qbox")==0 ){
26086           ColModeOpts cmo = ColModeOpts_default_qbox;
26087           zMode = "box";
26088           cmOpts = cmo;
26089         }
26090       }else if( zTabname==0 ){
26091         zTabname = z;
26092       }else if( z[0]=='-' ){
26093         eputf("unknown option: %s\n", z);
26094         eputz("options:\n"
26095               "  --noquote\n"
26096               "  --quote\n"
26097               "  --wordwrap on/off\n"
26098               "  --wrap N\n"
26099               "  --ww\n");
26100         rc = 1;
26101         goto meta_command_exit;
26102       }else{
26103         eputf("extra argument: \"%s\"\n", z);
26104         rc = 1;
26105         goto meta_command_exit;
26106       }
26107     }
26108     if( zMode==0 ){
26109       if( p->mode==MODE_Column
26110        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
26111       ){
26112         oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
26113               modeDescr[p->mode], p->cmOpts.iWrap,
26114               p->cmOpts.bWordWrap ? "on" : "off",
26115               p->cmOpts.bQuote ? "" : "no");
26116       }else{
26117         oputf("current output mode: %s\n", modeDescr[p->mode]);
26118       }
26119       zMode = modeDescr[p->mode];
26120     }
26121     n2 = strlen30(zMode);
26122     if( cli_strncmp(zMode,"lines",n2)==0 ){
26123       p->mode = MODE_Line;
26124       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26125     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
26126       p->mode = MODE_Column;
26127       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
26128         p->showHeader = 1;
26129       }
26130       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26131       p->cmOpts = cmOpts;
26132     }else if( cli_strncmp(zMode,"list",n2)==0 ){
26133       p->mode = MODE_List;
26134       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
26135       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26136     }else if( cli_strncmp(zMode,"html",n2)==0 ){
26137       p->mode = MODE_Html;
26138     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
26139       p->mode = MODE_Tcl;
26140       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
26141       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26142     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
26143       p->mode = MODE_Csv;
26144       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26145       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
26146     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
26147       p->mode = MODE_List;
26148       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
26149     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
26150       p->mode = MODE_Insert;
26151       set_table_name(p, zTabname ? zTabname : "table");
26152     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
26153       p->mode = MODE_Quote;
26154       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26155       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26156     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
26157       p->mode = MODE_Ascii;
26158       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
26159       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
26160     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
26161       p->mode = MODE_Markdown;
26162       p->cmOpts = cmOpts;
26163     }else if( cli_strncmp(zMode,"table",n2)==0 ){
26164       p->mode = MODE_Table;
26165       p->cmOpts = cmOpts;
26166     }else if( cli_strncmp(zMode,"box",n2)==0 ){
26167       p->mode = MODE_Box;
26168       p->cmOpts = cmOpts;
26169     }else if( cli_strncmp(zMode,"count",n2)==0 ){
26170       p->mode = MODE_Count;
26171     }else if( cli_strncmp(zMode,"off",n2)==0 ){
26172       p->mode = MODE_Off;
26173     }else if( cli_strncmp(zMode,"json",n2)==0 ){
26174       p->mode = MODE_Json;
26175     }else{
26176       eputz("Error: mode should be one of: "
26177             "ascii box column csv html insert json line list markdown "
26178             "qbox quote table tabs tcl\n");
26179       rc = 1;
26180     }
26181     p->cMode = p->mode;
26182   }else
26183 
26184 #ifndef SQLITE_SHELL_FIDDLE
26185   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
26186     if( nArg!=2 ){
26187       eputz("Usage: .nonce NONCE\n");
26188       rc = 1;
26189     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
26190       eputf("line %d: incorrect nonce: \"%s\"\n",
26191             p->lineno, azArg[1]);
26192       exit(1);
26193     }else{
26194       p->bSafeMode = 0;
26195       return 0;  /* Return immediately to bypass the safe mode reset
26196                  ** at the end of this procedure */
26197     }
26198   }else
26199 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26200 
26201   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
26202     if( nArg==2 ){
26203       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
26204                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
26205     }else{
26206       eputz("Usage: .nullvalue STRING\n");
26207       rc = 1;
26208     }
26209   }else
26210 
26211   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
26212     const char *zFN = 0;     /* Pointer to constant filename */
26213     char *zNewFilename = 0;  /* Name of the database file to open */
26214     int iName = 1;           /* Index in azArg[] of the filename */
26215     int newFlag = 0;         /* True to delete file before opening */
26216     int openMode = SHELL_OPEN_UNSPEC;
26217 
26218     /* Check for command-line arguments */
26219     for(iName=1; iName<nArg; iName++){
26220       const char *z = azArg[iName];
26221 #ifndef SQLITE_SHELL_FIDDLE
26222       if( optionMatch(z,"new") ){
26223         newFlag = 1;
26224 #ifdef SQLITE_HAVE_ZLIB
26225       }else if( optionMatch(z, "zip") ){
26226         openMode = SHELL_OPEN_ZIPFILE;
26227 #endif
26228       }else if( optionMatch(z, "append") ){
26229         openMode = SHELL_OPEN_APPENDVFS;
26230       }else if( optionMatch(z, "readonly") ){
26231         openMode = SHELL_OPEN_READONLY;
26232       }else if( optionMatch(z, "nofollow") ){
26233         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
26234 #ifndef SQLITE_OMIT_DESERIALIZE
26235       }else if( optionMatch(z, "deserialize") ){
26236         openMode = SHELL_OPEN_DESERIALIZE;
26237       }else if( optionMatch(z, "hexdb") ){
26238         openMode = SHELL_OPEN_HEXDB;
26239       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
26240         p->szMax = integerValue(azArg[++iName]);
26241 #endif /* SQLITE_OMIT_DESERIALIZE */
26242       }else
26243 #endif /* !SQLITE_SHELL_FIDDLE */
26244       if( z[0]=='-' ){
26245         eputf("unknown option: %s\n", z);
26246         rc = 1;
26247         goto meta_command_exit;
26248       }else if( zFN ){
26249         eputf("extra argument: \"%s\"\n", z);
26250         rc = 1;
26251         goto meta_command_exit;
26252       }else{
26253         zFN = z;
26254       }
26255     }
26256 
26257     /* Close the existing database */
26258     session_close_all(p, -1);
26259     close_db(p->db);
26260     p->db = 0;
26261     p->pAuxDb->zDbFilename = 0;
26262     sqlite3_free(p->pAuxDb->zFreeOnClose);
26263     p->pAuxDb->zFreeOnClose = 0;
26264     p->openMode = openMode;
26265     p->openFlags = 0;
26266     p->szMax = 0;
26267 
26268     /* If a filename is specified, try to open it first */
26269     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
26270       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
26271 #ifndef SQLITE_SHELL_FIDDLE
26272       if( p->bSafeMode
26273        && p->openMode!=SHELL_OPEN_HEXDB
26274        && zFN
26275        && cli_strcmp(zFN,":memory:")!=0
26276       ){
26277         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
26278       }
26279 #else
26280       /* WASM mode has its own sandboxed pseudo-filesystem. */
26281 #endif
26282       if( zFN ){
26283         zNewFilename = sqlite3_mprintf("%s", zFN);
26284         shell_check_oom(zNewFilename);
26285       }else{
26286         zNewFilename = 0;
26287       }
26288       p->pAuxDb->zDbFilename = zNewFilename;
26289       open_db(p, OPEN_DB_KEEPALIVE);
26290       if( p->db==0 ){
26291         eputf("Error: cannot open '%s'\n", zNewFilename);
26292         sqlite3_free(zNewFilename);
26293       }else{
26294         p->pAuxDb->zFreeOnClose = zNewFilename;
26295       }
26296     }
26297     if( p->db==0 ){
26298       /* As a fall-back open a TEMP database */
26299       p->pAuxDb->zDbFilename = 0;
26300       open_db(p, 0);
26301     }
26302   }else
26303 
26304 #ifndef SQLITE_SHELL_FIDDLE
26305   if( (c=='o'
26306         && (cli_strncmp(azArg[0], "output", n)==0
26307             || cli_strncmp(azArg[0], "once", n)==0))
26308    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
26309   ){
26310     char *zFile = 0;
26311     int bTxtMode = 0;
26312     int i;
26313     int eMode = 0;
26314     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
26315     static const char *zBomUtf8 = "\xef\xbb\xbf";
26316     const char *zBom = 0;
26317 
26318     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
26319     if( c=='e' ){
26320       eMode = 'x';
26321       bOnce = 2;
26322     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
26323       bOnce = 1;
26324     }
26325     for(i=1; i<nArg; i++){
26326       char *z = azArg[i];
26327       if( z[0]=='-' ){
26328         if( z[1]=='-' ) z++;
26329         if( cli_strcmp(z,"-bom")==0 ){
26330           zBom = zBomUtf8;
26331         }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
26332           eMode = 'x';  /* spreadsheet */
26333         }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
26334           eMode = 'e';  /* text editor */
26335         }else{
26336           oputf("ERROR: unknown option: \"%s\".  Usage:\n", azArg[i]);
26337           showHelp(p->out, azArg[0]);
26338           rc = 1;
26339           goto meta_command_exit;
26340         }
26341       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
26342         zFile = sqlite3_mprintf("%s", z);
26343         if( zFile && zFile[0]=='|' ){
26344           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
26345           break;
26346         }
26347       }else{
26348         oputf("ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
26349         showHelp(p->out, azArg[0]);
26350         rc = 1;
26351         sqlite3_free(zFile);
26352         goto meta_command_exit;
26353       }
26354     }
26355     if( zFile==0 ){
26356       zFile = sqlite3_mprintf("stdout");
26357     }
26358     if( bOnce ){
26359       p->outCount = 2;
26360     }else{
26361       p->outCount = 0;
26362     }
26363     output_reset(p);
26364 #ifndef SQLITE_NOHAVE_SYSTEM
26365     if( eMode=='e' || eMode=='x' ){
26366       p->doXdgOpen = 1;
26367       outputModePush(p);
26368       if( eMode=='x' ){
26369         /* spreadsheet mode.  Output as CSV. */
26370         newTempFile(p, "csv");
26371         ShellClearFlag(p, SHFLG_Echo);
26372         p->mode = MODE_Csv;
26373         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26374         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
26375       }else{
26376         /* text editor mode */
26377         newTempFile(p, "txt");
26378         bTxtMode = 1;
26379       }
26380       sqlite3_free(zFile);
26381       zFile = sqlite3_mprintf("%s", p->zTempFile);
26382     }
26383 #endif /* SQLITE_NOHAVE_SYSTEM */
26384     shell_check_oom(zFile);
26385     if( zFile[0]=='|' ){
26386 #ifdef SQLITE_OMIT_POPEN
26387       eputz("Error: pipes are not supported in this OS\n");
26388       rc = 1;
26389       output_redir(p, stdout);
26390 #else
26391       FILE *pfPipe = popen(zFile + 1, "w");
26392       if( pfPipe==0 ){
26393         eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
26394         rc = 1;
26395       }else{
26396         output_redir(p, pfPipe);
26397         if( zBom ) oputz(zBom);
26398         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
26399       }
26400 #endif
26401     }else{
26402       FILE *pfFile = output_file_open(zFile, bTxtMode);
26403       if( pfFile==0 ){
26404         if( cli_strcmp(zFile,"off")!=0 ){
26405           eputf("Error: cannot write to \"%s\"\n", zFile);
26406         }
26407         rc = 1;
26408       } else {
26409         output_redir(p, pfFile);
26410         if( zBom ) oputz(zBom);
26411         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
26412       }
26413     }
26414     sqlite3_free(zFile);
26415   }else
26416 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26417 
26418   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
26419     open_db(p,0);
26420     if( nArg<=1 ) goto parameter_syntax_error;
26421 
26422     /* .parameter clear
26423     ** Clear all bind parameters by dropping the TEMP table that holds them.
26424     */
26425     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
26426       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
26427                    0, 0, 0);
26428     }else
26429 
26430     /* .parameter list
26431     ** List all bind parameters.
26432     */
26433     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
26434       sqlite3_stmt *pStmt = 0;
26435       int rx;
26436       int len = 0;
26437       rx = sqlite3_prepare_v2(p->db,
26438              "SELECT max(length(key)) "
26439              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
26440       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26441         len = sqlite3_column_int(pStmt, 0);
26442         if( len>40 ) len = 40;
26443       }
26444       sqlite3_finalize(pStmt);
26445       pStmt = 0;
26446       if( len ){
26447         rx = sqlite3_prepare_v2(p->db,
26448              "SELECT key, quote(value) "
26449              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
26450         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26451           oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
26452                 sqlite3_column_text(pStmt,1));
26453         }
26454         sqlite3_finalize(pStmt);
26455       }
26456     }else
26457 
26458     /* .parameter init
26459     ** Make sure the TEMP table used to hold bind parameters exists.
26460     ** Create it if necessary.
26461     */
26462     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
26463       bind_table_init(p);
26464     }else
26465 
26466     /* .parameter set NAME VALUE
26467     ** Set or reset a bind parameter.  NAME should be the full parameter
26468     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
26469     ** VALUE can be in either SQL literal notation, or if not it will be
26470     ** understood to be a text string.
26471     */
26472     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
26473       int rx;
26474       char *zSql;
26475       sqlite3_stmt *pStmt;
26476       const char *zKey = azArg[2];
26477       const char *zValue = azArg[3];
26478       bind_table_init(p);
26479       zSql = sqlite3_mprintf(
26480                   "REPLACE INTO temp.sqlite_parameters(key,value)"
26481                   "VALUES(%Q,%s);", zKey, zValue);
26482       shell_check_oom(zSql);
26483       pStmt = 0;
26484       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
26485       sqlite3_free(zSql);
26486       if( rx!=SQLITE_OK ){
26487         sqlite3_finalize(pStmt);
26488         pStmt = 0;
26489         zSql = sqlite3_mprintf(
26490                    "REPLACE INTO temp.sqlite_parameters(key,value)"
26491                    "VALUES(%Q,%Q);", zKey, zValue);
26492         shell_check_oom(zSql);
26493         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
26494         sqlite3_free(zSql);
26495         if( rx!=SQLITE_OK ){
26496           oputf("Error: %s\n", sqlite3_errmsg(p->db));
26497           sqlite3_finalize(pStmt);
26498           pStmt = 0;
26499           rc = 1;
26500         }
26501       }
26502       sqlite3_step(pStmt);
26503       sqlite3_finalize(pStmt);
26504     }else
26505 
26506     /* .parameter unset NAME
26507     ** Remove the NAME binding from the parameter binding table, if it
26508     ** exists.
26509     */
26510     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
26511       char *zSql = sqlite3_mprintf(
26512           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
26513       shell_check_oom(zSql);
26514       sqlite3_exec(p->db, zSql, 0, 0, 0);
26515       sqlite3_free(zSql);
26516     }else
26517     /* If no command name matches, show a syntax error */
26518     parameter_syntax_error:
26519     showHelp(p->out, "parameter");
26520   }else
26521 
26522   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
26523     int i;
26524     for(i=1; i<nArg; i++){
26525       if( i>1 ) oputz(" ");
26526       oputz(azArg[i]);
26527     }
26528     oputz("\n");
26529   }else
26530 
26531 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
26532   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
26533     int i;
26534     int nn = 0;
26535     p->flgProgress = 0;
26536     p->mxProgress = 0;
26537     p->nProgress = 0;
26538     for(i=1; i<nArg; i++){
26539       const char *z = azArg[i];
26540       if( z[0]=='-' ){
26541         z++;
26542         if( z[0]=='-' ) z++;
26543         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
26544           p->flgProgress |= SHELL_PROGRESS_QUIET;
26545           continue;
26546         }
26547         if( cli_strcmp(z,"reset")==0 ){
26548           p->flgProgress |= SHELL_PROGRESS_RESET;
26549           continue;
26550         }
26551         if( cli_strcmp(z,"once")==0 ){
26552           p->flgProgress |= SHELL_PROGRESS_ONCE;
26553           continue;
26554         }
26555         if( cli_strcmp(z,"limit")==0 ){
26556           if( i+1>=nArg ){
26557             eputz("Error: missing argument on --limit\n");
26558             rc = 1;
26559             goto meta_command_exit;
26560           }else{
26561             p->mxProgress = (int)integerValue(azArg[++i]);
26562           }
26563           continue;
26564         }
26565         eputf("Error: unknown option: \"%s\"\n", azArg[i]);
26566         rc = 1;
26567         goto meta_command_exit;
26568       }else{
26569         nn = (int)integerValue(z);
26570       }
26571     }
26572     open_db(p, 0);
26573     sqlite3_progress_handler(p->db, nn, progress_handler, p);
26574   }else
26575 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
26576 
26577   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
26578     if( nArg >= 2) {
26579       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
26580     }
26581     if( nArg >= 3) {
26582       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
26583     }
26584   }else
26585 
26586 #ifndef SQLITE_SHELL_FIDDLE
26587   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
26588     rc = 2;
26589   }else
26590 #endif
26591 
26592 #ifndef SQLITE_SHELL_FIDDLE
26593   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
26594     FILE *inSaved = p->in;
26595     int savedLineno = p->lineno;
26596     failIfSafeMode(p, "cannot run .read in safe mode");
26597     if( nArg!=2 ){
26598       eputz("Usage: .read FILE\n");
26599       rc = 1;
26600       goto meta_command_exit;
26601     }
26602     if( azArg[1][0]=='|' ){
26603 #ifdef SQLITE_OMIT_POPEN
26604       eputz("Error: pipes are not supported in this OS\n");
26605       rc = 1;
26606       p->out = stdout;
26607 #else
26608       p->in = popen(azArg[1]+1, "r");
26609       if( p->in==0 ){
26610         eputf("Error: cannot open \"%s\"\n", azArg[1]);
26611         rc = 1;
26612       }else{
26613         rc = process_input(p);
26614         pclose(p->in);
26615       }
26616 #endif
26617     }else if( (p->in = openChrSource(azArg[1]))==0 ){
26618       eputf("Error: cannot open \"%s\"\n", azArg[1]);
26619       rc = 1;
26620     }else{
26621       rc = process_input(p);
26622       fclose(p->in);
26623     }
26624     p->in = inSaved;
26625     p->lineno = savedLineno;
26626   }else
26627 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26628 
26629 #ifndef SQLITE_SHELL_FIDDLE
26630   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
26631     const char *zSrcFile;
26632     const char *zDb;
26633     sqlite3 *pSrc;
26634     sqlite3_backup *pBackup;
26635     int nTimeout = 0;
26636 
26637     failIfSafeMode(p, "cannot run .restore in safe mode");
26638     if( nArg==2 ){
26639       zSrcFile = azArg[1];
26640       zDb = "main";
26641     }else if( nArg==3 ){
26642       zSrcFile = azArg[2];
26643       zDb = azArg[1];
26644     }else{
26645       eputz("Usage: .restore ?DB? FILE\n");
26646       rc = 1;
26647       goto meta_command_exit;
26648     }
26649     rc = sqlite3_open(zSrcFile, &pSrc);
26650     if( rc!=SQLITE_OK ){
26651       eputf("Error: cannot open \"%s\"\n", zSrcFile);
26652       close_db(pSrc);
26653       return 1;
26654     }
26655     open_db(p, 0);
26656     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
26657     if( pBackup==0 ){
26658       eputf("Error: %s\n", sqlite3_errmsg(p->db));
26659       close_db(pSrc);
26660       return 1;
26661     }
26662     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
26663           || rc==SQLITE_BUSY  ){
26664       if( rc==SQLITE_BUSY ){
26665         if( nTimeout++ >= 3 ) break;
26666         sqlite3_sleep(100);
26667       }
26668     }
26669     sqlite3_backup_finish(pBackup);
26670     if( rc==SQLITE_DONE ){
26671       rc = 0;
26672     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
26673       eputz("Error: source database is busy\n");
26674       rc = 1;
26675     }else{
26676       eputf("Error: %s\n", sqlite3_errmsg(p->db));
26677       rc = 1;
26678     }
26679     close_db(pSrc);
26680   }else
26681 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26682 
26683   if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
26684     if( nArg==2 ){
26685       if( cli_strcmp(azArg[1], "vm")==0 ){
26686         p->scanstatsOn = 3;
26687       }else
26688       if( cli_strcmp(azArg[1], "est")==0 ){
26689         p->scanstatsOn = 2;
26690       }else{
26691         p->scanstatsOn = (u8)booleanValue(azArg[1]);
26692       }
26693       open_db(p, 0);
26694       sqlite3_db_config(
26695           p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
26696       );
26697 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
26698       eputz("Warning: .scanstats not available in this build.\n");
26699 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
26700       if( p->scanstatsOn==3 ){
26701         eputz("Warning: \".scanstats vm\" not available in this build.\n");
26702       }
26703 #endif
26704     }else{
26705       eputz("Usage: .scanstats on|off|est\n");
26706       rc = 1;
26707     }
26708   }else
26709 
26710   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
26711     ShellText sSelect;
26712     ShellState data;
26713     char *zErrMsg = 0;
26714     const char *zDiv = "(";
26715     const char *zName = 0;
26716     int iSchema = 0;
26717     int bDebug = 0;
26718     int bNoSystemTabs = 0;
26719     int ii;
26720 
26721     open_db(p, 0);
26722     memcpy(&data, p, sizeof(data));
26723     data.showHeader = 0;
26724     data.cMode = data.mode = MODE_Semi;
26725     initText(&sSelect);
26726     for(ii=1; ii<nArg; ii++){
26727       if( optionMatch(azArg[ii],"indent") ){
26728         data.cMode = data.mode = MODE_Pretty;
26729       }else if( optionMatch(azArg[ii],"debug") ){
26730         bDebug = 1;
26731       }else if( optionMatch(azArg[ii],"nosys") ){
26732         bNoSystemTabs = 1;
26733       }else if( azArg[ii][0]=='-' ){
26734         eputf("Unknown option: \"%s\"\n", azArg[ii]);
26735         rc = 1;
26736         goto meta_command_exit;
26737       }else if( zName==0 ){
26738         zName = azArg[ii];
26739       }else{
26740         eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
26741         rc = 1;
26742         goto meta_command_exit;
26743       }
26744     }
26745     if( zName!=0 ){
26746       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
26747                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
26748                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
26749                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
26750       if( isSchema ){
26751         char *new_argv[2], *new_colv[2];
26752         new_argv[0] = sqlite3_mprintf(
26753                       "CREATE TABLE %s (\n"
26754                       "  type text,\n"
26755                       "  name text,\n"
26756                       "  tbl_name text,\n"
26757                       "  rootpage integer,\n"
26758                       "  sql text\n"
26759                       ")", zName);
26760         shell_check_oom(new_argv[0]);
26761         new_argv[1] = 0;
26762         new_colv[0] = "sql";
26763         new_colv[1] = 0;
26764         callback(&data, 1, new_argv, new_colv);
26765         sqlite3_free(new_argv[0]);
26766       }
26767     }
26768     if( zDiv ){
26769       sqlite3_stmt *pStmt = 0;
26770       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
26771                               -1, &pStmt, 0);
26772       if( rc ){
26773         eputf("Error: %s\n", sqlite3_errmsg(p->db));
26774         sqlite3_finalize(pStmt);
26775         rc = 1;
26776         goto meta_command_exit;
26777       }
26778       appendText(&sSelect, "SELECT sql FROM", 0);
26779       iSchema = 0;
26780       while( sqlite3_step(pStmt)==SQLITE_ROW ){
26781         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
26782         char zScNum[30];
26783         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
26784         appendText(&sSelect, zDiv, 0);
26785         zDiv = " UNION ALL ";
26786         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
26787         if( sqlite3_stricmp(zDb, "main")!=0 ){
26788           appendText(&sSelect, zDb, '\'');
26789         }else{
26790           appendText(&sSelect, "NULL", 0);
26791         }
26792         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
26793         appendText(&sSelect, zScNum, 0);
26794         appendText(&sSelect, " AS snum, ", 0);
26795         appendText(&sSelect, zDb, '\'');
26796         appendText(&sSelect, " AS sname FROM ", 0);
26797         appendText(&sSelect, zDb, quoteChar(zDb));
26798         appendText(&sSelect, ".sqlite_schema", 0);
26799       }
26800       sqlite3_finalize(pStmt);
26801 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
26802       if( zName ){
26803         appendText(&sSelect,
26804            " UNION ALL SELECT shell_module_schema(name),"
26805            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
26806         0);
26807       }
26808 #endif
26809       appendText(&sSelect, ") WHERE ", 0);
26810       if( zName ){
26811         char *zQarg = sqlite3_mprintf("%Q", zName);
26812         int bGlob;
26813         shell_check_oom(zQarg);
26814         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
26815                 strchr(zName, '[') != 0;
26816         if( strchr(zName, '.') ){
26817           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
26818         }else{
26819           appendText(&sSelect, "lower(tbl_name)", 0);
26820         }
26821         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
26822         appendText(&sSelect, zQarg, 0);
26823         if( !bGlob ){
26824           appendText(&sSelect, " ESCAPE '\\' ", 0);
26825         }
26826         appendText(&sSelect, " AND ", 0);
26827         sqlite3_free(zQarg);
26828       }
26829       if( bNoSystemTabs ){
26830         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
26831       }
26832       appendText(&sSelect, "sql IS NOT NULL"
26833                            " ORDER BY snum, rowid", 0);
26834       if( bDebug ){
26835         oputf("SQL: %s;\n", sSelect.z);
26836       }else{
26837         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
26838       }
26839       freeText(&sSelect);
26840     }
26841     if( zErrMsg ){
26842       eputf("Error: %s\n", zErrMsg);
26843       sqlite3_free(zErrMsg);
26844       rc = 1;
26845     }else if( rc != SQLITE_OK ){
26846       eputz("Error: querying schema information\n");
26847       rc = 1;
26848     }else{
26849       rc = 0;
26850     }
26851   }else
26852 
26853   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
26854    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
26855   ){
26856     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
26857     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
26858   }else
26859 
26860 #if defined(SQLITE_ENABLE_SESSION)
26861   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
26862     struct AuxDb *pAuxDb = p->pAuxDb;
26863     OpenSession *pSession = &pAuxDb->aSession[0];
26864     char **azCmd = &azArg[1];
26865     int iSes = 0;
26866     int nCmd = nArg - 1;
26867     int i;
26868     if( nArg<=1 ) goto session_syntax_error;
26869     open_db(p, 0);
26870     if( nArg>=3 ){
26871       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
26872         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
26873       }
26874       if( iSes<pAuxDb->nSession ){
26875         pSession = &pAuxDb->aSession[iSes];
26876         azCmd++;
26877         nCmd--;
26878       }else{
26879         pSession = &pAuxDb->aSession[0];
26880         iSes = 0;
26881       }
26882     }
26883 
26884     /* .session attach TABLE
26885     ** Invoke the sqlite3session_attach() interface to attach a particular
26886     ** table so that it is never filtered.
26887     */
26888     if( cli_strcmp(azCmd[0],"attach")==0 ){
26889       if( nCmd!=2 ) goto session_syntax_error;
26890       if( pSession->p==0 ){
26891         session_not_open:
26892         eputz("ERROR: No sessions are open\n");
26893       }else{
26894         rc = sqlite3session_attach(pSession->p, azCmd[1]);
26895         if( rc ){
26896           eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
26897           rc = 0;
26898         }
26899       }
26900     }else
26901 
26902     /* .session changeset FILE
26903     ** .session patchset FILE
26904     ** Write a changeset or patchset into a file.  The file is overwritten.
26905     */
26906     if( cli_strcmp(azCmd[0],"changeset")==0
26907      || cli_strcmp(azCmd[0],"patchset")==0
26908     ){
26909       FILE *out = 0;
26910       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
26911       if( nCmd!=2 ) goto session_syntax_error;
26912       if( pSession->p==0 ) goto session_not_open;
26913       out = fopen(azCmd[1], "wb");
26914       if( out==0 ){
26915         eputf("ERROR: cannot open \"%s\" for writing\n",
26916               azCmd[1]);
26917       }else{
26918         int szChng;
26919         void *pChng;
26920         if( azCmd[0][0]=='c' ){
26921           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
26922         }else{
26923           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
26924         }
26925         if( rc ){
26926           sputf(stdout, "Error: error code %d\n", rc);
26927           rc = 0;
26928         }
26929         if( pChng
26930           && fwrite(pChng, szChng, 1, out)!=1 ){
26931           eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
26932         }
26933         sqlite3_free(pChng);
26934         fclose(out);
26935       }
26936     }else
26937 
26938     /* .session close
26939     ** Close the identified session
26940     */
26941     if( cli_strcmp(azCmd[0], "close")==0 ){
26942       if( nCmd!=1 ) goto session_syntax_error;
26943       if( pAuxDb->nSession ){
26944         session_close(pSession);
26945         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
26946       }
26947     }else
26948 
26949     /* .session enable ?BOOLEAN?
26950     ** Query or set the enable flag
26951     */
26952     if( cli_strcmp(azCmd[0], "enable")==0 ){
26953       int ii;
26954       if( nCmd>2 ) goto session_syntax_error;
26955       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
26956       if( pAuxDb->nSession ){
26957         ii = sqlite3session_enable(pSession->p, ii);
26958         oputf("session %s enable flag = %d\n", pSession->zName, ii);
26959       }
26960     }else
26961 
26962     /* .session filter GLOB ....
26963     ** Set a list of GLOB patterns of table names to be excluded.
26964     */
26965     if( cli_strcmp(azCmd[0], "filter")==0 ){
26966       int ii, nByte;
26967       if( nCmd<2 ) goto session_syntax_error;
26968       if( pAuxDb->nSession ){
26969         for(ii=0; ii<pSession->nFilter; ii++){
26970           sqlite3_free(pSession->azFilter[ii]);
26971         }
26972         sqlite3_free(pSession->azFilter);
26973         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
26974         pSession->azFilter = sqlite3_malloc( nByte );
26975         shell_check_oom( pSession->azFilter );
26976         for(ii=1; ii<nCmd; ii++){
26977           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
26978           shell_check_oom(x);
26979         }
26980         pSession->nFilter = ii-1;
26981       }
26982     }else
26983 
26984     /* .session indirect ?BOOLEAN?
26985     ** Query or set the indirect flag
26986     */
26987     if( cli_strcmp(azCmd[0], "indirect")==0 ){
26988       int ii;
26989       if( nCmd>2 ) goto session_syntax_error;
26990       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
26991       if( pAuxDb->nSession ){
26992         ii = sqlite3session_indirect(pSession->p, ii);
26993         oputf("session %s indirect flag = %d\n", pSession->zName, ii);
26994       }
26995     }else
26996 
26997     /* .session isempty
26998     ** Determine if the session is empty
26999     */
27000     if( cli_strcmp(azCmd[0], "isempty")==0 ){
27001       int ii;
27002       if( nCmd!=1 ) goto session_syntax_error;
27003       if( pAuxDb->nSession ){
27004         ii = sqlite3session_isempty(pSession->p);
27005         oputf("session %s isempty flag = %d\n", pSession->zName, ii);
27006       }
27007     }else
27008 
27009     /* .session list
27010     ** List all currently open sessions
27011     */
27012     if( cli_strcmp(azCmd[0],"list")==0 ){
27013       for(i=0; i<pAuxDb->nSession; i++){
27014         oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
27015       }
27016     }else
27017 
27018     /* .session open DB NAME
27019     ** Open a new session called NAME on the attached database DB.
27020     ** DB is normally "main".
27021     */
27022     if( cli_strcmp(azCmd[0],"open")==0 ){
27023       char *zName;
27024       if( nCmd!=3 ) goto session_syntax_error;
27025       zName = azCmd[2];
27026       if( zName[0]==0 ) goto session_syntax_error;
27027       for(i=0; i<pAuxDb->nSession; i++){
27028         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
27029           eputf("Session \"%s\" already exists\n", zName);
27030           goto meta_command_exit;
27031         }
27032       }
27033       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
27034         eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
27035         goto meta_command_exit;
27036       }
27037       pSession = &pAuxDb->aSession[pAuxDb->nSession];
27038       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
27039       if( rc ){
27040         eputf("Cannot open session: error code=%d\n", rc);
27041         rc = 0;
27042         goto meta_command_exit;
27043       }
27044       pSession->nFilter = 0;
27045       sqlite3session_table_filter(pSession->p, session_filter, pSession);
27046       pAuxDb->nSession++;
27047       pSession->zName = sqlite3_mprintf("%s", zName);
27048       shell_check_oom(pSession->zName);
27049     }else
27050     /* If no command name matches, show a syntax error */
27051     session_syntax_error:
27052     showHelp(p->out, "session");
27053   }else
27054 #endif
27055 
27056 #ifdef SQLITE_DEBUG
27057   /* Undocumented commands for internal testing.  Subject to change
27058   ** without notice. */
27059   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
27060     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
27061       int i, v;
27062       for(i=1; i<nArg; i++){
27063         v = booleanValue(azArg[i]);
27064         oputf("%s: %d 0x%x\n", azArg[i], v, v);
27065       }
27066     }
27067     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
27068       int i; sqlite3_int64 v;
27069       for(i=1; i<nArg; i++){
27070         char zBuf[200];
27071         v = integerValue(azArg[i]);
27072         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
27073         oputz(zBuf);
27074       }
27075     }
27076   }else
27077 #endif
27078 
27079   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
27080     int bIsInit = 0;         /* True to initialize the SELFTEST table */
27081     int bVerbose = 0;        /* Verbose output */
27082     int bSelftestExists;     /* True if SELFTEST already exists */
27083     int i, k;                /* Loop counters */
27084     int nTest = 0;           /* Number of tests runs */
27085     int nErr = 0;            /* Number of errors seen */
27086     ShellText str;           /* Answer for a query */
27087     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
27088 
27089     open_db(p,0);
27090     for(i=1; i<nArg; i++){
27091       const char *z = azArg[i];
27092       if( z[0]=='-' && z[1]=='-' ) z++;
27093       if( cli_strcmp(z,"-init")==0 ){
27094         bIsInit = 1;
27095       }else
27096       if( cli_strcmp(z,"-v")==0 ){
27097         bVerbose++;
27098       }else
27099       {
27100         eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
27101         eputz("Should be one of: --init -v\n");
27102         rc = 1;
27103         goto meta_command_exit;
27104       }
27105     }
27106     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
27107            != SQLITE_OK ){
27108       bSelftestExists = 0;
27109     }else{
27110       bSelftestExists = 1;
27111     }
27112     if( bIsInit ){
27113       createSelftestTable(p);
27114       bSelftestExists = 1;
27115     }
27116     initText(&str);
27117     appendText(&str, "x", 0);
27118     for(k=bSelftestExists; k>=0; k--){
27119       if( k==1 ){
27120         rc = sqlite3_prepare_v2(p->db,
27121             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
27122             -1, &pStmt, 0);
27123       }else{
27124         rc = sqlite3_prepare_v2(p->db,
27125           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
27126           "      (1,'run','PRAGMA integrity_check','ok')",
27127           -1, &pStmt, 0);
27128       }
27129       if( rc ){
27130         eputz("Error querying the selftest table\n");
27131         rc = 1;
27132         sqlite3_finalize(pStmt);
27133         goto meta_command_exit;
27134       }
27135       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
27136         int tno = sqlite3_column_int(pStmt, 0);
27137         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
27138         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
27139         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
27140 
27141         if( zOp==0 ) continue;
27142         if( zSql==0 ) continue;
27143         if( zAns==0 ) continue;
27144         k = 0;
27145         if( bVerbose>0 ){
27146           sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
27147         }
27148         if( cli_strcmp(zOp,"memo")==0 ){
27149           oputf("%s\n", zSql);
27150         }else
27151         if( cli_strcmp(zOp,"run")==0 ){
27152           char *zErrMsg = 0;
27153           str.n = 0;
27154           str.z[0] = 0;
27155           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
27156           nTest++;
27157           if( bVerbose ){
27158             oputf("Result: %s\n", str.z);
27159           }
27160           if( rc || zErrMsg ){
27161             nErr++;
27162             rc = 1;
27163             oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
27164             sqlite3_free(zErrMsg);
27165           }else if( cli_strcmp(zAns,str.z)!=0 ){
27166             nErr++;
27167             rc = 1;
27168             oputf("%d: Expected: [%s]\n", tno, zAns);
27169             oputf("%d:      Got: [%s]\n", tno, str.z);
27170           }
27171         }
27172         else{
27173           eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
27174           rc = 1;
27175           break;
27176         }
27177       } /* End loop over rows of content from SELFTEST */
27178       sqlite3_finalize(pStmt);
27179     } /* End loop over k */
27180     freeText(&str);
27181     oputf("%d errors out of %d tests\n", nErr, nTest);
27182   }else
27183 
27184   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
27185     if( nArg<2 || nArg>3 ){
27186       eputz("Usage: .separator COL ?ROW?\n");
27187       rc = 1;
27188     }
27189     if( nArg>=2 ){
27190       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
27191                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
27192     }
27193     if( nArg>=3 ){
27194       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
27195                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
27196     }
27197   }else
27198 
27199   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
27200     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
27201     int i;                   /* Loop counter */
27202     int bSchema = 0;         /* Also hash the schema */
27203     int bSeparate = 0;       /* Hash each table separately */
27204     int iSize = 224;         /* Hash algorithm to use */
27205     int bDebug = 0;          /* Only show the query that would have run */
27206     sqlite3_stmt *pStmt;     /* For querying tables names */
27207     char *zSql;              /* SQL to be run */
27208     char *zSep;              /* Separator */
27209     ShellText sSql;          /* Complete SQL for the query to run the hash */
27210     ShellText sQuery;        /* Set of queries used to read all content */
27211     open_db(p, 0);
27212     for(i=1; i<nArg; i++){
27213       const char *z = azArg[i];
27214       if( z[0]=='-' ){
27215         z++;
27216         if( z[0]=='-' ) z++;
27217         if( cli_strcmp(z,"schema")==0 ){
27218           bSchema = 1;
27219         }else
27220         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
27221          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
27222         ){
27223           iSize = atoi(&z[5]);
27224         }else
27225         if( cli_strcmp(z,"debug")==0 ){
27226           bDebug = 1;
27227         }else
27228         {
27229           eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
27230           showHelp(p->out, azArg[0]);
27231           rc = 1;
27232           goto meta_command_exit;
27233         }
27234       }else if( zLike ){
27235         eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
27236         rc = 1;
27237         goto meta_command_exit;
27238       }else{
27239         zLike = z;
27240         bSeparate = 1;
27241         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
27242       }
27243     }
27244     if( bSchema ){
27245       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
27246              " WHERE type='table' AND coalesce(rootpage,0)>1"
27247              " UNION ALL SELECT 'sqlite_schema'"
27248              " ORDER BY 1 collate nocase";
27249     }else{
27250       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
27251              " WHERE type='table' AND coalesce(rootpage,0)>1"
27252              " AND name NOT LIKE 'sqlite_%'"
27253              " ORDER BY 1 collate nocase";
27254     }
27255     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27256     initText(&sQuery);
27257     initText(&sSql);
27258     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
27259     zSep = "VALUES(";
27260     while( SQLITE_ROW==sqlite3_step(pStmt) ){
27261       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
27262       if( zTab==0 ) continue;
27263       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
27264       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
27265         appendText(&sQuery,"SELECT * FROM ", 0);
27266         appendText(&sQuery,zTab,'"');
27267         appendText(&sQuery," NOT INDEXED;", 0);
27268       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
27269         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
27270                            " ORDER BY name;", 0);
27271       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
27272         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
27273                            " ORDER BY name;", 0);
27274       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
27275         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
27276                            " ORDER BY tbl,idx;", 0);
27277       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
27278         appendText(&sQuery, "SELECT * FROM ", 0);
27279         appendText(&sQuery, zTab, 0);
27280         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
27281       }
27282       appendText(&sSql, zSep, 0);
27283       appendText(&sSql, sQuery.z, '\'');
27284       sQuery.n = 0;
27285       appendText(&sSql, ",", 0);
27286       appendText(&sSql, zTab, '\'');
27287       zSep = "),(";
27288     }
27289     sqlite3_finalize(pStmt);
27290     if( bSeparate ){
27291       zSql = sqlite3_mprintf(
27292           "%s))"
27293           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
27294           "   FROM [sha3sum$query]",
27295           sSql.z, iSize);
27296     }else{
27297       zSql = sqlite3_mprintf(
27298           "%s))"
27299           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
27300           "   FROM [sha3sum$query]",
27301           sSql.z, iSize);
27302     }
27303     shell_check_oom(zSql);
27304     freeText(&sQuery);
27305     freeText(&sSql);
27306     if( bDebug ){
27307       oputf("%s\n", zSql);
27308     }else{
27309       shell_exec(p, zSql, 0);
27310     }
27311 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27312     {
27313       int lrc;
27314       char *zRevText = /* Query for reversible to-blob-to-text check */
27315         "SELECT lower(name) as tname FROM sqlite_schema\n"
27316         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
27317         "AND name NOT LIKE 'sqlite_%%'%s\n"
27318         "ORDER BY 1 collate nocase";
27319       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
27320       zRevText = sqlite3_mprintf(
27321           /* lower-case query is first run, producing upper-case query. */
27322           "with tabcols as materialized(\n"
27323           "select tname, cname\n"
27324           "from ("
27325           " select printf('\"%%w\"',ss.tname) as tname,"
27326           " printf('\"%%w\"',ti.name) as cname\n"
27327           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
27328           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
27329           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
27330           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
27331           "FROM '||tname||' WHERE '\n"
27332           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
27333           "|| ' AND typeof('||cname||')=''text'' ',\n"
27334           "' OR ') as query, tname from tabcols group by tname)"
27335           , zRevText);
27336       shell_check_oom(zRevText);
27337       if( bDebug ) oputf("%s\n", zRevText);
27338       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
27339       if( lrc!=SQLITE_OK ){
27340         /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
27341         ** user does cruel and unnatural things like ".limit expr_depth 0". */
27342         rc = 1;
27343       }else{
27344         if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
27345         lrc = SQLITE_ROW==sqlite3_step(pStmt);
27346         if( lrc ){
27347           const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
27348           sqlite3_stmt *pCheckStmt;
27349           lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
27350           if( bDebug ) oputf("%s\n", zGenQuery);
27351           if( lrc!=SQLITE_OK ){
27352             rc = 1;
27353           }else{
27354             if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
27355               double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
27356               if( countIrreversible>0 ){
27357                 int sz = (int)(countIrreversible + 0.5);
27358                 eputf("Digest includes %d invalidly encoded text field%s.\n",
27359                       sz, (sz>1)? "s": "");
27360               }
27361             }
27362             sqlite3_finalize(pCheckStmt);
27363           }
27364           sqlite3_finalize(pStmt);
27365         }
27366       }
27367       if( rc ) eputz(".sha3sum failed.\n");
27368       sqlite3_free(zRevText);
27369     }
27370 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
27371     sqlite3_free(zSql);
27372   }else
27373 
27374 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
27375   if( c=='s'
27376    && (cli_strncmp(azArg[0], "shell", n)==0
27377        || cli_strncmp(azArg[0],"system",n)==0)
27378   ){
27379     char *zCmd;
27380     int i, x;
27381     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
27382     if( nArg<2 ){
27383       eputz("Usage: .system COMMAND\n");
27384       rc = 1;
27385       goto meta_command_exit;
27386     }
27387     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
27388     for(i=2; i<nArg && zCmd!=0; i++){
27389       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
27390                              zCmd, azArg[i]);
27391     }
27392     consoleRestore();
27393     x = zCmd!=0 ? system(zCmd) : 1;
27394     consoleRenewSetup();
27395     sqlite3_free(zCmd);
27396     if( x ) eputf("System command returns %d\n", x);
27397   }else
27398 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
27399 
27400   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
27401     static const char *azBool[] = { "off", "on", "trigger", "full"};
27402     const char *zOut;
27403     int i;
27404     if( nArg!=1 ){
27405       eputz("Usage: .show\n");
27406       rc = 1;
27407       goto meta_command_exit;
27408     }
27409     oputf("%12.12s: %s\n","echo",
27410           azBool[ShellHasFlag(p, SHFLG_Echo)]);
27411     oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
27412     oputf("%12.12s: %s\n","explain",
27413           p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
27414     oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
27415     if( p->mode==MODE_Column
27416      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
27417     ){
27418       oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
27419             modeDescr[p->mode], p->cmOpts.iWrap,
27420             p->cmOpts.bWordWrap ? "on" : "off",
27421             p->cmOpts.bQuote ? "" : "no");
27422     }else{
27423       oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
27424     }
27425     oputf("%12.12s: ", "nullvalue");
27426     output_c_string(p->nullValue);
27427     oputz("\n");
27428     oputf("%12.12s: %s\n","output",
27429           strlen30(p->outfile) ? p->outfile : "stdout");
27430     oputf("%12.12s: ", "colseparator");
27431      output_c_string(p->colSeparator);
27432      oputz("\n");
27433     oputf("%12.12s: ", "rowseparator");
27434      output_c_string(p->rowSeparator);
27435      oputz("\n");
27436     switch( p->statsOn ){
27437       case 0:  zOut = "off";     break;
27438       default: zOut = "on";      break;
27439       case 2:  zOut = "stmt";    break;
27440       case 3:  zOut = "vmstep";  break;
27441     }
27442     oputf("%12.12s: %s\n","stats", zOut);
27443     oputf("%12.12s: ", "width");
27444     for (i=0;i<p->nWidth;i++) {
27445       oputf("%d ", p->colWidth[i]);
27446     }
27447     oputz("\n");
27448     oputf("%12.12s: %s\n", "filename",
27449           p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
27450   }else
27451 
27452   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
27453     if( nArg==2 ){
27454       if( cli_strcmp(azArg[1],"stmt")==0 ){
27455         p->statsOn = 2;
27456       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
27457         p->statsOn = 3;
27458       }else{
27459         p->statsOn = (u8)booleanValue(azArg[1]);
27460       }
27461     }else if( nArg==1 ){
27462       display_stats(p->db, p, 0);
27463     }else{
27464       eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
27465       rc = 1;
27466     }
27467   }else
27468 
27469   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
27470    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
27471                  || cli_strncmp(azArg[0], "indexes", n)==0) )
27472   ){
27473     sqlite3_stmt *pStmt;
27474     char **azResult;
27475     int nRow, nAlloc;
27476     int ii;
27477     ShellText s;
27478     initText(&s);
27479     open_db(p, 0);
27480     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
27481     if( rc ){
27482       sqlite3_finalize(pStmt);
27483       return shellDatabaseError(p->db);
27484     }
27485 
27486     if( nArg>2 && c=='i' ){
27487       /* It is an historical accident that the .indexes command shows an error
27488       ** when called with the wrong number of arguments whereas the .tables
27489       ** command does not. */
27490       eputz("Usage: .indexes ?LIKE-PATTERN?\n");
27491       rc = 1;
27492       sqlite3_finalize(pStmt);
27493       goto meta_command_exit;
27494     }
27495     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
27496       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
27497       if( zDbName==0 ) continue;
27498       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
27499       if( sqlite3_stricmp(zDbName, "main")==0 ){
27500         appendText(&s, "SELECT name FROM ", 0);
27501       }else{
27502         appendText(&s, "SELECT ", 0);
27503         appendText(&s, zDbName, '\'');
27504         appendText(&s, "||'.'||name FROM ", 0);
27505       }
27506       appendText(&s, zDbName, '"');
27507       appendText(&s, ".sqlite_schema ", 0);
27508       if( c=='t' ){
27509         appendText(&s," WHERE type IN ('table','view')"
27510                       "   AND name NOT LIKE 'sqlite_%'"
27511                       "   AND name LIKE ?1", 0);
27512       }else{
27513         appendText(&s," WHERE type='index'"
27514                       "   AND tbl_name LIKE ?1", 0);
27515       }
27516     }
27517     rc = sqlite3_finalize(pStmt);
27518     if( rc==SQLITE_OK ){
27519       appendText(&s, " ORDER BY 1", 0);
27520       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
27521     }
27522     freeText(&s);
27523     if( rc ) return shellDatabaseError(p->db);
27524 
27525     /* Run the SQL statement prepared by the above block. Store the results
27526     ** as an array of nul-terminated strings in azResult[].  */
27527     nRow = nAlloc = 0;
27528     azResult = 0;
27529     if( nArg>1 ){
27530       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
27531     }else{
27532       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
27533     }
27534     while( sqlite3_step(pStmt)==SQLITE_ROW ){
27535       if( nRow>=nAlloc ){
27536         char **azNew;
27537         int n2 = nAlloc*2 + 10;
27538         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
27539         shell_check_oom(azNew);
27540         nAlloc = n2;
27541         azResult = azNew;
27542       }
27543       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
27544       shell_check_oom(azResult[nRow]);
27545       nRow++;
27546     }
27547     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
27548       rc = shellDatabaseError(p->db);
27549     }
27550 
27551     /* Pretty-print the contents of array azResult[] to the output */
27552     if( rc==0 && nRow>0 ){
27553       int len, maxlen = 0;
27554       int i, j;
27555       int nPrintCol, nPrintRow;
27556       for(i=0; i<nRow; i++){
27557         len = strlen30(azResult[i]);
27558         if( len>maxlen ) maxlen = len;
27559       }
27560       nPrintCol = 80/(maxlen+2);
27561       if( nPrintCol<1 ) nPrintCol = 1;
27562       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
27563       for(i=0; i<nPrintRow; i++){
27564         for(j=i; j<nRow; j+=nPrintRow){
27565           char *zSp = j<nPrintRow ? "" : "  ";
27566           oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
27567         }
27568         oputz("\n");
27569       }
27570     }
27571 
27572     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
27573     sqlite3_free(azResult);
27574   }else
27575 
27576 #ifndef SQLITE_SHELL_FIDDLE
27577   /* Begin redirecting output to the file "testcase-out.txt" */
27578   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
27579     output_reset(p);
27580     p->out = output_file_open("testcase-out.txt", 0);
27581     if( p->out==0 ){
27582       eputz("Error: cannot open 'testcase-out.txt'\n");
27583     }
27584     if( nArg>=2 ){
27585       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
27586     }else{
27587       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
27588     }
27589   }else
27590 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
27591 
27592 #ifndef SQLITE_UNTESTABLE
27593   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
27594     static const struct {
27595        const char *zCtrlName;   /* Name of a test-control option */
27596        int ctrlCode;            /* Integer code for that option */
27597        int unSafe;              /* Not valid unless --unsafe-testing */
27598        const char *zUsage;      /* Usage notes */
27599     } aCtrl[] = {
27600     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
27601     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
27602   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
27603   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
27604     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
27605     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
27606   /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
27607     {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
27608     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
27609     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
27610     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
27611     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
27612     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
27613 #ifdef YYCOVERAGE
27614     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
27615 #endif
27616     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
27617     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
27618     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
27619     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
27620     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
27621     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
27622     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
27623     {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
27624     };
27625     int testctrl = -1;
27626     int iCtrl = -1;
27627     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
27628     int isOk = 0;
27629     int i, n2;
27630     const char *zCmd = 0;
27631 
27632     open_db(p, 0);
27633     zCmd = nArg>=2 ? azArg[1] : "help";
27634 
27635     /* The argument can optionally begin with "-" or "--" */
27636     if( zCmd[0]=='-' && zCmd[1] ){
27637       zCmd++;
27638       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
27639     }
27640 
27641     /* --help lists all test-controls */
27642     if( cli_strcmp(zCmd,"help")==0 ){
27643       oputz("Available test-controls:\n");
27644       for(i=0; i<ArraySize(aCtrl); i++){
27645         if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
27646         oputf("  .testctrl %s %s\n",
27647               aCtrl[i].zCtrlName, aCtrl[i].zUsage);
27648       }
27649       rc = 1;
27650       goto meta_command_exit;
27651     }
27652 
27653     /* convert testctrl text option to value. allow any unique prefix
27654     ** of the option name, or a numerical value. */
27655     n2 = strlen30(zCmd);
27656     for(i=0; i<ArraySize(aCtrl); i++){
27657       if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
27658       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
27659         if( testctrl<0 ){
27660           testctrl = aCtrl[i].ctrlCode;
27661           iCtrl = i;
27662         }else{
27663           eputf("Error: ambiguous test-control: \"%s\"\n"
27664                 "Use \".testctrl --help\" for help\n", zCmd);
27665           rc = 1;
27666           goto meta_command_exit;
27667         }
27668       }
27669     }
27670     if( testctrl<0 ){
27671       eputf("Error: unknown test-control: %s\n"
27672             "Use \".testctrl --help\" for help\n", zCmd);
27673     }else{
27674       switch(testctrl){
27675 
27676         /* sqlite3_test_control(int, db, int) */
27677         case SQLITE_TESTCTRL_OPTIMIZATIONS:
27678         case SQLITE_TESTCTRL_FK_NO_ACTION:
27679           if( nArg==3 ){
27680             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
27681             rc2 = sqlite3_test_control(testctrl, p->db, opt);
27682             isOk = 3;
27683           }
27684           break;
27685 
27686         /* sqlite3_test_control(int) */
27687         case SQLITE_TESTCTRL_PRNG_SAVE:
27688         case SQLITE_TESTCTRL_PRNG_RESTORE:
27689         case SQLITE_TESTCTRL_BYTEORDER:
27690           if( nArg==2 ){
27691             rc2 = sqlite3_test_control(testctrl);
27692             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
27693           }
27694           break;
27695 
27696         /* sqlite3_test_control(int, uint) */
27697         case SQLITE_TESTCTRL_PENDING_BYTE:
27698           if( nArg==3 ){
27699             unsigned int opt = (unsigned int)integerValue(azArg[2]);
27700             rc2 = sqlite3_test_control(testctrl, opt);
27701             isOk = 3;
27702           }
27703           break;
27704 
27705         /* sqlite3_test_control(int, int, sqlite3*) */
27706         case SQLITE_TESTCTRL_PRNG_SEED:
27707           if( nArg==3 || nArg==4 ){
27708             int ii = (int)integerValue(azArg[2]);
27709             sqlite3 *db;
27710             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
27711               sqlite3_randomness(sizeof(ii),&ii);
27712               sputf(stdout, "-- random seed: %d\n", ii);
27713             }
27714             if( nArg==3 ){
27715               db = 0;
27716             }else{
27717               db = p->db;
27718               /* Make sure the schema has been loaded */
27719               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
27720             }
27721             rc2 = sqlite3_test_control(testctrl, ii, db);
27722             isOk = 3;
27723           }
27724           break;
27725 
27726         /* sqlite3_test_control(int, int) */
27727         case SQLITE_TESTCTRL_ASSERT:
27728         case SQLITE_TESTCTRL_ALWAYS:
27729           if( nArg==3 ){
27730             int opt = booleanValue(azArg[2]);
27731             rc2 = sqlite3_test_control(testctrl, opt);
27732             isOk = 1;
27733           }
27734           break;
27735 
27736         /* sqlite3_test_control(int, int) */
27737         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
27738         case SQLITE_TESTCTRL_NEVER_CORRUPT:
27739           if( nArg==3 ){
27740             int opt = booleanValue(azArg[2]);
27741             rc2 = sqlite3_test_control(testctrl, opt);
27742             isOk = 3;
27743           }
27744           break;
27745 
27746         /* sqlite3_test_control(int, int) */
27747         case SQLITE_TESTCTRL_USELONGDOUBLE: {
27748           int opt = -1;
27749           if( nArg==3 ){
27750             if( cli_strcmp(azArg[2],"default")==0 ){
27751               opt = 2;
27752             }else{
27753               opt = booleanValue(azArg[2]);
27754             }
27755           }
27756           rc2 = sqlite3_test_control(testctrl, opt);
27757           isOk = 1;
27758           break;
27759         }
27760 
27761         /* sqlite3_test_control(sqlite3*) */
27762         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
27763           rc2 = sqlite3_test_control(testctrl, p->db);
27764           isOk = 3;
27765           break;
27766 
27767         case SQLITE_TESTCTRL_IMPOSTER:
27768           if( nArg==5 ){
27769             rc2 = sqlite3_test_control(testctrl, p->db,
27770                           azArg[2],
27771                           integerValue(azArg[3]),
27772                           integerValue(azArg[4]));
27773             isOk = 3;
27774           }
27775           break;
27776 
27777         case SQLITE_TESTCTRL_SEEK_COUNT: {
27778           u64 x = 0;
27779           rc2 = sqlite3_test_control(testctrl, p->db, &x);
27780           oputf("%llu\n", x);
27781           isOk = 3;
27782           break;
27783         }
27784 
27785 #ifdef YYCOVERAGE
27786         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
27787           if( nArg==2 ){
27788             sqlite3_test_control(testctrl, p->out);
27789             isOk = 3;
27790           }
27791           break;
27792         }
27793 #endif
27794 #ifdef SQLITE_DEBUG
27795         case SQLITE_TESTCTRL_TUNE: {
27796           if( nArg==4 ){
27797             int id = (int)integerValue(azArg[2]);
27798             int val = (int)integerValue(azArg[3]);
27799             sqlite3_test_control(testctrl, id, &val);
27800             isOk = 3;
27801           }else if( nArg==3 ){
27802             int id = (int)integerValue(azArg[2]);
27803             sqlite3_test_control(testctrl, -id, &rc2);
27804             isOk = 1;
27805           }else if( nArg==2 ){
27806             int id = 1;
27807             while(1){
27808               int val = 0;
27809               rc2 = sqlite3_test_control(testctrl, -id, &val);
27810               if( rc2!=SQLITE_OK ) break;
27811               if( id>1 ) oputz("  ");
27812               oputf("%d: %d", id, val);
27813               id++;
27814             }
27815             if( id>1 ) oputz("\n");
27816             isOk = 3;
27817           }
27818           break;
27819         }
27820 #endif
27821         case SQLITE_TESTCTRL_SORTER_MMAP:
27822           if( nArg==3 ){
27823             int opt = (unsigned int)integerValue(azArg[2]);
27824             rc2 = sqlite3_test_control(testctrl, p->db, opt);
27825             isOk = 3;
27826           }
27827           break;
27828       }
27829     }
27830     if( isOk==0 && iCtrl>=0 ){
27831       oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
27832       rc = 1;
27833     }else if( isOk==1 ){
27834       oputf("%d\n", rc2);
27835     }else if( isOk==2 ){
27836       oputf("0x%08x\n", rc2);
27837     }
27838   }else
27839 #endif /* !defined(SQLITE_UNTESTABLE) */
27840 
27841   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
27842     open_db(p, 0);
27843     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
27844   }else
27845 
27846   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
27847     if( nArg==2 ){
27848       enableTimer = booleanValue(azArg[1]);
27849       if( enableTimer && !HAS_TIMER ){
27850         eputz("Error: timer not available on this system.\n");
27851         enableTimer = 0;
27852       }
27853     }else{
27854       eputz("Usage: .timer on|off\n");
27855       rc = 1;
27856     }
27857   }else
27858 
27859 #ifndef SQLITE_OMIT_TRACE
27860   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
27861     int mType = 0;
27862     int jj;
27863     open_db(p, 0);
27864     for(jj=1; jj<nArg; jj++){
27865       const char *z = azArg[jj];
27866       if( z[0]=='-' ){
27867         if( optionMatch(z, "expanded") ){
27868           p->eTraceType = SHELL_TRACE_EXPANDED;
27869         }
27870 #ifdef SQLITE_ENABLE_NORMALIZE
27871         else if( optionMatch(z, "normalized") ){
27872           p->eTraceType = SHELL_TRACE_NORMALIZED;
27873         }
27874 #endif
27875         else if( optionMatch(z, "plain") ){
27876           p->eTraceType = SHELL_TRACE_PLAIN;
27877         }
27878         else if( optionMatch(z, "profile") ){
27879           mType |= SQLITE_TRACE_PROFILE;
27880         }
27881         else if( optionMatch(z, "row") ){
27882           mType |= SQLITE_TRACE_ROW;
27883         }
27884         else if( optionMatch(z, "stmt") ){
27885           mType |= SQLITE_TRACE_STMT;
27886         }
27887         else if( optionMatch(z, "close") ){
27888           mType |= SQLITE_TRACE_CLOSE;
27889         }
27890         else {
27891           eputf("Unknown option \"%s\" on \".trace\"\n", z);
27892           rc = 1;
27893           goto meta_command_exit;
27894         }
27895       }else{
27896         output_file_close(p->traceOut);
27897         p->traceOut = output_file_open(z, 0);
27898       }
27899     }
27900     if( p->traceOut==0 ){
27901       sqlite3_trace_v2(p->db, 0, 0, 0);
27902     }else{
27903       if( mType==0 ) mType = SQLITE_TRACE_STMT;
27904       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
27905     }
27906   }else
27907 #endif /* !defined(SQLITE_OMIT_TRACE) */
27908 
27909 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27910   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
27911     int ii;
27912     int lenOpt;
27913     char *zOpt;
27914     if( nArg<2 ){
27915       eputz("Usage: .unmodule [--allexcept] NAME ...\n");
27916       rc = 1;
27917       goto meta_command_exit;
27918     }
27919     open_db(p, 0);
27920     zOpt = azArg[1];
27921     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
27922     lenOpt = (int)strlen(zOpt);
27923     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
27924       assert( azArg[nArg]==0 );
27925       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
27926     }else{
27927       for(ii=1; ii<nArg; ii++){
27928         sqlite3_create_module(p->db, azArg[ii], 0, 0);
27929       }
27930     }
27931   }else
27932 #endif
27933 
27934 #if SQLITE_USER_AUTHENTICATION
27935   if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
27936     if( nArg<2 ){
27937       eputz("Usage: .user SUBCOMMAND ...\n");
27938       rc = 1;
27939       goto meta_command_exit;
27940     }
27941     open_db(p, 0);
27942     if( cli_strcmp(azArg[1],"login")==0 ){
27943       if( nArg!=4 ){
27944         eputz("Usage: .user login USER PASSWORD\n");
27945         rc = 1;
27946         goto meta_command_exit;
27947       }
27948       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
27949                                      strlen30(azArg[3]));
27950       if( rc ){
27951         eputf("Authentication failed for user %s\n", azArg[2]);
27952         rc = 1;
27953       }
27954     }else if( cli_strcmp(azArg[1],"add")==0 ){
27955       if( nArg!=5 ){
27956         eputz("Usage: .user add USER PASSWORD ISADMIN\n");
27957         rc = 1;
27958         goto meta_command_exit;
27959       }
27960       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
27961                             booleanValue(azArg[4]));
27962       if( rc ){
27963         eputf("User-Add failed: %d\n", rc);
27964         rc = 1;
27965       }
27966     }else if( cli_strcmp(azArg[1],"edit")==0 ){
27967       if( nArg!=5 ){
27968         eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
27969         rc = 1;
27970         goto meta_command_exit;
27971       }
27972       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
27973                               booleanValue(azArg[4]));
27974       if( rc ){
27975         eputf("User-Edit failed: %d\n", rc);
27976         rc = 1;
27977       }
27978     }else if( cli_strcmp(azArg[1],"delete")==0 ){
27979       if( nArg!=3 ){
27980         eputz("Usage: .user delete USER\n");
27981         rc = 1;
27982         goto meta_command_exit;
27983       }
27984       rc = sqlite3_user_delete(p->db, azArg[2]);
27985       if( rc ){
27986         eputf("User-Delete failed: %d\n", rc);
27987         rc = 1;
27988       }
27989     }else{
27990       eputz("Usage: .user login|add|edit|delete ...\n");
27991       rc = 1;
27992       goto meta_command_exit;
27993     }
27994   }else
27995 #endif /* SQLITE_USER_AUTHENTICATION */
27996 
27997   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
27998     char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
27999     oputf("SQLite %s %s\n" /*extra-version-info*/,
28000           sqlite3_libversion(), sqlite3_sourceid());
28001 #if SQLITE_HAVE_ZLIB
28002     oputf("zlib version %s\n", zlibVersion());
28003 #endif
28004 #define CTIMEOPT_VAL_(opt) #opt
28005 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
28006 #if defined(__clang__) && defined(__clang_major__)
28007     oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
28008           CTIMEOPT_VAL(__clang_minor__) "."
28009           CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
28010 #elif defined(_MSC_VER)
28011     oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
28012 #elif defined(__GNUC__) && defined(__VERSION__)
28013     oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
28014 #endif
28015   }else
28016 
28017   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
28018     const char *zDbName = nArg==2 ? azArg[1] : "main";
28019     sqlite3_vfs *pVfs = 0;
28020     if( p->db ){
28021       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
28022       if( pVfs ){
28023         oputf("vfs.zName      = \"%s\"\n", pVfs->zName);
28024         oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
28025         oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
28026         oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
28027       }
28028     }
28029   }else
28030 
28031   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
28032     sqlite3_vfs *pVfs;
28033     sqlite3_vfs *pCurrent = 0;
28034     if( p->db ){
28035       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
28036     }
28037     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
28038       oputf("vfs.zName      = \"%s\"%s\n", pVfs->zName,
28039             pVfs==pCurrent ? "  <--- CURRENT" : "");
28040       oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
28041       oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
28042       oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
28043       if( pVfs->pNext ){
28044         oputz("-----------------------------------\n");
28045       }
28046     }
28047   }else
28048 
28049   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
28050     const char *zDbName = nArg==2 ? azArg[1] : "main";
28051     char *zVfsName = 0;
28052     if( p->db ){
28053       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
28054       if( zVfsName ){
28055         oputf("%s\n", zVfsName);
28056         sqlite3_free(zVfsName);
28057       }
28058     }
28059   }else
28060 
28061   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
28062     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
28063     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
28064   }else
28065 
28066   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
28067     int j;
28068     assert( nArg<=ArraySize(azArg) );
28069     p->nWidth = nArg-1;
28070     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
28071     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
28072     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
28073     for(j=1; j<nArg; j++){
28074       p->colWidth[j-1] = (int)integerValue(azArg[j]);
28075     }
28076   }else
28077 
28078   {
28079     eputf("Error: unknown command or invalid arguments: "
28080           " \"%s\". Enter \".help\" for help\n", azArg[0]);
28081     rc = 1;
28082   }
28083 
28084 meta_command_exit:
28085   if( p->outCount ){
28086     p->outCount--;
28087     if( p->outCount==0 ) output_reset(p);
28088   }
28089   p->bSafeMode = p->bSafeModePersist;
28090   return rc;
28091 }
28092 
28093 /* Line scan result and intermediate states (supporting scan resumption)
28094 */
28095 #ifndef CHAR_BIT
28096 # define CHAR_BIT 8
28097 #endif
28098 typedef enum {
28099   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
28100   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
28101   QSS_Start = 0
28102 } QuickScanState;
28103 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
28104 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
28105 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
28106 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
28107 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
28108 
28109 /*
28110 ** Scan line for classification to guide shell's handling.
28111 ** The scan is resumable for subsequent lines when prior
28112 ** return values are passed as the 2nd argument.
28113 */
quickscan(char * zLine,QuickScanState qss,SCAN_TRACKER_REFTYPE pst)28114 static QuickScanState quickscan(char *zLine, QuickScanState qss,
28115                                 SCAN_TRACKER_REFTYPE pst){
28116   char cin;
28117   char cWait = (char)qss; /* intentional narrowing loss */
28118   if( cWait==0 ){
28119   PlainScan:
28120     assert( cWait==0 );
28121     while( (cin = *zLine++)!=0 ){
28122       if( IsSpace(cin) )
28123         continue;
28124       switch (cin){
28125       case '-':
28126         if( *zLine!='-' )
28127           break;
28128         while((cin = *++zLine)!=0 )
28129           if( cin=='\n')
28130             goto PlainScan;
28131         return qss;
28132       case ';':
28133         qss |= QSS_EndingSemi;
28134         continue;
28135       case '/':
28136         if( *zLine=='*' ){
28137           ++zLine;
28138           cWait = '*';
28139           CONTINUE_PROMPT_AWAITS(pst, "/*");
28140           qss = QSS_SETV(qss, cWait);
28141           goto TermScan;
28142         }
28143         break;
28144       case '[':
28145         cin = ']';
28146         deliberate_fall_through;
28147       case '`': case '\'': case '"':
28148         cWait = cin;
28149         qss = QSS_HasDark | cWait;
28150         CONTINUE_PROMPT_AWAITC(pst, cin);
28151         goto TermScan;
28152       case '(':
28153         CONTINUE_PAREN_INCR(pst, 1);
28154         break;
28155       case ')':
28156         CONTINUE_PAREN_INCR(pst, -1);
28157         break;
28158       default:
28159         break;
28160       }
28161       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
28162     }
28163   }else{
28164   TermScan:
28165     while( (cin = *zLine++)!=0 ){
28166       if( cin==cWait ){
28167         switch( cWait ){
28168         case '*':
28169           if( *zLine != '/' )
28170             continue;
28171           ++zLine;
28172           cWait = 0;
28173           CONTINUE_PROMPT_AWAITC(pst, 0);
28174           qss = QSS_SETV(qss, 0);
28175           goto PlainScan;
28176         case '`': case '\'': case '"':
28177           if(*zLine==cWait){
28178             /* Swallow doubled end-delimiter.*/
28179             ++zLine;
28180             continue;
28181           }
28182           deliberate_fall_through;
28183         case ']':
28184           cWait = 0;
28185           CONTINUE_PROMPT_AWAITC(pst, 0);
28186           qss = QSS_SETV(qss, 0);
28187           goto PlainScan;
28188         default: assert(0);
28189         }
28190       }
28191     }
28192   }
28193   return qss;
28194 }
28195 
28196 /*
28197 ** Return TRUE if the line typed in is an SQL command terminator other
28198 ** than a semi-colon.  The SQL Server style "go" command is understood
28199 ** as is the Oracle "/".
28200 */
line_is_command_terminator(char * zLine)28201 static int line_is_command_terminator(char *zLine){
28202   while( IsSpace(zLine[0]) ){ zLine++; };
28203   if( zLine[0]=='/' )
28204     zLine += 1; /* Oracle */
28205   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
28206     zLine += 2; /* SQL Server */
28207   else
28208     return 0;
28209   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
28210 }
28211 
28212 /*
28213 ** The CLI needs a working sqlite3_complete() to work properly.  So error
28214 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
28215 */
28216 #ifdef SQLITE_OMIT_COMPLETE
28217 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
28218 #endif
28219 
28220 /*
28221 ** Return true if zSql is a complete SQL statement.  Return false if it
28222 ** ends in the middle of a string literal or C-style comment.
28223 */
line_is_complete(char * zSql,int nSql)28224 static int line_is_complete(char *zSql, int nSql){
28225   int rc;
28226   if( zSql==0 ) return 1;
28227   zSql[nSql] = ';';
28228   zSql[nSql+1] = 0;
28229   rc = sqlite3_complete(zSql);
28230   zSql[nSql] = 0;
28231   return rc;
28232 }
28233 
28234 /*
28235 ** Run a single line of SQL.  Return the number of errors.
28236 */
runOneSqlLine(ShellState * p,char * zSql,FILE * in,int startline)28237 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
28238   int rc;
28239   char *zErrMsg = 0;
28240 
28241   open_db(p, 0);
28242   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
28243   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
28244   BEGIN_TIMER;
28245   rc = shell_exec(p, zSql, &zErrMsg);
28246   END_TIMER;
28247   if( rc || zErrMsg ){
28248     char zPrefix[100];
28249     const char *zErrorTail;
28250     const char *zErrorType;
28251     if( zErrMsg==0 ){
28252       zErrorType = "Error";
28253       zErrorTail = sqlite3_errmsg(p->db);
28254     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
28255       zErrorType = "Parse error";
28256       zErrorTail = &zErrMsg[12];
28257     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
28258       zErrorType = "Runtime error";
28259       zErrorTail = &zErrMsg[10];
28260     }else{
28261       zErrorType = "Error";
28262       zErrorTail = zErrMsg;
28263     }
28264     if( in!=0 || !stdin_is_interactive ){
28265       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
28266                        "%s near line %d:", zErrorType, startline);
28267     }else{
28268       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
28269     }
28270     eputf("%s %s\n", zPrefix, zErrorTail);
28271     sqlite3_free(zErrMsg);
28272     zErrMsg = 0;
28273     return 1;
28274   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
28275     char zLineBuf[2000];
28276     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
28277             "changes: %lld   total_changes: %lld",
28278             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
28279     oputf("%s\n", zLineBuf);
28280   }
28281   return 0;
28282 }
28283 
echo_group_input(ShellState * p,const char * zDo)28284 static void echo_group_input(ShellState *p, const char *zDo){
28285   if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
28286 }
28287 
28288 #ifdef SQLITE_SHELL_FIDDLE
28289 /*
28290 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
28291 ** impl because we need the global shellState and cannot access it from that
28292 ** function without moving lots of code around (creating a larger/messier diff).
28293 */
one_input_line(FILE * in,char * zPrior,int isContinuation)28294 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
28295   /* Parse the next line from shellState.wasm.zInput. */
28296   const char *zBegin = shellState.wasm.zPos;
28297   const char *z = zBegin;
28298   char *zLine = 0;
28299   i64 nZ = 0;
28300 
28301   UNUSED_PARAMETER(in);
28302   UNUSED_PARAMETER(isContinuation);
28303   if(!z || !*z){
28304     return 0;
28305   }
28306   while(*z && isspace(*z)) ++z;
28307   zBegin = z;
28308   for(; *z && '\n'!=*z; ++nZ, ++z){}
28309   if(nZ>0 && '\r'==zBegin[nZ-1]){
28310     --nZ;
28311   }
28312   shellState.wasm.zPos = z;
28313   zLine = realloc(zPrior, nZ+1);
28314   shell_check_oom(zLine);
28315   memcpy(zLine, zBegin, nZ);
28316   zLine[nZ] = 0;
28317   return zLine;
28318 }
28319 #endif /* SQLITE_SHELL_FIDDLE */
28320 
28321 /*
28322 ** Read input from *in and process it.  If *in==0 then input
28323 ** is interactive - the user is typing it it.  Otherwise, input
28324 ** is coming from a file or device.  A prompt is issued and history
28325 ** is saved only if input is interactive.  An interrupt signal will
28326 ** cause this routine to exit immediately, unless input is interactive.
28327 **
28328 ** Return the number of errors.
28329 */
process_input(ShellState * p)28330 static int process_input(ShellState *p){
28331   char *zLine = 0;          /* A single input line */
28332   char *zSql = 0;           /* Accumulated SQL text */
28333   i64 nLine;                /* Length of current line */
28334   i64 nSql = 0;             /* Bytes of zSql[] used */
28335   i64 nAlloc = 0;           /* Allocated zSql[] space */
28336   int rc;                   /* Error code */
28337   int errCnt = 0;           /* Number of errors seen */
28338   i64 startline = 0;        /* Line number for start of current input */
28339   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
28340 
28341   if( p->inputNesting==MAX_INPUT_NESTING ){
28342     /* This will be more informative in a later version. */
28343     eputf("Input nesting limit (%d) reached at line %d."
28344           " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
28345     return 1;
28346   }
28347   ++p->inputNesting;
28348   p->lineno = 0;
28349   CONTINUE_PROMPT_RESET;
28350   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
28351     fflush(p->out);
28352     zLine = one_input_line(p->in, zLine, nSql>0);
28353     if( zLine==0 ){
28354       /* End of input */
28355       if( p->in==0 && stdin_is_interactive ) oputz("\n");
28356       break;
28357     }
28358     if( seenInterrupt ){
28359       if( p->in!=0 ) break;
28360       seenInterrupt = 0;
28361     }
28362     p->lineno++;
28363     if( QSS_INPLAIN(qss)
28364         && line_is_command_terminator(zLine)
28365         && line_is_complete(zSql, nSql) ){
28366       memcpy(zLine,";",2);
28367     }
28368     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
28369     if( QSS_PLAINWHITE(qss) && nSql==0 ){
28370       /* Just swallow single-line whitespace */
28371       echo_group_input(p, zLine);
28372       qss = QSS_Start;
28373       continue;
28374     }
28375     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
28376       CONTINUE_PROMPT_RESET;
28377       echo_group_input(p, zLine);
28378       if( zLine[0]=='.' ){
28379         rc = do_meta_command(zLine, p);
28380         if( rc==2 ){ /* exit requested */
28381           break;
28382         }else if( rc ){
28383           errCnt++;
28384         }
28385       }
28386       qss = QSS_Start;
28387       continue;
28388     }
28389     /* No single-line dispositions remain; accumulate line(s). */
28390     nLine = strlen(zLine);
28391     if( nSql+nLine+2>=nAlloc ){
28392       /* Grow buffer by half-again increments when big. */
28393       nAlloc = nSql+(nSql>>1)+nLine+100;
28394       zSql = realloc(zSql, nAlloc);
28395       shell_check_oom(zSql);
28396     }
28397     if( nSql==0 ){
28398       i64 i;
28399       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
28400       assert( nAlloc>0 && zSql!=0 );
28401       memcpy(zSql, zLine+i, nLine+1-i);
28402       startline = p->lineno;
28403       nSql = nLine-i;
28404     }else{
28405       zSql[nSql++] = '\n';
28406       memcpy(zSql+nSql, zLine, nLine+1);
28407       nSql += nLine;
28408     }
28409     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
28410       echo_group_input(p, zSql);
28411       errCnt += runOneSqlLine(p, zSql, p->in, startline);
28412       CONTINUE_PROMPT_RESET;
28413       nSql = 0;
28414       if( p->outCount ){
28415         output_reset(p);
28416         p->outCount = 0;
28417       }else{
28418         clearTempFile(p);
28419       }
28420       p->bSafeMode = p->bSafeModePersist;
28421       qss = QSS_Start;
28422     }else if( nSql && QSS_PLAINWHITE(qss) ){
28423       echo_group_input(p, zSql);
28424       nSql = 0;
28425       qss = QSS_Start;
28426     }
28427   }
28428   if( nSql ){
28429     /* This may be incomplete. Let the SQL parser deal with that. */
28430     echo_group_input(p, zSql);
28431     errCnt += runOneSqlLine(p, zSql, p->in, startline);
28432     CONTINUE_PROMPT_RESET;
28433   }
28434   free(zSql);
28435   free(zLine);
28436   --p->inputNesting;
28437   return errCnt>0;
28438 }
28439 
28440 /*
28441 ** Return a pathname which is the user's home directory.  A
28442 ** 0 return indicates an error of some kind.
28443 */
find_home_dir(int clearFlag)28444 static char *find_home_dir(int clearFlag){
28445   static char *home_dir = NULL;
28446   if( clearFlag ){
28447     free(home_dir);
28448     home_dir = 0;
28449     return 0;
28450   }
28451   if( home_dir ) return home_dir;
28452 
28453 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
28454      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
28455   {
28456     struct passwd *pwent;
28457     uid_t uid = getuid();
28458     if( (pwent=getpwuid(uid)) != NULL) {
28459       home_dir = pwent->pw_dir;
28460     }
28461   }
28462 #endif
28463 
28464 #if defined(_WIN32_WCE)
28465   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
28466    */
28467   home_dir = "/";
28468 #else
28469 
28470 #if defined(_WIN32) || defined(WIN32)
28471   if (!home_dir) {
28472     home_dir = getenv("USERPROFILE");
28473   }
28474 #endif
28475 
28476   if (!home_dir) {
28477     home_dir = getenv("HOME");
28478   }
28479 
28480 #if defined(_WIN32) || defined(WIN32)
28481   if (!home_dir) {
28482     char *zDrive, *zPath;
28483     int n;
28484     zDrive = getenv("HOMEDRIVE");
28485     zPath = getenv("HOMEPATH");
28486     if( zDrive && zPath ){
28487       n = strlen30(zDrive) + strlen30(zPath) + 1;
28488       home_dir = malloc( n );
28489       if( home_dir==0 ) return 0;
28490       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
28491       return home_dir;
28492     }
28493     home_dir = "c:\\";
28494   }
28495 #endif
28496 
28497 #endif /* !_WIN32_WCE */
28498 
28499   if( home_dir ){
28500     i64 n = strlen(home_dir) + 1;
28501     char *z = malloc( n );
28502     if( z ) memcpy(z, home_dir, n);
28503     home_dir = z;
28504   }
28505 
28506   return home_dir;
28507 }
28508 
28509 /*
28510 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
28511 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
28512 ** the path to it, else return 0. The result is cached for
28513 ** subsequent calls.
28514 */
find_xdg_config(void)28515 static const char *find_xdg_config(void){
28516 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
28517      || defined(__RTP__) || defined(_WRS_KERNEL)
28518   return 0;
28519 #else
28520   static int alreadyTried = 0;
28521   static char *zConfig = 0;
28522   const char *zXdgHome;
28523 
28524   if( alreadyTried!=0 ){
28525     return zConfig;
28526   }
28527   alreadyTried = 1;
28528   zXdgHome = getenv("XDG_CONFIG_HOME");
28529   if( zXdgHome==0 ){
28530     return 0;
28531   }
28532   zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
28533   shell_check_oom(zConfig);
28534   if( access(zConfig,0)!=0 ){
28535     sqlite3_free(zConfig);
28536     zConfig = 0;
28537   }
28538   return zConfig;
28539 #endif
28540 }
28541 
28542 /*
28543 ** Read input from the file given by sqliterc_override.  Or if that
28544 ** parameter is NULL, take input from the first of find_xdg_config()
28545 ** or ~/.sqliterc which is found.
28546 **
28547 ** Returns the number of errors.
28548 */
process_sqliterc(ShellState * p,const char * sqliterc_override)28549 static void process_sqliterc(
28550   ShellState *p,                  /* Configuration data */
28551   const char *sqliterc_override   /* Name of config file. NULL to use default */
28552 ){
28553   char *home_dir = NULL;
28554   const char *sqliterc = sqliterc_override;
28555   char *zBuf = 0;
28556   FILE *inSaved = p->in;
28557   int savedLineno = p->lineno;
28558 
28559   if( sqliterc == NULL ){
28560     sqliterc = find_xdg_config();
28561   }
28562   if( sqliterc == NULL ){
28563     home_dir = find_home_dir(0);
28564     if( home_dir==0 ){
28565       eputz("-- warning: cannot find home directory;"
28566             " cannot read ~/.sqliterc\n");
28567       return;
28568     }
28569     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
28570     shell_check_oom(zBuf);
28571     sqliterc = zBuf;
28572   }
28573   p->in = fopen(sqliterc,"rb");
28574   if( p->in ){
28575     if( stdin_is_interactive ){
28576       eputf("-- Loading resources from %s\n", sqliterc);
28577     }
28578     if( process_input(p) && bail_on_error ) exit(1);
28579     fclose(p->in);
28580   }else if( sqliterc_override!=0 ){
28581     eputf("cannot open: \"%s\"\n", sqliterc);
28582     if( bail_on_error ) exit(1);
28583   }
28584   p->in = inSaved;
28585   p->lineno = savedLineno;
28586   sqlite3_free(zBuf);
28587 }
28588 
28589 /*
28590 ** Show available command line options
28591 */
28592 static const char zOptions[] =
28593   "   --                   treat no subsequent arguments as options\n"
28594 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
28595   "   -A ARGS...           run \".archive ARGS\" and exit\n"
28596 #endif
28597   "   -append              append the database to the end of the file\n"
28598   "   -ascii               set output mode to 'ascii'\n"
28599   "   -bail                stop after hitting an error\n"
28600   "   -batch               force batch I/O\n"
28601   "   -box                 set output mode to 'box'\n"
28602   "   -column              set output mode to 'column'\n"
28603   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
28604   "   -csv                 set output mode to 'csv'\n"
28605 #if !defined(SQLITE_OMIT_DESERIALIZE)
28606   "   -deserialize         open the database using sqlite3_deserialize()\n"
28607 #endif
28608   "   -echo                print inputs before execution\n"
28609   "   -init FILENAME       read/process named file\n"
28610   "   -[no]header          turn headers on or off\n"
28611 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
28612   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
28613 #endif
28614   "   -help                show this message\n"
28615   "   -html                set output mode to HTML\n"
28616   "   -interactive         force interactive I/O\n"
28617   "   -json                set output mode to 'json'\n"
28618   "   -line                set output mode to 'line'\n"
28619   "   -list                set output mode to 'list'\n"
28620   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
28621   "   -markdown            set output mode to 'markdown'\n"
28622 #if !defined(SQLITE_OMIT_DESERIALIZE)
28623   "   -maxsize N           maximum size for a --deserialize database\n"
28624 #endif
28625   "   -memtrace            trace all memory allocations and deallocations\n"
28626   "   -mmap N              default mmap size set to N\n"
28627 #ifdef SQLITE_ENABLE_MULTIPLEX
28628   "   -multiplex           enable the multiplexor VFS\n"
28629 #endif
28630   "   -newline SEP         set output row separator. Default: '\\n'\n"
28631   "   -nofollow            refuse to open symbolic links to database files\n"
28632   "   -nonce STRING        set the safe-mode escape nonce\n"
28633   "   -no-rowid-in-view    Disable rowid-in-view using sqlite3_config()\n"
28634   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
28635   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
28636   "   -pcachetrace         trace all page cache operations\n"
28637   "   -quote               set output mode to 'quote'\n"
28638   "   -readonly            open the database read-only\n"
28639   "   -safe                enable safe-mode\n"
28640   "   -separator SEP       set output column separator. Default: '|'\n"
28641 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
28642   "   -sorterref SIZE      sorter references threshold size\n"
28643 #endif
28644   "   -stats               print memory stats before each finalize\n"
28645   "   -table               set output mode to 'table'\n"
28646   "   -tabs                set output mode to 'tabs'\n"
28647   "   -unsafe-testing      allow unsafe commands and modes for testing\n"
28648   "   -version             show SQLite version\n"
28649   "   -vfs NAME            use NAME as the default VFS\n"
28650 #ifdef SQLITE_ENABLE_VFSTRACE
28651   "   -vfstrace            enable tracing of all VFS calls\n"
28652 #endif
28653 #ifdef SQLITE_HAVE_ZLIB
28654   "   -zip                 open the file as a ZIP Archive\n"
28655 #endif
28656 ;
usage(int showDetail)28657 static void usage(int showDetail){
28658   eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
28659        "FILENAME is the name of an SQLite database. A new database is created\n"
28660        "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
28661   if( showDetail ){
28662     eputf("OPTIONS include:\n%s", zOptions);
28663   }else{
28664     eputz("Use the -help option for additional information\n");
28665   }
28666   exit(1);
28667 }
28668 
28669 /*
28670 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
28671 ** error message if it is initialized.
28672 */
verify_uninitialized(void)28673 static void verify_uninitialized(void){
28674   if( sqlite3_config(-1)==SQLITE_MISUSE ){
28675     sputz(stdout, "WARNING: attempt to configure SQLite after"
28676           " initialization.\n");
28677   }
28678 }
28679 
28680 /*
28681 ** Initialize the state information in data
28682 */
main_init(ShellState * data)28683 static void main_init(ShellState *data) {
28684   memset(data, 0, sizeof(*data));
28685   data->normalMode = data->cMode = data->mode = MODE_List;
28686   data->autoExplain = 1;
28687   data->pAuxDb = &data->aAuxDb[0];
28688   memcpy(data->colSeparator,SEP_Column, 2);
28689   memcpy(data->rowSeparator,SEP_Row, 2);
28690   data->showHeader = 0;
28691   data->shellFlgs = SHFLG_Lookaside;
28692   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
28693 #if !defined(SQLITE_SHELL_FIDDLE)
28694   verify_uninitialized();
28695 #endif
28696   sqlite3_config(SQLITE_CONFIG_URI, 1);
28697   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
28698   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
28699   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
28700 }
28701 
28702 /*
28703 ** Output text to the console in a font that attracts extra attention.
28704 */
28705 #if defined(_WIN32) || defined(WIN32)
printBold(const char * zText)28706 static void printBold(const char *zText){
28707 #if !SQLITE_OS_WINRT
28708   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
28709   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
28710   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
28711   SetConsoleTextAttribute(out,
28712          FOREGROUND_RED|FOREGROUND_INTENSITY
28713   );
28714 #endif
28715   oputz(zText);
28716 #if !SQLITE_OS_WINRT
28717   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
28718 #endif
28719 }
28720 #else
printBold(const char * zText)28721 static void printBold(const char *zText){
28722   oputf("\033[1m%s\033[0m", zText);
28723 }
28724 #endif
28725 
28726 /*
28727 ** Get the argument to an --option.  Throw an error and die if no argument
28728 ** is available.
28729 */
cmdline_option_value(int argc,char ** argv,int i)28730 static char *cmdline_option_value(int argc, char **argv, int i){
28731   if( i==argc ){
28732     eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
28733     exit(1);
28734   }
28735   return argv[i];
28736 }
28737 
sayAbnormalExit(void)28738 static void sayAbnormalExit(void){
28739   if( seenInterrupt ) eputz("Program interrupted.\n");
28740 }
28741 
28742 #ifndef SQLITE_SHELL_IS_UTF8
28743 #  if (defined(_WIN32) || defined(WIN32)) \
28744    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
28745 #    define SQLITE_SHELL_IS_UTF8          (0)
28746 #  else
28747 #    define SQLITE_SHELL_IS_UTF8          (1)
28748 #  endif
28749 #endif
28750 
28751 #ifdef SQLITE_SHELL_FIDDLE
28752 #  define main fiddle_main
28753 #endif
28754 
28755 #if SQLITE_SHELL_IS_UTF8
main(int argc,char ** argv)28756 int SQLITE_CDECL main(int argc, char **argv){
28757 #else
28758 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
28759   char **argv;
28760 #endif
28761 #ifdef SQLITE_DEBUG
28762   sqlite3_int64 mem_main_enter = 0;
28763 #endif
28764   char *zErrMsg = 0;
28765 #ifdef SQLITE_SHELL_FIDDLE
28766 #  define data shellState
28767 #else
28768   ShellState data;
28769   StreamsAreConsole consStreams = SAC_NoConsole;
28770 #endif
28771   const char *zInitFile = 0;
28772   int i;
28773   int rc = 0;
28774   int warnInmemoryDb = 0;
28775   int readStdin = 1;
28776   int nCmd = 0;
28777   int nOptsEnd = argc;
28778   char **azCmd = 0;
28779   const char *zVfs = 0;           /* Value of -vfs command-line option */
28780 #if !SQLITE_SHELL_IS_UTF8
28781   char **argvToFree = 0;
28782   int argcToFree = 0;
28783 #endif
28784   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
28785 
28786 #ifdef SQLITE_SHELL_FIDDLE
28787   stdin_is_interactive = 0;
28788   stdout_is_console = 1;
28789   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
28790 #else
28791   consStreams = consoleClassifySetup(stdin, stdout, stderr);
28792   stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
28793   stdout_is_console = (consStreams & SAC_OutConsole)!=0;
28794   atexit(consoleRestore);
28795 #endif
28796   atexit(sayAbnormalExit);
28797 #ifdef SQLITE_DEBUG
28798   mem_main_enter = sqlite3_memory_used();
28799 #endif
28800 #if !defined(_WIN32_WCE)
28801   if( getenv("SQLITE_DEBUG_BREAK") ){
28802     if( isatty(0) && isatty(2) ){
28803       eputf("attach debugger to process %d and press any key to continue.\n",
28804             GETPID());
28805       fgetc(stdin);
28806     }else{
28807 #if defined(_WIN32) || defined(WIN32)
28808 #if SQLITE_OS_WINRT
28809       __debugbreak();
28810 #else
28811       DebugBreak();
28812 #endif
28813 #elif defined(SIGTRAP)
28814       raise(SIGTRAP);
28815 #endif
28816     }
28817   }
28818 #endif
28819   /* Register a valid signal handler early, before much else is done. */
28820 #ifdef SIGINT
28821   signal(SIGINT, interrupt_handler);
28822 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
28823   if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
28824     eputz("No ^C handler.\n");
28825   }
28826 #endif
28827 
28828 #if USE_SYSTEM_SQLITE+0!=1
28829   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
28830     eputf("SQLite header and source version mismatch\n%s\n%s\n",
28831           sqlite3_sourceid(), SQLITE_SOURCE_ID);
28832     exit(1);
28833   }
28834 #endif
28835   main_init(&data);
28836 
28837   /* On Windows, we must translate command-line arguments into UTF-8.
28838   ** The SQLite memory allocator subsystem has to be enabled in order to
28839   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
28840   ** subsequent sqlite3_config() calls will work.  So copy all results into
28841   ** memory that does not come from the SQLite memory allocator.
28842   */
28843 #if !SQLITE_SHELL_IS_UTF8
28844   sqlite3_initialize();
28845   argvToFree = malloc(sizeof(argv[0])*argc*2);
28846   shell_check_oom(argvToFree);
28847   argcToFree = argc;
28848   argv = argvToFree + argc;
28849   for(i=0; i<argc; i++){
28850     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
28851     i64 n;
28852     shell_check_oom(z);
28853     n = strlen(z);
28854     argv[i] = malloc( n+1 );
28855     shell_check_oom(argv[i]);
28856     memcpy(argv[i], z, n+1);
28857     argvToFree[i] = argv[i];
28858     sqlite3_free(z);
28859   }
28860   sqlite3_shutdown();
28861 #endif
28862 
28863   assert( argc>=1 && argv && argv[0] );
28864   Argv0 = argv[0];
28865 
28866 #ifdef SQLITE_SHELL_DBNAME_PROC
28867   {
28868     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
28869     ** of a C-function that will provide the name of the database file.  Use
28870     ** this compile-time option to embed this shell program in larger
28871     ** applications. */
28872     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
28873     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
28874     warnInmemoryDb = 0;
28875   }
28876 #endif
28877 
28878   /* Do an initial pass through the command-line argument to locate
28879   ** the name of the database file, the name of the initialization file,
28880   ** the size of the alternative malloc heap, options affecting commands
28881   ** or SQL run from the command line, and the first command to execute.
28882   */
28883 #ifndef SQLITE_SHELL_FIDDLE
28884   verify_uninitialized();
28885 #endif
28886   for(i=1; i<argc; i++){
28887     char *z;
28888     z = argv[i];
28889     if( z[0]!='-' || i>nOptsEnd ){
28890       if( data.aAuxDb->zDbFilename==0 ){
28891         data.aAuxDb->zDbFilename = z;
28892       }else{
28893         /* Excess arguments are interpreted as SQL (or dot-commands) and
28894         ** mean that nothing is read from stdin */
28895         readStdin = 0;
28896         nCmd++;
28897         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
28898         shell_check_oom(azCmd);
28899         azCmd[nCmd-1] = z;
28900       }
28901       continue;
28902     }
28903     if( z[1]=='-' ) z++;
28904     if( cli_strcmp(z, "-")==0 ){
28905       nOptsEnd = i;
28906       continue;
28907     }else if( cli_strcmp(z,"-separator")==0
28908      || cli_strcmp(z,"-nullvalue")==0
28909      || cli_strcmp(z,"-newline")==0
28910      || cli_strcmp(z,"-cmd")==0
28911     ){
28912       (void)cmdline_option_value(argc, argv, ++i);
28913     }else if( cli_strcmp(z,"-init")==0 ){
28914       zInitFile = cmdline_option_value(argc, argv, ++i);
28915     }else if( cli_strcmp(z,"-interactive")==0 ){
28916       /* Need to check for interactive override here to so that it can
28917       ** affect console setup (for Windows only) and testing thereof.
28918       */
28919       stdin_is_interactive = 1;
28920     }else if( cli_strcmp(z,"-batch")==0 ){
28921       /* Need to check for batch mode here to so we can avoid printing
28922       ** informational messages (like from process_sqliterc) before
28923       ** we do the actual processing of arguments later in a second pass.
28924       */
28925       stdin_is_interactive = 0;
28926     }else if( cli_strcmp(z,"-utf8")==0 ){
28927     }else if( cli_strcmp(z,"-no-utf8")==0 ){
28928     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
28929       int val = 0;
28930       sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
28931       assert( val==0 );
28932     }else if( cli_strcmp(z,"-heap")==0 ){
28933 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
28934       const char *zSize;
28935       sqlite3_int64 szHeap;
28936 
28937       zSize = cmdline_option_value(argc, argv, ++i);
28938       szHeap = integerValue(zSize);
28939       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
28940       verify_uninitialized();
28941       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
28942 #else
28943       (void)cmdline_option_value(argc, argv, ++i);
28944 #endif
28945     }else if( cli_strcmp(z,"-pagecache")==0 ){
28946       sqlite3_int64 n, sz;
28947       sz = integerValue(cmdline_option_value(argc,argv,++i));
28948       if( sz>70000 ) sz = 70000;
28949       if( sz<0 ) sz = 0;
28950       n = integerValue(cmdline_option_value(argc,argv,++i));
28951       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
28952         n = 0xffffffffffffLL/sz;
28953       }
28954       verify_uninitialized();
28955       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
28956                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
28957       data.shellFlgs |= SHFLG_Pagecache;
28958     }else if( cli_strcmp(z,"-lookaside")==0 ){
28959       int n, sz;
28960       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
28961       if( sz<0 ) sz = 0;
28962       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
28963       if( n<0 ) n = 0;
28964       verify_uninitialized();
28965       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
28966       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
28967     }else if( cli_strcmp(z,"-threadsafe")==0 ){
28968       int n;
28969       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
28970       verify_uninitialized();
28971       switch( n ){
28972          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
28973          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
28974          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
28975       }
28976 #ifdef SQLITE_ENABLE_VFSTRACE
28977     }else if( cli_strcmp(z,"-vfstrace")==0 ){
28978       extern int vfstrace_register(
28979          const char *zTraceName,
28980          const char *zOldVfsName,
28981          int (*xOut)(const char*,void*),
28982          void *pOutArg,
28983          int makeDefault
28984       );
28985       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
28986 #endif
28987 #ifdef SQLITE_ENABLE_MULTIPLEX
28988     }else if( cli_strcmp(z,"-multiplex")==0 ){
28989       extern int sqlite3_multiplex_initialize(const char*,int);
28990       sqlite3_multiplex_initialize(0, 1);
28991 #endif
28992     }else if( cli_strcmp(z,"-mmap")==0 ){
28993       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
28994       verify_uninitialized();
28995       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
28996 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
28997     }else if( cli_strcmp(z,"-sorterref")==0 ){
28998       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
28999       verify_uninitialized();
29000       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
29001 #endif
29002     }else if( cli_strcmp(z,"-vfs")==0 ){
29003       zVfs = cmdline_option_value(argc, argv, ++i);
29004 #ifdef SQLITE_HAVE_ZLIB
29005     }else if( cli_strcmp(z,"-zip")==0 ){
29006       data.openMode = SHELL_OPEN_ZIPFILE;
29007 #endif
29008     }else if( cli_strcmp(z,"-append")==0 ){
29009       data.openMode = SHELL_OPEN_APPENDVFS;
29010 #ifndef SQLITE_OMIT_DESERIALIZE
29011     }else if( cli_strcmp(z,"-deserialize")==0 ){
29012       data.openMode = SHELL_OPEN_DESERIALIZE;
29013     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29014       data.szMax = integerValue(argv[++i]);
29015 #endif
29016     }else if( cli_strcmp(z,"-readonly")==0 ){
29017       data.openMode = SHELL_OPEN_READONLY;
29018     }else if( cli_strcmp(z,"-nofollow")==0 ){
29019       data.openFlags = SQLITE_OPEN_NOFOLLOW;
29020 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
29021     }else if( cli_strncmp(z, "-A",2)==0 ){
29022       /* All remaining command-line arguments are passed to the ".archive"
29023       ** command, so ignore them */
29024       break;
29025 #endif
29026     }else if( cli_strcmp(z, "-memtrace")==0 ){
29027       sqlite3MemTraceActivate(stderr);
29028     }else if( cli_strcmp(z, "-pcachetrace")==0 ){
29029       sqlite3PcacheTraceActivate(stderr);
29030     }else if( cli_strcmp(z,"-bail")==0 ){
29031       bail_on_error = 1;
29032     }else if( cli_strcmp(z,"-nonce")==0 ){
29033       free(data.zNonce);
29034       data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
29035     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29036       ShellSetFlag(&data,SHFLG_TestingMode);
29037     }else if( cli_strcmp(z,"-safe")==0 ){
29038       /* no-op - catch this on the second pass */
29039     }
29040   }
29041 #ifndef SQLITE_SHELL_FIDDLE
29042   verify_uninitialized();
29043 #endif
29044 
29045 
29046 #ifdef SQLITE_SHELL_INIT_PROC
29047   {
29048     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
29049     ** of a C-function that will perform initialization actions on SQLite that
29050     ** occur just before or after sqlite3_initialize(). Use this compile-time
29051     ** option to embed this shell program in larger applications. */
29052     extern void SQLITE_SHELL_INIT_PROC(void);
29053     SQLITE_SHELL_INIT_PROC();
29054   }
29055 #else
29056   /* All the sqlite3_config() calls have now been made. So it is safe
29057   ** to call sqlite3_initialize() and process any command line -vfs option. */
29058   sqlite3_initialize();
29059 #endif
29060 
29061   if( zVfs ){
29062     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
29063     if( pVfs ){
29064       sqlite3_vfs_register(pVfs, 1);
29065     }else{
29066       eputf("no such VFS: \"%s\"\n", zVfs);
29067       exit(1);
29068     }
29069   }
29070 
29071   if( data.pAuxDb->zDbFilename==0 ){
29072 #ifndef SQLITE_OMIT_MEMORYDB
29073     data.pAuxDb->zDbFilename = ":memory:";
29074     warnInmemoryDb = argc==1;
29075 #else
29076     eputf("%s: Error: no database filename specified\n", Argv0);
29077     return 1;
29078 #endif
29079   }
29080   data.out = stdout;
29081 #ifndef SQLITE_SHELL_FIDDLE
29082   sqlite3_appendvfs_init(0,0,0);
29083 #endif
29084 
29085   /* Go ahead and open the database file if it already exists.  If the
29086   ** file does not exist, delay opening it.  This prevents empty database
29087   ** files from being created if a user mistypes the database name argument
29088   ** to the sqlite command-line tool.
29089   */
29090   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
29091     open_db(&data, 0);
29092   }
29093 
29094   /* Process the initialization file if there is one.  If no -init option
29095   ** is given on the command line, look for a file named ~/.sqliterc and
29096   ** try to process it.
29097   */
29098   process_sqliterc(&data,zInitFile);
29099 
29100   /* Make a second pass through the command-line argument and set
29101   ** options.  This second pass is delayed until after the initialization
29102   ** file is processed so that the command-line arguments will override
29103   ** settings in the initialization file.
29104   */
29105   for(i=1; i<argc; i++){
29106     char *z = argv[i];
29107     if( z[0]!='-' || i>=nOptsEnd ) continue;
29108     if( z[1]=='-' ){ z++; }
29109     if( cli_strcmp(z,"-init")==0 ){
29110       i++;
29111     }else if( cli_strcmp(z,"-html")==0 ){
29112       data.mode = MODE_Html;
29113     }else if( cli_strcmp(z,"-list")==0 ){
29114       data.mode = MODE_List;
29115     }else if( cli_strcmp(z,"-quote")==0 ){
29116       data.mode = MODE_Quote;
29117       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
29118       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
29119     }else if( cli_strcmp(z,"-line")==0 ){
29120       data.mode = MODE_Line;
29121     }else if( cli_strcmp(z,"-column")==0 ){
29122       data.mode = MODE_Column;
29123     }else if( cli_strcmp(z,"-json")==0 ){
29124       data.mode = MODE_Json;
29125     }else if( cli_strcmp(z,"-markdown")==0 ){
29126       data.mode = MODE_Markdown;
29127     }else if( cli_strcmp(z,"-table")==0 ){
29128       data.mode = MODE_Table;
29129     }else if( cli_strcmp(z,"-box")==0 ){
29130       data.mode = MODE_Box;
29131     }else if( cli_strcmp(z,"-csv")==0 ){
29132       data.mode = MODE_Csv;
29133       memcpy(data.colSeparator,",",2);
29134 #ifdef SQLITE_HAVE_ZLIB
29135     }else if( cli_strcmp(z,"-zip")==0 ){
29136       data.openMode = SHELL_OPEN_ZIPFILE;
29137 #endif
29138     }else if( cli_strcmp(z,"-append")==0 ){
29139       data.openMode = SHELL_OPEN_APPENDVFS;
29140 #ifndef SQLITE_OMIT_DESERIALIZE
29141     }else if( cli_strcmp(z,"-deserialize")==0 ){
29142       data.openMode = SHELL_OPEN_DESERIALIZE;
29143     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29144       data.szMax = integerValue(argv[++i]);
29145 #endif
29146     }else if( cli_strcmp(z,"-readonly")==0 ){
29147       data.openMode = SHELL_OPEN_READONLY;
29148     }else if( cli_strcmp(z,"-nofollow")==0 ){
29149       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
29150     }else if( cli_strcmp(z,"-ascii")==0 ){
29151       data.mode = MODE_Ascii;
29152       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
29153       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
29154     }else if( cli_strcmp(z,"-tabs")==0 ){
29155       data.mode = MODE_List;
29156       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
29157       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
29158     }else if( cli_strcmp(z,"-separator")==0 ){
29159       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
29160                        "%s",cmdline_option_value(argc,argv,++i));
29161     }else if( cli_strcmp(z,"-newline")==0 ){
29162       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
29163                        "%s",cmdline_option_value(argc,argv,++i));
29164     }else if( cli_strcmp(z,"-nullvalue")==0 ){
29165       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
29166                        "%s",cmdline_option_value(argc,argv,++i));
29167     }else if( cli_strcmp(z,"-header")==0 ){
29168       data.showHeader = 1;
29169       ShellSetFlag(&data, SHFLG_HeaderSet);
29170      }else if( cli_strcmp(z,"-noheader")==0 ){
29171       data.showHeader = 0;
29172       ShellSetFlag(&data, SHFLG_HeaderSet);
29173     }else if( cli_strcmp(z,"-echo")==0 ){
29174       ShellSetFlag(&data, SHFLG_Echo);
29175     }else if( cli_strcmp(z,"-eqp")==0 ){
29176       data.autoEQP = AUTOEQP_on;
29177     }else if( cli_strcmp(z,"-eqpfull")==0 ){
29178       data.autoEQP = AUTOEQP_full;
29179     }else if( cli_strcmp(z,"-stats")==0 ){
29180       data.statsOn = 1;
29181     }else if( cli_strcmp(z,"-scanstats")==0 ){
29182       data.scanstatsOn = 1;
29183     }else if( cli_strcmp(z,"-backslash")==0 ){
29184       /* Undocumented command-line option: -backslash
29185       ** Causes C-style backslash escapes to be evaluated in SQL statements
29186       ** prior to sending the SQL into SQLite.  Useful for injecting
29187       ** crazy bytes in the middle of SQL statements for testing and debugging.
29188       */
29189       ShellSetFlag(&data, SHFLG_Backslash);
29190     }else if( cli_strcmp(z,"-bail")==0 ){
29191       /* No-op.  The bail_on_error flag should already be set. */
29192     }else if( cli_strcmp(z,"-version")==0 ){
29193       oputf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
29194             8*(int)sizeof(char*));
29195       return 0;
29196     }else if( cli_strcmp(z,"-interactive")==0 ){
29197       /* already handled */
29198     }else if( cli_strcmp(z,"-batch")==0 ){
29199       /* already handled */
29200     }else if( cli_strcmp(z,"-utf8")==0 ){
29201       /* already handled */
29202     }else if( cli_strcmp(z,"-no-utf8")==0 ){
29203       /* already handled */
29204     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
29205       /* already handled */
29206     }else if( cli_strcmp(z,"-heap")==0 ){
29207       i++;
29208     }else if( cli_strcmp(z,"-pagecache")==0 ){
29209       i+=2;
29210     }else if( cli_strcmp(z,"-lookaside")==0 ){
29211       i+=2;
29212     }else if( cli_strcmp(z,"-threadsafe")==0 ){
29213       i+=2;
29214     }else if( cli_strcmp(z,"-nonce")==0 ){
29215       i += 2;
29216     }else if( cli_strcmp(z,"-mmap")==0 ){
29217       i++;
29218     }else if( cli_strcmp(z,"-memtrace")==0 ){
29219       i++;
29220     }else if( cli_strcmp(z,"-pcachetrace")==0 ){
29221       i++;
29222 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
29223     }else if( cli_strcmp(z,"-sorterref")==0 ){
29224       i++;
29225 #endif
29226     }else if( cli_strcmp(z,"-vfs")==0 ){
29227       i++;
29228 #ifdef SQLITE_ENABLE_VFSTRACE
29229     }else if( cli_strcmp(z,"-vfstrace")==0 ){
29230       i++;
29231 #endif
29232 #ifdef SQLITE_ENABLE_MULTIPLEX
29233     }else if( cli_strcmp(z,"-multiplex")==0 ){
29234       i++;
29235 #endif
29236     }else if( cli_strcmp(z,"-help")==0 ){
29237       usage(1);
29238     }else if( cli_strcmp(z,"-cmd")==0 ){
29239       /* Run commands that follow -cmd first and separately from commands
29240       ** that simply appear on the command-line.  This seems goofy.  It would
29241       ** be better if all commands ran in the order that they appear.  But
29242       ** we retain the goofy behavior for historical compatibility. */
29243       if( i==argc-1 ) break;
29244       z = cmdline_option_value(argc,argv,++i);
29245       if( z[0]=='.' ){
29246         rc = do_meta_command(z, &data);
29247         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
29248       }else{
29249         open_db(&data, 0);
29250         rc = shell_exec(&data, z, &zErrMsg);
29251         if( zErrMsg!=0 ){
29252           eputf("Error: %s\n", zErrMsg);
29253           if( bail_on_error ) return rc!=0 ? rc : 1;
29254         }else if( rc!=0 ){
29255           eputf("Error: unable to process SQL \"%s\"\n", z);
29256           if( bail_on_error ) return rc;
29257         }
29258       }
29259 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
29260     }else if( cli_strncmp(z, "-A", 2)==0 ){
29261       if( nCmd>0 ){
29262         eputf("Error: cannot mix regular SQL or dot-commands"
29263               " with \"%s\"\n", z);
29264         return 1;
29265       }
29266       open_db(&data, OPEN_DB_ZIPFILE);
29267       if( z[2] ){
29268         argv[i] = &z[2];
29269         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
29270       }else{
29271         arDotCommand(&data, 1, argv+i, argc-i);
29272       }
29273       readStdin = 0;
29274       break;
29275 #endif
29276     }else if( cli_strcmp(z,"-safe")==0 ){
29277       data.bSafeMode = data.bSafeModePersist = 1;
29278     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29279       /* Acted upon in first pass. */
29280     }else{
29281       eputf("%s: Error: unknown option: %s\n", Argv0, z);
29282       eputz("Use -help for a list of options.\n");
29283       return 1;
29284     }
29285     data.cMode = data.mode;
29286   }
29287 
29288   if( !readStdin ){
29289     /* Run all arguments that do not begin with '-' as if they were separate
29290     ** command-line inputs, except for the argToSkip argument which contains
29291     ** the database filename.
29292     */
29293     for(i=0; i<nCmd; i++){
29294       if( azCmd[i][0]=='.' ){
29295         rc = do_meta_command(azCmd[i], &data);
29296         if( rc ){
29297           free(azCmd);
29298           return rc==2 ? 0 : rc;
29299         }
29300       }else{
29301         open_db(&data, 0);
29302         echo_group_input(&data, azCmd[i]);
29303         rc = shell_exec(&data, azCmd[i], &zErrMsg);
29304         if( zErrMsg || rc ){
29305           if( zErrMsg!=0 ){
29306             eputf("Error: %s\n", zErrMsg);
29307           }else{
29308             eputf("Error: unable to process SQL: %s\n", azCmd[i]);
29309           }
29310           sqlite3_free(zErrMsg);
29311           free(azCmd);
29312           return rc!=0 ? rc : 1;
29313         }
29314       }
29315     }
29316   }else{
29317     /* Run commands received from standard input
29318     */
29319     if( stdin_is_interactive ){
29320       char *zHome;
29321       char *zHistory;
29322       int nHistory;
29323 #if CIO_WIN_WC_XLATE
29324 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
29325 #else
29326 # define SHELL_CIO_CHAR_SET ""
29327 #endif
29328       oputf("SQLite version %s %.19s%s\n" /*extra-version-info*/
29329             "Enter \".help\" for usage hints.\n",
29330             sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
29331       if( warnInmemoryDb ){
29332         oputz("Connected to a ");
29333         printBold("transient in-memory database");
29334         oputz(".\nUse \".open FILENAME\" to reopen on a"
29335               " persistent database.\n");
29336       }
29337       zHistory = getenv("SQLITE_HISTORY");
29338       if( zHistory ){
29339         zHistory = strdup(zHistory);
29340       }else if( (zHome = find_home_dir(0))!=0 ){
29341         nHistory = strlen30(zHome) + 20;
29342         if( (zHistory = malloc(nHistory))!=0 ){
29343           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
29344         }
29345       }
29346       if( zHistory ){ shell_read_history(zHistory); }
29347 #if HAVE_READLINE || HAVE_EDITLINE
29348       rl_attempted_completion_function = readline_completion;
29349 #elif HAVE_LINENOISE
29350       linenoiseSetCompletionCallback(linenoise_completion);
29351 #endif
29352       data.in = 0;
29353       rc = process_input(&data);
29354       if( zHistory ){
29355         shell_stifle_history(2000);
29356         shell_write_history(zHistory);
29357         free(zHistory);
29358       }
29359     }else{
29360       data.in = stdin;
29361       rc = process_input(&data);
29362     }
29363   }
29364 #ifndef SQLITE_SHELL_FIDDLE
29365   /* In WASM mode we have to leave the db state in place so that
29366   ** client code can "push" SQL into it after this call returns. */
29367   free(azCmd);
29368   set_table_name(&data, 0);
29369   if( data.db ){
29370     session_close_all(&data, -1);
29371     close_db(data.db);
29372   }
29373   for(i=0; i<ArraySize(data.aAuxDb); i++){
29374     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
29375     if( data.aAuxDb[i].db ){
29376       session_close_all(&data, i);
29377       close_db(data.aAuxDb[i].db);
29378     }
29379   }
29380   find_home_dir(1);
29381   output_reset(&data);
29382   data.doXdgOpen = 0;
29383   clearTempFile(&data);
29384 #if !SQLITE_SHELL_IS_UTF8
29385   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
29386   free(argvToFree);
29387 #endif
29388   free(data.colWidth);
29389   free(data.zNonce);
29390   /* Clear the global data structure so that valgrind will detect memory
29391   ** leaks */
29392   memset(&data, 0, sizeof(data));
29393 #ifdef SQLITE_DEBUG
29394   if( sqlite3_memory_used()>mem_main_enter ){
29395     eputf("Memory leaked: %u bytes\n",
29396           (unsigned int)(sqlite3_memory_used()-mem_main_enter));
29397   }
29398 #endif
29399 #endif /* !SQLITE_SHELL_FIDDLE */
29400   return rc;
29401 }
29402 
29403 
29404 #ifdef SQLITE_SHELL_FIDDLE
29405 /* Only for emcc experimentation purposes. */
29406 int fiddle_experiment(int a,int b){
29407   return a + b;
29408 }
29409 
29410 /*
29411 ** Returns a pointer to the current DB handle.
29412 */
29413 sqlite3 * fiddle_db_handle(){
29414   return globalDb;
29415 }
29416 
29417 /*
29418 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
29419 ** "main" is assumed. Returns 0 if no db with the given name is
29420 ** open.
29421 */
29422 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
29423   sqlite3_vfs * pVfs = 0;
29424   if(globalDb){
29425     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
29426                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
29427   }
29428   return pVfs;
29429 }
29430 
29431 /* Only for emcc experimentation purposes. */
29432 sqlite3 * fiddle_db_arg(sqlite3 *arg){
29433     printf("fiddle_db_arg(%p)\n", (const void*)arg);
29434     return arg;
29435 }
29436 
29437 /*
29438 ** Intended to be called via a SharedWorker() while a separate
29439 ** SharedWorker() (which manages the wasm module) is performing work
29440 ** which should be interrupted. Unfortunately, SharedWorker is not
29441 ** portable enough to make real use of.
29442 */
29443 void fiddle_interrupt(void){
29444   if( globalDb ) sqlite3_interrupt(globalDb);
29445 }
29446 
29447 /*
29448 ** Returns the filename of the given db name, assuming "main" if
29449 ** zDbName is NULL. Returns NULL if globalDb is not opened.
29450 */
29451 const char * fiddle_db_filename(const char * zDbName){
29452     return globalDb
29453       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
29454       : NULL;
29455 }
29456 
29457 /*
29458 ** Completely wipes out the contents of the currently-opened database
29459 ** but leaves its storage intact for reuse.
29460 */
29461 void fiddle_reset_db(void){
29462   if( globalDb ){
29463     int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
29464     if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
29465     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
29466   }
29467 }
29468 
29469 /*
29470 ** Uses the current database's VFS xRead to stream the db file's
29471 ** contents out to the given callback. The callback gets a single
29472 ** chunk of size n (its 2nd argument) on each call and must return 0
29473 ** on success, non-0 on error. This function returns 0 on success,
29474 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
29475 ** code from the callback. Note that this is not thread-friendly: it
29476 ** expects that it will be the only thread reading the db file and
29477 ** takes no measures to ensure that is the case.
29478 */
29479 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
29480   sqlite3_int64 nSize = 0;
29481   sqlite3_int64 nPos = 0;
29482   sqlite3_file * pFile = 0;
29483   unsigned char buf[1024 * 8];
29484   int nBuf = (int)sizeof(buf);
29485   int rc = shellState.db
29486     ? sqlite3_file_control(shellState.db, "main",
29487                            SQLITE_FCNTL_FILE_POINTER, &pFile)
29488     : SQLITE_NOTFOUND;
29489   if( rc ) return rc;
29490   rc = pFile->pMethods->xFileSize(pFile, &nSize);
29491   if( rc ) return rc;
29492   if(nSize % nBuf){
29493     /* DB size is not an even multiple of the buffer size. Reduce
29494     ** buffer size so that we do not unduly inflate the db size when
29495     ** exporting. */
29496     if(0 == nSize % 4096) nBuf = 4096;
29497     else if(0 == nSize % 2048) nBuf = 2048;
29498     else if(0 == nSize % 1024) nBuf = 1024;
29499     else nBuf = 512;
29500   }
29501   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
29502     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
29503     if(SQLITE_IOERR_SHORT_READ == rc){
29504       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
29505     }
29506     if( 0==rc ) rc = xCallback(buf, nBuf);
29507   }
29508   return rc;
29509 }
29510 
29511 /*
29512 ** Trivial exportable function for emscripten. It processes zSql as if
29513 ** it were input to the sqlite3 shell and redirects all output to the
29514 ** wasm binding. fiddle_main() must have been called before this
29515 ** is called, or results are undefined.
29516 */
29517 void fiddle_exec(const char * zSql){
29518   if(zSql && *zSql){
29519     if('.'==*zSql) puts(zSql);
29520     shellState.wasm.zInput = zSql;
29521     shellState.wasm.zPos = zSql;
29522     process_input(&shellState);
29523     shellState.wasm.zInput = shellState.wasm.zPos = 0;
29524   }
29525 }
29526 #endif /* SQLITE_SHELL_FIDDLE */
29527