xref: /aosp_15_r20/external/sqlite/dist/sqlite-autoconf-3440300/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 // Begin Android Add
131 #ifndef NO_ANDROID_FUNCS
132 #include <sqlite3_android.h>
133 #endif
134 // End Android Add
135 
136 #if !defined(_WIN32) && !defined(WIN32)
137 # include <signal.h>
138 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
139 #  include <pwd.h>
140 # endif
141 #endif
142 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
143 # include <unistd.h>
144 # include <dirent.h>
145 # define GETPID getpid
146 # if defined(__MINGW32__)
147 #  define DIRENT dirent
148 #  ifndef S_ISLNK
149 #   define S_ISLNK(mode) (0)
150 #  endif
151 # endif
152 #else
153 # define GETPID (int)GetCurrentProcessId
154 #endif
155 #include <sys/types.h>
156 #include <sys/stat.h>
157 
158 #if HAVE_READLINE
159 # include <readline/readline.h>
160 # include <readline/history.h>
161 #endif
162 
163 #if HAVE_EDITLINE
164 # include <editline/readline.h>
165 #endif
166 
167 #if HAVE_EDITLINE || HAVE_READLINE
168 
169 # define shell_add_history(X) add_history(X)
170 # define shell_read_history(X) read_history(X)
171 # define shell_write_history(X) write_history(X)
172 # define shell_stifle_history(X) stifle_history(X)
173 # define shell_readline(X) readline(X)
174 
175 #elif HAVE_LINENOISE
176 
177 # include "linenoise.h"
178 # define shell_add_history(X) linenoiseHistoryAdd(X)
179 # define shell_read_history(X) linenoiseHistoryLoad(X)
180 # define shell_write_history(X) linenoiseHistorySave(X)
181 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
182 # define shell_readline(X) linenoise(X)
183 
184 #else
185 
186 # define shell_read_history(X)
187 # define shell_write_history(X)
188 # define shell_stifle_history(X)
189 
190 # define SHELL_USE_LOCAL_GETLINE 1
191 #endif
192 
193 #ifndef deliberate_fall_through
194 /* Quiet some compilers about some of our intentional code. */
195 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
196 #  define deliberate_fall_through __attribute__((fallthrough));
197 # else
198 #  define deliberate_fall_through
199 # endif
200 #endif
201 
202 #if defined(_WIN32) || defined(WIN32)
203 # if SQLITE_OS_WINRT
204 #  define SQLITE_OMIT_POPEN 1
205 # else
206 #  include <io.h>
207 #  include <fcntl.h>
208 #  define isatty(h) _isatty(h)
209 #  ifndef access
210 #   define access(f,m) _access((f),(m))
211 #  endif
212 #  ifndef unlink
213 #   define unlink _unlink
214 #  endif
215 #  ifndef strdup
216 #   define strdup _strdup
217 #  endif
218 #  undef popen
219 #  define popen _popen
220 #  undef pclose
221 #  define pclose _pclose
222 # endif
223 #else
224  /* Make sure isatty() has a prototype. */
225  extern int isatty(int);
226 
227 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
228   /* popen and pclose are not C89 functions and so are
229   ** sometimes omitted from the <stdio.h> header */
230    extern FILE *popen(const char*,const char*);
231    extern int pclose(FILE*);
232 # else
233 #  define SQLITE_OMIT_POPEN 1
234 # endif
235 #endif
236 
237 #if defined(_WIN32_WCE)
238 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
239  * thus we always assume that we have a console. That can be
240  * overridden with the -batch command line option.
241  */
242 #define isatty(x) 1
243 #endif
244 
245 /* ctype macros that work with signed characters */
246 #define IsSpace(X)  isspace((unsigned char)X)
247 #define IsDigit(X)  isdigit((unsigned char)X)
248 #define ToLower(X)  (char)tolower((unsigned char)X)
249 
250 #if defined(_WIN32) || defined(WIN32)
251 #if SQLITE_OS_WINRT
252 #include <intrin.h>
253 #endif
254 #undef WIN32_LEAN_AND_MEAN
255 #define WIN32_LEAN_AND_MEAN
256 #include <windows.h>
257 
258 /* string conversion routines only needed on Win32 */
259 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
260 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
261 #endif
262 
263 /* Use console I/O package as a direct INCLUDE. */
264 #define SQLITE_INTERNAL_LINKAGE static
265 
266 #ifdef SQLITE_SHELL_FIDDLE
267 /* Deselect most features from the console I/O package for Fiddle. */
268 # define SQLITE_CIO_NO_REDIRECT
269 # define SQLITE_CIO_NO_CLASSIFY
270 # define SQLITE_CIO_NO_TRANSLATE
271 # define SQLITE_CIO_NO_SETMODE
272 #endif
273 /************************* Begin ../ext/consio/console_io.h ******************/
274 /*
275 ** 2023 November 1
276 **
277 ** The author disclaims copyright to this source code.  In place of
278 ** a legal notice, here is a blessing:
279 **
280 **    May you do good and not evil.
281 **    May you find forgiveness for yourself and forgive others.
282 **    May you share freely, never taking more than you give.
283 **
284 ********************************************************************************
285 ** This file exposes various interfaces used for console and other I/O
286 ** by the SQLite project command-line tools. These interfaces are used
287 ** at either source conglomeration time, compilation time, or run time.
288 ** This source provides for either inclusion into conglomerated,
289 ** "single-source" forms or separate compilation then linking.
290 **
291 ** Platform dependencies are "hidden" here by various stratagems so
292 ** that, provided certain conditions are met, the programs using this
293 ** source or object code compiled from it need no explicit conditional
294 ** compilation in their source for their console and stream I/O.
295 **
296 ** The symbols and functionality exposed here are not a public API.
297 ** This code may change in tandem with other project code as needed.
298 **
299 ** When this .h file and its companion .c are directly incorporated into
300 ** a source conglomeration (such as shell.c), the preprocessor symbol
301 ** CIO_WIN_WC_XLATE is defined as 0 or 1, reflecting whether console I/O
302 ** translation for Windows is effected for the build.
303 */
304 
305 #ifndef SQLITE_INTERNAL_LINKAGE
306 # define SQLITE_INTERNAL_LINKAGE extern /* external to translation unit */
307 # include <stdio.h>
308 #else
309 # define SHELL_NO_SYSINC /* Better yet, modify mkshellc.tcl for this. */
310 #endif
311 
312 #ifndef SQLITE3_H
313 /* # include "sqlite3.h" */
314 #endif
315 
316 #ifndef SQLITE_CIO_NO_CLASSIFY
317 
318 /* Define enum for use with following function. */
319 typedef enum StreamsAreConsole {
320   SAC_NoConsole = 0,
321   SAC_InConsole = 1, SAC_OutConsole = 2, SAC_ErrConsole = 4,
322   SAC_AnyConsole = 0x7
323 } StreamsAreConsole;
324 
325 /*
326 ** Classify the three standard I/O streams according to whether
327 ** they are connected to a console attached to the process.
328 **
329 ** Returns the bit-wise OR of SAC_{In,Out,Err}Console values,
330 ** or SAC_NoConsole if none of the streams reaches a console.
331 **
332 ** This function should be called before any I/O is done with
333 ** the given streams. As a side-effect, the given inputs are
334 ** recorded so that later I/O operations on them may be done
335 ** differently than the C library FILE* I/O would be done,
336 ** iff the stream is used for the I/O functions that follow,
337 ** and to support the ones that use an implicit stream.
338 **
339 ** On some platforms, stream or console mode alteration (aka
340 ** "Setup") may be made which is undone by consoleRestore().
341 */
342 SQLITE_INTERNAL_LINKAGE StreamsAreConsole
343 consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr );
344 /* A usual call for convenience: */
345 #define SQLITE_STD_CONSOLE_INIT() consoleClassifySetup(stdin,stdout,stderr)
346 
347 /*
348 ** After an initial call to consoleClassifySetup(...), renew
349 ** the same setup it effected. (A call not after is an error.)
350 ** This will restore state altered by consoleRestore();
351 **
352 ** Applications which run an inferior (child) process which
353 ** inherits the same I/O streams may call this function after
354 ** such a process exits to guard against console mode changes.
355 */
356 SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void);
357 
358 /*
359 ** Undo any side-effects left by consoleClassifySetup(...).
360 **
361 ** This should be called after consoleClassifySetup() and
362 ** before the process terminates normally. It is suitable
363 ** for use with the atexit() C library procedure. After
364 ** this call, no console I/O should be done until one of
365 ** console{Classify or Renew}Setup(...) is called again.
366 **
367 ** Applications which run an inferior (child) process that
368 ** inherits the same I/O streams might call this procedure
369 ** before so that said process will have a console setup
370 ** however users have configured it or come to expect.
371 */
372 SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void );
373 
374 #else /* defined(SQLITE_CIO_NO_CLASSIFY) */
375 # define consoleClassifySetup(i,o,e)
376 # define consoleRenewSetup()
377 # define consoleRestore()
378 #endif /* defined(SQLITE_CIO_NO_CLASSIFY) */
379 
380 #ifndef SQLITE_CIO_NO_REDIRECT
381 /*
382 ** Set stream to be used for the functions below which write
383 ** to "the designated X stream", where X is Output or Error.
384 ** Returns the previous value.
385 **
386 ** Alternatively, pass the special value, invalidFileStream,
387 ** to get the designated stream value without setting it.
388 **
389 ** Before the designated streams are set, they default to
390 ** those passed to consoleClassifySetup(...), and before
391 ** that is called they default to stdout and stderr.
392 **
393 ** It is error to close a stream so designated, then, without
394 ** designating another, use the corresponding {o,e}Emit(...).
395 */
396 SQLITE_INTERNAL_LINKAGE FILE *invalidFileStream;
397 SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf);
398 # ifdef CONSIO_SET_ERROR_STREAM
399 SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf);
400 # endif
401 #else
402 # define setOutputStream(pf)
403 # define setErrorStream(pf)
404 #endif /* !defined(SQLITE_CIO_NO_REDIRECT) */
405 
406 #ifndef SQLITE_CIO_NO_TRANSLATE
407 /*
408 ** Emit output like fprintf(). If the output is going to the
409 ** console and translation from UTF-8 is necessary, perform
410 ** the needed translation. Otherwise, write formatted output
411 ** to the provided stream almost as-is, possibly with newline
412 ** translation as specified by set{Binary,Text}Mode().
413 */
414 SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...);
415 /* Like fPrintfUtf8 except stream is always the designated output. */
416 SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...);
417 /* Like fPrintfUtf8 except stream is always the designated error. */
418 SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...);
419 
420 /*
421 ** Emit output like fputs(). If the output is going to the
422 ** console and translation from UTF-8 is necessary, perform
423 ** the needed translation. Otherwise, write given text to the
424 ** provided stream almost as-is, possibly with newline
425 ** translation as specified by set{Binary,Text}Mode().
426 */
427 SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO);
428 /* Like fPutsUtf8 except stream is always the designated output. */
429 SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z);
430 /* Like fPutsUtf8 except stream is always the designated error. */
431 SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z);
432 
433 /*
434 ** Emit output like fPutsUtf8(), except that the length of the
435 ** accepted char or character sequence is limited by nAccept.
436 **
437 ** Returns the number of accepted char values.
438 */
439 #ifdef CONSIO_SPUTB
440 SQLITE_INTERNAL_LINKAGE int
441 fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
442 #endif
443 /* Like fPutbUtf8 except stream is always the designated output. */
444 SQLITE_INTERNAL_LINKAGE int
445 oPutbUtf8(const char *cBuf, int nAccept);
446 /* Like fPutbUtf8 except stream is always the designated error. */
447 #ifdef CONSIO_EPUTB
448 SQLITE_INTERNAL_LINKAGE int
449 ePutbUtf8(const char *cBuf, int nAccept);
450 #endif
451 
452 /*
453 ** Collect input like fgets(...) with special provisions for input
454 ** from the console on platforms that require same. Defers to the
455 ** C library fgets() when input is not from the console. Newline
456 ** translation may be done as set by set{Binary,Text}Mode(). As a
457 ** convenience, pfIn==NULL is treated as stdin.
458 */
459 SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn);
460 /* Like fGetsUtf8 except stream is always the designated input. */
461 /* SQLITE_INTERNAL_LINKAGE char* iGetsUtf8(char *cBuf, int ncMax); */
462 
463 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
464 
465 #ifndef SQLITE_CIO_NO_SETMODE
466 /*
467 ** Set given stream for binary mode, where newline translation is
468 ** not done, or for text mode where, for some platforms, newlines
469 ** are translated to the platform's conventional char sequence.
470 ** If bFlush true, flush the stream.
471 **
472 ** An additional side-effect is that if the stream is one passed
473 ** to consoleClassifySetup() as an output, it is flushed first.
474 **
475 ** Note that binary/text mode has no effect on console I/O
476 ** translation. On all platforms, newline to the console starts
477 ** a new line and CR,LF chars from the console become a newline.
478 */
479 SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *, short bFlush);
480 SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *, short bFlush);
481 #endif
482 
483 #ifdef SQLITE_CIO_PROMPTED_IN
484 typedef struct Prompts {
485   int numPrompts;
486   const char **azPrompts;
487 } Prompts;
488 
489 /*
490 ** Macros for use of a line editor.
491 **
492 ** The following macros define operations involving use of a
493 ** line-editing library or simple console interaction.
494 ** A "T" argument is a text (char *) buffer or filename.
495 ** A "N" argument is an integer.
496 **
497 ** SHELL_ADD_HISTORY(T) // Record text as line(s) of history.
498 ** SHELL_READ_HISTORY(T) // Read history from file named by T.
499 ** SHELL_WRITE_HISTORY(T) // Write history to file named by T.
500 ** SHELL_STIFLE_HISTORY(N) // Limit history to N entries.
501 **
502 ** A console program which does interactive console input is
503 ** expected to call:
504 ** SHELL_READ_HISTORY(T) before collecting such input;
505 ** SHELL_ADD_HISTORY(T) as record-worthy input is taken;
506 ** SHELL_STIFLE_HISTORY(N) after console input ceases; then
507 ** SHELL_WRITE_HISTORY(T) before the program exits.
508 */
509 
510 /*
511 ** Retrieve a single line of input text from an input stream.
512 **
513 ** If pfIn is the input stream passed to consoleClassifySetup(),
514 ** and azPrompt is not NULL, then a prompt is issued before the
515 ** line is collected, as selected by the isContinuation flag.
516 ** Array azPrompt[{0,1}] holds the {main,continuation} prompt.
517 **
518 ** If zBufPrior is not NULL then it is a buffer from a prior
519 ** call to this routine that can be reused, or will be freed.
520 **
521 ** The result is stored in space obtained from malloc() and
522 ** must either be freed by the caller or else passed back to
523 ** this function as zBufPrior for reuse.
524 **
525 ** This function may call upon services of a line-editing
526 ** library to interactively collect line edited input.
527 */
528 SQLITE_INTERNAL_LINKAGE char *
529 shellGetLine(FILE *pfIn, char *zBufPrior, int nLen,
530              short isContinuation, Prompts azPrompt);
531 #endif /* defined(SQLITE_CIO_PROMPTED_IN) */
532 /*
533 ** TBD: Define an interface for application(s) to generate
534 ** completion candidates for use by the line-editor.
535 **
536 ** This may be premature; the CLI is the only application
537 ** that does this. Yet, getting line-editing melded into
538 ** console I/O is desirable because a line-editing library
539 ** may have to establish console operating mode, possibly
540 ** in a way that interferes with the above functionality.
541 */
542 
543 #if !(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))
544 /* Skip over as much z[] input char sequence as is valid UTF-8,
545 ** limited per nAccept char's or whole characters and containing
546 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
547 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
548 ** Limit: nAccept>=0 => char count, nAccept<0 => character
549  */
550 SQLITE_INTERNAL_LINKAGE const char*
551 zSkipValidUtf8(const char *z, int nAccept, long ccm);
552 
553 #endif
554 
555 /************************* End ../ext/consio/console_io.h ********************/
556 /************************* Begin ../ext/consio/console_io.c ******************/
557 /*
558 ** 2023 November 4
559 **
560 ** The author disclaims copyright to this source code.  In place of
561 ** a legal notice, here is a blessing:
562 **
563 **    May you do good and not evil.
564 **    May you find forgiveness for yourself and forgive others.
565 **    May you share freely, never taking more than you give.
566 **
567 ********************************************************************************
568 ** This file implements various interfaces used for console and stream I/O
569 ** by the SQLite project command-line tools, as explained in console_io.h .
570 ** Functions prefixed by "SQLITE_INTERNAL_LINKAGE" behave as described there.
571 */
572 
573 #ifndef SQLITE_CDECL
574 # define SQLITE_CDECL
575 #endif
576 
577 #ifndef SHELL_NO_SYSINC
578 # include <stdarg.h>
579 # include <string.h>
580 # include <stdlib.h>
581 # include <limits.h>
582 # include <assert.h>
583 # include "console_io.h"
584 /* # include "sqlite3.h" */
585 #endif
586 
587 #ifndef SQLITE_CIO_NO_TRANSLATE
588 # if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
589 #  ifndef SHELL_NO_SYSINC
590 #   include <io.h>
591 #   include <fcntl.h>
592 #   undef WIN32_LEAN_AND_MEAN
593 #   define WIN32_LEAN_AND_MEAN
594 #   include <windows.h>
595 #  endif
596 #  define CIO_WIN_WC_XLATE 1 /* Use WCHAR Windows APIs for console I/O */
597 # else
598 #  ifndef SHELL_NO_SYSINC
599 #   include <unistd.h>
600 #  endif
601 #  define CIO_WIN_WC_XLATE 0 /* Use plain C library stream I/O at console */
602 # endif
603 #else
604 # define CIO_WIN_WC_XLATE 0 /* Not exposing translation routines at all */
605 #endif
606 
607 #if CIO_WIN_WC_XLATE
608 /* Character used to represent a known-incomplete UTF-8 char group (�) */
609 static WCHAR cBadGroup = 0xfffd;
610 #endif
611 
612 #if CIO_WIN_WC_XLATE
handleOfFile(FILE * pf)613 static HANDLE handleOfFile(FILE *pf){
614   int fileDesc = _fileno(pf);
615   union { intptr_t osfh; HANDLE fh; } fid = {
616     (fileDesc>=0)? _get_osfhandle(fileDesc) : (intptr_t)INVALID_HANDLE_VALUE
617   };
618   return fid.fh;
619 }
620 #endif
621 
622 #ifndef SQLITE_CIO_NO_TRANSLATE
623 typedef struct PerStreamTags {
624 # if CIO_WIN_WC_XLATE
625   HANDLE hx;
626   DWORD consMode;
627   char acIncomplete[4];
628 # else
629   short reachesConsole;
630 # endif
631   FILE *pf;
632 } PerStreamTags;
633 
634 /* Define NULL-like value for things which can validly be 0. */
635 # define SHELL_INVALID_FILE_PTR ((FILE *)~0)
636 # if CIO_WIN_WC_XLATE
637 #  define SHELL_INVALID_CONS_MODE 0xFFFF0000
638 # endif
639 
640 # if CIO_WIN_WC_XLATE
641 #  define PST_INITIALIZER { INVALID_HANDLE_VALUE, SHELL_INVALID_CONS_MODE, \
642       {0,0,0,0}, SHELL_INVALID_FILE_PTR }
643 # else
644 #  define PST_INITIALIZER { 0, SHELL_INVALID_FILE_PTR }
645 # endif
646 
647 /* Quickly say whether a known output is going to the console. */
648 # if CIO_WIN_WC_XLATE
pstReachesConsole(PerStreamTags * ppst)649 static short pstReachesConsole(PerStreamTags *ppst){
650   return (ppst->hx != INVALID_HANDLE_VALUE);
651 }
652 # else
653 #  define pstReachesConsole(ppst) 0
654 # endif
655 
656 # if CIO_WIN_WC_XLATE
restoreConsoleArb(PerStreamTags * ppst)657 static void restoreConsoleArb(PerStreamTags *ppst){
658   if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode);
659 }
660 # else
661 #  define restoreConsoleArb(ppst)
662 # endif
663 
664 /* Say whether FILE* appears to be a console, collect associated info. */
streamOfConsole(FILE * pf,PerStreamTags * ppst)665 static short streamOfConsole(FILE *pf, /* out */ PerStreamTags *ppst){
666 # if CIO_WIN_WC_XLATE
667   short rv = 0;
668   DWORD dwCM = SHELL_INVALID_CONS_MODE;
669   HANDLE fh = handleOfFile(pf);
670   ppst->pf = pf;
671   if( INVALID_HANDLE_VALUE != fh ){
672     rv = (GetFileType(fh) == FILE_TYPE_CHAR && GetConsoleMode(fh,&dwCM));
673   }
674   ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE;
675   ppst->consMode = dwCM;
676   return rv;
677 # else
678   ppst->pf = pf;
679   ppst->reachesConsole = ( (short)isatty(fileno(pf)) );
680   return ppst->reachesConsole;
681 # endif
682 }
683 
684 # if CIO_WIN_WC_XLATE
685 /* Define console modes for use with the Windows Console API. */
686 #  define SHELL_CONI_MODE \
687   (ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE | ENABLE_LINE_INPUT | 0x80 \
688   | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS | ENABLE_PROCESSED_INPUT)
689 #  define SHELL_CONO_MODE (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT \
690   | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
691 # endif
692 
693 typedef struct ConsoleInfo {
694   PerStreamTags pstSetup[3];
695   PerStreamTags pstDesignated[3];
696   StreamsAreConsole sacSetup;
697 } ConsoleInfo;
698 
isValidStreamInfo(PerStreamTags * ppst)699 static short isValidStreamInfo(PerStreamTags *ppst){
700   return (ppst->pf != SHELL_INVALID_FILE_PTR);
701 }
702 
703 static ConsoleInfo consoleInfo = {
704   { /* pstSetup */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
705   { /* pstDesignated[] */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
706   SAC_NoConsole /* sacSetup */
707 };
708 
709 SQLITE_INTERNAL_LINKAGE FILE* invalidFileStream = (FILE *)~0;
710 
711 # if CIO_WIN_WC_XLATE
maybeSetupAsConsole(PerStreamTags * ppst,short odir)712 static void maybeSetupAsConsole(PerStreamTags *ppst, short odir){
713   if( pstReachesConsole(ppst) ){
714     DWORD cm = odir? SHELL_CONO_MODE : SHELL_CONI_MODE;
715     SetConsoleMode(ppst->hx, cm);
716   }
717 }
718 # else
719 #  define maybeSetupAsConsole(ppst,odir)
720 # endif
721 
consoleRenewSetup(void)722 SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void){
723 # if CIO_WIN_WC_XLATE
724   int ix = 0;
725   while( ix < 6 ){
726     PerStreamTags *ppst = (ix<3)?
727       &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3];
728     maybeSetupAsConsole(ppst, (ix % 3)>0);
729     ++ix;
730   }
731 # endif
732 }
733 
734 SQLITE_INTERNAL_LINKAGE StreamsAreConsole
consoleClassifySetup(FILE * pfIn,FILE * pfOut,FILE * pfErr)735 consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr ){
736   StreamsAreConsole rv = SAC_NoConsole;
737   FILE* apf[3] = { pfIn, pfOut, pfErr };
738   int ix;
739   for( ix = 2; ix >= 0; --ix ){
740     PerStreamTags *ppst = &consoleInfo.pstSetup[ix];
741     if( streamOfConsole(apf[ix], ppst) ){
742       rv |= (SAC_InConsole<<ix);
743     }
744     consoleInfo.pstDesignated[ix] = *ppst;
745     if( ix > 0 ) fflush(apf[ix]);
746   }
747   consoleInfo.sacSetup = rv;
748   consoleRenewSetup();
749   return rv;
750 }
751 
consoleRestore(void)752 SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void ){
753 # if CIO_WIN_WC_XLATE
754   static ConsoleInfo *pci = &consoleInfo;
755   if( pci->sacSetup ){
756     int ix;
757     for( ix=0; ix<3; ++ix ){
758       if( pci->sacSetup & (SAC_InConsole<<ix) ){
759         PerStreamTags *ppst = &pci->pstSetup[ix];
760         SetConsoleMode(ppst->hx, ppst->consMode);
761       }
762     }
763   }
764 # endif
765 }
766 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
767 
768 #ifdef SQLITE_CIO_INPUT_REDIR
769 /* Say whether given FILE* is among those known, via either
770 ** consoleClassifySetup() or set{Output,Error}Stream, as
771 ** readable, and return an associated PerStreamTags pointer
772 ** if so. Otherwise, return 0.
773 */
isKnownReadable(FILE * pf)774 static PerStreamTags * isKnownReadable(FILE *pf){
775   static PerStreamTags *apst[] = {
776     &consoleInfo.pstDesignated[0], &consoleInfo.pstSetup[0], 0
777   };
778   int ix = 0;
779   do {
780     if( apst[ix]->pf == pf ) break;
781   } while( apst[++ix] != 0 );
782   return apst[ix];
783 }
784 #endif
785 
786 #ifndef SQLITE_CIO_NO_TRANSLATE
787 /* Say whether given FILE* is among those known, via either
788 ** consoleClassifySetup() or set{Output,Error}Stream, as
789 ** writable, and return an associated PerStreamTags pointer
790 ** if so. Otherwise, return 0.
791 */
isKnownWritable(FILE * pf)792 static PerStreamTags * isKnownWritable(FILE *pf){
793   static PerStreamTags *apst[] = {
794     &consoleInfo.pstDesignated[1], &consoleInfo.pstDesignated[2],
795     &consoleInfo.pstSetup[1], &consoleInfo.pstSetup[2], 0
796   };
797   int ix = 0;
798   do {
799     if( apst[ix]->pf == pf ) break;
800   } while( apst[++ix] != 0 );
801   return apst[ix];
802 }
803 
designateEmitStream(FILE * pf,unsigned chix)804 static FILE *designateEmitStream(FILE *pf, unsigned chix){
805   FILE *rv = consoleInfo.pstDesignated[chix].pf;
806   if( pf == invalidFileStream ) return rv;
807   else{
808     /* Setting a possibly new output stream. */
809     PerStreamTags *ppst = isKnownWritable(pf);
810     if( ppst != 0 ){
811       PerStreamTags pst = *ppst;
812       consoleInfo.pstDesignated[chix] = pst;
813     }else streamOfConsole(pf, &consoleInfo.pstDesignated[chix]);
814   }
815   return rv;
816 }
817 
setOutputStream(FILE * pf)818 SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf){
819   return designateEmitStream(pf, 1);
820 }
821 # ifdef CONSIO_SET_ERROR_STREAM
setErrorStream(FILE * pf)822 SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf){
823   return designateEmitStream(pf, 2);
824 }
825 # endif
826 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
827 
828 #ifndef SQLITE_CIO_NO_SETMODE
829 # if CIO_WIN_WC_XLATE
setModeFlushQ(FILE * pf,short bFlush,int mode)830 static void setModeFlushQ(FILE *pf, short bFlush, int mode){
831   if( bFlush ) fflush(pf);
832   _setmode(_fileno(pf), mode);
833 }
834 # else
835 #  define setModeFlushQ(f, b, m) if(b) fflush(f)
836 # endif
837 
setBinaryMode(FILE * pf,short bFlush)838 SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *pf, short bFlush){
839   setModeFlushQ(pf, bFlush, _O_BINARY);
840 }
setTextMode(FILE * pf,short bFlush)841 SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *pf, short bFlush){
842   setModeFlushQ(pf, bFlush, _O_TEXT);
843 }
844 # undef setModeFlushQ
845 
846 #else /* defined(SQLITE_CIO_NO_SETMODE) */
847 # define setBinaryMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
848 # define setTextMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
849 #endif /* defined(SQLITE_CIO_NO_SETMODE) */
850 
851 #ifndef SQLITE_CIO_NO_TRANSLATE
852 # if CIO_WIN_WC_XLATE
853 /* Write buffer cBuf as output to stream known to reach console,
854 ** limited to ncTake char's. Return ncTake on success, else 0. */
conZstrEmit(PerStreamTags * ppst,const char * z,int ncTake)855 static int conZstrEmit(PerStreamTags *ppst, const char *z, int ncTake){
856   int rv = 0;
857   if( z!=NULL ){
858     int nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, 0,0);
859     if( nwc > 0 ){
860       WCHAR *zw = sqlite3_malloc64(nwc*sizeof(WCHAR));
861       if( zw!=NULL ){
862         nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, zw,nwc);
863         if( nwc > 0 ){
864           /* Translation from UTF-8 to UTF-16, then WCHARs out. */
865           if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){
866             rv = ncTake;
867           }
868         }
869         sqlite3_free(zw);
870       }
871     }
872   }
873   return rv;
874 }
875 
876 /* For {f,o,e}PrintfUtf8() when stream is known to reach console. */
conioVmPrintf(PerStreamTags * ppst,const char * zFormat,va_list ap)877 static int conioVmPrintf(PerStreamTags *ppst, const char *zFormat, va_list ap){
878   char *z = sqlite3_vmprintf(zFormat, ap);
879   if( z ){
880     int rv = conZstrEmit(ppst, z, (int)strlen(z));
881     sqlite3_free(z);
882     return rv;
883   }else return 0;
884 }
885 # endif /* CIO_WIN_WC_XLATE */
886 
887 # ifdef CONSIO_GET_EMIT_STREAM
getDesignatedEmitStream(FILE * pf,unsigned chix,PerStreamTags * ppst)888 static PerStreamTags * getDesignatedEmitStream(FILE *pf, unsigned chix,
889                                                PerStreamTags *ppst){
890   PerStreamTags *rv = isKnownWritable(pf);
891   short isValid = (rv!=0)? isValidStreamInfo(rv) : 0;
892   if( rv != 0 && isValid ) return rv;
893   streamOfConsole(pf, ppst);
894   return ppst;
895 }
896 # endif
897 
898 /* Get stream info, either for designated output or error stream when
899 ** chix equals 1 or 2, or for an arbitrary stream when chix == 0.
900 ** In either case, ppst references a caller-owned PerStreamTags
901 ** struct which may be filled in if none of the known writable
902 ** streams is being held by consoleInfo. The ppf parameter is a
903 ** byref output when chix!=0 and a byref input when chix==0.
904  */
905 static PerStreamTags *
getEmitStreamInfo(unsigned chix,PerStreamTags * ppst,FILE ** ppf)906 getEmitStreamInfo(unsigned chix, PerStreamTags *ppst,
907                   /* in/out */ FILE **ppf){
908   PerStreamTags *ppstTry;
909   FILE *pfEmit;
910   if( chix > 0 ){
911     ppstTry = &consoleInfo.pstDesignated[chix];
912     if( !isValidStreamInfo(ppstTry) ){
913       ppstTry = &consoleInfo.pstSetup[chix];
914       pfEmit = ppst->pf;
915     }else pfEmit = ppstTry->pf;
916     if( !isValidStreamInfo(ppstTry) ){
917       pfEmit = (chix > 1)? stderr : stdout;
918       ppstTry = ppst;
919       streamOfConsole(pfEmit, ppstTry);
920     }
921     *ppf = pfEmit;
922   }else{
923     ppstTry = isKnownWritable(*ppf);
924     if( ppstTry != 0 ) return ppstTry;
925     streamOfConsole(*ppf, ppst);
926     return ppst;
927   }
928   return ppstTry;
929 }
930 
oPrintfUtf8(const char * zFormat,...)931 SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...){
932   va_list ap;
933   int rv;
934   FILE *pfOut;
935   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
936 # if CIO_WIN_WC_XLATE
937   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
938 # else
939   getEmitStreamInfo(1, &pst, &pfOut);
940 # endif
941   assert(zFormat!=0);
942   va_start(ap, zFormat);
943 # if CIO_WIN_WC_XLATE
944   if( pstReachesConsole(ppst) ){
945     rv = conioVmPrintf(ppst, zFormat, ap);
946   }else{
947 # endif
948     rv = vfprintf(pfOut, zFormat, ap);
949 # if CIO_WIN_WC_XLATE
950   }
951 # endif
952   va_end(ap);
953   return rv;
954 }
955 
ePrintfUtf8(const char * zFormat,...)956 SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...){
957   va_list ap;
958   int rv;
959   FILE *pfErr;
960   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
961 # if CIO_WIN_WC_XLATE
962   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
963 # else
964   getEmitStreamInfo(2, &pst, &pfErr);
965 # endif
966   assert(zFormat!=0);
967   va_start(ap, zFormat);
968 # if CIO_WIN_WC_XLATE
969   if( pstReachesConsole(ppst) ){
970     rv = conioVmPrintf(ppst, zFormat, ap);
971   }else{
972 # endif
973     rv = vfprintf(pfErr, zFormat, ap);
974 # if CIO_WIN_WC_XLATE
975   }
976 # endif
977   va_end(ap);
978   return rv;
979 }
980 
fPrintfUtf8(FILE * pfO,const char * zFormat,...)981 SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...){
982   va_list ap;
983   int rv;
984   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
985 # if CIO_WIN_WC_XLATE
986   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
987 # else
988   getEmitStreamInfo(0, &pst, &pfO);
989 # endif
990   assert(zFormat!=0);
991   va_start(ap, zFormat);
992 # if CIO_WIN_WC_XLATE
993   if( pstReachesConsole(ppst) ){
994     maybeSetupAsConsole(ppst, 1);
995     rv = conioVmPrintf(ppst, zFormat, ap);
996     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
997   }else{
998 # endif
999     rv = vfprintf(pfO, zFormat, ap);
1000 # if CIO_WIN_WC_XLATE
1001   }
1002 # endif
1003   va_end(ap);
1004   return rv;
1005 }
1006 
fPutsUtf8(const char * z,FILE * pfO)1007 SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO){
1008   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1009 # if CIO_WIN_WC_XLATE
1010   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1011 # else
1012   getEmitStreamInfo(0, &pst, &pfO);
1013 # endif
1014   assert(z!=0);
1015 # if CIO_WIN_WC_XLATE
1016   if( pstReachesConsole(ppst) ){
1017     int rv;
1018     maybeSetupAsConsole(ppst, 1);
1019     rv = conZstrEmit(ppst, z, (int)strlen(z));
1020     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1021     return rv;
1022   }else {
1023 # endif
1024     return (fputs(z, pfO)<0)? 0 : (int)strlen(z);
1025 # if CIO_WIN_WC_XLATE
1026   }
1027 # endif
1028 }
1029 
ePutsUtf8(const char * z)1030 SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z){
1031   FILE *pfErr;
1032   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1033 # if CIO_WIN_WC_XLATE
1034   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1035 # else
1036   getEmitStreamInfo(2, &pst, &pfErr);
1037 # endif
1038   assert(z!=0);
1039 # if CIO_WIN_WC_XLATE
1040   if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1041   else {
1042 # endif
1043     return (fputs(z, pfErr)<0)? 0 : (int)strlen(z);
1044 # if CIO_WIN_WC_XLATE
1045   }
1046 # endif
1047 }
1048 
oPutsUtf8(const char * z)1049 SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z){
1050   FILE *pfOut;
1051   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1052 # if CIO_WIN_WC_XLATE
1053   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1054 # else
1055   getEmitStreamInfo(1, &pst, &pfOut);
1056 # endif
1057   assert(z!=0);
1058 # if CIO_WIN_WC_XLATE
1059   if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1060   else {
1061 # endif
1062     return (fputs(z, pfOut)<0)? 0 : (int)strlen(z);
1063 # if CIO_WIN_WC_XLATE
1064   }
1065 # endif
1066 }
1067 
1068 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1069 
1070 #if !(defined(SQLITE_CIO_NO_UTF8SCAN) && defined(SQLITE_CIO_NO_TRANSLATE))
1071 /* Skip over as much z[] input char sequence as is valid UTF-8,
1072 ** limited per nAccept char's or whole characters and containing
1073 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
1074 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
1075 ** Limit: nAccept>=0 => char count, nAccept<0 => character
1076  */
1077 SQLITE_INTERNAL_LINKAGE const char*
zSkipValidUtf8(const char * z,int nAccept,long ccm)1078 zSkipValidUtf8(const char *z, int nAccept, long ccm){
1079   int ng = (nAccept<0)? -nAccept : 0;
1080   const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
1081   assert(z!=0);
1082   while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
1083     char c = *z;
1084     if( (c & 0x80) == 0 ){
1085       if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
1086       ++z; /* ASCII */
1087     }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
1088     else{
1089       const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
1090       do{
1091         if( pcLimit && zt >= pcLimit ) return z;
1092         else{
1093           char ct = *zt++;
1094           if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
1095             /* Trailing bytes are too few, too many, or invalid. */
1096             return z;
1097           }
1098         }
1099       } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
1100       z = zt;
1101     }
1102   }
1103   return z;
1104 }
1105 #endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
1106 
1107 #ifndef SQLITE_CIO_NO_TRANSLATE
1108 
1109 #ifdef CONSIO_SPUTB
1110 SQLITE_INTERNAL_LINKAGE int
fPutbUtf8(FILE * pfO,const char * cBuf,int nAccept)1111 fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
1112   assert(pfO!=0);
1113 # if CIO_WIN_WC_XLATE
1114   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1115   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1116   if( pstReachesConsole(ppst) ){
1117     int rv;
1118     maybeSetupAsConsole(ppst, 1);
1119     rv = conZstrEmit(ppst, cBuf, nAccept);
1120     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1121     return rv;
1122   }else {
1123 # endif
1124     return (int)fwrite(cBuf, 1, nAccept, pfO);
1125 # if CIO_WIN_WC_XLATE
1126   }
1127 # endif
1128 }
1129 #endif /* defined(CONSIO_SPUTB) */
1130 
1131 SQLITE_INTERNAL_LINKAGE int
oPutbUtf8(const char * cBuf,int nAccept)1132 oPutbUtf8(const char *cBuf, int nAccept){
1133   FILE *pfOut;
1134   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1135 # if CIO_WIN_WC_XLATE
1136   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1137 # else
1138   getEmitStreamInfo(1, &pst, &pfOut);
1139 # endif
1140 # if CIO_WIN_WC_XLATE
1141   if( pstReachesConsole(ppst) ){
1142     return conZstrEmit(ppst, cBuf, nAccept);
1143   }else {
1144 # endif
1145     return (int)fwrite(cBuf, 1, nAccept, pfOut);
1146 # if CIO_WIN_WC_XLATE
1147   }
1148 # endif
1149 }
1150 
1151 # ifdef CONSIO_EPUTB
1152 SQLITE_INTERNAL_LINKAGE int
ePutbUtf8(const char * cBuf,int nAccept)1153 ePutbUtf8(const char *cBuf, int nAccept){
1154   FILE *pfErr;
1155   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1156   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1157 #  if CIO_WIN_WC_XLATE
1158   if( pstReachesConsole(ppst) ){
1159     return conZstrEmit(ppst, cBuf, nAccept);
1160   }else {
1161 #  endif
1162     return (int)fwrite(cBuf, 1, nAccept, pfErr);
1163 #  if CIO_WIN_WC_XLATE
1164   }
1165 #  endif
1166 }
1167 # endif /* defined(CONSIO_EPUTB) */
1168 
fGetsUtf8(char * cBuf,int ncMax,FILE * pfIn)1169 SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn){
1170   if( pfIn==0 ) pfIn = stdin;
1171 # if CIO_WIN_WC_XLATE
1172   if( pfIn == consoleInfo.pstSetup[0].pf
1173       && (consoleInfo.sacSetup & SAC_InConsole)!=0 ){
1174 #  if CIO_WIN_WC_XLATE==1
1175 #   define SHELL_GULP 150 /* Count of WCHARS to be gulped at a time */
1176     WCHAR wcBuf[SHELL_GULP+1];
1177     int lend = 0, noc = 0;
1178     if( ncMax > 0 ) cBuf[0] = 0;
1179     while( noc < ncMax-8-1 && !lend ){
1180       /* There is room for at least 2 more characters and a 0-terminator. */
1181       int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4;
1182 #   undef SHELL_GULP
1183       DWORD nbr = 0;
1184       BOOL bRC = ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf, na, &nbr, 0);
1185       if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){
1186         /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */
1187         DWORD nbrx;
1188         bRC &= ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf+nbr, 1, &nbrx, 0);
1189         if( bRC ) nbr += nbrx;
1190       }
1191       if( !bRC || (noc==0 && nbr==0) ) return 0;
1192       if( nbr > 0 ){
1193         int nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,0,0,0,0);
1194         if( nmb != 0 && noc+nmb <= ncMax ){
1195           int iseg = noc;
1196           nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,cBuf+noc,nmb,0,0);
1197           noc += nmb;
1198           /* Fixup line-ends as coded by Windows for CR (or "Enter".)
1199           ** This is done without regard for any setMode{Text,Binary}()
1200           ** call that might have been done on the interactive input.
1201           */
1202           if( noc > 0 ){
1203             if( cBuf[noc-1]=='\n' ){
1204               lend = 1;
1205               if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n';
1206             }
1207           }
1208           /* Check for ^Z (anywhere in line) too, to act as EOF. */
1209           while( iseg < noc ){
1210             if( cBuf[iseg]=='\x1a' ){
1211               noc = iseg; /* Chop ^Z and anything following. */
1212               lend = 1; /* Counts as end of line too. */
1213               break;
1214             }
1215             ++iseg;
1216           }
1217         }else break; /* Drop apparent garbage in. (Could assert.) */
1218       }else break;
1219     }
1220     /* If got nothing, (after ^Z chop), must be at end-of-file. */
1221     if( noc > 0 ){
1222       cBuf[noc] = 0;
1223       return cBuf;
1224     }else return 0;
1225 #  endif
1226   }else{
1227 # endif
1228     return fgets(cBuf, ncMax, pfIn);
1229 # if CIO_WIN_WC_XLATE
1230   }
1231 # endif
1232 }
1233 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1234 
1235 #undef SHELL_INVALID_FILE_PTR
1236 
1237 /************************* End ../ext/consio/console_io.c ********************/
1238 
1239 #ifndef SQLITE_SHELL_FIDDLE
1240 /* From here onward, fgets() is redirected to the console_io library. */
1241 # define fgets(b,n,f) fGetsUtf8(b,n,f)
1242 /*
1243  * Define macros for emitting output text in various ways:
1244  *  sputz(s, z)      => emit 0-terminated string z to given stream s
1245  *  sputf(s, f, ...) => emit varargs per format f to given stream s
1246  *  oputz(z)         => emit 0-terminated string z to default stream
1247  *  oputf(f, ...)    => emit varargs per format f to default stream
1248  *  eputz(z)         => emit 0-terminated string z to error stream
1249  *  eputf(f, ...)    => emit varargs per format f to error stream
1250  *  oputb(b, n)      => emit char buffer b[0..n-1] to default stream
1251  *
1252  * Note that the default stream is whatever has been last set via:
1253  *   setOutputStream(FILE *pf)
1254  * This is normally the stream that CLI normal output goes to.
1255  * For the stand-alone CLI, it is stdout with no .output redirect.
1256  */
1257 # define sputz(s,z) fPutsUtf8(z,s)
1258 # define sputf fPrintfUtf8
1259 # define oputz(z) oPutsUtf8(z)
1260 # define oputf oPrintfUtf8
1261 # define eputz(z) ePutsUtf8(z)
1262 # define eputf ePrintfUtf8
1263 # define oputb(buf,na) oPutbUtf8(buf,na)
1264 #else
1265 /* For Fiddle, all console handling and emit redirection is omitted. */
1266 # define sputz(fp,z) fputs(z,fp)
1267 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
1268 # define oputz(z) fputs(z,stdout)
1269 # define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
1270 # define eputz(z) fputs(z,stderr)
1271 # define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
1272 # define oputb(buf,na) fwrite(buf,1,na,stdout)
1273 #endif
1274 
1275 /* True if the timer is enabled */
1276 static int enableTimer = 0;
1277 
1278 /* A version of strcmp() that works with NULL values */
cli_strcmp(const char * a,const char * b)1279 static int cli_strcmp(const char *a, const char *b){
1280   if( a==0 ) a = "";
1281   if( b==0 ) b = "";
1282   return strcmp(a,b);
1283 }
cli_strncmp(const char * a,const char * b,size_t n)1284 static int cli_strncmp(const char *a, const char *b, size_t n){
1285   if( a==0 ) a = "";
1286   if( b==0 ) b = "";
1287   return strncmp(a,b,n);
1288 }
1289 
1290 /* Return the current wall-clock time */
timeOfDay(void)1291 static sqlite3_int64 timeOfDay(void){
1292   static sqlite3_vfs *clockVfs = 0;
1293   sqlite3_int64 t;
1294   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
1295   if( clockVfs==0 ) return 0;  /* Never actually happens */
1296   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
1297     clockVfs->xCurrentTimeInt64(clockVfs, &t);
1298   }else{
1299     double r;
1300     clockVfs->xCurrentTime(clockVfs, &r);
1301     t = (sqlite3_int64)(r*86400000.0);
1302   }
1303   return t;
1304 }
1305 
1306 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
1307 #include <sys/time.h>
1308 #include <sys/resource.h>
1309 
1310 /* VxWorks does not support getrusage() as far as we can determine */
1311 #if defined(_WRS_KERNEL) || defined(__RTP__)
1312 struct rusage {
1313   struct timeval ru_utime; /* user CPU time used */
1314   struct timeval ru_stime; /* system CPU time used */
1315 };
1316 #define getrusage(A,B) memset(B,0,sizeof(*B))
1317 #endif
1318 
1319 /* Saved resource information for the beginning of an operation */
1320 static struct rusage sBegin;  /* CPU time at start */
1321 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
1322 
1323 /*
1324 ** Begin timing an operation
1325 */
beginTimer(void)1326 static void beginTimer(void){
1327   if( enableTimer ){
1328     getrusage(RUSAGE_SELF, &sBegin);
1329     iBegin = timeOfDay();
1330   }
1331 }
1332 
1333 /* Return the difference of two time_structs in seconds */
timeDiff(struct timeval * pStart,struct timeval * pEnd)1334 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
1335   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
1336          (double)(pEnd->tv_sec - pStart->tv_sec);
1337 }
1338 
1339 /*
1340 ** Print the timing results.
1341 */
endTimer(void)1342 static void endTimer(void){
1343   if( enableTimer ){
1344     sqlite3_int64 iEnd = timeOfDay();
1345     struct rusage sEnd;
1346     getrusage(RUSAGE_SELF, &sEnd);
1347     oputf("Run Time: real %.3f user %f sys %f\n",
1348           (iEnd - iBegin)*0.001,
1349           timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
1350           timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
1351   }
1352 }
1353 
1354 #define BEGIN_TIMER beginTimer()
1355 #define END_TIMER endTimer()
1356 #define HAS_TIMER 1
1357 
1358 #elif (defined(_WIN32) || defined(WIN32))
1359 
1360 /* Saved resource information for the beginning of an operation */
1361 static HANDLE hProcess;
1362 static FILETIME ftKernelBegin;
1363 static FILETIME ftUserBegin;
1364 static sqlite3_int64 ftWallBegin;
1365 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
1366                                     LPFILETIME, LPFILETIME);
1367 static GETPROCTIMES getProcessTimesAddr = NULL;
1368 
1369 /*
1370 ** Check to see if we have timer support.  Return 1 if necessary
1371 ** support found (or found previously).
1372 */
hasTimer(void)1373 static int hasTimer(void){
1374   if( getProcessTimesAddr ){
1375     return 1;
1376   } else {
1377 #if !SQLITE_OS_WINRT
1378     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
1379     ** versions. See if the version we are running on has it, and if it
1380     ** does, save off a pointer to it and the current process handle.
1381     */
1382     hProcess = GetCurrentProcess();
1383     if( hProcess ){
1384       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
1385       if( NULL != hinstLib ){
1386         getProcessTimesAddr =
1387             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
1388         if( NULL != getProcessTimesAddr ){
1389           return 1;
1390         }
1391         FreeLibrary(hinstLib);
1392       }
1393     }
1394 #endif
1395   }
1396   return 0;
1397 }
1398 
1399 /*
1400 ** Begin timing an operation
1401 */
beginTimer(void)1402 static void beginTimer(void){
1403   if( enableTimer && getProcessTimesAddr ){
1404     FILETIME ftCreation, ftExit;
1405     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
1406                         &ftKernelBegin,&ftUserBegin);
1407     ftWallBegin = timeOfDay();
1408   }
1409 }
1410 
1411 /* Return the difference of two FILETIME structs in seconds */
timeDiff(FILETIME * pStart,FILETIME * pEnd)1412 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
1413   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
1414   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
1415   return (double) ((i64End - i64Start) / 10000000.0);
1416 }
1417 
1418 /*
1419 ** Print the timing results.
1420 */
endTimer(void)1421 static void endTimer(void){
1422   if( enableTimer && getProcessTimesAddr){
1423     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
1424     sqlite3_int64 ftWallEnd = timeOfDay();
1425     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1426     oputf("Run Time: real %.3f user %f sys %f\n",
1427           (ftWallEnd - ftWallBegin)*0.001,
1428           timeDiff(&ftUserBegin, &ftUserEnd),
1429           timeDiff(&ftKernelBegin, &ftKernelEnd));
1430   }
1431 }
1432 
1433 #define BEGIN_TIMER beginTimer()
1434 #define END_TIMER endTimer()
1435 #define HAS_TIMER hasTimer()
1436 
1437 #else
1438 #define BEGIN_TIMER
1439 #define END_TIMER
1440 #define HAS_TIMER 0
1441 #endif
1442 
1443 /*
1444 ** Used to prevent warnings about unused parameters
1445 */
1446 #define UNUSED_PARAMETER(x) (void)(x)
1447 
1448 /*
1449 ** Number of elements in an array
1450 */
1451 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
1452 
1453 /*
1454 ** If the following flag is set, then command execution stops
1455 ** at an error if we are not interactive.
1456 */
1457 static int bail_on_error = 0;
1458 
1459 /*
1460 ** Treat stdin as an interactive input if the following variable
1461 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
1462 */
1463 static int stdin_is_interactive = 1;
1464 
1465 /*
1466 ** On Windows systems we need to know if standard output is a console
1467 ** in order to show that UTF-16 translation is done in the sign-on
1468 ** banner. The following variable is true if it is the console.
1469 */
1470 static int stdout_is_console = 1;
1471 
1472 /*
1473 ** The following is the open SQLite database.  We make a pointer
1474 ** to this database a static variable so that it can be accessed
1475 ** by the SIGINT handler to interrupt database processing.
1476 */
1477 static sqlite3 *globalDb = 0;
1478 
1479 /*
1480 ** True if an interrupt (Control-C) has been received.
1481 */
1482 static volatile int seenInterrupt = 0;
1483 
1484 /*
1485 ** This is the name of our program. It is set in main(), used
1486 ** in a number of other places, mostly for error messages.
1487 */
1488 static char *Argv0;
1489 
1490 /*
1491 ** Prompt strings. Initialized in main. Settable with
1492 **   .prompt main continue
1493 */
1494 #define PROMPT_LEN_MAX 20
1495 /* First line prompt.   default: "sqlite> " */
1496 static char mainPrompt[PROMPT_LEN_MAX];
1497 /* Continuation prompt. default: "   ...> " */
1498 static char continuePrompt[PROMPT_LEN_MAX];
1499 
1500 /* This is variant of the standard-library strncpy() routine with the
1501 ** one change that the destination string is always zero-terminated, even
1502 ** if there is no zero-terminator in the first n-1 characters of the source
1503 ** string.
1504 */
shell_strncpy(char * dest,const char * src,size_t n)1505 static char *shell_strncpy(char *dest, const char *src, size_t n){
1506   size_t i;
1507   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
1508   dest[i] = 0;
1509   return dest;
1510 }
1511 
1512 /*
1513 ** Optionally disable dynamic continuation prompt.
1514 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
1515 ** or open parentheses level if non-zero, or continuation prompt as set.
1516 ** This facility interacts with the scanner and process_input() where the
1517 ** below 5 macros are used.
1518 */
1519 #ifdef SQLITE_OMIT_DYNAPROMPT
1520 # define CONTINUATION_PROMPT continuePrompt
1521 # define CONTINUE_PROMPT_RESET
1522 # define CONTINUE_PROMPT_AWAITS(p,s)
1523 # define CONTINUE_PROMPT_AWAITC(p,c)
1524 # define CONTINUE_PAREN_INCR(p,n)
1525 # define CONTINUE_PROMPT_PSTATE 0
1526 typedef void *t_NoDynaPrompt;
1527 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
1528 #else
1529 # define CONTINUATION_PROMPT dynamicContinuePrompt()
1530 # define CONTINUE_PROMPT_RESET \
1531   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
1532 # define CONTINUE_PROMPT_AWAITS(p,s) \
1533   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
1534 # define CONTINUE_PROMPT_AWAITC(p,c) \
1535   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
1536 # define CONTINUE_PAREN_INCR(p,n) \
1537   if(p && stdin_is_interactive) (trackParenLevel(p,n))
1538 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
1539 typedef struct DynaPrompt *t_DynaPromptRef;
1540 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
1541 
1542 static struct DynaPrompt {
1543   char dynamicPrompt[PROMPT_LEN_MAX];
1544   char acAwait[2];
1545   int inParenLevel;
1546   char *zScannerAwaits;
1547 } dynPrompt = { {0}, {0}, 0, 0 };
1548 
1549 /* Record parenthesis nesting level change, or force level to 0. */
trackParenLevel(struct DynaPrompt * p,int ni)1550 static void trackParenLevel(struct DynaPrompt *p, int ni){
1551   p->inParenLevel += ni;
1552   if( ni==0 ) p->inParenLevel = 0;
1553   p->zScannerAwaits = 0;
1554 }
1555 
1556 /* Record that a lexeme is opened, or closed with args==0. */
setLexemeOpen(struct DynaPrompt * p,char * s,char c)1557 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
1558   if( s!=0 || c==0 ){
1559     p->zScannerAwaits = s;
1560     p->acAwait[0] = 0;
1561   }else{
1562     p->acAwait[0] = c;
1563     p->zScannerAwaits = p->acAwait;
1564   }
1565 }
1566 
1567 /* Upon demand, derive the continuation prompt to display. */
dynamicContinuePrompt(void)1568 static char *dynamicContinuePrompt(void){
1569   if( continuePrompt[0]==0
1570       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
1571     return continuePrompt;
1572   }else{
1573     if( dynPrompt.zScannerAwaits ){
1574       size_t ncp = strlen(continuePrompt);
1575       size_t ndp = strlen(dynPrompt.zScannerAwaits);
1576       if( ndp > ncp-3 ) return continuePrompt;
1577       strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
1578       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
1579       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1580               PROMPT_LEN_MAX-4);
1581     }else{
1582       if( dynPrompt.inParenLevel>9 ){
1583         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
1584       }else if( dynPrompt.inParenLevel<0 ){
1585         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
1586       }else{
1587         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
1588         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
1589       }
1590       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1591                     PROMPT_LEN_MAX-4);
1592     }
1593   }
1594   return dynPrompt.dynamicPrompt;
1595 }
1596 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
1597 
1598 /* Indicate out-of-memory and exit. */
shell_out_of_memory(void)1599 static void shell_out_of_memory(void){
1600   eputz("Error: out of memory\n");
1601   exit(1);
1602 }
1603 
1604 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
1605 ** out-of-memory error.
1606 */
shell_check_oom(const void * p)1607 static void shell_check_oom(const void *p){
1608   if( p==0 ) shell_out_of_memory();
1609 }
1610 
1611 /*
1612 ** Write I/O traces to the following stream.
1613 */
1614 #ifdef SQLITE_ENABLE_IOTRACE
1615 static FILE *iotrace = 0;
1616 #endif
1617 
1618 /*
1619 ** This routine works like printf in that its first argument is a
1620 ** format string and subsequent arguments are values to be substituted
1621 ** in place of % fields.  The result of formatting this string
1622 ** is written to iotrace.
1623 */
1624 #ifdef SQLITE_ENABLE_IOTRACE
iotracePrintf(const char * zFormat,...)1625 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
1626   va_list ap;
1627   char *z;
1628   if( iotrace==0 ) return;
1629   va_start(ap, zFormat);
1630   z = sqlite3_vmprintf(zFormat, ap);
1631   va_end(ap);
1632   sputf(iotrace, "%s", z);
1633   sqlite3_free(z);
1634 }
1635 #endif
1636 
1637 /*
1638 ** Output string zUtf to Out stream as w characters.  If w is negative,
1639 ** then right-justify the text.  W is the width in UTF-8 characters, not
1640 ** in bytes.  This is different from the %*.*s specification in printf
1641 ** since with %*.*s the width is measured in bytes, not characters.
1642 */
utf8_width_print(int w,const char * zUtf)1643 static void utf8_width_print(int w, const char *zUtf){
1644   int i;
1645   int n;
1646   int aw = w<0 ? -w : w;
1647   if( zUtf==0 ) zUtf = "";
1648   for(i=n=0; zUtf[i]; i++){
1649     if( (zUtf[i]&0xc0)!=0x80 ){
1650       n++;
1651       if( n==aw ){
1652         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
1653         break;
1654       }
1655     }
1656   }
1657   if( n>=aw ){
1658     oputf("%.*s", i, zUtf);
1659   }else if( w<0 ){
1660     oputf("%*s%s", aw-n, "", zUtf);
1661   }else{
1662     oputf("%s%*s", zUtf, aw-n, "");
1663   }
1664 }
1665 
1666 
1667 /*
1668 ** Determines if a string is a number of not.
1669 */
isNumber(const char * z,int * realnum)1670 static int isNumber(const char *z, int *realnum){
1671   if( *z=='-' || *z=='+' ) z++;
1672   if( !IsDigit(*z) ){
1673     return 0;
1674   }
1675   z++;
1676   if( realnum ) *realnum = 0;
1677   while( IsDigit(*z) ){ z++; }
1678   if( *z=='.' ){
1679     z++;
1680     if( !IsDigit(*z) ) return 0;
1681     while( IsDigit(*z) ){ z++; }
1682     if( realnum ) *realnum = 1;
1683   }
1684   if( *z=='e' || *z=='E' ){
1685     z++;
1686     if( *z=='+' || *z=='-' ) z++;
1687     if( !IsDigit(*z) ) return 0;
1688     while( IsDigit(*z) ){ z++; }
1689     if( realnum ) *realnum = 1;
1690   }
1691   return *z==0;
1692 }
1693 
1694 /*
1695 ** Compute a string length that is limited to what can be stored in
1696 ** lower 30 bits of a 32-bit signed integer.
1697 */
strlen30(const char * z)1698 static int strlen30(const char *z){
1699   const char *z2 = z;
1700   while( *z2 ){ z2++; }
1701   return 0x3fffffff & (int)(z2 - z);
1702 }
1703 
1704 /*
1705 ** Return the length of a string in characters.  Multibyte UTF8 characters
1706 ** count as a single character.
1707 */
strlenChar(const char * z)1708 static int strlenChar(const char *z){
1709   int n = 0;
1710   while( *z ){
1711     if( (0xc0&*(z++))!=0x80 ) n++;
1712   }
1713   return n;
1714 }
1715 
1716 /*
1717 ** Return open FILE * if zFile exists, can be opened for read
1718 ** and is an ordinary file or a character stream source.
1719 ** Otherwise return 0.
1720 */
openChrSource(const char * zFile)1721 static FILE * openChrSource(const char *zFile){
1722 #if defined(_WIN32) || defined(WIN32)
1723   struct _stat x = {0};
1724 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1725   /* On Windows, open first, then check the stream nature. This order
1726   ** is necessary because _stat() and sibs, when checking a named pipe,
1727   ** effectively break the pipe as its supplier sees it. */
1728   FILE *rv = fopen(zFile, "rb");
1729   if( rv==0 ) return 0;
1730   if( _fstat(_fileno(rv), &x) != 0
1731       || !STAT_CHR_SRC(x.st_mode)){
1732     fclose(rv);
1733     rv = 0;
1734   }
1735   return rv;
1736 #else
1737   struct stat x = {0};
1738   int rc = stat(zFile, &x);
1739 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
1740   if( rc!=0 ) return 0;
1741   if( STAT_CHR_SRC(x.st_mode) ){
1742     return fopen(zFile, "rb");
1743   }else{
1744     return 0;
1745   }
1746 #endif
1747 #undef STAT_CHR_SRC
1748 }
1749 
1750 /*
1751 ** This routine reads a line of text from FILE in, stores
1752 ** the text in memory obtained from malloc() and returns a pointer
1753 ** to the text.  NULL is returned at end of file, or if malloc()
1754 ** fails.
1755 **
1756 ** If zLine is not NULL then it is a malloced buffer returned from
1757 ** a previous call to this routine that may be reused.
1758 */
local_getline(char * zLine,FILE * in)1759 static char *local_getline(char *zLine, FILE *in){
1760   int nLine = zLine==0 ? 0 : 100;
1761   int n = 0;
1762 
1763   while( 1 ){
1764     if( n+100>nLine ){
1765       nLine = nLine*2 + 100;
1766       zLine = realloc(zLine, nLine);
1767       shell_check_oom(zLine);
1768     }
1769     if( fgets(&zLine[n], nLine - n, in)==0 ){
1770       if( n==0 ){
1771         free(zLine);
1772         return 0;
1773       }
1774       zLine[n] = 0;
1775       break;
1776     }
1777     while( zLine[n] ) n++;
1778     if( n>0 && zLine[n-1]=='\n' ){
1779       n--;
1780       if( n>0 && zLine[n-1]=='\r' ) n--;
1781       zLine[n] = 0;
1782       break;
1783     }
1784   }
1785   return zLine;
1786 }
1787 
1788 /*
1789 ** Retrieve a single line of input text.
1790 **
1791 ** If in==0 then read from standard input and prompt before each line.
1792 ** If isContinuation is true, then a continuation prompt is appropriate.
1793 ** If isContinuation is zero, then the main prompt should be used.
1794 **
1795 ** If zPrior is not NULL then it is a buffer from a prior call to this
1796 ** routine that can be reused.
1797 **
1798 ** The result is stored in space obtained from malloc() and must either
1799 ** be freed by the caller or else passed back into this routine via the
1800 ** zPrior argument for reuse.
1801 */
1802 #ifndef SQLITE_SHELL_FIDDLE
one_input_line(FILE * in,char * zPrior,int isContinuation)1803 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1804   char *zPrompt;
1805   char *zResult;
1806   if( in!=0 ){
1807     zResult = local_getline(zPrior, in);
1808   }else{
1809     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1810 #if SHELL_USE_LOCAL_GETLINE
1811     sputz(stdout, zPrompt);
1812     fflush(stdout);
1813     do{
1814       zResult = local_getline(zPrior, stdin);
1815       zPrior = 0;
1816       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1817       if( zResult==0 ) sqlite3_sleep(50);
1818     }while( zResult==0 && seenInterrupt>0 );
1819 #else
1820     free(zPrior);
1821     zResult = shell_readline(zPrompt);
1822     while( zResult==0 ){
1823       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1824       sqlite3_sleep(50);
1825       if( seenInterrupt==0 ) break;
1826       zResult = shell_readline("");
1827     }
1828     if( zResult && *zResult ) shell_add_history(zResult);
1829 #endif
1830   }
1831   return zResult;
1832 }
1833 #endif /* !SQLITE_SHELL_FIDDLE */
1834 
1835 /*
1836 ** Return the value of a hexadecimal digit.  Return -1 if the input
1837 ** is not a hex digit.
1838 */
hexDigitValue(char c)1839 static int hexDigitValue(char c){
1840   if( c>='0' && c<='9' ) return c - '0';
1841   if( c>='a' && c<='f' ) return c - 'a' + 10;
1842   if( c>='A' && c<='F' ) return c - 'A' + 10;
1843   return -1;
1844 }
1845 
1846 /*
1847 ** Interpret zArg as an integer value, possibly with suffixes.
1848 */
integerValue(const char * zArg)1849 static sqlite3_int64 integerValue(const char *zArg){
1850   sqlite3_int64 v = 0;
1851   static const struct { char *zSuffix; int iMult; } aMult[] = {
1852     { "KiB", 1024 },
1853     { "MiB", 1024*1024 },
1854     { "GiB", 1024*1024*1024 },
1855     { "KB",  1000 },
1856     { "MB",  1000000 },
1857     { "GB",  1000000000 },
1858     { "K",   1000 },
1859     { "M",   1000000 },
1860     { "G",   1000000000 },
1861   };
1862   int i;
1863   int isNeg = 0;
1864   if( zArg[0]=='-' ){
1865     isNeg = 1;
1866     zArg++;
1867   }else if( zArg[0]=='+' ){
1868     zArg++;
1869   }
1870   if( zArg[0]=='0' && zArg[1]=='x' ){
1871     int x;
1872     zArg += 2;
1873     while( (x = hexDigitValue(zArg[0]))>=0 ){
1874       v = (v<<4) + x;
1875       zArg++;
1876     }
1877   }else{
1878     while( IsDigit(zArg[0]) ){
1879       v = v*10 + zArg[0] - '0';
1880       zArg++;
1881     }
1882   }
1883   for(i=0; i<ArraySize(aMult); i++){
1884     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1885       v *= aMult[i].iMult;
1886       break;
1887     }
1888   }
1889   return isNeg? -v : v;
1890 }
1891 
1892 /*
1893 ** A variable length string to which one can append text.
1894 */
1895 typedef struct ShellText ShellText;
1896 struct ShellText {
1897   char *z;
1898   int n;
1899   int nAlloc;
1900 };
1901 
1902 /*
1903 ** Initialize and destroy a ShellText object
1904 */
initText(ShellText * p)1905 static void initText(ShellText *p){
1906   memset(p, 0, sizeof(*p));
1907 }
freeText(ShellText * p)1908 static void freeText(ShellText *p){
1909   free(p->z);
1910   initText(p);
1911 }
1912 
1913 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1914 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1915 ** added to zIn, and the result returned in memory obtained from malloc().
1916 ** zIn, if it was not NULL, is freed.
1917 **
1918 ** If the third argument, quote, is not '\0', then it is used as a
1919 ** quote character for zAppend.
1920 */
appendText(ShellText * p,const char * zAppend,char quote)1921 static void appendText(ShellText *p, const char *zAppend, char quote){
1922   i64 len;
1923   i64 i;
1924   i64 nAppend = strlen30(zAppend);
1925 
1926   len = nAppend+p->n+1;
1927   if( quote ){
1928     len += 2;
1929     for(i=0; i<nAppend; i++){
1930       if( zAppend[i]==quote ) len++;
1931     }
1932   }
1933 
1934   if( p->z==0 || p->n+len>=p->nAlloc ){
1935     p->nAlloc = p->nAlloc*2 + len + 20;
1936     p->z = realloc(p->z, p->nAlloc);
1937     shell_check_oom(p->z);
1938   }
1939 
1940   if( quote ){
1941     char *zCsr = p->z+p->n;
1942     *zCsr++ = quote;
1943     for(i=0; i<nAppend; i++){
1944       *zCsr++ = zAppend[i];
1945       if( zAppend[i]==quote ) *zCsr++ = quote;
1946     }
1947     *zCsr++ = quote;
1948     p->n = (int)(zCsr - p->z);
1949     *zCsr = '\0';
1950   }else{
1951     memcpy(p->z+p->n, zAppend, nAppend);
1952     p->n += nAppend;
1953     p->z[p->n] = '\0';
1954   }
1955 }
1956 
1957 /*
1958 ** Attempt to determine if identifier zName needs to be quoted, either
1959 ** because it contains non-alphanumeric characters, or because it is an
1960 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1961 ** that quoting is required.
1962 **
1963 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1964 */
quoteChar(const char * zName)1965 static char quoteChar(const char *zName){
1966   int i;
1967   if( zName==0 ) return '"';
1968   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1969   for(i=0; zName[i]; i++){
1970     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1971   }
1972   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1973 }
1974 
1975 /*
1976 ** Construct a fake object name and column list to describe the structure
1977 ** of the view, virtual table, or table valued function zSchema.zName.
1978 */
shellFakeSchema(sqlite3 * db,const char * zSchema,const char * zName)1979 static char *shellFakeSchema(
1980   sqlite3 *db,            /* The database connection containing the vtab */
1981   const char *zSchema,    /* Schema of the database holding the vtab */
1982   const char *zName       /* The name of the virtual table */
1983 ){
1984   sqlite3_stmt *pStmt = 0;
1985   char *zSql;
1986   ShellText s;
1987   char cQuote;
1988   char *zDiv = "(";
1989   int nRow = 0;
1990 
1991   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1992                          zSchema ? zSchema : "main", zName);
1993   shell_check_oom(zSql);
1994   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1995   sqlite3_free(zSql);
1996   initText(&s);
1997   if( zSchema ){
1998     cQuote = quoteChar(zSchema);
1999     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
2000     appendText(&s, zSchema, cQuote);
2001     appendText(&s, ".", 0);
2002   }
2003   cQuote = quoteChar(zName);
2004   appendText(&s, zName, cQuote);
2005   while( sqlite3_step(pStmt)==SQLITE_ROW ){
2006     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
2007     nRow++;
2008     appendText(&s, zDiv, 0);
2009     zDiv = ",";
2010     if( zCol==0 ) zCol = "";
2011     cQuote = quoteChar(zCol);
2012     appendText(&s, zCol, cQuote);
2013   }
2014   appendText(&s, ")", 0);
2015   sqlite3_finalize(pStmt);
2016   if( nRow==0 ){
2017     freeText(&s);
2018     s.z = 0;
2019   }
2020   return s.z;
2021 }
2022 
2023 /*
2024 ** SQL function:  strtod(X)
2025 **
2026 ** Use the C-library strtod() function to convert string X into a double.
2027 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
2028 ** routines against the C-library.
2029 */
shellStrtod(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2030 static void shellStrtod(
2031   sqlite3_context *pCtx,
2032   int nVal,
2033   sqlite3_value **apVal
2034 ){
2035   char *z = (char*)sqlite3_value_text(apVal[0]);
2036   UNUSED_PARAMETER(nVal);
2037   if( z==0 ) return;
2038   sqlite3_result_double(pCtx, strtod(z,0));
2039 }
2040 
2041 /*
2042 ** SQL function:  dtostr(X)
2043 **
2044 ** Use the C-library printf() function to convert real value X into a string.
2045 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
2046 ** routines against the C-library.
2047 */
shellDtostr(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2048 static void shellDtostr(
2049   sqlite3_context *pCtx,
2050   int nVal,
2051   sqlite3_value **apVal
2052 ){
2053   double r = sqlite3_value_double(apVal[0]);
2054   int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
2055   char z[400];
2056   if( n<1 ) n = 1;
2057   if( n>350 ) n = 350;
2058   sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
2059   sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
2060 }
2061 
2062 
2063 /*
2064 ** SQL function:  shell_module_schema(X)
2065 **
2066 ** Return a fake schema for the table-valued function or eponymous virtual
2067 ** table X.
2068 */
shellModuleSchema(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2069 static void shellModuleSchema(
2070   sqlite3_context *pCtx,
2071   int nVal,
2072   sqlite3_value **apVal
2073 ){
2074   const char *zName;
2075   char *zFake;
2076   UNUSED_PARAMETER(nVal);
2077   zName = (const char*)sqlite3_value_text(apVal[0]);
2078   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
2079   if( zFake ){
2080     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
2081                         -1, sqlite3_free);
2082     free(zFake);
2083   }
2084 }
2085 
2086 /*
2087 ** SQL function:  shell_add_schema(S,X)
2088 **
2089 ** Add the schema name X to the CREATE statement in S and return the result.
2090 ** Examples:
2091 **
2092 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
2093 **
2094 ** Also works on
2095 **
2096 **    CREATE INDEX
2097 **    CREATE UNIQUE INDEX
2098 **    CREATE VIEW
2099 **    CREATE TRIGGER
2100 **    CREATE VIRTUAL TABLE
2101 **
2102 ** This UDF is used by the .schema command to insert the schema name of
2103 ** attached databases into the middle of the sqlite_schema.sql field.
2104 */
shellAddSchemaName(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2105 static void shellAddSchemaName(
2106   sqlite3_context *pCtx,
2107   int nVal,
2108   sqlite3_value **apVal
2109 ){
2110   static const char *aPrefix[] = {
2111      "TABLE",
2112      "INDEX",
2113      "UNIQUE INDEX",
2114      "VIEW",
2115      "TRIGGER",
2116      "VIRTUAL TABLE"
2117   };
2118   int i = 0;
2119   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
2120   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
2121   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
2122   sqlite3 *db = sqlite3_context_db_handle(pCtx);
2123   UNUSED_PARAMETER(nVal);
2124   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
2125     for(i=0; i<ArraySize(aPrefix); i++){
2126       int n = strlen30(aPrefix[i]);
2127       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
2128         char *z = 0;
2129         char *zFake = 0;
2130         if( zSchema ){
2131           char cQuote = quoteChar(zSchema);
2132           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
2133             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
2134           }else{
2135             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
2136           }
2137         }
2138         if( zName
2139          && aPrefix[i][0]=='V'
2140          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
2141         ){
2142           if( z==0 ){
2143             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
2144           }else{
2145             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
2146           }
2147           free(zFake);
2148         }
2149         if( z ){
2150           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
2151           return;
2152         }
2153       }
2154     }
2155   }
2156   sqlite3_result_value(pCtx, apVal[0]);
2157 }
2158 
2159 /*
2160 ** The source code for several run-time loadable extensions is inserted
2161 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
2162 ** code, we need to override some macros to make the included program code
2163 ** work here in the middle of this regular program.
2164 */
2165 #define SQLITE_EXTENSION_INIT1
2166 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
2167 
2168 #if defined(_WIN32) && defined(_MSC_VER)
2169 /************************* Begin test_windirent.h ******************/
2170 /*
2171 ** 2015 November 30
2172 **
2173 ** The author disclaims copyright to this source code.  In place of
2174 ** a legal notice, here is a blessing:
2175 **
2176 **    May you do good and not evil.
2177 **    May you find forgiveness for yourself and forgive others.
2178 **    May you share freely, never taking more than you give.
2179 **
2180 *************************************************************************
2181 ** This file contains declarations for most of the opendir() family of
2182 ** POSIX functions on Win32 using the MSVCRT.
2183 */
2184 
2185 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
2186 #define SQLITE_WINDIRENT_H
2187 
2188 /*
2189 ** We need several data types from the Windows SDK header.
2190 */
2191 
2192 #ifndef WIN32_LEAN_AND_MEAN
2193 #define WIN32_LEAN_AND_MEAN
2194 #endif
2195 
2196 #include "windows.h"
2197 
2198 /*
2199 ** We need several support functions from the SQLite core.
2200 */
2201 
2202 /* #include "sqlite3.h" */
2203 
2204 /*
2205 ** We need several things from the ANSI and MSVCRT headers.
2206 */
2207 
2208 #include <stdio.h>
2209 #include <stdlib.h>
2210 #include <errno.h>
2211 #include <io.h>
2212 #include <limits.h>
2213 #include <sys/types.h>
2214 #include <sys/stat.h>
2215 
2216 /*
2217 ** We may need several defines that should have been in "sys/stat.h".
2218 */
2219 
2220 #ifndef S_ISREG
2221 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
2222 #endif
2223 
2224 #ifndef S_ISDIR
2225 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
2226 #endif
2227 
2228 #ifndef S_ISLNK
2229 #define S_ISLNK(mode) (0)
2230 #endif
2231 
2232 /*
2233 ** We may need to provide the "mode_t" type.
2234 */
2235 
2236 #ifndef MODE_T_DEFINED
2237   #define MODE_T_DEFINED
2238   typedef unsigned short mode_t;
2239 #endif
2240 
2241 /*
2242 ** We may need to provide the "ino_t" type.
2243 */
2244 
2245 #ifndef INO_T_DEFINED
2246   #define INO_T_DEFINED
2247   typedef unsigned short ino_t;
2248 #endif
2249 
2250 /*
2251 ** We need to define "NAME_MAX" if it was not present in "limits.h".
2252 */
2253 
2254 #ifndef NAME_MAX
2255 #  ifdef FILENAME_MAX
2256 #    define NAME_MAX (FILENAME_MAX)
2257 #  else
2258 #    define NAME_MAX (260)
2259 #  endif
2260 #endif
2261 
2262 /*
2263 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
2264 */
2265 
2266 #ifndef NULL_INTPTR_T
2267 #  define NULL_INTPTR_T ((intptr_t)(0))
2268 #endif
2269 
2270 #ifndef BAD_INTPTR_T
2271 #  define BAD_INTPTR_T ((intptr_t)(-1))
2272 #endif
2273 
2274 /*
2275 ** We need to provide the necessary structures and related types.
2276 */
2277 
2278 #ifndef DIRENT_DEFINED
2279 #define DIRENT_DEFINED
2280 typedef struct DIRENT DIRENT;
2281 typedef DIRENT *LPDIRENT;
2282 struct DIRENT {
2283   ino_t d_ino;               /* Sequence number, do not use. */
2284   unsigned d_attributes;     /* Win32 file attributes. */
2285   char d_name[NAME_MAX + 1]; /* Name within the directory. */
2286 };
2287 #endif
2288 
2289 #ifndef DIR_DEFINED
2290 #define DIR_DEFINED
2291 typedef struct DIR DIR;
2292 typedef DIR *LPDIR;
2293 struct DIR {
2294   intptr_t d_handle; /* Value returned by "_findfirst". */
2295   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
2296   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
2297 };
2298 #endif
2299 
2300 /*
2301 ** Provide a macro, for use by the implementation, to determine if a
2302 ** particular directory entry should be skipped over when searching for
2303 ** the next directory entry that should be returned by the readdir() or
2304 ** readdir_r() functions.
2305 */
2306 
2307 #ifndef is_filtered
2308 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
2309 #endif
2310 
2311 /*
2312 ** Provide the function prototype for the POSIX compatible getenv()
2313 ** function.  This function is not thread-safe.
2314 */
2315 
2316 extern const char *windirent_getenv(const char *name);
2317 
2318 /*
2319 ** Finally, we can provide the function prototypes for the opendir(),
2320 ** readdir(), readdir_r(), and closedir() POSIX functions.
2321 */
2322 
2323 extern LPDIR opendir(const char *dirname);
2324 extern LPDIRENT readdir(LPDIR dirp);
2325 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
2326 extern INT closedir(LPDIR dirp);
2327 
2328 #endif /* defined(WIN32) && defined(_MSC_VER) */
2329 
2330 /************************* End test_windirent.h ********************/
2331 /************************* Begin test_windirent.c ******************/
2332 /*
2333 ** 2015 November 30
2334 **
2335 ** The author disclaims copyright to this source code.  In place of
2336 ** a legal notice, here is a blessing:
2337 **
2338 **    May you do good and not evil.
2339 **    May you find forgiveness for yourself and forgive others.
2340 **    May you share freely, never taking more than you give.
2341 **
2342 *************************************************************************
2343 ** This file contains code to implement most of the opendir() family of
2344 ** POSIX functions on Win32 using the MSVCRT.
2345 */
2346 
2347 #if defined(_WIN32) && defined(_MSC_VER)
2348 /* #include "test_windirent.h" */
2349 
2350 /*
2351 ** Implementation of the POSIX getenv() function using the Win32 API.
2352 ** This function is not thread-safe.
2353 */
windirent_getenv(const char * name)2354 const char *windirent_getenv(
2355   const char *name
2356 ){
2357   static char value[32768]; /* Maximum length, per MSDN */
2358   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
2359   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
2360 
2361   memset(value, 0, sizeof(value));
2362   dwRet = GetEnvironmentVariableA(name, value, dwSize);
2363   if( dwRet==0 || dwRet>dwSize ){
2364     /*
2365     ** The function call to GetEnvironmentVariableA() failed -OR-
2366     ** the buffer is not large enough.  Either way, return NULL.
2367     */
2368     return 0;
2369   }else{
2370     /*
2371     ** The function call to GetEnvironmentVariableA() succeeded
2372     ** -AND- the buffer contains the entire value.
2373     */
2374     return value;
2375   }
2376 }
2377 
2378 /*
2379 ** Implementation of the POSIX opendir() function using the MSVCRT.
2380 */
opendir(const char * dirname)2381 LPDIR opendir(
2382   const char *dirname
2383 ){
2384   struct _finddata_t data;
2385   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
2386   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
2387 
2388   if( dirp==NULL ) return NULL;
2389   memset(dirp, 0, sizeof(DIR));
2390 
2391   /* TODO: Remove this if Unix-style root paths are not used. */
2392   if( sqlite3_stricmp(dirname, "/")==0 ){
2393     dirname = windirent_getenv("SystemDrive");
2394   }
2395 
2396   memset(&data, 0, sizeof(struct _finddata_t));
2397   _snprintf(data.name, namesize, "%s\\*", dirname);
2398   dirp->d_handle = _findfirst(data.name, &data);
2399 
2400   if( dirp->d_handle==BAD_INTPTR_T ){
2401     closedir(dirp);
2402     return NULL;
2403   }
2404 
2405   /* TODO: Remove this block to allow hidden and/or system files. */
2406   if( is_filtered(data) ){
2407 next:
2408 
2409     memset(&data, 0, sizeof(struct _finddata_t));
2410     if( _findnext(dirp->d_handle, &data)==-1 ){
2411       closedir(dirp);
2412       return NULL;
2413     }
2414 
2415     /* TODO: Remove this block to allow hidden and/or system files. */
2416     if( is_filtered(data) ) goto next;
2417   }
2418 
2419   dirp->d_first.d_attributes = data.attrib;
2420   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
2421   dirp->d_first.d_name[NAME_MAX] = '\0';
2422 
2423   return dirp;
2424 }
2425 
2426 /*
2427 ** Implementation of the POSIX readdir() function using the MSVCRT.
2428 */
readdir(LPDIR dirp)2429 LPDIRENT readdir(
2430   LPDIR dirp
2431 ){
2432   struct _finddata_t data;
2433 
2434   if( dirp==NULL ) return NULL;
2435 
2436   if( dirp->d_first.d_ino==0 ){
2437     dirp->d_first.d_ino++;
2438     dirp->d_next.d_ino++;
2439 
2440     return &dirp->d_first;
2441   }
2442 
2443 next:
2444 
2445   memset(&data, 0, sizeof(struct _finddata_t));
2446   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
2447 
2448   /* TODO: Remove this block to allow hidden and/or system files. */
2449   if( is_filtered(data) ) goto next;
2450 
2451   dirp->d_next.d_ino++;
2452   dirp->d_next.d_attributes = data.attrib;
2453   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
2454   dirp->d_next.d_name[NAME_MAX] = '\0';
2455 
2456   return &dirp->d_next;
2457 }
2458 
2459 /*
2460 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
2461 */
readdir_r(LPDIR dirp,LPDIRENT entry,LPDIRENT * result)2462 INT readdir_r(
2463   LPDIR dirp,
2464   LPDIRENT entry,
2465   LPDIRENT *result
2466 ){
2467   struct _finddata_t data;
2468 
2469   if( dirp==NULL ) return EBADF;
2470 
2471   if( dirp->d_first.d_ino==0 ){
2472     dirp->d_first.d_ino++;
2473     dirp->d_next.d_ino++;
2474 
2475     entry->d_ino = dirp->d_first.d_ino;
2476     entry->d_attributes = dirp->d_first.d_attributes;
2477     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
2478     entry->d_name[NAME_MAX] = '\0';
2479 
2480     *result = entry;
2481     return 0;
2482   }
2483 
2484 next:
2485 
2486   memset(&data, 0, sizeof(struct _finddata_t));
2487   if( _findnext(dirp->d_handle, &data)==-1 ){
2488     *result = NULL;
2489     return ENOENT;
2490   }
2491 
2492   /* TODO: Remove this block to allow hidden and/or system files. */
2493   if( is_filtered(data) ) goto next;
2494 
2495   entry->d_ino = (ino_t)-1; /* not available */
2496   entry->d_attributes = data.attrib;
2497   strncpy(entry->d_name, data.name, NAME_MAX);
2498   entry->d_name[NAME_MAX] = '\0';
2499 
2500   *result = entry;
2501   return 0;
2502 }
2503 
2504 /*
2505 ** Implementation of the POSIX closedir() function using the MSVCRT.
2506 */
closedir(LPDIR dirp)2507 INT closedir(
2508   LPDIR dirp
2509 ){
2510   INT result = 0;
2511 
2512   if( dirp==NULL ) return EINVAL;
2513 
2514   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
2515     result = _findclose(dirp->d_handle);
2516   }
2517 
2518   sqlite3_free(dirp);
2519   return result;
2520 }
2521 
2522 #endif /* defined(WIN32) && defined(_MSC_VER) */
2523 
2524 /************************* End test_windirent.c ********************/
2525 #define dirent DIRENT
2526 #endif
2527 /************************* Begin ../ext/misc/memtrace.c ******************/
2528 /*
2529 ** 2019-01-21
2530 **
2531 ** The author disclaims copyright to this source code.  In place of
2532 ** a legal notice, here is a blessing:
2533 **
2534 **    May you do good and not evil.
2535 **    May you find forgiveness for yourself and forgive others.
2536 **    May you share freely, never taking more than you give.
2537 **
2538 *************************************************************************
2539 **
2540 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
2541 ** mechanism to add a tracing layer on top of SQLite.  If this extension
2542 ** is registered prior to sqlite3_initialize(), it will cause all memory
2543 ** allocation activities to be logged on standard output, or to some other
2544 ** FILE specified by the initializer.
2545 **
2546 ** This file needs to be compiled into the application that uses it.
2547 **
2548 ** This extension is used to implement the --memtrace option of the
2549 ** command-line shell.
2550 */
2551 #include <assert.h>
2552 #include <string.h>
2553 #include <stdio.h>
2554 
2555 /* The original memory allocation routines */
2556 static sqlite3_mem_methods memtraceBase;
2557 static FILE *memtraceOut;
2558 
2559 /* Methods that trace memory allocations */
memtraceMalloc(int n)2560 static void *memtraceMalloc(int n){
2561   if( memtraceOut ){
2562     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
2563             memtraceBase.xRoundup(n));
2564   }
2565   return memtraceBase.xMalloc(n);
2566 }
memtraceFree(void * p)2567 static void memtraceFree(void *p){
2568   if( p==0 ) return;
2569   if( memtraceOut ){
2570     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
2571   }
2572   memtraceBase.xFree(p);
2573 }
memtraceRealloc(void * p,int n)2574 static void *memtraceRealloc(void *p, int n){
2575   if( p==0 ) return memtraceMalloc(n);
2576   if( n==0 ){
2577     memtraceFree(p);
2578     return 0;
2579   }
2580   if( memtraceOut ){
2581     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
2582             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
2583   }
2584   return memtraceBase.xRealloc(p, n);
2585 }
memtraceSize(void * p)2586 static int memtraceSize(void *p){
2587   return memtraceBase.xSize(p);
2588 }
memtraceRoundup(int n)2589 static int memtraceRoundup(int n){
2590   return memtraceBase.xRoundup(n);
2591 }
memtraceInit(void * p)2592 static int memtraceInit(void *p){
2593   return memtraceBase.xInit(p);
2594 }
memtraceShutdown(void * p)2595 static void memtraceShutdown(void *p){
2596   memtraceBase.xShutdown(p);
2597 }
2598 
2599 /* The substitute memory allocator */
2600 static sqlite3_mem_methods ersaztMethods = {
2601   memtraceMalloc,
2602   memtraceFree,
2603   memtraceRealloc,
2604   memtraceSize,
2605   memtraceRoundup,
2606   memtraceInit,
2607   memtraceShutdown,
2608   0
2609 };
2610 
2611 /* Begin tracing memory allocations to out. */
sqlite3MemTraceActivate(FILE * out)2612 int sqlite3MemTraceActivate(FILE *out){
2613   int rc = SQLITE_OK;
2614   if( memtraceBase.xMalloc==0 ){
2615     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
2616     if( rc==SQLITE_OK ){
2617       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
2618     }
2619   }
2620   memtraceOut = out;
2621   return rc;
2622 }
2623 
2624 /* Deactivate memory tracing */
sqlite3MemTraceDeactivate(void)2625 int sqlite3MemTraceDeactivate(void){
2626   int rc = SQLITE_OK;
2627   if( memtraceBase.xMalloc!=0 ){
2628     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
2629     if( rc==SQLITE_OK ){
2630       memset(&memtraceBase, 0, sizeof(memtraceBase));
2631     }
2632   }
2633   memtraceOut = 0;
2634   return rc;
2635 }
2636 
2637 /************************* End ../ext/misc/memtrace.c ********************/
2638 /************************* Begin ../ext/misc/pcachetrace.c ******************/
2639 /*
2640 ** 2023-06-21
2641 **
2642 ** The author disclaims copyright to this source code.  In place of
2643 ** a legal notice, here is a blessing:
2644 **
2645 **    May you do good and not evil.
2646 **    May you find forgiveness for yourself and forgive others.
2647 **    May you share freely, never taking more than you give.
2648 **
2649 *************************************************************************
2650 **
2651 ** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
2652 ** mechanism to add a tracing layer on top of pluggable page cache of
2653 ** SQLite.  If this extension is registered prior to sqlite3_initialize(),
2654 ** it will cause all page cache activities to be logged on standard output,
2655 ** or to some other FILE specified by the initializer.
2656 **
2657 ** This file needs to be compiled into the application that uses it.
2658 **
2659 ** This extension is used to implement the --pcachetrace option of the
2660 ** command-line shell.
2661 */
2662 #include <assert.h>
2663 #include <string.h>
2664 #include <stdio.h>
2665 
2666 /* The original page cache routines */
2667 static sqlite3_pcache_methods2 pcacheBase;
2668 static FILE *pcachetraceOut;
2669 
2670 /* Methods that trace pcache activity */
pcachetraceInit(void * pArg)2671 static int pcachetraceInit(void *pArg){
2672   int nRes;
2673   if( pcachetraceOut ){
2674     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
2675   }
2676   nRes = pcacheBase.xInit(pArg);
2677   if( pcachetraceOut ){
2678     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
2679   }
2680   return nRes;
2681 }
pcachetraceShutdown(void * pArg)2682 static void pcachetraceShutdown(void *pArg){
2683   if( pcachetraceOut ){
2684     fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
2685   }
2686   pcacheBase.xShutdown(pArg);
2687 }
pcachetraceCreate(int szPage,int szExtra,int bPurge)2688 static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
2689   sqlite3_pcache *pRes;
2690   if( pcachetraceOut ){
2691     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
2692             szPage, szExtra, bPurge);
2693   }
2694   pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
2695   if( pcachetraceOut ){
2696     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
2697             szPage, szExtra, bPurge, pRes);
2698   }
2699   return pRes;
2700 }
pcachetraceCachesize(sqlite3_pcache * p,int nCachesize)2701 static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
2702   if( pcachetraceOut ){
2703     fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
2704   }
2705   pcacheBase.xCachesize(p, nCachesize);
2706 }
pcachetracePagecount(sqlite3_pcache * p)2707 static int pcachetracePagecount(sqlite3_pcache *p){
2708   int nRes;
2709   if( pcachetraceOut ){
2710     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
2711   }
2712   nRes = pcacheBase.xPagecount(p);
2713   if( pcachetraceOut ){
2714     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
2715   }
2716   return nRes;
2717 }
pcachetraceFetch(sqlite3_pcache * p,unsigned key,int crFg)2718 static sqlite3_pcache_page *pcachetraceFetch(
2719   sqlite3_pcache *p,
2720   unsigned key,
2721   int crFg
2722 ){
2723   sqlite3_pcache_page *pRes;
2724   if( pcachetraceOut ){
2725     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
2726   }
2727   pRes = pcacheBase.xFetch(p, key, crFg);
2728   if( pcachetraceOut ){
2729     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
2730             p, key, crFg, pRes);
2731   }
2732   return pRes;
2733 }
pcachetraceUnpin(sqlite3_pcache * p,sqlite3_pcache_page * pPg,int bDiscard)2734 static void pcachetraceUnpin(
2735   sqlite3_pcache *p,
2736   sqlite3_pcache_page *pPg,
2737   int bDiscard
2738 ){
2739   if( pcachetraceOut ){
2740     fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
2741             p, pPg, bDiscard);
2742   }
2743   pcacheBase.xUnpin(p, pPg, bDiscard);
2744 }
pcachetraceRekey(sqlite3_pcache * p,sqlite3_pcache_page * pPg,unsigned oldKey,unsigned newKey)2745 static void pcachetraceRekey(
2746   sqlite3_pcache *p,
2747   sqlite3_pcache_page *pPg,
2748   unsigned oldKey,
2749   unsigned newKey
2750 ){
2751   if( pcachetraceOut ){
2752     fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
2753         p, pPg, oldKey, newKey);
2754   }
2755   pcacheBase.xRekey(p, pPg, oldKey, newKey);
2756 }
pcachetraceTruncate(sqlite3_pcache * p,unsigned n)2757 static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
2758   if( pcachetraceOut ){
2759     fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
2760   }
2761   pcacheBase.xTruncate(p, n);
2762 }
pcachetraceDestroy(sqlite3_pcache * p)2763 static void pcachetraceDestroy(sqlite3_pcache *p){
2764   if( pcachetraceOut ){
2765     fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
2766   }
2767   pcacheBase.xDestroy(p);
2768 }
pcachetraceShrink(sqlite3_pcache * p)2769 static void pcachetraceShrink(sqlite3_pcache *p){
2770   if( pcachetraceOut ){
2771     fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
2772   }
2773   pcacheBase.xShrink(p);
2774 }
2775 
2776 /* The substitute pcache methods */
2777 static sqlite3_pcache_methods2 ersaztPcacheMethods = {
2778   0,
2779   0,
2780   pcachetraceInit,
2781   pcachetraceShutdown,
2782   pcachetraceCreate,
2783   pcachetraceCachesize,
2784   pcachetracePagecount,
2785   pcachetraceFetch,
2786   pcachetraceUnpin,
2787   pcachetraceRekey,
2788   pcachetraceTruncate,
2789   pcachetraceDestroy,
2790   pcachetraceShrink
2791 };
2792 
2793 /* Begin tracing memory allocations to out. */
sqlite3PcacheTraceActivate(FILE * out)2794 int sqlite3PcacheTraceActivate(FILE *out){
2795   int rc = SQLITE_OK;
2796   if( pcacheBase.xFetch==0 ){
2797     rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
2798     if( rc==SQLITE_OK ){
2799       rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
2800     }
2801   }
2802   pcachetraceOut = out;
2803   return rc;
2804 }
2805 
2806 /* Deactivate memory tracing */
sqlite3PcacheTraceDeactivate(void)2807 int sqlite3PcacheTraceDeactivate(void){
2808   int rc = SQLITE_OK;
2809   if( pcacheBase.xFetch!=0 ){
2810     rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
2811     if( rc==SQLITE_OK ){
2812       memset(&pcacheBase, 0, sizeof(pcacheBase));
2813     }
2814   }
2815   pcachetraceOut = 0;
2816   return rc;
2817 }
2818 
2819 /************************* End ../ext/misc/pcachetrace.c ********************/
2820 /************************* Begin ../ext/misc/shathree.c ******************/
2821 /*
2822 ** 2017-03-08
2823 **
2824 ** The author disclaims copyright to this source code.  In place of
2825 ** a legal notice, here is a blessing:
2826 **
2827 **    May you do good and not evil.
2828 **    May you find forgiveness for yourself and forgive others.
2829 **    May you share freely, never taking more than you give.
2830 **
2831 ******************************************************************************
2832 **
2833 ** This SQLite extension implements functions that compute SHA3 hashes
2834 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2835 ** Two SQL functions are implemented:
2836 **
2837 **     sha3(X,SIZE)
2838 **     sha3_query(Y,SIZE)
2839 **
2840 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
2841 ** X is NULL.
2842 **
2843 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
2844 ** and returns a hash of their results.
2845 **
2846 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
2847 ** is used.  If SIZE is included it must be one of the integers 224, 256,
2848 ** 384, or 512, to determine SHA3 hash variant that is computed.
2849 */
2850 /* #include "sqlite3ext.h" */
2851 SQLITE_EXTENSION_INIT1
2852 #include <assert.h>
2853 #include <string.h>
2854 #include <stdarg.h>
2855 
2856 #ifndef SQLITE_AMALGAMATION
2857 /* typedef sqlite3_uint64 u64; */
2858 #endif /* SQLITE_AMALGAMATION */
2859 
2860 /******************************************************************************
2861 ** The Hash Engine
2862 */
2863 /*
2864 ** Macros to determine whether the machine is big or little endian,
2865 ** and whether or not that determination is run-time or compile-time.
2866 **
2867 ** For best performance, an attempt is made to guess at the byte-order
2868 ** using C-preprocessor macros.  If that is unsuccessful, or if
2869 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2870 ** at run-time.
2871 */
2872 #ifndef SHA3_BYTEORDER
2873 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
2874      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
2875      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
2876      defined(__arm__)
2877 #   define SHA3_BYTEORDER    1234
2878 # elif defined(sparc)    || defined(__ppc__)
2879 #   define SHA3_BYTEORDER    4321
2880 # else
2881 #   define SHA3_BYTEORDER 0
2882 # endif
2883 #endif
2884 
2885 
2886 /*
2887 ** State structure for a SHA3 hash in progress
2888 */
2889 typedef struct SHA3Context SHA3Context;
2890 struct SHA3Context {
2891   union {
2892     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
2893     unsigned char x[1600];    /* ... or 1600 bytes */
2894   } u;
2895   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
2896   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
2897   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
2898 };
2899 
2900 /*
2901 ** A single step of the Keccak mixing function for a 1600-bit state
2902 */
KeccakF1600Step(SHA3Context * p)2903 static void KeccakF1600Step(SHA3Context *p){
2904   int i;
2905   u64 b0, b1, b2, b3, b4;
2906   u64 c0, c1, c2, c3, c4;
2907   u64 d0, d1, d2, d3, d4;
2908   static const u64 RC[] = {
2909     0x0000000000000001ULL,  0x0000000000008082ULL,
2910     0x800000000000808aULL,  0x8000000080008000ULL,
2911     0x000000000000808bULL,  0x0000000080000001ULL,
2912     0x8000000080008081ULL,  0x8000000000008009ULL,
2913     0x000000000000008aULL,  0x0000000000000088ULL,
2914     0x0000000080008009ULL,  0x000000008000000aULL,
2915     0x000000008000808bULL,  0x800000000000008bULL,
2916     0x8000000000008089ULL,  0x8000000000008003ULL,
2917     0x8000000000008002ULL,  0x8000000000000080ULL,
2918     0x000000000000800aULL,  0x800000008000000aULL,
2919     0x8000000080008081ULL,  0x8000000000008080ULL,
2920     0x0000000080000001ULL,  0x8000000080008008ULL
2921   };
2922 # define a00 (p->u.s[0])
2923 # define a01 (p->u.s[1])
2924 # define a02 (p->u.s[2])
2925 # define a03 (p->u.s[3])
2926 # define a04 (p->u.s[4])
2927 # define a10 (p->u.s[5])
2928 # define a11 (p->u.s[6])
2929 # define a12 (p->u.s[7])
2930 # define a13 (p->u.s[8])
2931 # define a14 (p->u.s[9])
2932 # define a20 (p->u.s[10])
2933 # define a21 (p->u.s[11])
2934 # define a22 (p->u.s[12])
2935 # define a23 (p->u.s[13])
2936 # define a24 (p->u.s[14])
2937 # define a30 (p->u.s[15])
2938 # define a31 (p->u.s[16])
2939 # define a32 (p->u.s[17])
2940 # define a33 (p->u.s[18])
2941 # define a34 (p->u.s[19])
2942 # define a40 (p->u.s[20])
2943 # define a41 (p->u.s[21])
2944 # define a42 (p->u.s[22])
2945 # define a43 (p->u.s[23])
2946 # define a44 (p->u.s[24])
2947 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
2948 
2949   for(i=0; i<24; i+=4){
2950     c0 = a00^a10^a20^a30^a40;
2951     c1 = a01^a11^a21^a31^a41;
2952     c2 = a02^a12^a22^a32^a42;
2953     c3 = a03^a13^a23^a33^a43;
2954     c4 = a04^a14^a24^a34^a44;
2955     d0 = c4^ROL64(c1, 1);
2956     d1 = c0^ROL64(c2, 1);
2957     d2 = c1^ROL64(c3, 1);
2958     d3 = c2^ROL64(c4, 1);
2959     d4 = c3^ROL64(c0, 1);
2960 
2961     b0 = (a00^d0);
2962     b1 = ROL64((a11^d1), 44);
2963     b2 = ROL64((a22^d2), 43);
2964     b3 = ROL64((a33^d3), 21);
2965     b4 = ROL64((a44^d4), 14);
2966     a00 =   b0 ^((~b1)&  b2 );
2967     a00 ^= RC[i];
2968     a11 =   b1 ^((~b2)&  b3 );
2969     a22 =   b2 ^((~b3)&  b4 );
2970     a33 =   b3 ^((~b4)&  b0 );
2971     a44 =   b4 ^((~b0)&  b1 );
2972 
2973     b2 = ROL64((a20^d0), 3);
2974     b3 = ROL64((a31^d1), 45);
2975     b4 = ROL64((a42^d2), 61);
2976     b0 = ROL64((a03^d3), 28);
2977     b1 = ROL64((a14^d4), 20);
2978     a20 =   b0 ^((~b1)&  b2 );
2979     a31 =   b1 ^((~b2)&  b3 );
2980     a42 =   b2 ^((~b3)&  b4 );
2981     a03 =   b3 ^((~b4)&  b0 );
2982     a14 =   b4 ^((~b0)&  b1 );
2983 
2984     b4 = ROL64((a40^d0), 18);
2985     b0 = ROL64((a01^d1), 1);
2986     b1 = ROL64((a12^d2), 6);
2987     b2 = ROL64((a23^d3), 25);
2988     b3 = ROL64((a34^d4), 8);
2989     a40 =   b0 ^((~b1)&  b2 );
2990     a01 =   b1 ^((~b2)&  b3 );
2991     a12 =   b2 ^((~b3)&  b4 );
2992     a23 =   b3 ^((~b4)&  b0 );
2993     a34 =   b4 ^((~b0)&  b1 );
2994 
2995     b1 = ROL64((a10^d0), 36);
2996     b2 = ROL64((a21^d1), 10);
2997     b3 = ROL64((a32^d2), 15);
2998     b4 = ROL64((a43^d3), 56);
2999     b0 = ROL64((a04^d4), 27);
3000     a10 =   b0 ^((~b1)&  b2 );
3001     a21 =   b1 ^((~b2)&  b3 );
3002     a32 =   b2 ^((~b3)&  b4 );
3003     a43 =   b3 ^((~b4)&  b0 );
3004     a04 =   b4 ^((~b0)&  b1 );
3005 
3006     b3 = ROL64((a30^d0), 41);
3007     b4 = ROL64((a41^d1), 2);
3008     b0 = ROL64((a02^d2), 62);
3009     b1 = ROL64((a13^d3), 55);
3010     b2 = ROL64((a24^d4), 39);
3011     a30 =   b0 ^((~b1)&  b2 );
3012     a41 =   b1 ^((~b2)&  b3 );
3013     a02 =   b2 ^((~b3)&  b4 );
3014     a13 =   b3 ^((~b4)&  b0 );
3015     a24 =   b4 ^((~b0)&  b1 );
3016 
3017     c0 = a00^a20^a40^a10^a30;
3018     c1 = a11^a31^a01^a21^a41;
3019     c2 = a22^a42^a12^a32^a02;
3020     c3 = a33^a03^a23^a43^a13;
3021     c4 = a44^a14^a34^a04^a24;
3022     d0 = c4^ROL64(c1, 1);
3023     d1 = c0^ROL64(c2, 1);
3024     d2 = c1^ROL64(c3, 1);
3025     d3 = c2^ROL64(c4, 1);
3026     d4 = c3^ROL64(c0, 1);
3027 
3028     b0 = (a00^d0);
3029     b1 = ROL64((a31^d1), 44);
3030     b2 = ROL64((a12^d2), 43);
3031     b3 = ROL64((a43^d3), 21);
3032     b4 = ROL64((a24^d4), 14);
3033     a00 =   b0 ^((~b1)&  b2 );
3034     a00 ^= RC[i+1];
3035     a31 =   b1 ^((~b2)&  b3 );
3036     a12 =   b2 ^((~b3)&  b4 );
3037     a43 =   b3 ^((~b4)&  b0 );
3038     a24 =   b4 ^((~b0)&  b1 );
3039 
3040     b2 = ROL64((a40^d0), 3);
3041     b3 = ROL64((a21^d1), 45);
3042     b4 = ROL64((a02^d2), 61);
3043     b0 = ROL64((a33^d3), 28);
3044     b1 = ROL64((a14^d4), 20);
3045     a40 =   b0 ^((~b1)&  b2 );
3046     a21 =   b1 ^((~b2)&  b3 );
3047     a02 =   b2 ^((~b3)&  b4 );
3048     a33 =   b3 ^((~b4)&  b0 );
3049     a14 =   b4 ^((~b0)&  b1 );
3050 
3051     b4 = ROL64((a30^d0), 18);
3052     b0 = ROL64((a11^d1), 1);
3053     b1 = ROL64((a42^d2), 6);
3054     b2 = ROL64((a23^d3), 25);
3055     b3 = ROL64((a04^d4), 8);
3056     a30 =   b0 ^((~b1)&  b2 );
3057     a11 =   b1 ^((~b2)&  b3 );
3058     a42 =   b2 ^((~b3)&  b4 );
3059     a23 =   b3 ^((~b4)&  b0 );
3060     a04 =   b4 ^((~b0)&  b1 );
3061 
3062     b1 = ROL64((a20^d0), 36);
3063     b2 = ROL64((a01^d1), 10);
3064     b3 = ROL64((a32^d2), 15);
3065     b4 = ROL64((a13^d3), 56);
3066     b0 = ROL64((a44^d4), 27);
3067     a20 =   b0 ^((~b1)&  b2 );
3068     a01 =   b1 ^((~b2)&  b3 );
3069     a32 =   b2 ^((~b3)&  b4 );
3070     a13 =   b3 ^((~b4)&  b0 );
3071     a44 =   b4 ^((~b0)&  b1 );
3072 
3073     b3 = ROL64((a10^d0), 41);
3074     b4 = ROL64((a41^d1), 2);
3075     b0 = ROL64((a22^d2), 62);
3076     b1 = ROL64((a03^d3), 55);
3077     b2 = ROL64((a34^d4), 39);
3078     a10 =   b0 ^((~b1)&  b2 );
3079     a41 =   b1 ^((~b2)&  b3 );
3080     a22 =   b2 ^((~b3)&  b4 );
3081     a03 =   b3 ^((~b4)&  b0 );
3082     a34 =   b4 ^((~b0)&  b1 );
3083 
3084     c0 = a00^a40^a30^a20^a10;
3085     c1 = a31^a21^a11^a01^a41;
3086     c2 = a12^a02^a42^a32^a22;
3087     c3 = a43^a33^a23^a13^a03;
3088     c4 = a24^a14^a04^a44^a34;
3089     d0 = c4^ROL64(c1, 1);
3090     d1 = c0^ROL64(c2, 1);
3091     d2 = c1^ROL64(c3, 1);
3092     d3 = c2^ROL64(c4, 1);
3093     d4 = c3^ROL64(c0, 1);
3094 
3095     b0 = (a00^d0);
3096     b1 = ROL64((a21^d1), 44);
3097     b2 = ROL64((a42^d2), 43);
3098     b3 = ROL64((a13^d3), 21);
3099     b4 = ROL64((a34^d4), 14);
3100     a00 =   b0 ^((~b1)&  b2 );
3101     a00 ^= RC[i+2];
3102     a21 =   b1 ^((~b2)&  b3 );
3103     a42 =   b2 ^((~b3)&  b4 );
3104     a13 =   b3 ^((~b4)&  b0 );
3105     a34 =   b4 ^((~b0)&  b1 );
3106 
3107     b2 = ROL64((a30^d0), 3);
3108     b3 = ROL64((a01^d1), 45);
3109     b4 = ROL64((a22^d2), 61);
3110     b0 = ROL64((a43^d3), 28);
3111     b1 = ROL64((a14^d4), 20);
3112     a30 =   b0 ^((~b1)&  b2 );
3113     a01 =   b1 ^((~b2)&  b3 );
3114     a22 =   b2 ^((~b3)&  b4 );
3115     a43 =   b3 ^((~b4)&  b0 );
3116     a14 =   b4 ^((~b0)&  b1 );
3117 
3118     b4 = ROL64((a10^d0), 18);
3119     b0 = ROL64((a31^d1), 1);
3120     b1 = ROL64((a02^d2), 6);
3121     b2 = ROL64((a23^d3), 25);
3122     b3 = ROL64((a44^d4), 8);
3123     a10 =   b0 ^((~b1)&  b2 );
3124     a31 =   b1 ^((~b2)&  b3 );
3125     a02 =   b2 ^((~b3)&  b4 );
3126     a23 =   b3 ^((~b4)&  b0 );
3127     a44 =   b4 ^((~b0)&  b1 );
3128 
3129     b1 = ROL64((a40^d0), 36);
3130     b2 = ROL64((a11^d1), 10);
3131     b3 = ROL64((a32^d2), 15);
3132     b4 = ROL64((a03^d3), 56);
3133     b0 = ROL64((a24^d4), 27);
3134     a40 =   b0 ^((~b1)&  b2 );
3135     a11 =   b1 ^((~b2)&  b3 );
3136     a32 =   b2 ^((~b3)&  b4 );
3137     a03 =   b3 ^((~b4)&  b0 );
3138     a24 =   b4 ^((~b0)&  b1 );
3139 
3140     b3 = ROL64((a20^d0), 41);
3141     b4 = ROL64((a41^d1), 2);
3142     b0 = ROL64((a12^d2), 62);
3143     b1 = ROL64((a33^d3), 55);
3144     b2 = ROL64((a04^d4), 39);
3145     a20 =   b0 ^((~b1)&  b2 );
3146     a41 =   b1 ^((~b2)&  b3 );
3147     a12 =   b2 ^((~b3)&  b4 );
3148     a33 =   b3 ^((~b4)&  b0 );
3149     a04 =   b4 ^((~b0)&  b1 );
3150 
3151     c0 = a00^a30^a10^a40^a20;
3152     c1 = a21^a01^a31^a11^a41;
3153     c2 = a42^a22^a02^a32^a12;
3154     c3 = a13^a43^a23^a03^a33;
3155     c4 = a34^a14^a44^a24^a04;
3156     d0 = c4^ROL64(c1, 1);
3157     d1 = c0^ROL64(c2, 1);
3158     d2 = c1^ROL64(c3, 1);
3159     d3 = c2^ROL64(c4, 1);
3160     d4 = c3^ROL64(c0, 1);
3161 
3162     b0 = (a00^d0);
3163     b1 = ROL64((a01^d1), 44);
3164     b2 = ROL64((a02^d2), 43);
3165     b3 = ROL64((a03^d3), 21);
3166     b4 = ROL64((a04^d4), 14);
3167     a00 =   b0 ^((~b1)&  b2 );
3168     a00 ^= RC[i+3];
3169     a01 =   b1 ^((~b2)&  b3 );
3170     a02 =   b2 ^((~b3)&  b4 );
3171     a03 =   b3 ^((~b4)&  b0 );
3172     a04 =   b4 ^((~b0)&  b1 );
3173 
3174     b2 = ROL64((a10^d0), 3);
3175     b3 = ROL64((a11^d1), 45);
3176     b4 = ROL64((a12^d2), 61);
3177     b0 = ROL64((a13^d3), 28);
3178     b1 = ROL64((a14^d4), 20);
3179     a10 =   b0 ^((~b1)&  b2 );
3180     a11 =   b1 ^((~b2)&  b3 );
3181     a12 =   b2 ^((~b3)&  b4 );
3182     a13 =   b3 ^((~b4)&  b0 );
3183     a14 =   b4 ^((~b0)&  b1 );
3184 
3185     b4 = ROL64((a20^d0), 18);
3186     b0 = ROL64((a21^d1), 1);
3187     b1 = ROL64((a22^d2), 6);
3188     b2 = ROL64((a23^d3), 25);
3189     b3 = ROL64((a24^d4), 8);
3190     a20 =   b0 ^((~b1)&  b2 );
3191     a21 =   b1 ^((~b2)&  b3 );
3192     a22 =   b2 ^((~b3)&  b4 );
3193     a23 =   b3 ^((~b4)&  b0 );
3194     a24 =   b4 ^((~b0)&  b1 );
3195 
3196     b1 = ROL64((a30^d0), 36);
3197     b2 = ROL64((a31^d1), 10);
3198     b3 = ROL64((a32^d2), 15);
3199     b4 = ROL64((a33^d3), 56);
3200     b0 = ROL64((a34^d4), 27);
3201     a30 =   b0 ^((~b1)&  b2 );
3202     a31 =   b1 ^((~b2)&  b3 );
3203     a32 =   b2 ^((~b3)&  b4 );
3204     a33 =   b3 ^((~b4)&  b0 );
3205     a34 =   b4 ^((~b0)&  b1 );
3206 
3207     b3 = ROL64((a40^d0), 41);
3208     b4 = ROL64((a41^d1), 2);
3209     b0 = ROL64((a42^d2), 62);
3210     b1 = ROL64((a43^d3), 55);
3211     b2 = ROL64((a44^d4), 39);
3212     a40 =   b0 ^((~b1)&  b2 );
3213     a41 =   b1 ^((~b2)&  b3 );
3214     a42 =   b2 ^((~b3)&  b4 );
3215     a43 =   b3 ^((~b4)&  b0 );
3216     a44 =   b4 ^((~b0)&  b1 );
3217   }
3218 }
3219 
3220 /*
3221 ** Initialize a new hash.  iSize determines the size of the hash
3222 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
3223 ** can be zero to use the default hash size of 256 bits.
3224 */
SHA3Init(SHA3Context * p,int iSize)3225 static void SHA3Init(SHA3Context *p, int iSize){
3226   memset(p, 0, sizeof(*p));
3227   if( iSize>=128 && iSize<=512 ){
3228     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
3229   }else{
3230     p->nRate = (1600 - 2*256)/8;
3231   }
3232 #if SHA3_BYTEORDER==1234
3233   /* Known to be little-endian at compile-time. No-op */
3234 #elif SHA3_BYTEORDER==4321
3235   p->ixMask = 7;  /* Big-endian */
3236 #else
3237   {
3238     static unsigned int one = 1;
3239     if( 1==*(unsigned char*)&one ){
3240       /* Little endian.  No byte swapping. */
3241       p->ixMask = 0;
3242     }else{
3243       /* Big endian.  Byte swap. */
3244       p->ixMask = 7;
3245     }
3246   }
3247 #endif
3248 }
3249 
3250 /*
3251 ** Make consecutive calls to the SHA3Update function to add new content
3252 ** to the hash
3253 */
SHA3Update(SHA3Context * p,const unsigned char * aData,unsigned int nData)3254 static void SHA3Update(
3255   SHA3Context *p,
3256   const unsigned char *aData,
3257   unsigned int nData
3258 ){
3259   unsigned int i = 0;
3260   if( aData==0 ) return;
3261 #if SHA3_BYTEORDER==1234
3262   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
3263     for(; i+7<nData; i+=8){
3264       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
3265       p->nLoaded += 8;
3266       if( p->nLoaded>=p->nRate ){
3267         KeccakF1600Step(p);
3268         p->nLoaded = 0;
3269       }
3270     }
3271   }
3272 #endif
3273   for(; i<nData; i++){
3274 #if SHA3_BYTEORDER==1234
3275     p->u.x[p->nLoaded] ^= aData[i];
3276 #elif SHA3_BYTEORDER==4321
3277     p->u.x[p->nLoaded^0x07] ^= aData[i];
3278 #else
3279     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
3280 #endif
3281     p->nLoaded++;
3282     if( p->nLoaded==p->nRate ){
3283       KeccakF1600Step(p);
3284       p->nLoaded = 0;
3285     }
3286   }
3287 }
3288 
3289 /*
3290 ** After all content has been added, invoke SHA3Final() to compute
3291 ** the final hash.  The function returns a pointer to the binary
3292 ** hash value.
3293 */
SHA3Final(SHA3Context * p)3294 static unsigned char *SHA3Final(SHA3Context *p){
3295   unsigned int i;
3296   if( p->nLoaded==p->nRate-1 ){
3297     const unsigned char c1 = 0x86;
3298     SHA3Update(p, &c1, 1);
3299   }else{
3300     const unsigned char c2 = 0x06;
3301     const unsigned char c3 = 0x80;
3302     SHA3Update(p, &c2, 1);
3303     p->nLoaded = p->nRate - 1;
3304     SHA3Update(p, &c3, 1);
3305   }
3306   for(i=0; i<p->nRate; i++){
3307     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
3308   }
3309   return &p->u.x[p->nRate];
3310 }
3311 /* End of the hashing logic
3312 *****************************************************************************/
3313 
3314 /*
3315 ** Implementation of the sha3(X,SIZE) function.
3316 **
3317 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
3318 ** size is 256.  If X is a BLOB, it is hashed as is.
3319 ** For all other non-NULL types of input, X is converted into a UTF-8 string
3320 ** and the string is hashed without the trailing 0x00 terminator.  The hash
3321 ** of a NULL value is NULL.
3322 */
sha3Func(sqlite3_context * context,int argc,sqlite3_value ** argv)3323 static void sha3Func(
3324   sqlite3_context *context,
3325   int argc,
3326   sqlite3_value **argv
3327 ){
3328   SHA3Context cx;
3329   int eType = sqlite3_value_type(argv[0]);
3330   int nByte = sqlite3_value_bytes(argv[0]);
3331   int iSize;
3332   if( argc==1 ){
3333     iSize = 256;
3334   }else{
3335     iSize = sqlite3_value_int(argv[1]);
3336     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3337       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3338                                     "384 512", -1);
3339       return;
3340     }
3341   }
3342   if( eType==SQLITE_NULL ) return;
3343   SHA3Init(&cx, iSize);
3344   if( eType==SQLITE_BLOB ){
3345     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
3346   }else{
3347     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
3348   }
3349   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3350 }
3351 
3352 /* Compute a string using sqlite3_vsnprintf() with a maximum length
3353 ** of 50 bytes and add it to the hash.
3354 */
sha3_step_vformat(SHA3Context * p,const char * zFormat,...)3355 static void sha3_step_vformat(
3356   SHA3Context *p,                 /* Add content to this context */
3357   const char *zFormat,
3358   ...
3359 ){
3360   va_list ap;
3361   int n;
3362   char zBuf[50];
3363   va_start(ap, zFormat);
3364   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
3365   va_end(ap);
3366   n = (int)strlen(zBuf);
3367   SHA3Update(p, (unsigned char*)zBuf, n);
3368 }
3369 
3370 /*
3371 ** Implementation of the sha3_query(SQL,SIZE) function.
3372 **
3373 ** This function compiles and runs the SQL statement(s) given in the
3374 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
3375 ** size is 256.
3376 **
3377 ** The format of the byte stream that is hashed is summarized as follows:
3378 **
3379 **       S<n>:<sql>
3380 **       R
3381 **       N
3382 **       I<int>
3383 **       F<ieee-float>
3384 **       B<size>:<bytes>
3385 **       T<size>:<text>
3386 **
3387 ** <sql> is the original SQL text for each statement run and <n> is
3388 ** the size of that text.  The SQL text is UTF-8.  A single R character
3389 ** occurs before the start of each row.  N means a NULL value.
3390 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
3391 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3392 ** B means blobs of <size> bytes.  T means text rendered as <size>
3393 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
3394 ** text integers.
3395 **
3396 ** For each SQL statement in the X input, there is one S segment.  Each
3397 ** S segment is followed by zero or more R segments, one for each row in the
3398 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
3399 ** one for each column in the result set.  Segments are concatentated directly
3400 ** with no delimiters of any kind.
3401 */
sha3QueryFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)3402 static void sha3QueryFunc(
3403   sqlite3_context *context,
3404   int argc,
3405   sqlite3_value **argv
3406 ){
3407   sqlite3 *db = sqlite3_context_db_handle(context);
3408   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
3409   sqlite3_stmt *pStmt = 0;
3410   int nCol;                   /* Number of columns in the result set */
3411   int i;                      /* Loop counter */
3412   int rc;
3413   int n;
3414   const char *z;
3415   SHA3Context cx;
3416   int iSize;
3417 
3418   if( argc==1 ){
3419     iSize = 256;
3420   }else{
3421     iSize = sqlite3_value_int(argv[1]);
3422     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3423       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3424                                     "384 512", -1);
3425       return;
3426     }
3427   }
3428   if( zSql==0 ) return;
3429   SHA3Init(&cx, iSize);
3430   while( zSql[0] ){
3431     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
3432     if( rc ){
3433       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
3434                                    zSql, sqlite3_errmsg(db));
3435       sqlite3_finalize(pStmt);
3436       sqlite3_result_error(context, zMsg, -1);
3437       sqlite3_free(zMsg);
3438       return;
3439     }
3440     if( !sqlite3_stmt_readonly(pStmt) ){
3441       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
3442       sqlite3_finalize(pStmt);
3443       sqlite3_result_error(context, zMsg, -1);
3444       sqlite3_free(zMsg);
3445       return;
3446     }
3447     nCol = sqlite3_column_count(pStmt);
3448     z = sqlite3_sql(pStmt);
3449     if( z ){
3450       n = (int)strlen(z);
3451       sha3_step_vformat(&cx,"S%d:",n);
3452       SHA3Update(&cx,(unsigned char*)z,n);
3453     }
3454 
3455     /* Compute a hash over the result of the query */
3456     while( SQLITE_ROW==sqlite3_step(pStmt) ){
3457       SHA3Update(&cx,(const unsigned char*)"R",1);
3458       for(i=0; i<nCol; i++){
3459         switch( sqlite3_column_type(pStmt,i) ){
3460           case SQLITE_NULL: {
3461             SHA3Update(&cx, (const unsigned char*)"N",1);
3462             break;
3463           }
3464           case SQLITE_INTEGER: {
3465             sqlite3_uint64 u;
3466             int j;
3467             unsigned char x[9];
3468             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
3469             memcpy(&u, &v, 8);
3470             for(j=8; j>=1; j--){
3471               x[j] = u & 0xff;
3472               u >>= 8;
3473             }
3474             x[0] = 'I';
3475             SHA3Update(&cx, x, 9);
3476             break;
3477           }
3478           case SQLITE_FLOAT: {
3479             sqlite3_uint64 u;
3480             int j;
3481             unsigned char x[9];
3482             double r = sqlite3_column_double(pStmt,i);
3483             memcpy(&u, &r, 8);
3484             for(j=8; j>=1; j--){
3485               x[j] = u & 0xff;
3486               u >>= 8;
3487             }
3488             x[0] = 'F';
3489             SHA3Update(&cx,x,9);
3490             break;
3491           }
3492           case SQLITE_TEXT: {
3493             int n2 = sqlite3_column_bytes(pStmt, i);
3494             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
3495             sha3_step_vformat(&cx,"T%d:",n2);
3496             SHA3Update(&cx, z2, n2);
3497             break;
3498           }
3499           case SQLITE_BLOB: {
3500             int n2 = sqlite3_column_bytes(pStmt, i);
3501             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
3502             sha3_step_vformat(&cx,"B%d:",n2);
3503             SHA3Update(&cx, z2, n2);
3504             break;
3505           }
3506         }
3507       }
3508     }
3509     sqlite3_finalize(pStmt);
3510   }
3511   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3512 }
3513 
3514 
3515 #ifdef _WIN32
3516 
3517 #endif
sqlite3_shathree_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3518 int sqlite3_shathree_init(
3519   sqlite3 *db,
3520   char **pzErrMsg,
3521   const sqlite3_api_routines *pApi
3522 ){
3523   int rc = SQLITE_OK;
3524   SQLITE_EXTENSION_INIT2(pApi);
3525   (void)pzErrMsg;  /* Unused parameter */
3526   rc = sqlite3_create_function(db, "sha3", 1,
3527                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3528                       0, sha3Func, 0, 0);
3529   if( rc==SQLITE_OK ){
3530     rc = sqlite3_create_function(db, "sha3", 2,
3531                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3532                       0, sha3Func, 0, 0);
3533   }
3534   if( rc==SQLITE_OK ){
3535     rc = sqlite3_create_function(db, "sha3_query", 1,
3536                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3537                       0, sha3QueryFunc, 0, 0);
3538   }
3539   if( rc==SQLITE_OK ){
3540     rc = sqlite3_create_function(db, "sha3_query", 2,
3541                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3542                       0, sha3QueryFunc, 0, 0);
3543   }
3544   return rc;
3545 }
3546 
3547 /************************* End ../ext/misc/shathree.c ********************/
3548 /************************* Begin ../ext/misc/uint.c ******************/
3549 /*
3550 ** 2020-04-14
3551 **
3552 ** The author disclaims copyright to this source code.  In place of
3553 ** a legal notice, here is a blessing:
3554 **
3555 **    May you do good and not evil.
3556 **    May you find forgiveness for yourself and forgive others.
3557 **    May you share freely, never taking more than you give.
3558 **
3559 ******************************************************************************
3560 **
3561 ** This SQLite extension implements the UINT collating sequence.
3562 **
3563 ** UINT works like BINARY for text, except that embedded strings
3564 ** of digits compare in numeric order.
3565 **
3566 **     *   Leading zeros are handled properly, in the sense that
3567 **         they do not mess of the maginitude comparison of embedded
3568 **         strings of digits.  "x00123y" is equal to "x123y".
3569 **
3570 **     *   Only unsigned integers are recognized.  Plus and minus
3571 **         signs are ignored.  Decimal points and exponential notation
3572 **         are ignored.
3573 **
3574 **     *   Embedded integers can be of arbitrary length.  Comparison
3575 **         is *not* limited integers that can be expressed as a
3576 **         64-bit machine integer.
3577 */
3578 /* #include "sqlite3ext.h" */
3579 SQLITE_EXTENSION_INIT1
3580 #include <assert.h>
3581 #include <string.h>
3582 #include <ctype.h>
3583 
3584 /*
3585 ** Compare text in lexicographic order, except strings of digits
3586 ** compare in numeric order.
3587 */
uintCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)3588 static int uintCollFunc(
3589   void *notUsed,
3590   int nKey1, const void *pKey1,
3591   int nKey2, const void *pKey2
3592 ){
3593   const unsigned char *zA = (const unsigned char*)pKey1;
3594   const unsigned char *zB = (const unsigned char*)pKey2;
3595   int i=0, j=0, x;
3596   (void)notUsed;
3597   while( i<nKey1 && j<nKey2 ){
3598     x = zA[i] - zB[j];
3599     if( isdigit(zA[i]) ){
3600       int k;
3601       if( !isdigit(zB[j]) ) return x;
3602       while( i<nKey1 && zA[i]=='0' ){ i++; }
3603       while( j<nKey2 && zB[j]=='0' ){ j++; }
3604       k = 0;
3605       while( i+k<nKey1 && isdigit(zA[i+k])
3606              && j+k<nKey2 && isdigit(zB[j+k]) ){
3607         k++;
3608       }
3609       if( i+k<nKey1 && isdigit(zA[i+k]) ){
3610         return +1;
3611       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
3612         return -1;
3613       }else{
3614         x = memcmp(zA+i, zB+j, k);
3615         if( x ) return x;
3616         i += k;
3617         j += k;
3618       }
3619     }else if( x ){
3620       return x;
3621     }else{
3622       i++;
3623       j++;
3624     }
3625   }
3626   return (nKey1 - i) - (nKey2 - j);
3627 }
3628 
3629 #ifdef _WIN32
3630 
3631 #endif
sqlite3_uint_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3632 int sqlite3_uint_init(
3633   sqlite3 *db,
3634   char **pzErrMsg,
3635   const sqlite3_api_routines *pApi
3636 ){
3637   SQLITE_EXTENSION_INIT2(pApi);
3638   (void)pzErrMsg;  /* Unused parameter */
3639   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
3640 }
3641 
3642 /************************* End ../ext/misc/uint.c ********************/
3643 /************************* Begin ../ext/misc/decimal.c ******************/
3644 /*
3645 ** 2020-06-22
3646 **
3647 ** The author disclaims copyright to this source code.  In place of
3648 ** a legal notice, here is a blessing:
3649 **
3650 **    May you do good and not evil.
3651 **    May you find forgiveness for yourself and forgive others.
3652 **    May you share freely, never taking more than you give.
3653 **
3654 ******************************************************************************
3655 **
3656 ** Routines to implement arbitrary-precision decimal math.
3657 **
3658 ** The focus here is on simplicity and correctness, not performance.
3659 */
3660 /* #include "sqlite3ext.h" */
3661 SQLITE_EXTENSION_INIT1
3662 #include <assert.h>
3663 #include <string.h>
3664 #include <ctype.h>
3665 #include <stdlib.h>
3666 
3667 /* Mark a function parameter as unused, to suppress nuisance compiler
3668 ** warnings. */
3669 #ifndef UNUSED_PARAMETER
3670 # define UNUSED_PARAMETER(X)  (void)(X)
3671 #endif
3672 
3673 
3674 /* A decimal object */
3675 typedef struct Decimal Decimal;
3676 struct Decimal {
3677   char sign;        /* 0 for positive, 1 for negative */
3678   char oom;         /* True if an OOM is encountered */
3679   char isNull;      /* True if holds a NULL rather than a number */
3680   char isInit;      /* True upon initialization */
3681   int nDigit;       /* Total number of digits */
3682   int nFrac;        /* Number of digits to the right of the decimal point */
3683   signed char *a;   /* Array of digits.  Most significant first. */
3684 };
3685 
3686 /*
3687 ** Release memory held by a Decimal, but do not free the object itself.
3688 */
decimal_clear(Decimal * p)3689 static void decimal_clear(Decimal *p){
3690   sqlite3_free(p->a);
3691 }
3692 
3693 /*
3694 ** Destroy a Decimal object
3695 */
decimal_free(Decimal * p)3696 static void decimal_free(Decimal *p){
3697   if( p ){
3698     decimal_clear(p);
3699     sqlite3_free(p);
3700   }
3701 }
3702 
3703 /*
3704 ** Allocate a new Decimal object initialized to the text in zIn[].
3705 ** Return NULL if any kind of error occurs.
3706 */
decimalNewFromText(const char * zIn,int n)3707 static Decimal *decimalNewFromText(const char *zIn, int n){
3708   Decimal *p = 0;
3709   int i;
3710   int iExp = 0;
3711 
3712   p = sqlite3_malloc( sizeof(*p) );
3713   if( p==0 ) goto new_from_text_failed;
3714   p->sign = 0;
3715   p->oom = 0;
3716   p->isInit = 1;
3717   p->isNull = 0;
3718   p->nDigit = 0;
3719   p->nFrac = 0;
3720   p->a = sqlite3_malloc64( n+1 );
3721   if( p->a==0 ) goto new_from_text_failed;
3722   for(i=0; isspace(zIn[i]); i++){}
3723   if( zIn[i]=='-' ){
3724     p->sign = 1;
3725     i++;
3726   }else if( zIn[i]=='+' ){
3727     i++;
3728   }
3729   while( i<n && zIn[i]=='0' ) i++;
3730   while( i<n ){
3731     char c = zIn[i];
3732     if( c>='0' && c<='9' ){
3733       p->a[p->nDigit++] = c - '0';
3734     }else if( c=='.' ){
3735       p->nFrac = p->nDigit + 1;
3736     }else if( c=='e' || c=='E' ){
3737       int j = i+1;
3738       int neg = 0;
3739       if( j>=n ) break;
3740       if( zIn[j]=='-' ){
3741         neg = 1;
3742         j++;
3743       }else if( zIn[j]=='+' ){
3744         j++;
3745       }
3746       while( j<n && iExp<1000000 ){
3747         if( zIn[j]>='0' && zIn[j]<='9' ){
3748           iExp = iExp*10 + zIn[j] - '0';
3749         }
3750         j++;
3751       }
3752       if( neg ) iExp = -iExp;
3753       break;
3754     }
3755     i++;
3756   }
3757   if( p->nFrac ){
3758     p->nFrac = p->nDigit - (p->nFrac - 1);
3759   }
3760   if( iExp>0 ){
3761     if( p->nFrac>0 ){
3762       if( iExp<=p->nFrac ){
3763         p->nFrac -= iExp;
3764         iExp = 0;
3765       }else{
3766         iExp -= p->nFrac;
3767         p->nFrac = 0;
3768       }
3769     }
3770     if( iExp>0 ){
3771       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3772       if( p->a==0 ) goto new_from_text_failed;
3773       memset(p->a+p->nDigit, 0, iExp);
3774       p->nDigit += iExp;
3775     }
3776   }else if( iExp<0 ){
3777     int nExtra;
3778     iExp = -iExp;
3779     nExtra = p->nDigit - p->nFrac - 1;
3780     if( nExtra ){
3781       if( nExtra>=iExp ){
3782         p->nFrac += iExp;
3783         iExp  = 0;
3784       }else{
3785         iExp -= nExtra;
3786         p->nFrac = p->nDigit - 1;
3787       }
3788     }
3789     if( iExp>0 ){
3790       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3791       if( p->a==0 ) goto new_from_text_failed;
3792       memmove(p->a+iExp, p->a, p->nDigit);
3793       memset(p->a, 0, iExp);
3794       p->nDigit += iExp;
3795       p->nFrac += iExp;
3796     }
3797   }
3798   return p;
3799 
3800 new_from_text_failed:
3801   if( p ){
3802     if( p->a ) sqlite3_free(p->a);
3803     sqlite3_free(p);
3804   }
3805   return 0;
3806 }
3807 
3808 /* Forward reference */
3809 static Decimal *decimalFromDouble(double);
3810 
3811 /*
3812 ** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
3813 ** to the new object, or NULL if there is an error.  If the pCtx argument
3814 ** is not NULL, then errors are reported on it as well.
3815 **
3816 ** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3817 ** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
3818 ** 8 bytes, the resulting double value is expanded into its decimal equivalent.
3819 ** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3820 ** then NULL is returned.
3821 */
decimal_new(sqlite3_context * pCtx,sqlite3_value * pIn,int bTextOnly)3822 static Decimal *decimal_new(
3823   sqlite3_context *pCtx,       /* Report error here, if not null */
3824   sqlite3_value *pIn,          /* Construct the decimal object from this */
3825   int bTextOnly                /* Always interpret pIn as text if true */
3826 ){
3827   Decimal *p = 0;
3828   int eType = sqlite3_value_type(pIn);
3829   if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
3830     eType = SQLITE_TEXT;
3831   }
3832   switch( eType ){
3833     case SQLITE_TEXT:
3834     case SQLITE_INTEGER: {
3835       const char *zIn = (const char*)sqlite3_value_text(pIn);
3836       int n = sqlite3_value_bytes(pIn);
3837       p = decimalNewFromText(zIn, n);
3838       if( p==0 ) goto new_failed;
3839       break;
3840     }
3841 
3842     case SQLITE_FLOAT: {
3843       p = decimalFromDouble(sqlite3_value_double(pIn));
3844       break;
3845     }
3846 
3847     case SQLITE_BLOB: {
3848       const unsigned char *x;
3849       unsigned int i;
3850       sqlite3_uint64 v = 0;
3851       double r;
3852 
3853       if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
3854       x = sqlite3_value_blob(pIn);
3855       for(i=0; i<sizeof(r); i++){
3856         v = (v<<8) | x[i];
3857       }
3858       memcpy(&r, &v, sizeof(r));
3859       p = decimalFromDouble(r);
3860       break;
3861     }
3862 
3863     case SQLITE_NULL: {
3864       break;
3865     }
3866   }
3867   return p;
3868 
3869 new_failed:
3870   if( pCtx ) sqlite3_result_error_nomem(pCtx);
3871   sqlite3_free(p);
3872   return 0;
3873 }
3874 
3875 /*
3876 ** Make the given Decimal the result.
3877 */
decimal_result(sqlite3_context * pCtx,Decimal * p)3878 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
3879   char *z;
3880   int i, j;
3881   int n;
3882   if( p==0 || p->oom ){
3883     sqlite3_result_error_nomem(pCtx);
3884     return;
3885   }
3886   if( p->isNull ){
3887     sqlite3_result_null(pCtx);
3888     return;
3889   }
3890   z = sqlite3_malloc( p->nDigit+4 );
3891   if( z==0 ){
3892     sqlite3_result_error_nomem(pCtx);
3893     return;
3894   }
3895   i = 0;
3896   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
3897     p->sign = 0;
3898   }
3899   if( p->sign ){
3900     z[0] = '-';
3901     i = 1;
3902   }
3903   n = p->nDigit - p->nFrac;
3904   if( n<=0 ){
3905     z[i++] = '0';
3906   }
3907   j = 0;
3908   while( n>1 && p->a[j]==0 ){
3909     j++;
3910     n--;
3911   }
3912   while( n>0  ){
3913     z[i++] = p->a[j] + '0';
3914     j++;
3915     n--;
3916   }
3917   if( p->nFrac ){
3918     z[i++] = '.';
3919     do{
3920       z[i++] = p->a[j] + '0';
3921       j++;
3922     }while( j<p->nDigit );
3923   }
3924   z[i] = 0;
3925   sqlite3_result_text(pCtx, z, i, sqlite3_free);
3926 }
3927 
3928 /*
3929 ** Make the given Decimal the result in an format similar to  '%+#e'.
3930 ** In other words, show exponential notation with leading and trailing
3931 ** zeros omitted.
3932 */
decimal_result_sci(sqlite3_context * pCtx,Decimal * p)3933 static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){
3934   char *z;       /* The output buffer */
3935   int i;         /* Loop counter */
3936   int nZero;     /* Number of leading zeros */
3937   int nDigit;    /* Number of digits not counting trailing zeros */
3938   int nFrac;     /* Digits to the right of the decimal point */
3939   int exp;       /* Exponent value */
3940   signed char zero;     /* Zero value */
3941   signed char *a;       /* Array of digits */
3942 
3943   if( p==0 || p->oom ){
3944     sqlite3_result_error_nomem(pCtx);
3945     return;
3946   }
3947   if( p->isNull ){
3948     sqlite3_result_null(pCtx);
3949     return;
3950   }
3951   for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){}
3952   for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
3953   nFrac = p->nFrac + (nDigit - p->nDigit);
3954   nDigit -= nZero;
3955   z = sqlite3_malloc( nDigit+20 );
3956   if( z==0 ){
3957     sqlite3_result_error_nomem(pCtx);
3958     return;
3959   }
3960   if( nDigit==0 ){
3961     zero = 0;
3962     a = &zero;
3963     nDigit = 1;
3964     nFrac = 0;
3965   }else{
3966     a = &p->a[nZero];
3967   }
3968   if( p->sign && nDigit>0 ){
3969     z[0] = '-';
3970   }else{
3971     z[0] = '+';
3972   }
3973   z[1] = a[0]+'0';
3974   z[2] = '.';
3975   if( nDigit==1 ){
3976     z[3] = '0';
3977     i = 4;
3978   }else{
3979     for(i=1; i<nDigit; i++){
3980       z[2+i] = a[i]+'0';
3981     }
3982     i = nDigit+2;
3983   }
3984   exp = nDigit - nFrac - 1;
3985   sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
3986   sqlite3_result_text(pCtx, z, -1, sqlite3_free);
3987 }
3988 
3989 /*
3990 ** Compare to Decimal objects.  Return negative, 0, or positive if the
3991 ** first object is less than, equal to, or greater than the second.
3992 **
3993 ** Preconditions for this routine:
3994 **
3995 **    pA!=0
3996 **    pA->isNull==0
3997 **    pB!=0
3998 **    pB->isNull==0
3999 */
decimal_cmp(const Decimal * pA,const Decimal * pB)4000 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4001   int nASig, nBSig, rc, n;
4002   if( pA->sign!=pB->sign ){
4003     return pA->sign ? -1 : +1;
4004   }
4005   if( pA->sign ){
4006     const Decimal *pTemp = pA;
4007     pA = pB;
4008     pB = pTemp;
4009   }
4010   nASig = pA->nDigit - pA->nFrac;
4011   nBSig = pB->nDigit - pB->nFrac;
4012   if( nASig!=nBSig ){
4013     return nASig - nBSig;
4014   }
4015   n = pA->nDigit;
4016   if( n>pB->nDigit ) n = pB->nDigit;
4017   rc = memcmp(pA->a, pB->a, n);
4018   if( rc==0 ){
4019     rc = pA->nDigit - pB->nDigit;
4020   }
4021   return rc;
4022 }
4023 
4024 /*
4025 ** SQL Function:   decimal_cmp(X, Y)
4026 **
4027 ** Return negative, zero, or positive if X is less then, equal to, or
4028 ** greater than Y.
4029 */
decimalCmpFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4030 static void decimalCmpFunc(
4031   sqlite3_context *context,
4032   int argc,
4033   sqlite3_value **argv
4034 ){
4035   Decimal *pA = 0, *pB = 0;
4036   int rc;
4037 
4038   UNUSED_PARAMETER(argc);
4039   pA = decimal_new(context, argv[0], 1);
4040   if( pA==0 || pA->isNull ) goto cmp_done;
4041   pB = decimal_new(context, argv[1], 1);
4042   if( pB==0 || pB->isNull ) goto cmp_done;
4043   rc = decimal_cmp(pA, pB);
4044   if( rc<0 ) rc = -1;
4045   else if( rc>0 ) rc = +1;
4046   sqlite3_result_int(context, rc);
4047 cmp_done:
4048   decimal_free(pA);
4049   decimal_free(pB);
4050 }
4051 
4052 /*
4053 ** Expand the Decimal so that it has a least nDigit digits and nFrac
4054 ** digits to the right of the decimal point.
4055 */
decimal_expand(Decimal * p,int nDigit,int nFrac)4056 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4057   int nAddSig;
4058   int nAddFrac;
4059   if( p==0 ) return;
4060   nAddFrac = nFrac - p->nFrac;
4061   nAddSig = (nDigit - p->nDigit) - nAddFrac;
4062   if( nAddFrac==0 && nAddSig==0 ) return;
4063   p->a = sqlite3_realloc64(p->a, nDigit+1);
4064   if( p->a==0 ){
4065     p->oom = 1;
4066     return;
4067   }
4068   if( nAddSig ){
4069     memmove(p->a+nAddSig, p->a, p->nDigit);
4070     memset(p->a, 0, nAddSig);
4071     p->nDigit += nAddSig;
4072   }
4073   if( nAddFrac ){
4074     memset(p->a+p->nDigit, 0, nAddFrac);
4075     p->nDigit += nAddFrac;
4076     p->nFrac += nAddFrac;
4077   }
4078 }
4079 
4080 /*
4081 ** Add the value pB into pA.   A := A + B.
4082 **
4083 ** Both pA and pB might become denormalized by this routine.
4084 */
decimal_add(Decimal * pA,Decimal * pB)4085 static void decimal_add(Decimal *pA, Decimal *pB){
4086   int nSig, nFrac, nDigit;
4087   int i, rc;
4088   if( pA==0 ){
4089     return;
4090   }
4091   if( pA->oom || pB==0 || pB->oom ){
4092     pA->oom = 1;
4093     return;
4094   }
4095   if( pA->isNull || pB->isNull ){
4096     pA->isNull = 1;
4097     return;
4098   }
4099   nSig = pA->nDigit - pA->nFrac;
4100   if( nSig && pA->a[0]==0 ) nSig--;
4101   if( nSig<pB->nDigit-pB->nFrac ){
4102     nSig = pB->nDigit - pB->nFrac;
4103   }
4104   nFrac = pA->nFrac;
4105   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4106   nDigit = nSig + nFrac + 1;
4107   decimal_expand(pA, nDigit, nFrac);
4108   decimal_expand(pB, nDigit, nFrac);
4109   if( pA->oom || pB->oom ){
4110     pA->oom = 1;
4111   }else{
4112     if( pA->sign==pB->sign ){
4113       int carry = 0;
4114       for(i=nDigit-1; i>=0; i--){
4115         int x = pA->a[i] + pB->a[i] + carry;
4116         if( x>=10 ){
4117           carry = 1;
4118           pA->a[i] = x - 10;
4119         }else{
4120           carry = 0;
4121           pA->a[i] = x;
4122         }
4123       }
4124     }else{
4125       signed char *aA, *aB;
4126       int borrow = 0;
4127       rc = memcmp(pA->a, pB->a, nDigit);
4128       if( rc<0 ){
4129         aA = pB->a;
4130         aB = pA->a;
4131         pA->sign = !pA->sign;
4132       }else{
4133         aA = pA->a;
4134         aB = pB->a;
4135       }
4136       for(i=nDigit-1; i>=0; i--){
4137         int x = aA[i] - aB[i] - borrow;
4138         if( x<0 ){
4139           pA->a[i] = x+10;
4140           borrow = 1;
4141         }else{
4142           pA->a[i] = x;
4143           borrow = 0;
4144         }
4145       }
4146     }
4147   }
4148 }
4149 
4150 /*
4151 ** Multiply A by B.   A := A * B
4152 **
4153 ** All significant digits after the decimal point are retained.
4154 ** Trailing zeros after the decimal point are omitted as long as
4155 ** the number of digits after the decimal point is no less than
4156 ** either the number of digits in either input.
4157 */
decimalMul(Decimal * pA,Decimal * pB)4158 static void decimalMul(Decimal *pA, Decimal *pB){
4159   signed char *acc = 0;
4160   int i, j, k;
4161   int minFrac;
4162 
4163   if( pA==0 || pA->oom || pA->isNull
4164    || pB==0 || pB->oom || pB->isNull
4165   ){
4166     goto mul_end;
4167   }
4168   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
4169   if( acc==0 ){
4170     pA->oom = 1;
4171     goto mul_end;
4172   }
4173   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
4174   minFrac = pA->nFrac;
4175   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
4176   for(i=pA->nDigit-1; i>=0; i--){
4177     signed char f = pA->a[i];
4178     int carry = 0, x;
4179     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
4180       x = acc[k] + f*pB->a[j] + carry;
4181       acc[k] = x%10;
4182       carry = x/10;
4183     }
4184     x = acc[k] + carry;
4185     acc[k] = x%10;
4186     acc[k-1] += x/10;
4187   }
4188   sqlite3_free(pA->a);
4189   pA->a = acc;
4190   acc = 0;
4191   pA->nDigit += pB->nDigit + 2;
4192   pA->nFrac += pB->nFrac;
4193   pA->sign ^= pB->sign;
4194   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
4195     pA->nFrac--;
4196     pA->nDigit--;
4197   }
4198 
4199 mul_end:
4200   sqlite3_free(acc);
4201 }
4202 
4203 /*
4204 ** Create a new Decimal object that contains an integer power of 2.
4205 */
decimalPow2(int N)4206 static Decimal *decimalPow2(int N){
4207   Decimal *pA = 0;      /* The result to be returned */
4208   Decimal *pX = 0;      /* Multiplier */
4209   if( N<-20000 || N>20000 ) goto pow2_fault;
4210   pA = decimalNewFromText("1.0", 3);
4211   if( pA==0 || pA->oom ) goto pow2_fault;
4212   if( N==0 ) return pA;
4213   if( N>0 ){
4214     pX = decimalNewFromText("2.0", 3);
4215   }else{
4216     N = -N;
4217     pX = decimalNewFromText("0.5", 3);
4218   }
4219   if( pX==0 || pX->oom ) goto pow2_fault;
4220   while( 1 /* Exit by break */ ){
4221     if( N & 1 ){
4222       decimalMul(pA, pX);
4223       if( pA->oom ) goto pow2_fault;
4224     }
4225     N >>= 1;
4226     if( N==0 ) break;
4227     decimalMul(pX, pX);
4228   }
4229   decimal_free(pX);
4230   return pA;
4231 
4232 pow2_fault:
4233   decimal_free(pA);
4234   decimal_free(pX);
4235   return 0;
4236 }
4237 
4238 /*
4239 ** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
4240 */
decimalFromDouble(double r)4241 static Decimal *decimalFromDouble(double r){
4242   sqlite3_int64 m, a;
4243   int e;
4244   int isNeg;
4245   Decimal *pA;
4246   Decimal *pX;
4247   char zNum[100];
4248   if( r<0.0 ){
4249     isNeg = 1;
4250     r = -r;
4251   }else{
4252     isNeg = 0;
4253   }
4254   memcpy(&a,&r,sizeof(a));
4255   if( a==0 ){
4256     e = 0;
4257     m = 0;
4258   }else{
4259     e = a>>52;
4260     m = a & ((((sqlite3_int64)1)<<52)-1);
4261     if( e==0 ){
4262       m <<= 1;
4263     }else{
4264       m |= ((sqlite3_int64)1)<<52;
4265     }
4266     while( e<1075 && m>0 && (m&1)==0 ){
4267       m >>= 1;
4268       e++;
4269     }
4270     if( isNeg ) m = -m;
4271     e = e - 1075;
4272     if( e>971 ){
4273       return 0;  /* A NaN or an Infinity */
4274     }
4275   }
4276 
4277   /* At this point m is the integer significand and e is the exponent */
4278   sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
4279   pA = decimalNewFromText(zNum, (int)strlen(zNum));
4280   pX = decimalPow2(e);
4281   decimalMul(pA, pX);
4282   decimal_free(pX);
4283   return pA;
4284 }
4285 
4286 /*
4287 ** SQL Function:   decimal(X)
4288 ** OR:             decimal_exp(X)
4289 **
4290 ** Convert input X into decimal and then back into text.
4291 **
4292 ** If X is originally a float, then a full decimal expansion of that floating
4293 ** point value is done.  Or if X is an 8-byte blob, it is interpreted
4294 ** as a float and similarly expanded.
4295 **
4296 ** The decimal_exp(X) function returns the result in exponential notation.
4297 ** decimal(X) returns a complete decimal, without the e+NNN at the end.
4298 */
decimalFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4299 static void decimalFunc(
4300   sqlite3_context *context,
4301   int argc,
4302   sqlite3_value **argv
4303 ){
4304   Decimal *p =  decimal_new(context, argv[0], 0);
4305   UNUSED_PARAMETER(argc);
4306   if( p ){
4307     if( sqlite3_user_data(context)!=0 ){
4308       decimal_result_sci(context, p);
4309     }else{
4310       decimal_result(context, p);
4311     }
4312     decimal_free(p);
4313   }
4314 }
4315 
4316 /*
4317 ** Compare text in decimal order.
4318 */
decimalCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)4319 static int decimalCollFunc(
4320   void *notUsed,
4321   int nKey1, const void *pKey1,
4322   int nKey2, const void *pKey2
4323 ){
4324   const unsigned char *zA = (const unsigned char*)pKey1;
4325   const unsigned char *zB = (const unsigned char*)pKey2;
4326   Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
4327   Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
4328   int rc;
4329   UNUSED_PARAMETER(notUsed);
4330   if( pA==0 || pB==0 ){
4331     rc = 0;
4332   }else{
4333     rc = decimal_cmp(pA, pB);
4334   }
4335   decimal_free(pA);
4336   decimal_free(pB);
4337   return rc;
4338 }
4339 
4340 
4341 /*
4342 ** SQL Function:   decimal_add(X, Y)
4343 **                 decimal_sub(X, Y)
4344 **
4345 ** Return the sum or difference of X and Y.
4346 */
decimalAddFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4347 static void decimalAddFunc(
4348   sqlite3_context *context,
4349   int argc,
4350   sqlite3_value **argv
4351 ){
4352   Decimal *pA = decimal_new(context, argv[0], 1);
4353   Decimal *pB = decimal_new(context, argv[1], 1);
4354   UNUSED_PARAMETER(argc);
4355   decimal_add(pA, pB);
4356   decimal_result(context, pA);
4357   decimal_free(pA);
4358   decimal_free(pB);
4359 }
decimalSubFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4360 static void decimalSubFunc(
4361   sqlite3_context *context,
4362   int argc,
4363   sqlite3_value **argv
4364 ){
4365   Decimal *pA = decimal_new(context, argv[0], 1);
4366   Decimal *pB = decimal_new(context, argv[1], 1);
4367   UNUSED_PARAMETER(argc);
4368   if( pB ){
4369     pB->sign = !pB->sign;
4370     decimal_add(pA, pB);
4371     decimal_result(context, pA);
4372   }
4373   decimal_free(pA);
4374   decimal_free(pB);
4375 }
4376 
4377 /* Aggregate funcion:   decimal_sum(X)
4378 **
4379 ** Works like sum() except that it uses decimal arithmetic for unlimited
4380 ** precision.
4381 */
decimalSumStep(sqlite3_context * context,int argc,sqlite3_value ** argv)4382 static void decimalSumStep(
4383   sqlite3_context *context,
4384   int argc,
4385   sqlite3_value **argv
4386 ){
4387   Decimal *p;
4388   Decimal *pArg;
4389   UNUSED_PARAMETER(argc);
4390   p = sqlite3_aggregate_context(context, sizeof(*p));
4391   if( p==0 ) return;
4392   if( !p->isInit ){
4393     p->isInit = 1;
4394     p->a = sqlite3_malloc(2);
4395     if( p->a==0 ){
4396       p->oom = 1;
4397     }else{
4398       p->a[0] = 0;
4399     }
4400     p->nDigit = 1;
4401     p->nFrac = 0;
4402   }
4403   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4404   pArg = decimal_new(context, argv[0], 1);
4405   decimal_add(p, pArg);
4406   decimal_free(pArg);
4407 }
decimalSumInverse(sqlite3_context * context,int argc,sqlite3_value ** argv)4408 static void decimalSumInverse(
4409   sqlite3_context *context,
4410   int argc,
4411   sqlite3_value **argv
4412 ){
4413   Decimal *p;
4414   Decimal *pArg;
4415   UNUSED_PARAMETER(argc);
4416   p = sqlite3_aggregate_context(context, sizeof(*p));
4417   if( p==0 ) return;
4418   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4419   pArg = decimal_new(context, argv[0], 1);
4420   if( pArg ) pArg->sign = !pArg->sign;
4421   decimal_add(p, pArg);
4422   decimal_free(pArg);
4423 }
decimalSumValue(sqlite3_context * context)4424 static void decimalSumValue(sqlite3_context *context){
4425   Decimal *p = sqlite3_aggregate_context(context, 0);
4426   if( p==0 ) return;
4427   decimal_result(context, p);
4428 }
decimalSumFinalize(sqlite3_context * context)4429 static void decimalSumFinalize(sqlite3_context *context){
4430   Decimal *p = sqlite3_aggregate_context(context, 0);
4431   if( p==0 ) return;
4432   decimal_result(context, p);
4433   decimal_clear(p);
4434 }
4435 
4436 /*
4437 ** SQL Function:   decimal_mul(X, Y)
4438 **
4439 ** Return the product of X and Y.
4440 */
decimalMulFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4441 static void decimalMulFunc(
4442   sqlite3_context *context,
4443   int argc,
4444   sqlite3_value **argv
4445 ){
4446   Decimal *pA = decimal_new(context, argv[0], 1);
4447   Decimal *pB = decimal_new(context, argv[1], 1);
4448   UNUSED_PARAMETER(argc);
4449   if( pA==0 || pA->oom || pA->isNull
4450    || pB==0 || pB->oom || pB->isNull
4451   ){
4452     goto mul_end;
4453   }
4454   decimalMul(pA, pB);
4455   if( pA->oom ){
4456     goto mul_end;
4457   }
4458   decimal_result(context, pA);
4459 
4460 mul_end:
4461   decimal_free(pA);
4462   decimal_free(pB);
4463 }
4464 
4465 /*
4466 ** SQL Function:   decimal_pow2(N)
4467 **
4468 ** Return the N-th power of 2.  N must be an integer.
4469 */
decimalPow2Func(sqlite3_context * context,int argc,sqlite3_value ** argv)4470 static void decimalPow2Func(
4471   sqlite3_context *context,
4472   int argc,
4473   sqlite3_value **argv
4474 ){
4475   UNUSED_PARAMETER(argc);
4476   if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
4477     Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
4478     decimal_result_sci(context, pA);
4479     decimal_free(pA);
4480   }
4481 }
4482 
4483 #ifdef _WIN32
4484 
4485 #endif
sqlite3_decimal_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)4486 int sqlite3_decimal_init(
4487   sqlite3 *db,
4488   char **pzErrMsg,
4489   const sqlite3_api_routines *pApi
4490 ){
4491   int rc = SQLITE_OK;
4492   static const struct {
4493     const char *zFuncName;
4494     int nArg;
4495     int iArg;
4496     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4497   } aFunc[] = {
4498     { "decimal",       1, 0,  decimalFunc        },
4499     { "decimal_exp",   1, 1,  decimalFunc        },
4500     { "decimal_cmp",   2, 0,  decimalCmpFunc     },
4501     { "decimal_add",   2, 0,  decimalAddFunc     },
4502     { "decimal_sub",   2, 0,  decimalSubFunc     },
4503     { "decimal_mul",   2, 0,  decimalMulFunc     },
4504     { "decimal_pow2",  1, 0,  decimalPow2Func    },
4505   };
4506   unsigned int i;
4507   (void)pzErrMsg;  /* Unused parameter */
4508 
4509   SQLITE_EXTENSION_INIT2(pApi);
4510 
4511   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
4512     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
4513                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4514                    aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
4515   }
4516   if( rc==SQLITE_OK ){
4517     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
4518                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
4519                    decimalSumStep, decimalSumFinalize,
4520                    decimalSumValue, decimalSumInverse, 0);
4521   }
4522   if( rc==SQLITE_OK ){
4523     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
4524                                   0, decimalCollFunc);
4525   }
4526   return rc;
4527 }
4528 
4529 /************************* End ../ext/misc/decimal.c ********************/
4530 #undef sqlite3_base_init
4531 #define sqlite3_base_init sqlite3_base64_init
4532 /************************* Begin ../ext/misc/base64.c ******************/
4533 /*
4534 ** 2022-11-18
4535 **
4536 ** The author disclaims copyright to this source code.  In place of
4537 ** a legal notice, here is a blessing:
4538 **
4539 **    May you do good and not evil.
4540 **    May you find forgiveness for yourself and forgive others.
4541 **    May you share freely, never taking more than you give.
4542 **
4543 *************************************************************************
4544 **
4545 ** This is a SQLite extension for converting in either direction
4546 ** between a (binary) blob and base64 text. Base64 can transit a
4547 ** sane USASCII channel unmolested. It also plays nicely in CSV or
4548 ** written as TCL brace-enclosed literals or SQL string literals,
4549 ** and can be used unmodified in XML-like documents.
4550 **
4551 ** This is an independent implementation of conversions specified in
4552 ** RFC 4648, done on the above date by the author (Larry Brasfield)
4553 ** who thereby has the right to put this into the public domain.
4554 **
4555 ** The conversions meet RFC 4648 requirements, provided that this
4556 ** C source specifies that line-feeds are included in the encoded
4557 ** data to limit visible line lengths to 72 characters and to
4558 ** terminate any encoded blob having non-zero length.
4559 **
4560 ** Length limitations are not imposed except that the runtime
4561 ** SQLite string or blob length limits are respected. Otherwise,
4562 ** any length binary sequence can be represented and recovered.
4563 ** Generated base64 sequences, with their line-feeds included,
4564 ** can be concatenated; the result converted back to binary will
4565 ** be the concatenation of the represented binary sequences.
4566 **
4567 ** This SQLite3 extension creates a function, base64(x), which
4568 ** either: converts text x containing base64 to a returned blob;
4569 ** or converts a blob x to returned text containing base64. An
4570 ** error will be thrown for other input argument types.
4571 **
4572 ** This code relies on UTF-8 encoding only with respect to the
4573 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
4574 ** It will fail miserably if somehow made to try to convert EBCDIC.
4575 ** Because it is table-driven, it could be enhanced to handle that,
4576 ** but the world and SQLite have moved on from that anachronism.
4577 **
4578 ** To build the extension:
4579 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4580 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
4581 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
4582 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
4583 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
4584 */
4585 
4586 #include <assert.h>
4587 
4588 /* #include "sqlite3ext.h" */
4589 
4590 #ifndef deliberate_fall_through
4591 /* Quiet some compilers about some of our intentional code. */
4592 # if GCC_VERSION>=7000000
4593 #  define deliberate_fall_through __attribute__((fallthrough));
4594 # else
4595 #  define deliberate_fall_through
4596 # endif
4597 #endif
4598 
4599 SQLITE_EXTENSION_INIT1;
4600 
4601 #define PC 0x80 /* pad character */
4602 #define WS 0x81 /* whitespace */
4603 #define ND 0x82 /* Not above or digit-value */
4604 #define PAD_CHAR '='
4605 
4606 #ifndef U8_TYPEDEF
4607 /* typedef unsigned char u8; */
4608 #define U8_TYPEDEF
4609 #endif
4610 
4611 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
4612 static const u8 b64DigitValues[128] = {
4613   /*                             HT LF VT  FF CR       */
4614     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
4615   /*                                                US */
4616     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
4617   /*sp                                  +            / */
4618     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
4619   /* 0  1            5            9            =       */
4620     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
4621   /*    A                                            O */
4622     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
4623   /* P                               Z                 */
4624     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
4625   /*    a                                            o */
4626     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
4627   /* p                               z                 */
4628     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
4629 };
4630 
4631 static const char b64Numerals[64+1]
4632 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4633 
4634 #define BX_DV_PROTO(c) \
4635   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
4636 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
4637 #define IS_BX_WS(bdp) ((bdp)==WS)
4638 #define IS_BX_PAD(bdp) ((bdp)==PC)
4639 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
4640 /* Width of base64 lines. Should be an integer multiple of 4. */
4641 #define B64_DARK_MAX 72
4642 
4643 /* Encode a byte buffer into base64 text with linefeeds appended to limit
4644 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
4645 */
toBase64(u8 * pIn,int nbIn,char * pOut)4646 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
4647   int nCol = 0;
4648   while( nbIn >= 3 ){
4649     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
4650     pOut[0] = BX_NUMERAL(pIn[0]>>2);
4651     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
4652     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
4653     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
4654     pOut += 4;
4655     nbIn -= 3;
4656     pIn += 3;
4657     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
4658       *pOut++ = '\n';
4659       nCol = 0;
4660     }
4661   }
4662   if( nbIn > 0 ){
4663     signed char nco = nbIn+1;
4664     int nbe;
4665     unsigned long qv = *pIn++;
4666     for( nbe=1; nbe<3; ++nbe ){
4667       qv <<= 8;
4668       if( nbe<nbIn ) qv |= *pIn++;
4669     }
4670     for( nbe=3; nbe>=0; --nbe ){
4671       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
4672       qv >>= 6;
4673       pOut[nbe] = ce;
4674     }
4675     pOut += 4;
4676     *pOut++ = '\n';
4677   }
4678   *pOut = 0;
4679   return pOut;
4680 }
4681 
4682 /* Skip over text which is not base64 numeral(s). */
skipNonB64(char * s,int nc)4683 static char * skipNonB64( char *s, int nc ){
4684   char c;
4685   while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
4686   return s;
4687 }
4688 
4689 /* Decode base64 text into a byte buffer. */
fromBase64(char * pIn,int ncIn,u8 * pOut)4690 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
4691   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
4692   while( ncIn>0 && *pIn!=PAD_CHAR ){
4693     static signed char nboi[] = { 0, 0, 1, 2, 3 };
4694     char *pUse = skipNonB64(pIn, ncIn);
4695     unsigned long qv = 0L;
4696     int nti, nbo, nac;
4697     ncIn -= (pUse - pIn);
4698     pIn = pUse;
4699     nti = (ncIn>4)? 4 : ncIn;
4700     ncIn -= nti;
4701     nbo = nboi[nti];
4702     if( nbo==0 ) break;
4703     for( nac=0; nac<4; ++nac ){
4704       char c = (nac<nti)? *pIn++ : b64Numerals[0];
4705       u8 bdp = BX_DV_PROTO(c);
4706       switch( bdp ){
4707       case ND:
4708         /*  Treat dark non-digits as pad, but they terminate decode too. */
4709         ncIn = 0;
4710         deliberate_fall_through;
4711       case WS:
4712         /* Treat whitespace as pad and terminate this group.*/
4713         nti = nac;
4714         deliberate_fall_through;
4715       case PC:
4716         bdp = 0;
4717         --nbo;
4718         deliberate_fall_through;
4719       default: /* bdp is the digit value. */
4720         qv = qv<<6 | bdp;
4721         break;
4722       }
4723     }
4724     switch( nbo ){
4725     case 3:
4726       pOut[2] = (qv) & 0xff;
4727     case 2:
4728       pOut[1] = (qv>>8) & 0xff;
4729     case 1:
4730       pOut[0] = (qv>>16) & 0xff;
4731     }
4732     pOut += nbo;
4733   }
4734   return pOut;
4735 }
4736 
4737 /* This function does the work for the SQLite base64(x) UDF. */
base64(sqlite3_context * context,int na,sqlite3_value * av[])4738 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
4739   int nb, nc, nv = sqlite3_value_bytes(av[0]);
4740   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
4741                             SQLITE_LIMIT_LENGTH, -1);
4742   char *cBuf;
4743   u8 *bBuf;
4744   assert(na==1);
4745   switch( sqlite3_value_type(av[0]) ){
4746   case SQLITE_BLOB:
4747     nb = nv;
4748     nc = 4*(nv+2/3); /* quads needed */
4749     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
4750     if( nvMax < nc ){
4751       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
4752       return;
4753     }
4754     bBuf = (u8*)sqlite3_value_blob(av[0]);
4755     if( !bBuf ){
4756       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4757         goto memFail;
4758       }
4759       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
4760       break;
4761     }
4762     cBuf = sqlite3_malloc(nc);
4763     if( !cBuf ) goto memFail;
4764     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
4765     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
4766     break;
4767   case SQLITE_TEXT:
4768     nc = nv;
4769     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
4770     if( nvMax < nb ){
4771       sqlite3_result_error(context, "blob from base64 may be too big", -1);
4772       return;
4773     }else if( nb<1 ){
4774       nb = 1;
4775     }
4776     cBuf = (char *)sqlite3_value_text(av[0]);
4777     if( !cBuf ){
4778       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4779         goto memFail;
4780       }
4781       sqlite3_result_zeroblob(context, 0);
4782       break;
4783     }
4784     bBuf = sqlite3_malloc(nb);
4785     if( !bBuf ) goto memFail;
4786     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
4787     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
4788     break;
4789   default:
4790     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
4791     return;
4792   }
4793   return;
4794  memFail:
4795   sqlite3_result_error(context, "base64 OOM", -1);
4796 }
4797 
4798 /*
4799 ** Establish linkage to running SQLite library.
4800 */
4801 #ifndef SQLITE_SHELL_EXTFUNCS
4802 #ifdef _WIN32
4803 
4804 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)4805 int sqlite3_base_init
4806 #else
4807 static int sqlite3_base64_init
4808 #endif
4809 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
4810   SQLITE_EXTENSION_INIT2(pApi);
4811   (void)pzErr;
4812   return sqlite3_create_function
4813     (db, "base64", 1,
4814      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
4815      0, base64, 0, 0);
4816 }
4817 
4818 /*
4819 ** Define some macros to allow this extension to be built into the shell
4820 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
4821 ** allows shell.c, as distributed, to have this extension built in.
4822 */
4823 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
4824 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
4825 
4826 /************************* End ../ext/misc/base64.c ********************/
4827 #undef sqlite3_base_init
4828 #define sqlite3_base_init sqlite3_base85_init
4829 #define OMIT_BASE85_CHECKER
4830 /************************* Begin ../ext/misc/base85.c ******************/
4831 /*
4832 ** 2022-11-16
4833 **
4834 ** The author disclaims copyright to this source code.  In place of
4835 ** a legal notice, here is a blessing:
4836 **
4837 **    May you do good and not evil.
4838 **    May you find forgiveness for yourself and forgive others.
4839 **    May you share freely, never taking more than you give.
4840 **
4841 *************************************************************************
4842 **
4843 ** This is a utility for converting binary to base85 or vice-versa.
4844 ** It can be built as a standalone program or an SQLite3 extension.
4845 **
4846 ** Much like base64 representations, base85 can be sent through a
4847 ** sane USASCII channel unmolested. It also plays nicely in CSV or
4848 ** written as TCL brace-enclosed literals or SQL string literals.
4849 ** It is not suited for unmodified use in XML-like documents.
4850 **
4851 ** The encoding used resembles Ascii85, but was devised by the author
4852 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
4853 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
4854 ** Further, this is an independent implementation of a base85 system.
4855 ** Hence, the author has rightfully put this into the public domain.
4856 **
4857 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
4858 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
4859 ** in code order representing digit values 0 to 84 (base 10.)
4860 **
4861 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4862 ** are represented as 5-digit base85 numbers with MS to LS digit
4863 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
4864 ** still big-endian but 8-24 bit values. (Using big-endian yields
4865 ** the simplest transition to byte groups smaller than 4 bytes.
4866 ** These byte groups can also be considered base-256 numbers.)
4867 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
4868 ** No pad characters are used; Encoded base85 numeral sequence
4869 ** (aka "group") length maps 1-to-1 to the decoded binary length.
4870 **
4871 ** Any character not in the base85 numeral set delimits groups.
4872 ** When base85 is streamed or stored in containers of indefinite
4873 ** size, newline is used to separate it into sub-sequences of no
4874 ** more than 80 digits so that fgets() can be used to read it.
4875 **
4876 ** Length limitations are not imposed except that the runtime
4877 ** SQLite string or blob length limits are respected. Otherwise,
4878 ** any length binary sequence can be represented and recovered.
4879 ** Base85 sequences can be concatenated by separating them with
4880 ** a non-base85 character; the conversion to binary will then
4881 ** be the concatenation of the represented binary sequences.
4882 
4883 ** The standalone program either converts base85 on stdin to create
4884 ** a binary file or converts a binary file to base85 on stdout.
4885 ** Read or make it blurt its help for invocation details.
4886 **
4887 ** The SQLite3 extension creates a function, base85(x), which will
4888 ** either convert text base85 to a blob or a blob to text base85
4889 ** and return the result (or throw an error for other types.)
4890 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
4891 ** function, is_base85(t), which returns 1 iff the text t contains
4892 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
4893 **
4894 ** To build the extension:
4895 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4896 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4897 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4898 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4899 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4900 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4901 **
4902 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
4903 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4904 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4905 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4906 */
4907 
4908 #include <stdio.h>
4909 #include <memory.h>
4910 #include <string.h>
4911 #include <assert.h>
4912 #ifndef OMIT_BASE85_CHECKER
4913 # include <ctype.h>
4914 #endif
4915 
4916 #ifndef BASE85_STANDALONE
4917 
4918 /* # include "sqlite3ext.h" */
4919 
4920 SQLITE_EXTENSION_INIT1;
4921 
4922 #else
4923 
4924 # ifdef _WIN32
4925 #  include <io.h>
4926 #  include <fcntl.h>
4927 # else
4928 #  define setmode(fd,m)
4929 # endif
4930 
4931 static char *zHelp =
4932   "Usage: base85 <dirFlag> <binFile>\n"
4933   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4934   "   content to be converted to/from base85 on stdout/stdin.\n"
4935   " <binFile> names a binary file to be rendered or created.\n"
4936   "   Or, the name '-' refers to the stdin or stdout stream.\n"
4937   ;
4938 
sayHelp()4939 static void sayHelp(){
4940   printf("%s", zHelp);
4941 }
4942 #endif
4943 
4944 #ifndef U8_TYPEDEF
4945 /* typedef unsigned char u8; */
4946 #define U8_TYPEDEF
4947 #endif
4948 
4949 /* Classify c according to interval within USASCII set w.r.t. base85
4950  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
4951  */
4952 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
4953 
4954 /* Provide digitValue to b85Numeral offset as a function of above class. */
4955 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4956 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
4957 
4958 /* Say whether c is a base85 numeral. */
4959 #define IS_B85( c ) (B85_CLASS(c) & 1)
4960 
4961 #if 0 /* Not used, */
4962 static u8 base85DigitValue( char c ){
4963   u8 dv = (u8)(c - '#');
4964   if( dv>87 ) return 0xff;
4965   return (dv > 3)? dv-3 : dv;
4966 }
4967 #endif
4968 
4969 /* Width of base64 lines. Should be an integer multiple of 5. */
4970 #define B85_DARK_MAX 80
4971 
4972 
skipNonB85(char * s,int nc)4973 static char * skipNonB85( char *s, int nc ){
4974   char c;
4975   while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
4976   return s;
4977 }
4978 
4979 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
4980  * Do not use the macro form with argument expression having a side-effect.*/
4981 #if 0
4982 static char base85Numeral( u8 b ){
4983   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
4984 }
4985 #else
4986 # define base85Numeral( dn )\
4987   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
4988 #endif
4989 
putcs(char * pc,char * s)4990 static char *putcs(char *pc, char *s){
4991   char c;
4992   while( (c = *s++)!=0 ) *pc++ = c;
4993   return pc;
4994 }
4995 
4996 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
4997 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
4998 ** or to terminate the last group (to aid concatenation.)
4999 */
toBase85(u8 * pIn,int nbIn,char * pOut,char * pSep)5000 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
5001   int nCol = 0;
5002   while( nbIn >= 4 ){
5003     int nco = 5;
5004     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
5005                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
5006     while( nco > 0 ){
5007       unsigned nqv = (unsigned)(qbv/85UL);
5008       unsigned char dv = qbv - 85UL*nqv;
5009       qbv = nqv;
5010       pOut[--nco] = base85Numeral(dv);
5011     }
5012     nbIn -= 4;
5013     pIn += 4;
5014     pOut += 5;
5015     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
5016       pOut = putcs(pOut, pSep);
5017       nCol = 0;
5018     }
5019   }
5020   if( nbIn > 0 ){
5021     int nco = nbIn + 1;
5022     unsigned long qv = *pIn++;
5023     int nbe = 1;
5024     while( nbe++ < nbIn ){
5025       qv = (qv<<8) | *pIn++;
5026     }
5027     nCol += nco;
5028     while( nco > 0 ){
5029       u8 dv = (u8)(qv % 85);
5030       qv /= 85;
5031       pOut[--nco] = base85Numeral(dv);
5032     }
5033     pOut += (nbIn+1);
5034   }
5035   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
5036   *pOut = 0;
5037   return pOut;
5038 }
5039 
5040 /* Decode base85 text into a byte buffer. */
fromBase85(char * pIn,int ncIn,u8 * pOut)5041 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
5042   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
5043   while( ncIn>0 ){
5044     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
5045     char *pUse = skipNonB85(pIn, ncIn);
5046     unsigned long qv = 0L;
5047     int nti, nbo;
5048     ncIn -= (pUse - pIn);
5049     pIn = pUse;
5050     nti = (ncIn>5)? 5 : ncIn;
5051     nbo = nboi[nti];
5052     if( nbo==0 ) break;
5053     while( nti>0 ){
5054       char c = *pIn++;
5055       u8 cdo = B85_DNOS(c);
5056       --ncIn;
5057       if( cdo==0 ) break;
5058       qv = 85 * qv + (c - cdo);
5059       --nti;
5060     }
5061     nbo -= nti; /* Adjust for early (non-digit) end of group. */
5062     switch( nbo ){
5063     case 4:
5064       *pOut++ = (qv >> 24)&0xff;
5065     case 3:
5066       *pOut++ = (qv >> 16)&0xff;
5067     case 2:
5068       *pOut++ = (qv >> 8)&0xff;
5069     case 1:
5070       *pOut++ = qv&0xff;
5071     case 0:
5072       break;
5073     }
5074   }
5075   return pOut;
5076 }
5077 
5078 #ifndef OMIT_BASE85_CHECKER
5079 /* Say whether input char sequence is all (base85 and/or whitespace).*/
allBase85(char * p,int len)5080 static int allBase85( char *p, int len ){
5081   char c;
5082   while( len-- > 0 && (c = *p++) != 0 ){
5083     if( !IS_B85(c) && !isspace(c) ) return 0;
5084   }
5085   return 1;
5086 }
5087 #endif
5088 
5089 #ifndef BASE85_STANDALONE
5090 
5091 # ifndef OMIT_BASE85_CHECKER
5092 /* This function does the work for the SQLite is_base85(t) UDF. */
is_base85(sqlite3_context * context,int na,sqlite3_value * av[])5093 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5094   assert(na==1);
5095   switch( sqlite3_value_type(av[0]) ){
5096   case SQLITE_TEXT:
5097     {
5098       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
5099                           sqlite3_value_bytes(av[0]) );
5100       sqlite3_result_int(context, rv);
5101     }
5102     break;
5103   case SQLITE_NULL:
5104     sqlite3_result_null(context);
5105     break;
5106   default:
5107     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
5108     return;
5109   }
5110 }
5111 # endif
5112 
5113 /* This function does the work for the SQLite base85(x) UDF. */
base85(sqlite3_context * context,int na,sqlite3_value * av[])5114 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5115   int nb, nc, nv = sqlite3_value_bytes(av[0]);
5116   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
5117                             SQLITE_LIMIT_LENGTH, -1);
5118   char *cBuf;
5119   u8 *bBuf;
5120   assert(na==1);
5121   switch( sqlite3_value_type(av[0]) ){
5122   case SQLITE_BLOB:
5123     nb = nv;
5124     /*    ulongs    tail   newlines  tailenc+nul*/
5125     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
5126     if( nvMax < nc ){
5127       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
5128       return;
5129     }
5130     bBuf = (u8*)sqlite3_value_blob(av[0]);
5131     if( !bBuf ){
5132       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5133         goto memFail;
5134       }
5135       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
5136       break;
5137     }
5138     cBuf = sqlite3_malloc(nc);
5139     if( !cBuf ) goto memFail;
5140     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
5141     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
5142     break;
5143   case SQLITE_TEXT:
5144     nc = nv;
5145     nb = 4*(nv/5) + nv%5; /* may overestimate */
5146     if( nvMax < nb ){
5147       sqlite3_result_error(context, "blob from base85 may be too big", -1);
5148       return;
5149     }else if( nb<1 ){
5150       nb = 1;
5151     }
5152     cBuf = (char *)sqlite3_value_text(av[0]);
5153     if( !cBuf ){
5154       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5155         goto memFail;
5156       }
5157       sqlite3_result_zeroblob(context, 0);
5158       break;
5159     }
5160     bBuf = sqlite3_malloc(nb);
5161     if( !bBuf ) goto memFail;
5162     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
5163     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
5164     break;
5165   default:
5166     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
5167     return;
5168   }
5169   return;
5170  memFail:
5171   sqlite3_result_error(context, "base85 OOM", -1);
5172 }
5173 
5174 /*
5175 ** Establish linkage to running SQLite library.
5176 */
5177 #ifndef SQLITE_SHELL_EXTFUNCS
5178 #ifdef _WIN32
5179 
5180 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)5181 int sqlite3_base_init
5182 #else
5183 static int sqlite3_base85_init
5184 #endif
5185 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
5186   SQLITE_EXTENSION_INIT2(pApi);
5187   (void)pzErr;
5188 # ifndef OMIT_BASE85_CHECKER
5189   {
5190     int rc = sqlite3_create_function
5191       (db, "is_base85", 1,
5192        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
5193        0, is_base85, 0, 0);
5194     if( rc!=SQLITE_OK ) return rc;
5195   }
5196 # endif
5197   return sqlite3_create_function
5198     (db, "base85", 1,
5199      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
5200      0, base85, 0, 0);
5201 }
5202 
5203 /*
5204 ** Define some macros to allow this extension to be built into the shell
5205 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
5206 ** allows shell.c, as distributed, to have this extension built in.
5207 */
5208 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
5209 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
5210 
5211 #else /* standalone program */
5212 
main(int na,char * av[])5213 int main(int na, char *av[]){
5214   int cin;
5215   int rc = 0;
5216   u8 bBuf[4*(B85_DARK_MAX/5)];
5217   char cBuf[5*(sizeof(bBuf)/4)+2];
5218   size_t nio;
5219 # ifndef OMIT_BASE85_CHECKER
5220   int b85Clean = 1;
5221 # endif
5222   char rw;
5223   FILE *fb = 0, *foc = 0;
5224   char fmode[3] = "xb";
5225   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
5226     sayHelp();
5227     return 0;
5228   }
5229   fmode[0] = rw;
5230   if( av[2][0]=='-' && av[2][1]==0 ){
5231     switch( rw ){
5232     case 'r':
5233       fb = stdin;
5234       setmode(fileno(stdin), O_BINARY);
5235       break;
5236     case 'w':
5237       fb = stdout;
5238       setmode(fileno(stdout), O_BINARY);
5239       break;
5240     }
5241   }else{
5242     fb = fopen(av[2], fmode);
5243     foc = fb;
5244   }
5245   if( !fb ){
5246     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
5247     rc = 1;
5248   }else{
5249     switch( rw ){
5250     case 'r':
5251       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
5252         toBase85( bBuf, (int)nio, cBuf, 0 );
5253         fprintf(stdout, "%s\n", cBuf);
5254       }
5255       break;
5256     case 'w':
5257       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
5258         int nc = strlen(cBuf);
5259         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
5260         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
5261 # ifndef OMIT_BASE85_CHECKER
5262         b85Clean &= allBase85( cBuf, nc );
5263 # endif
5264       }
5265       break;
5266     default:
5267       sayHelp();
5268       rc = 1;
5269     }
5270     if( foc ) fclose(foc);
5271   }
5272 # ifndef OMIT_BASE85_CHECKER
5273   if( !b85Clean ){
5274     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
5275   }
5276 # endif
5277   return rc;
5278 }
5279 
5280 #endif
5281 
5282 /************************* End ../ext/misc/base85.c ********************/
5283 /************************* Begin ../ext/misc/ieee754.c ******************/
5284 /*
5285 ** 2013-04-17
5286 **
5287 ** The author disclaims copyright to this source code.  In place of
5288 ** a legal notice, here is a blessing:
5289 **
5290 **    May you do good and not evil.
5291 **    May you find forgiveness for yourself and forgive others.
5292 **    May you share freely, never taking more than you give.
5293 **
5294 ******************************************************************************
5295 **
5296 ** This SQLite extension implements functions for the exact display
5297 ** and input of IEEE754 Binary64 floating-point numbers.
5298 **
5299 **   ieee754(X)
5300 **   ieee754(Y,Z)
5301 **
5302 ** In the first form, the value X should be a floating-point number.
5303 ** The function will return a string of the form 'ieee754(Y,Z)' where
5304 ** Y and Z are integers such that X==Y*pow(2,Z).
5305 **
5306 ** In the second form, Y and Z are integers which are the mantissa and
5307 ** base-2 exponent of a new floating point number.  The function returns
5308 ** a floating-point value equal to Y*pow(2,Z).
5309 **
5310 ** Examples:
5311 **
5312 **     ieee754(2.0)             ->     'ieee754(2,0)'
5313 **     ieee754(45.25)           ->     'ieee754(181,-2)'
5314 **     ieee754(2, 0)            ->     2.0
5315 **     ieee754(181, -2)         ->     45.25
5316 **
5317 ** Two additional functions break apart the one-argument ieee754()
5318 ** result into separate integer values:
5319 **
5320 **     ieee754_mantissa(45.25)  ->     181
5321 **     ieee754_exponent(45.25)  ->     -2
5322 **
5323 ** These functions convert binary64 numbers into blobs and back again.
5324 **
5325 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5326 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5327 **
5328 ** In all single-argument functions, if the argument is an 8-byte blob
5329 ** then that blob is interpreted as a big-endian binary64 value.
5330 **
5331 **
5332 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5333 ** -----------------------------------------------
5334 **
5335 ** This extension in combination with the separate 'decimal' extension
5336 ** can be used to compute the exact decimal representation of binary64
5337 ** values.  To begin, first compute a table of exponent values:
5338 **
5339 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5340 **    WITH RECURSIVE c(x,v) AS (
5341 **      VALUES(0,'1')
5342 **      UNION ALL
5343 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5344 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5345 **    WITH RECURSIVE c(x,v) AS (
5346 **      VALUES(-1,'0.5')
5347 **      UNION ALL
5348 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5349 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5350 **
5351 ** Then, to compute the exact decimal representation of a floating
5352 ** point value (the value 47.49 is used in the example) do:
5353 **
5354 **    WITH c(n) AS (VALUES(47.49))
5355 **          ---------------^^^^^---- Replace with whatever you want
5356 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5357 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5358 **
5359 ** Here is a query to show various boundry values for the binary64
5360 ** number format:
5361 **
5362 **    WITH c(name,bin) AS (VALUES
5363 **       ('minimum positive value',        x'0000000000000001'),
5364 **       ('maximum subnormal value',       x'000fffffffffffff'),
5365 **       ('mininum positive nornal value', x'0010000000000000'),
5366 **       ('maximum value',                 x'7fefffffffffffff'))
5367 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5368 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5369 **
5370 */
5371 /* #include "sqlite3ext.h" */
5372 SQLITE_EXTENSION_INIT1
5373 #include <assert.h>
5374 #include <string.h>
5375 
5376 /* Mark a function parameter as unused, to suppress nuisance compiler
5377 ** warnings. */
5378 #ifndef UNUSED_PARAMETER
5379 # define UNUSED_PARAMETER(X)  (void)(X)
5380 #endif
5381 
5382 /*
5383 ** Implementation of the ieee754() function
5384 */
ieee754func(sqlite3_context * context,int argc,sqlite3_value ** argv)5385 static void ieee754func(
5386   sqlite3_context *context,
5387   int argc,
5388   sqlite3_value **argv
5389 ){
5390   if( argc==1 ){
5391     sqlite3_int64 m, a;
5392     double r;
5393     int e;
5394     int isNeg;
5395     char zResult[100];
5396     assert( sizeof(m)==sizeof(r) );
5397     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5398      && sqlite3_value_bytes(argv[0])==sizeof(r)
5399     ){
5400       const unsigned char *x = sqlite3_value_blob(argv[0]);
5401       unsigned int i;
5402       sqlite3_uint64 v = 0;
5403       for(i=0; i<sizeof(r); i++){
5404         v = (v<<8) | x[i];
5405       }
5406       memcpy(&r, &v, sizeof(r));
5407     }else{
5408       r = sqlite3_value_double(argv[0]);
5409     }
5410     if( r<0.0 ){
5411       isNeg = 1;
5412       r = -r;
5413     }else{
5414       isNeg = 0;
5415     }
5416     memcpy(&a,&r,sizeof(a));
5417     if( a==0 ){
5418       e = 0;
5419       m = 0;
5420     }else{
5421       e = a>>52;
5422       m = a & ((((sqlite3_int64)1)<<52)-1);
5423       if( e==0 ){
5424         m <<= 1;
5425       }else{
5426         m |= ((sqlite3_int64)1)<<52;
5427       }
5428       while( e<1075 && m>0 && (m&1)==0 ){
5429         m >>= 1;
5430         e++;
5431       }
5432       if( isNeg ) m = -m;
5433     }
5434     switch( *(int*)sqlite3_user_data(context) ){
5435       case 0:
5436         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5437                          m, e-1075);
5438         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5439         break;
5440       case 1:
5441         sqlite3_result_int64(context, m);
5442         break;
5443       case 2:
5444         sqlite3_result_int(context, e-1075);
5445         break;
5446     }
5447   }else{
5448     sqlite3_int64 m, e, a;
5449     double r;
5450     int isNeg = 0;
5451     m = sqlite3_value_int64(argv[0]);
5452     e = sqlite3_value_int64(argv[1]);
5453 
5454     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
5455     if( e>10000 ){
5456       e = 10000;
5457     }else if( e<-10000 ){
5458       e = -10000;
5459     }
5460 
5461     if( m<0 ){
5462       isNeg = 1;
5463       m = -m;
5464       if( m<0 ) return;
5465     }else if( m==0 && e>-1000 && e<1000 ){
5466       sqlite3_result_double(context, 0.0);
5467       return;
5468     }
5469     while( (m>>32)&0xffe00000 ){
5470       m >>= 1;
5471       e++;
5472     }
5473     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5474       m <<= 1;
5475       e--;
5476     }
5477     e += 1075;
5478     if( e<=0 ){
5479       /* Subnormal */
5480       if( 1-e >= 64 ){
5481         m = 0;
5482       }else{
5483         m >>= 1-e;
5484       }
5485       e = 0;
5486     }else if( e>0x7ff ){
5487       e = 0x7ff;
5488     }
5489     a = m & ((((sqlite3_int64)1)<<52)-1);
5490     a |= e<<52;
5491     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5492     memcpy(&r, &a, sizeof(r));
5493     sqlite3_result_double(context, r);
5494   }
5495 }
5496 
5497 /*
5498 ** Functions to convert between blobs and floats.
5499 */
ieee754func_from_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5500 static void ieee754func_from_blob(
5501   sqlite3_context *context,
5502   int argc,
5503   sqlite3_value **argv
5504 ){
5505   UNUSED_PARAMETER(argc);
5506   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5507    && sqlite3_value_bytes(argv[0])==sizeof(double)
5508   ){
5509     double r;
5510     const unsigned char *x = sqlite3_value_blob(argv[0]);
5511     unsigned int i;
5512     sqlite3_uint64 v = 0;
5513     for(i=0; i<sizeof(r); i++){
5514       v = (v<<8) | x[i];
5515     }
5516     memcpy(&r, &v, sizeof(r));
5517     sqlite3_result_double(context, r);
5518   }
5519 }
ieee754func_to_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5520 static void ieee754func_to_blob(
5521   sqlite3_context *context,
5522   int argc,
5523   sqlite3_value **argv
5524 ){
5525   UNUSED_PARAMETER(argc);
5526   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5527    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5528   ){
5529     double r = sqlite3_value_double(argv[0]);
5530     sqlite3_uint64 v;
5531     unsigned char a[sizeof(r)];
5532     unsigned int i;
5533     memcpy(&v, &r, sizeof(r));
5534     for(i=1; i<=sizeof(r); i++){
5535       a[sizeof(r)-i] = v&0xff;
5536       v >>= 8;
5537     }
5538     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5539   }
5540 }
5541 
5542 /*
5543 ** SQL Function:   ieee754_inc(r,N)
5544 **
5545 ** Move the floating point value r by N quantums and return the new
5546 ** values.
5547 **
5548 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
5549 ** integer, adds N, then casts the value back into float.
5550 **
5551 ** Example:  To find the smallest positive number:
5552 **
5553 **     SELECT ieee754_inc(0.0,+1);
5554 */
ieee754inc(sqlite3_context * context,int argc,sqlite3_value ** argv)5555 static void ieee754inc(
5556   sqlite3_context *context,
5557   int argc,
5558   sqlite3_value **argv
5559 ){
5560   double r;
5561   sqlite3_int64 N;
5562   sqlite3_uint64 m1, m2;
5563   double r2;
5564   UNUSED_PARAMETER(argc);
5565   r = sqlite3_value_double(argv[0]);
5566   N = sqlite3_value_int64(argv[1]);
5567   memcpy(&m1, &r, 8);
5568   m2 = m1 + N;
5569   memcpy(&r2, &m2, 8);
5570   sqlite3_result_double(context, r2);
5571 }
5572 
5573 
5574 #ifdef _WIN32
5575 
5576 #endif
sqlite3_ieee_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)5577 int sqlite3_ieee_init(
5578   sqlite3 *db,
5579   char **pzErrMsg,
5580   const sqlite3_api_routines *pApi
5581 ){
5582   static const struct {
5583     char *zFName;
5584     int nArg;
5585     int iAux;
5586     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5587   } aFunc[] = {
5588     { "ieee754",           1,   0, ieee754func },
5589     { "ieee754",           2,   0, ieee754func },
5590     { "ieee754_mantissa",  1,   1, ieee754func },
5591     { "ieee754_exponent",  1,   2, ieee754func },
5592     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5593     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5594     { "ieee754_inc",       2,   0, ieee754inc  },
5595   };
5596   unsigned int i;
5597   int rc = SQLITE_OK;
5598   SQLITE_EXTENSION_INIT2(pApi);
5599   (void)pzErrMsg;  /* Unused parameter */
5600   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5601     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
5602                                SQLITE_UTF8|SQLITE_INNOCUOUS,
5603                                (void*)&aFunc[i].iAux,
5604                                aFunc[i].xFunc, 0, 0);
5605   }
5606   return rc;
5607 }
5608 
5609 /************************* End ../ext/misc/ieee754.c ********************/
5610 /************************* Begin ../ext/misc/series.c ******************/
5611 /*
5612 ** 2015-08-18, 2023-04-28
5613 **
5614 ** The author disclaims copyright to this source code.  In place of
5615 ** a legal notice, here is a blessing:
5616 **
5617 **    May you do good and not evil.
5618 **    May you find forgiveness for yourself and forgive others.
5619 **    May you share freely, never taking more than you give.
5620 **
5621 *************************************************************************
5622 **
5623 ** This file demonstrates how to create a table-valued-function using
5624 ** a virtual table.  This demo implements the generate_series() function
5625 ** which gives the same results as the eponymous function in PostgreSQL,
5626 ** within the limitation that its arguments are signed 64-bit integers.
5627 **
5628 ** Considering its equivalents to generate_series(start,stop,step): A
5629 ** value V[n] sequence is produced for integer n ascending from 0 where
5630 **  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
5631 ** for each produced value (independent of production time ordering.)
5632 **
5633 ** All parameters must be either integer or convertable to integer.
5634 ** The start parameter is required.
5635 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
5636 ** The step parameter defaults to 1 and 0 is treated as 1.
5637 **
5638 ** Examples:
5639 **
5640 **      SELECT * FROM generate_series(0,100,5);
5641 **
5642 ** The query above returns integers from 0 through 100 counting by steps
5643 ** of 5.
5644 **
5645 **      SELECT * FROM generate_series(0,100);
5646 **
5647 ** Integers from 0 through 100 with a step size of 1.
5648 **
5649 **      SELECT * FROM generate_series(20) LIMIT 10;
5650 **
5651 ** Integers 20 through 29.
5652 **
5653 **      SELECT * FROM generate_series(0,-100,-5);
5654 **
5655 ** Integers 0 -5 -10 ... -100.
5656 **
5657 **      SELECT * FROM generate_series(0,-1);
5658 **
5659 ** Empty sequence.
5660 **
5661 ** HOW IT WORKS
5662 **
5663 ** The generate_series "function" is really a virtual table with the
5664 ** following schema:
5665 **
5666 **     CREATE TABLE generate_series(
5667 **       value,
5668 **       start HIDDEN,
5669 **       stop HIDDEN,
5670 **       step HIDDEN
5671 **     );
5672 **
5673 ** The virtual table also has a rowid, logically equivalent to n+1 where
5674 ** "n" is the ascending integer in the aforesaid production definition.
5675 **
5676 ** Function arguments in queries against this virtual table are translated
5677 ** into equality constraints against successive hidden columns.  In other
5678 ** words, the following pairs of queries are equivalent to each other:
5679 **
5680 **    SELECT * FROM generate_series(0,100,5);
5681 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5682 **
5683 **    SELECT * FROM generate_series(0,100);
5684 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5685 **
5686 **    SELECT * FROM generate_series(20) LIMIT 10;
5687 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5688 **
5689 ** The generate_series virtual table implementation leaves the xCreate method
5690 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5691 ** TABLE command with "generate_series" as the USING argument.  Instead, there
5692 ** is a single generate_series virtual table that is always available without
5693 ** having to be created first.
5694 **
5695 ** The xBestIndex method looks for equality constraints against the hidden
5696 ** start, stop, and step columns, and if present, it uses those constraints
5697 ** to bound the sequence of generated values.  If the equality constraints
5698 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5699 ** xBestIndex returns a small cost when both start and stop are available,
5700 ** and a very large cost if either start or stop are unavailable.  This
5701 ** encourages the query planner to order joins such that the bounds of the
5702 ** series are well-defined.
5703 */
5704 /* #include "sqlite3ext.h" */
5705 SQLITE_EXTENSION_INIT1
5706 #include <assert.h>
5707 #include <string.h>
5708 #include <limits.h>
5709 
5710 #ifndef SQLITE_OMIT_VIRTUALTABLE
5711 /*
5712 ** Return that member of a generate_series(...) sequence whose 0-based
5713 ** index is ix. The 0th member is given by smBase. The sequence members
5714 ** progress per ix increment by smStep.
5715 */
genSeqMember(sqlite3_int64 smBase,sqlite3_int64 smStep,sqlite3_uint64 ix)5716 static sqlite3_int64 genSeqMember(sqlite3_int64 smBase,
5717                                   sqlite3_int64 smStep,
5718                                   sqlite3_uint64 ix){
5719   if( ix>=(sqlite3_uint64)LLONG_MAX ){
5720     /* Get ix into signed i64 range. */
5721     ix -= (sqlite3_uint64)LLONG_MAX;
5722     /* With 2's complement ALU, this next can be 1 step, but is split into
5723      * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
5724     smBase += (LLONG_MAX/2) * smStep;
5725     smBase += (LLONG_MAX - LLONG_MAX/2) * smStep;
5726   }
5727   /* Under UBSAN (or on 1's complement machines), must do this last term
5728    * in steps to avoid the dreaded (and harmless) signed multiply overlow. */
5729   if( ix>=2 ){
5730     sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
5731     smBase += ix2*smStep;
5732     ix -= ix2;
5733   }
5734   return smBase + ((sqlite3_int64)ix)*smStep;
5735 }
5736 
5737 /* typedef unsigned char u8; */
5738 
5739 typedef struct SequenceSpec {
5740   sqlite3_int64 iBase;         /* Starting value ("start") */
5741   sqlite3_int64 iTerm;         /* Given terminal value ("stop") */
5742   sqlite3_int64 iStep;         /* Increment ("step") */
5743   sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
5744   sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
5745   sqlite3_int64 iValueNow;     /* Current value during generation */
5746   u8 isNotEOF;                 /* Sequence generation not exhausted */
5747   u8 isReversing;              /* Sequence is being reverse generated */
5748 } SequenceSpec;
5749 
5750 /*
5751 ** Prepare a SequenceSpec for use in generating an integer series
5752 ** given initialized iBase, iTerm and iStep values. Sequence is
5753 ** initialized per given isReversing. Other members are computed.
5754 */
setupSequence(SequenceSpec * pss)5755 static void setupSequence( SequenceSpec *pss ){
5756   int bSameSigns;
5757   pss->uSeqIndexMax = 0;
5758   pss->isNotEOF = 0;
5759   bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
5760   if( pss->iTerm < pss->iBase ){
5761     sqlite3_uint64 nuspan = 0;
5762     if( bSameSigns ){
5763       nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
5764     }else{
5765       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5766        * In this clause, iBase>=0 and iTerm<0 . */
5767       nuspan = 1;
5768       nuspan += pss->iBase;
5769       nuspan += -(pss->iTerm+1);
5770     }
5771     if( pss->iStep<0 ){
5772       pss->isNotEOF = 1;
5773       if( nuspan==ULONG_MAX ){
5774         pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
5775       }else if( pss->iStep>LLONG_MIN ){
5776         pss->uSeqIndexMax = nuspan/-pss->iStep;
5777       }
5778     }
5779   }else if( pss->iTerm > pss->iBase ){
5780     sqlite3_uint64 puspan = 0;
5781     if( bSameSigns ){
5782       puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
5783     }else{
5784       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5785        * In this clause, iTerm>=0 and iBase<0 . */
5786       puspan = 1;
5787       puspan += pss->iTerm;
5788       puspan += -(pss->iBase+1);
5789     }
5790     if( pss->iStep>0 ){
5791       pss->isNotEOF = 1;
5792       pss->uSeqIndexMax = puspan/pss->iStep;
5793     }
5794   }else if( pss->iTerm == pss->iBase ){
5795       pss->isNotEOF = 1;
5796       pss->uSeqIndexMax = 0;
5797   }
5798   pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
5799   pss->iValueNow = (pss->isReversing)
5800     ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
5801     : pss->iBase;
5802 }
5803 
5804 /*
5805 ** Progress sequence generator to yield next value, if any.
5806 ** Leave its state to either yield next value or be at EOF.
5807 ** Return whether there is a next value, or 0 at EOF.
5808 */
progressSequence(SequenceSpec * pss)5809 static int progressSequence( SequenceSpec *pss ){
5810   if( !pss->isNotEOF ) return 0;
5811   if( pss->isReversing ){
5812     if( pss->uSeqIndexNow > 0 ){
5813       pss->uSeqIndexNow--;
5814       pss->iValueNow -= pss->iStep;
5815     }else{
5816       pss->isNotEOF = 0;
5817     }
5818   }else{
5819     if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
5820       pss->uSeqIndexNow++;
5821       pss->iValueNow += pss->iStep;
5822     }else{
5823       pss->isNotEOF = 0;
5824     }
5825   }
5826   return pss->isNotEOF;
5827 }
5828 
5829 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
5830 ** serve as the underlying representation of a cursor that scans
5831 ** over rows of the result
5832 */
5833 typedef struct series_cursor series_cursor;
5834 struct series_cursor {
5835   sqlite3_vtab_cursor base;  /* Base class - must be first */
5836   SequenceSpec ss;           /* (this) Derived class data */
5837 };
5838 
5839 /*
5840 ** The seriesConnect() method is invoked to create a new
5841 ** series_vtab that describes the generate_series virtual table.
5842 **
5843 ** Think of this routine as the constructor for series_vtab objects.
5844 **
5845 ** All this routine needs to do is:
5846 **
5847 **    (1) Allocate the series_vtab object and initialize all fields.
5848 **
5849 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5850 **        result set of queries against generate_series will look like.
5851 */
seriesConnect(sqlite3 * db,void * pUnused,int argcUnused,const char * const * argvUnused,sqlite3_vtab ** ppVtab,char ** pzErrUnused)5852 static int seriesConnect(
5853   sqlite3 *db,
5854   void *pUnused,
5855   int argcUnused, const char *const*argvUnused,
5856   sqlite3_vtab **ppVtab,
5857   char **pzErrUnused
5858 ){
5859   sqlite3_vtab *pNew;
5860   int rc;
5861 
5862 /* Column numbers */
5863 #define SERIES_COLUMN_VALUE 0
5864 #define SERIES_COLUMN_START 1
5865 #define SERIES_COLUMN_STOP  2
5866 #define SERIES_COLUMN_STEP  3
5867 
5868   (void)pUnused;
5869   (void)argcUnused;
5870   (void)argvUnused;
5871   (void)pzErrUnused;
5872   rc = sqlite3_declare_vtab(db,
5873      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5874   if( rc==SQLITE_OK ){
5875     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5876     if( pNew==0 ) return SQLITE_NOMEM;
5877     memset(pNew, 0, sizeof(*pNew));
5878     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5879   }
5880   return rc;
5881 }
5882 
5883 /*
5884 ** This method is the destructor for series_cursor objects.
5885 */
seriesDisconnect(sqlite3_vtab * pVtab)5886 static int seriesDisconnect(sqlite3_vtab *pVtab){
5887   sqlite3_free(pVtab);
5888   return SQLITE_OK;
5889 }
5890 
5891 /*
5892 ** Constructor for a new series_cursor object.
5893 */
seriesOpen(sqlite3_vtab * pUnused,sqlite3_vtab_cursor ** ppCursor)5894 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5895   series_cursor *pCur;
5896   (void)pUnused;
5897   pCur = sqlite3_malloc( sizeof(*pCur) );
5898   if( pCur==0 ) return SQLITE_NOMEM;
5899   memset(pCur, 0, sizeof(*pCur));
5900   *ppCursor = &pCur->base;
5901   return SQLITE_OK;
5902 }
5903 
5904 /*
5905 ** Destructor for a series_cursor.
5906 */
seriesClose(sqlite3_vtab_cursor * cur)5907 static int seriesClose(sqlite3_vtab_cursor *cur){
5908   sqlite3_free(cur);
5909   return SQLITE_OK;
5910 }
5911 
5912 
5913 /*
5914 ** Advance a series_cursor to its next row of output.
5915 */
seriesNext(sqlite3_vtab_cursor * cur)5916 static int seriesNext(sqlite3_vtab_cursor *cur){
5917   series_cursor *pCur = (series_cursor*)cur;
5918   progressSequence( & pCur->ss );
5919   return SQLITE_OK;
5920 }
5921 
5922 /*
5923 ** Return values of columns for the row at which the series_cursor
5924 ** is currently pointing.
5925 */
seriesColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)5926 static int seriesColumn(
5927   sqlite3_vtab_cursor *cur,   /* The cursor */
5928   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5929   int i                       /* Which column to return */
5930 ){
5931   series_cursor *pCur = (series_cursor*)cur;
5932   sqlite3_int64 x = 0;
5933   switch( i ){
5934     case SERIES_COLUMN_START:  x = pCur->ss.iBase; break;
5935     case SERIES_COLUMN_STOP:   x = pCur->ss.iTerm; break;
5936     case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;   break;
5937     default:                   x = pCur->ss.iValueNow;  break;
5938   }
5939   sqlite3_result_int64(ctx, x);
5940   return SQLITE_OK;
5941 }
5942 
5943 #ifndef LARGEST_UINT64
5944 #define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32))
5945 #endif
5946 
5947 /*
5948 ** Return the rowid for the current row, logically equivalent to n+1 where
5949 ** "n" is the ascending integer in the aforesaid production definition.
5950 */
seriesRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)5951 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5952   series_cursor *pCur = (series_cursor*)cur;
5953   sqlite3_uint64 n = pCur->ss.uSeqIndexNow;
5954   *pRowid = (sqlite3_int64)((n<LARGEST_UINT64)? n+1 : 0);
5955   return SQLITE_OK;
5956 }
5957 
5958 /*
5959 ** Return TRUE if the cursor has been moved off of the last
5960 ** row of output.
5961 */
seriesEof(sqlite3_vtab_cursor * cur)5962 static int seriesEof(sqlite3_vtab_cursor *cur){
5963   series_cursor *pCur = (series_cursor*)cur;
5964   return !pCur->ss.isNotEOF;
5965 }
5966 
5967 /* True to cause run-time checking of the start=, stop=, and/or step=
5968 ** parameters.  The only reason to do this is for testing the
5969 ** constraint checking logic for virtual tables in the SQLite core.
5970 */
5971 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5972 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5973 #endif
5974 
5975 /*
5976 ** This method is called to "rewind" the series_cursor object back
5977 ** to the first row of output.  This method is always called at least
5978 ** once prior to any call to seriesColumn() or seriesRowid() or
5979 ** seriesEof().
5980 **
5981 ** The query plan selected by seriesBestIndex is passed in the idxNum
5982 ** parameter.  (idxStr is not used in this implementation.)  idxNum
5983 ** is a bitmask showing which constraints are available:
5984 **
5985 **    1:    start=VALUE
5986 **    2:    stop=VALUE
5987 **    4:    step=VALUE
5988 **
5989 ** Also, if bit 8 is set, that means that the series should be output
5990 ** in descending order rather than in ascending order.  If bit 16 is
5991 ** set, then output must appear in ascending order.
5992 **
5993 ** This routine should initialize the cursor and position it so that it
5994 ** is pointing at the first row, or pointing off the end of the table
5995 ** (so that seriesEof() will return true) if the table is empty.
5996 */
seriesFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStrUnused,int argc,sqlite3_value ** argv)5997 static int seriesFilter(
5998   sqlite3_vtab_cursor *pVtabCursor,
5999   int idxNum, const char *idxStrUnused,
6000   int argc, sqlite3_value **argv
6001 ){
6002   series_cursor *pCur = (series_cursor *)pVtabCursor;
6003   int i = 0;
6004   (void)idxStrUnused;
6005   if( idxNum & 1 ){
6006     pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
6007   }else{
6008     pCur->ss.iBase = 0;
6009   }
6010   if( idxNum & 2 ){
6011     pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
6012   }else{
6013     pCur->ss.iTerm = 0xffffffff;
6014   }
6015   if( idxNum & 4 ){
6016     pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
6017     if( pCur->ss.iStep==0 ){
6018       pCur->ss.iStep = 1;
6019     }else if( pCur->ss.iStep<0 ){
6020       if( (idxNum & 16)==0 ) idxNum |= 8;
6021     }
6022   }else{
6023     pCur->ss.iStep = 1;
6024   }
6025   for(i=0; i<argc; i++){
6026     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
6027       /* If any of the constraints have a NULL value, then return no rows.
6028       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
6029       pCur->ss.iBase = 1;
6030       pCur->ss.iTerm = 0;
6031       pCur->ss.iStep = 1;
6032       break;
6033     }
6034   }
6035   if( idxNum & 8 ){
6036     pCur->ss.isReversing = pCur->ss.iStep > 0;
6037   }else{
6038     pCur->ss.isReversing = pCur->ss.iStep < 0;
6039   }
6040   setupSequence( &pCur->ss );
6041   return SQLITE_OK;
6042 }
6043 
6044 /*
6045 ** SQLite will invoke this method one or more times while planning a query
6046 ** that uses the generate_series virtual table.  This routine needs to create
6047 ** a query plan for each invocation and compute an estimated cost for that
6048 ** plan.
6049 **
6050 ** In this implementation idxNum is used to represent the
6051 ** query plan.  idxStr is unused.
6052 **
6053 ** The query plan is represented by bits in idxNum:
6054 **
6055 **  (1)  start = $value  -- constraint exists
6056 **  (2)  stop = $value   -- constraint exists
6057 **  (4)  step = $value   -- constraint exists
6058 **  (8)  output in descending order
6059 */
seriesBestIndex(sqlite3_vtab * pVTab,sqlite3_index_info * pIdxInfo)6060 static int seriesBestIndex(
6061   sqlite3_vtab *pVTab,
6062   sqlite3_index_info *pIdxInfo
6063 ){
6064   int i, j;              /* Loop over constraints */
6065   int idxNum = 0;        /* The query plan bitmask */
6066   int bStartSeen = 0;    /* EQ constraint seen on the START column */
6067   int unusableMask = 0;  /* Mask of unusable constraints */
6068   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
6069   int aIdx[3];           /* Constraints on start, stop, and step */
6070   const struct sqlite3_index_constraint *pConstraint;
6071 
6072   /* This implementation assumes that the start, stop, and step columns
6073   ** are the last three columns in the virtual table. */
6074   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
6075   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
6076 
6077   aIdx[0] = aIdx[1] = aIdx[2] = -1;
6078   pConstraint = pIdxInfo->aConstraint;
6079   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6080     int iCol;    /* 0 for start, 1 for stop, 2 for step */
6081     int iMask;   /* bitmask for those column */
6082     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
6083     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
6084     assert( iCol>=0 && iCol<=2 );
6085     iMask = 1 << iCol;
6086     if( iCol==0 ) bStartSeen = 1;
6087     if( pConstraint->usable==0 ){
6088       unusableMask |=  iMask;
6089       continue;
6090     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
6091       idxNum |= iMask;
6092       aIdx[iCol] = i;
6093     }
6094   }
6095   for(i=0; i<3; i++){
6096     if( (j = aIdx[i])>=0 ){
6097       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
6098       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
6099     }
6100   }
6101   /* The current generate_column() implementation requires at least one
6102   ** argument (the START value).  Legacy versions assumed START=0 if the
6103   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
6104   ** to obtain the legacy behavior */
6105 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6106   if( !bStartSeen ){
6107     sqlite3_free(pVTab->zErrMsg);
6108     pVTab->zErrMsg = sqlite3_mprintf(
6109         "first argument to \"generate_series()\" missing or unusable");
6110     return SQLITE_ERROR;
6111   }
6112 #endif
6113   if( (unusableMask & ~idxNum)!=0 ){
6114     /* The start, stop, and step columns are inputs.  Therefore if there
6115     ** are unusable constraints on any of start, stop, or step then
6116     ** this plan is unusable */
6117     return SQLITE_CONSTRAINT;
6118   }
6119   if( (idxNum & 3)==3 ){
6120     /* Both start= and stop= boundaries are available.  This is the
6121     ** the preferred case */
6122     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
6123     pIdxInfo->estimatedRows = 1000;
6124     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
6125       if( pIdxInfo->aOrderBy[0].desc ){
6126         idxNum |= 8;
6127       }else{
6128         idxNum |= 16;
6129       }
6130       pIdxInfo->orderByConsumed = 1;
6131     }
6132   }else{
6133     /* If either boundary is missing, we have to generate a huge span
6134     ** of numbers.  Make this case very expensive so that the query
6135     ** planner will work hard to avoid it. */
6136     pIdxInfo->estimatedRows = 2147483647;
6137   }
6138   pIdxInfo->idxNum = idxNum;
6139   return SQLITE_OK;
6140 }
6141 
6142 /*
6143 ** This following structure defines all the methods for the
6144 ** generate_series virtual table.
6145 */
6146 static sqlite3_module seriesModule = {
6147   0,                         /* iVersion */
6148   0,                         /* xCreate */
6149   seriesConnect,             /* xConnect */
6150   seriesBestIndex,           /* xBestIndex */
6151   seriesDisconnect,          /* xDisconnect */
6152   0,                         /* xDestroy */
6153   seriesOpen,                /* xOpen - open a cursor */
6154   seriesClose,               /* xClose - close a cursor */
6155   seriesFilter,              /* xFilter - configure scan constraints */
6156   seriesNext,                /* xNext - advance a cursor */
6157   seriesEof,                 /* xEof - check for end of scan */
6158   seriesColumn,              /* xColumn - read data */
6159   seriesRowid,               /* xRowid - read data */
6160   0,                         /* xUpdate */
6161   0,                         /* xBegin */
6162   0,                         /* xSync */
6163   0,                         /* xCommit */
6164   0,                         /* xRollback */
6165   0,                         /* xFindMethod */
6166   0,                         /* xRename */
6167   0,                         /* xSavepoint */
6168   0,                         /* xRelease */
6169   0,                         /* xRollbackTo */
6170   0,                         /* xShadowName */
6171   0                          /* xIntegrity */
6172 };
6173 
6174 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6175 
6176 #ifdef _WIN32
6177 
6178 #endif
sqlite3_series_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)6179 int sqlite3_series_init(
6180   sqlite3 *db,
6181   char **pzErrMsg,
6182   const sqlite3_api_routines *pApi
6183 ){
6184   int rc = SQLITE_OK;
6185   SQLITE_EXTENSION_INIT2(pApi);
6186 #ifndef SQLITE_OMIT_VIRTUALTABLE
6187   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
6188     *pzErrMsg = sqlite3_mprintf(
6189         "generate_series() requires SQLite 3.8.12 or later");
6190     return SQLITE_ERROR;
6191   }
6192   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
6193 #endif
6194   return rc;
6195 }
6196 
6197 /************************* End ../ext/misc/series.c ********************/
6198 /************************* Begin ../ext/misc/regexp.c ******************/
6199 /*
6200 ** 2012-11-13
6201 **
6202 ** The author disclaims copyright to this source code.  In place of
6203 ** a legal notice, here is a blessing:
6204 **
6205 **    May you do good and not evil.
6206 **    May you find forgiveness for yourself and forgive others.
6207 **    May you share freely, never taking more than you give.
6208 **
6209 ******************************************************************************
6210 **
6211 ** The code in this file implements a compact but reasonably
6212 ** efficient regular-expression matcher for posix extended regular
6213 ** expressions against UTF8 text.
6214 **
6215 ** This file is an SQLite extension.  It registers a single function
6216 ** named "regexp(A,B)" where A is the regular expression and B is the
6217 ** string to be matched.  By registering this function, SQLite will also
6218 ** then implement the "B regexp A" operator.  Note that with the function
6219 ** the regular expression comes first, but with the operator it comes
6220 ** second.
6221 **
6222 **  The following regular expression syntax is supported:
6223 **
6224 **     X*      zero or more occurrences of X
6225 **     X+      one or more occurrences of X
6226 **     X?      zero or one occurrences of X
6227 **     X{p,q}  between p and q occurrences of X
6228 **     (X)     match X
6229 **     X|Y     X or Y
6230 **     ^X      X occurring at the beginning of the string
6231 **     X$      X occurring at the end of the string
6232 **     .       Match any single character
6233 **     \c      Character c where c is one of \{}()[]|*+?.
6234 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
6235 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
6236 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
6237 **     [abc]   Any single character from the set abc
6238 **     [^abc]  Any single character not in the set abc
6239 **     [a-z]   Any single character in the range a-z
6240 **     [^a-z]  Any single character not in the range a-z
6241 **     \b      Word boundary
6242 **     \w      Word character.  [A-Za-z0-9_]
6243 **     \W      Non-word character
6244 **     \d      Digit
6245 **     \D      Non-digit
6246 **     \s      Whitespace character
6247 **     \S      Non-whitespace character
6248 **
6249 ** A nondeterministic finite automaton (NFA) is used for matching, so the
6250 ** performance is bounded by O(N*M) where N is the size of the regular
6251 ** expression and M is the size of the input string.  The matcher never
6252 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
6253 ** to p copies of X following by q-p copies of X? and that the size of the
6254 ** regular expression in the O(N*M) performance bound is computed after
6255 ** this expansion.
6256 */
6257 #include <string.h>
6258 #include <stdlib.h>
6259 /* #include "sqlite3ext.h" */
6260 SQLITE_EXTENSION_INIT1
6261 
6262 /*
6263 ** The following #defines change the names of some functions implemented in
6264 ** this file to prevent name collisions with C-library functions of the
6265 ** same name.
6266 */
6267 #define re_match   sqlite3re_match
6268 #define re_compile sqlite3re_compile
6269 #define re_free    sqlite3re_free
6270 
6271 /* The end-of-input character */
6272 #define RE_EOF            0    /* End of input */
6273 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
6274 
6275 /* The NFA is implemented as sequence of opcodes taken from the following
6276 ** set.  Each opcode has a single integer argument.
6277 */
6278 #define RE_OP_MATCH       1    /* Match the one character in the argument */
6279 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
6280 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
6281 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
6282 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
6283 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
6284 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
6285 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
6286 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
6287 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
6288 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
6289 #define RE_OP_NOTWORD    12    /* Not a perl word character */
6290 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
6291 #define RE_OP_NOTDIGIT   14    /* Not a digit */
6292 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
6293 #define RE_OP_NOTSPACE   16    /* Not a digit */
6294 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
6295 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
6296 
6297 #if defined(SQLITE_DEBUG)
6298 /* Opcode names used for symbolic debugging */
6299 static const char *ReOpName[] = {
6300   "EOF",
6301   "MATCH",
6302   "ANY",
6303   "ANYSTAR",
6304   "FORK",
6305   "GOTO",
6306   "ACCEPT",
6307   "CC_INC",
6308   "CC_EXC",
6309   "CC_VALUE",
6310   "CC_RANGE",
6311   "WORD",
6312   "NOTWORD",
6313   "DIGIT",
6314   "NOTDIGIT",
6315   "SPACE",
6316   "NOTSPACE",
6317   "BOUNDARY",
6318   "ATSTART",
6319 };
6320 #endif /* SQLITE_DEBUG */
6321 
6322 
6323 /* Each opcode is a "state" in the NFA */
6324 typedef unsigned short ReStateNumber;
6325 
6326 /* Because this is an NFA and not a DFA, multiple states can be active at
6327 ** once.  An instance of the following object records all active states in
6328 ** the NFA.  The implementation is optimized for the common case where the
6329 ** number of actives states is small.
6330 */
6331 typedef struct ReStateSet {
6332   unsigned nState;            /* Number of current states */
6333   ReStateNumber *aState;      /* Current states */
6334 } ReStateSet;
6335 
6336 /* An input string read one character at a time.
6337 */
6338 typedef struct ReInput ReInput;
6339 struct ReInput {
6340   const unsigned char *z;  /* All text */
6341   int i;                   /* Next byte to read */
6342   int mx;                  /* EOF when i>=mx */
6343 };
6344 
6345 /* A compiled NFA (or an NFA that is in the process of being compiled) is
6346 ** an instance of the following object.
6347 */
6348 typedef struct ReCompiled ReCompiled;
6349 struct ReCompiled {
6350   ReInput sIn;                /* Regular expression text */
6351   const char *zErr;           /* Error message to return */
6352   char *aOp;                  /* Operators for the virtual machine */
6353   int *aArg;                  /* Arguments to each operator */
6354   unsigned (*xNextChar)(ReInput*);  /* Next character function */
6355   unsigned char zInit[12];    /* Initial text to match */
6356   int nInit;                  /* Number of bytes in zInit */
6357   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
6358   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
6359 };
6360 
6361 /* Add a state to the given state set if it is not already there */
re_add_state(ReStateSet * pSet,int newState)6362 static void re_add_state(ReStateSet *pSet, int newState){
6363   unsigned i;
6364   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
6365   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
6366 }
6367 
6368 /* Extract the next unicode character from *pzIn and return it.  Advance
6369 ** *pzIn to the first byte past the end of the character returned.  To
6370 ** be clear:  this routine converts utf8 to unicode.  This routine is
6371 ** optimized for the common case where the next character is a single byte.
6372 */
re_next_char(ReInput * p)6373 static unsigned re_next_char(ReInput *p){
6374   unsigned c;
6375   if( p->i>=p->mx ) return 0;
6376   c = p->z[p->i++];
6377   if( c>=0x80 ){
6378     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
6379       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
6380       if( c<0x80 ) c = 0xfffd;
6381     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
6382            && (p->z[p->i+1]&0xc0)==0x80 ){
6383       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
6384       p->i += 2;
6385       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
6386     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
6387            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
6388       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
6389                        | (p->z[p->i+2]&0x3f);
6390       p->i += 3;
6391       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
6392     }else{
6393       c = 0xfffd;
6394     }
6395   }
6396   return c;
6397 }
re_next_char_nocase(ReInput * p)6398 static unsigned re_next_char_nocase(ReInput *p){
6399   unsigned c = re_next_char(p);
6400   if( c>='A' && c<='Z' ) c += 'a' - 'A';
6401   return c;
6402 }
6403 
6404 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
re_word_char(int c)6405 static int re_word_char(int c){
6406   return (c>='0' && c<='9') || (c>='a' && c<='z')
6407       || (c>='A' && c<='Z') || c=='_';
6408 }
6409 
6410 /* Return true if c is a "digit" character:  [0-9] */
re_digit_char(int c)6411 static int re_digit_char(int c){
6412   return (c>='0' && c<='9');
6413 }
6414 
6415 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
re_space_char(int c)6416 static int re_space_char(int c){
6417   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
6418 }
6419 
6420 /* Run a compiled regular expression on the zero-terminated input
6421 ** string zIn[].  Return true on a match and false if there is no match.
6422 */
re_match(ReCompiled * pRe,const unsigned char * zIn,int nIn)6423 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
6424   ReStateSet aStateSet[2], *pThis, *pNext;
6425   ReStateNumber aSpace[100];
6426   ReStateNumber *pToFree;
6427   unsigned int i = 0;
6428   unsigned int iSwap = 0;
6429   int c = RE_START;
6430   int cPrev = 0;
6431   int rc = 0;
6432   ReInput in;
6433 
6434   in.z = zIn;
6435   in.i = 0;
6436   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
6437 
6438   /* Look for the initial prefix match, if there is one. */
6439   if( pRe->nInit ){
6440     unsigned char x = pRe->zInit[0];
6441     while( in.i+pRe->nInit<=in.mx
6442      && (zIn[in.i]!=x ||
6443          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
6444     ){
6445       in.i++;
6446     }
6447     if( in.i+pRe->nInit>in.mx ) return 0;
6448     c = RE_START-1;
6449   }
6450 
6451   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
6452     pToFree = 0;
6453     aStateSet[0].aState = aSpace;
6454   }else{
6455     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
6456     if( pToFree==0 ) return -1;
6457     aStateSet[0].aState = pToFree;
6458   }
6459   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
6460   pNext = &aStateSet[1];
6461   pNext->nState = 0;
6462   re_add_state(pNext, 0);
6463   while( c!=RE_EOF && pNext->nState>0 ){
6464     cPrev = c;
6465     c = pRe->xNextChar(&in);
6466     pThis = pNext;
6467     pNext = &aStateSet[iSwap];
6468     iSwap = 1 - iSwap;
6469     pNext->nState = 0;
6470     for(i=0; i<pThis->nState; i++){
6471       int x = pThis->aState[i];
6472       switch( pRe->aOp[x] ){
6473         case RE_OP_MATCH: {
6474           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
6475           break;
6476         }
6477         case RE_OP_ATSTART: {
6478           if( cPrev==RE_START ) re_add_state(pThis, x+1);
6479           break;
6480         }
6481         case RE_OP_ANY: {
6482           if( c!=0 ) re_add_state(pNext, x+1);
6483           break;
6484         }
6485         case RE_OP_WORD: {
6486           if( re_word_char(c) ) re_add_state(pNext, x+1);
6487           break;
6488         }
6489         case RE_OP_NOTWORD: {
6490           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
6491           break;
6492         }
6493         case RE_OP_DIGIT: {
6494           if( re_digit_char(c) ) re_add_state(pNext, x+1);
6495           break;
6496         }
6497         case RE_OP_NOTDIGIT: {
6498           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
6499           break;
6500         }
6501         case RE_OP_SPACE: {
6502           if( re_space_char(c) ) re_add_state(pNext, x+1);
6503           break;
6504         }
6505         case RE_OP_NOTSPACE: {
6506           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
6507           break;
6508         }
6509         case RE_OP_BOUNDARY: {
6510           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
6511           break;
6512         }
6513         case RE_OP_ANYSTAR: {
6514           re_add_state(pNext, x);
6515           re_add_state(pThis, x+1);
6516           break;
6517         }
6518         case RE_OP_FORK: {
6519           re_add_state(pThis, x+pRe->aArg[x]);
6520           re_add_state(pThis, x+1);
6521           break;
6522         }
6523         case RE_OP_GOTO: {
6524           re_add_state(pThis, x+pRe->aArg[x]);
6525           break;
6526         }
6527         case RE_OP_ACCEPT: {
6528           rc = 1;
6529           goto re_match_end;
6530         }
6531         case RE_OP_CC_EXC: {
6532           if( c==0 ) break;
6533           /* fall-through */ goto re_op_cc_inc;
6534         }
6535         case RE_OP_CC_INC: re_op_cc_inc: {
6536           int j = 1;
6537           int n = pRe->aArg[x];
6538           int hit = 0;
6539           for(j=1; j>0 && j<n; j++){
6540             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
6541               if( pRe->aArg[x+j]==c ){
6542                 hit = 1;
6543                 j = -1;
6544               }
6545             }else{
6546               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
6547                 hit = 1;
6548                 j = -1;
6549               }else{
6550                 j++;
6551               }
6552             }
6553           }
6554           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
6555           if( hit ) re_add_state(pNext, x+n);
6556           break;
6557         }
6558       }
6559     }
6560   }
6561   for(i=0; i<pNext->nState; i++){
6562     int x = pNext->aState[i];
6563     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
6564     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
6565   }
6566 re_match_end:
6567   sqlite3_free(pToFree);
6568   return rc;
6569 }
6570 
6571 /* Resize the opcode and argument arrays for an RE under construction.
6572 */
re_resize(ReCompiled * p,int N)6573 static int re_resize(ReCompiled *p, int N){
6574   char *aOp;
6575   int *aArg;
6576   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
6577   if( aOp==0 ) return 1;
6578   p->aOp = aOp;
6579   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
6580   if( aArg==0 ) return 1;
6581   p->aArg = aArg;
6582   p->nAlloc = N;
6583   return 0;
6584 }
6585 
6586 /* Insert a new opcode and argument into an RE under construction.  The
6587 ** insertion point is just prior to existing opcode iBefore.
6588 */
re_insert(ReCompiled * p,int iBefore,int op,int arg)6589 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
6590   int i;
6591   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
6592   for(i=p->nState; i>iBefore; i--){
6593     p->aOp[i] = p->aOp[i-1];
6594     p->aArg[i] = p->aArg[i-1];
6595   }
6596   p->nState++;
6597   p->aOp[iBefore] = (char)op;
6598   p->aArg[iBefore] = arg;
6599   return iBefore;
6600 }
6601 
6602 /* Append a new opcode and argument to the end of the RE under construction.
6603 */
re_append(ReCompiled * p,int op,int arg)6604 static int re_append(ReCompiled *p, int op, int arg){
6605   return re_insert(p, p->nState, op, arg);
6606 }
6607 
6608 /* Make a copy of N opcodes starting at iStart onto the end of the RE
6609 ** under construction.
6610 */
re_copy(ReCompiled * p,int iStart,int N)6611 static void re_copy(ReCompiled *p, int iStart, int N){
6612   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
6613   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
6614   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
6615   p->nState += N;
6616 }
6617 
6618 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
6619 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
6620 ** c is not a hex digit *pV is unchanged.
6621 */
re_hex(int c,int * pV)6622 static int re_hex(int c, int *pV){
6623   if( c>='0' && c<='9' ){
6624     c -= '0';
6625   }else if( c>='a' && c<='f' ){
6626     c -= 'a' - 10;
6627   }else if( c>='A' && c<='F' ){
6628     c -= 'A' - 10;
6629   }else{
6630     return 0;
6631   }
6632   *pV = (*pV)*16 + (c & 0xff);
6633   return 1;
6634 }
6635 
6636 /* A backslash character has been seen, read the next character and
6637 ** return its interpretation.
6638 */
re_esc_char(ReCompiled * p)6639 static unsigned re_esc_char(ReCompiled *p){
6640   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
6641   static const char zTrans[] = "\a\f\n\r\t\v";
6642   int i, v = 0;
6643   char c;
6644   if( p->sIn.i>=p->sIn.mx ) return 0;
6645   c = p->sIn.z[p->sIn.i];
6646   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
6647     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6648     if( re_hex(zIn[1],&v)
6649      && re_hex(zIn[2],&v)
6650      && re_hex(zIn[3],&v)
6651      && re_hex(zIn[4],&v)
6652     ){
6653       p->sIn.i += 5;
6654       return v;
6655     }
6656   }
6657   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
6658     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6659     if( re_hex(zIn[1],&v)
6660      && re_hex(zIn[2],&v)
6661     ){
6662       p->sIn.i += 3;
6663       return v;
6664     }
6665   }
6666   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
6667   if( zEsc[i] ){
6668     if( i<6 ) c = zTrans[i];
6669     p->sIn.i++;
6670   }else{
6671     p->zErr = "unknown \\ escape";
6672   }
6673   return c;
6674 }
6675 
6676 /* Forward declaration */
6677 static const char *re_subcompile_string(ReCompiled*);
6678 
6679 /* Peek at the next byte of input */
rePeek(ReCompiled * p)6680 static unsigned char rePeek(ReCompiled *p){
6681   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
6682 }
6683 
6684 /* Compile RE text into a sequence of opcodes.  Continue up to the
6685 ** first unmatched ")" character, then return.  If an error is found,
6686 ** return a pointer to the error message string.
6687 */
re_subcompile_re(ReCompiled * p)6688 static const char *re_subcompile_re(ReCompiled *p){
6689   const char *zErr;
6690   int iStart, iEnd, iGoto;
6691   iStart = p->nState;
6692   zErr = re_subcompile_string(p);
6693   if( zErr ) return zErr;
6694   while( rePeek(p)=='|' ){
6695     iEnd = p->nState;
6696     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
6697     iGoto = re_append(p, RE_OP_GOTO, 0);
6698     p->sIn.i++;
6699     zErr = re_subcompile_string(p);
6700     if( zErr ) return zErr;
6701     p->aArg[iGoto] = p->nState - iGoto;
6702   }
6703   return 0;
6704 }
6705 
6706 /* Compile an element of regular expression text (anything that can be
6707 ** an operand to the "|" operator).  Return NULL on success or a pointer
6708 ** to the error message if there is a problem.
6709 */
re_subcompile_string(ReCompiled * p)6710 static const char *re_subcompile_string(ReCompiled *p){
6711   int iPrev = -1;
6712   int iStart;
6713   unsigned c;
6714   const char *zErr;
6715   while( (c = p->xNextChar(&p->sIn))!=0 ){
6716     iStart = p->nState;
6717     switch( c ){
6718       case '|':
6719       case ')': {
6720         p->sIn.i--;
6721         return 0;
6722       }
6723       case '(': {
6724         zErr = re_subcompile_re(p);
6725         if( zErr ) return zErr;
6726         if( rePeek(p)!=')' ) return "unmatched '('";
6727         p->sIn.i++;
6728         break;
6729       }
6730       case '.': {
6731         if( rePeek(p)=='*' ){
6732           re_append(p, RE_OP_ANYSTAR, 0);
6733           p->sIn.i++;
6734         }else{
6735           re_append(p, RE_OP_ANY, 0);
6736         }
6737         break;
6738       }
6739       case '*': {
6740         if( iPrev<0 ) return "'*' without operand";
6741         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
6742         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
6743         break;
6744       }
6745       case '+': {
6746         if( iPrev<0 ) return "'+' without operand";
6747         re_append(p, RE_OP_FORK, iPrev - p->nState);
6748         break;
6749       }
6750       case '?': {
6751         if( iPrev<0 ) return "'?' without operand";
6752         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
6753         break;
6754       }
6755       case '$': {
6756         re_append(p, RE_OP_MATCH, RE_EOF);
6757         break;
6758       }
6759       case '^': {
6760         re_append(p, RE_OP_ATSTART, 0);
6761         break;
6762       }
6763       case '{': {
6764         int m = 0, n = 0;
6765         int sz, j;
6766         if( iPrev<0 ) return "'{m,n}' without operand";
6767         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
6768         n = m;
6769         if( c==',' ){
6770           p->sIn.i++;
6771           n = 0;
6772           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
6773         }
6774         if( c!='}' ) return "unmatched '{'";
6775         if( n>0 && n<m ) return "n less than m in '{m,n}'";
6776         p->sIn.i++;
6777         sz = p->nState - iPrev;
6778         if( m==0 ){
6779           if( n==0 ) return "both m and n are zero in '{m,n}'";
6780           re_insert(p, iPrev, RE_OP_FORK, sz+1);
6781           iPrev++;
6782           n--;
6783         }else{
6784           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
6785         }
6786         for(j=m; j<n; j++){
6787           re_append(p, RE_OP_FORK, sz+1);
6788           re_copy(p, iPrev, sz);
6789         }
6790         if( n==0 && m>0 ){
6791           re_append(p, RE_OP_FORK, -sz);
6792         }
6793         break;
6794       }
6795       case '[': {
6796         unsigned int iFirst = p->nState;
6797         if( rePeek(p)=='^' ){
6798           re_append(p, RE_OP_CC_EXC, 0);
6799           p->sIn.i++;
6800         }else{
6801           re_append(p, RE_OP_CC_INC, 0);
6802         }
6803         while( (c = p->xNextChar(&p->sIn))!=0 ){
6804           if( c=='[' && rePeek(p)==':' ){
6805             return "POSIX character classes not supported";
6806           }
6807           if( c=='\\' ) c = re_esc_char(p);
6808           if( rePeek(p)=='-' ){
6809             re_append(p, RE_OP_CC_RANGE, c);
6810             p->sIn.i++;
6811             c = p->xNextChar(&p->sIn);
6812             if( c=='\\' ) c = re_esc_char(p);
6813             re_append(p, RE_OP_CC_RANGE, c);
6814           }else{
6815             re_append(p, RE_OP_CC_VALUE, c);
6816           }
6817           if( rePeek(p)==']' ){ p->sIn.i++; break; }
6818         }
6819         if( c==0 ) return "unclosed '['";
6820         if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
6821         break;
6822       }
6823       case '\\': {
6824         int specialOp = 0;
6825         switch( rePeek(p) ){
6826           case 'b': specialOp = RE_OP_BOUNDARY;   break;
6827           case 'd': specialOp = RE_OP_DIGIT;      break;
6828           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
6829           case 's': specialOp = RE_OP_SPACE;      break;
6830           case 'S': specialOp = RE_OP_NOTSPACE;   break;
6831           case 'w': specialOp = RE_OP_WORD;       break;
6832           case 'W': specialOp = RE_OP_NOTWORD;    break;
6833         }
6834         if( specialOp ){
6835           p->sIn.i++;
6836           re_append(p, specialOp, 0);
6837         }else{
6838           c = re_esc_char(p);
6839           re_append(p, RE_OP_MATCH, c);
6840         }
6841         break;
6842       }
6843       default: {
6844         re_append(p, RE_OP_MATCH, c);
6845         break;
6846       }
6847     }
6848     iPrev = iStart;
6849   }
6850   return 0;
6851 }
6852 
6853 /* Free and reclaim all the memory used by a previously compiled
6854 ** regular expression.  Applications should invoke this routine once
6855 ** for every call to re_compile() to avoid memory leaks.
6856 */
re_free(ReCompiled * pRe)6857 static void re_free(ReCompiled *pRe){
6858   if( pRe ){
6859     sqlite3_free(pRe->aOp);
6860     sqlite3_free(pRe->aArg);
6861     sqlite3_free(pRe);
6862   }
6863 }
6864 
6865 /*
6866 ** Compile a textual regular expression in zIn[] into a compiled regular
6867 ** expression suitable for us by re_match() and return a pointer to the
6868 ** compiled regular expression in *ppRe.  Return NULL on success or an
6869 ** error message if something goes wrong.
6870 */
re_compile(ReCompiled ** ppRe,const char * zIn,int noCase)6871 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
6872   ReCompiled *pRe;
6873   const char *zErr;
6874   int i, j;
6875 
6876   *ppRe = 0;
6877   pRe = sqlite3_malloc( sizeof(*pRe) );
6878   if( pRe==0 ){
6879     return "out of memory";
6880   }
6881   memset(pRe, 0, sizeof(*pRe));
6882   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
6883   if( re_resize(pRe, 30) ){
6884     re_free(pRe);
6885     return "out of memory";
6886   }
6887   if( zIn[0]=='^' ){
6888     zIn++;
6889   }else{
6890     re_append(pRe, RE_OP_ANYSTAR, 0);
6891   }
6892   pRe->sIn.z = (unsigned char*)zIn;
6893   pRe->sIn.i = 0;
6894   pRe->sIn.mx = (int)strlen(zIn);
6895   zErr = re_subcompile_re(pRe);
6896   if( zErr ){
6897     re_free(pRe);
6898     return zErr;
6899   }
6900   if( pRe->sIn.i>=pRe->sIn.mx ){
6901     re_append(pRe, RE_OP_ACCEPT, 0);
6902     *ppRe = pRe;
6903   }else{
6904     re_free(pRe);
6905     return "unrecognized character";
6906   }
6907 
6908   /* The following is a performance optimization.  If the regex begins with
6909   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
6910   ** one or more matching characters, enter those matching characters into
6911   ** zInit[].  The re_match() routine can then search ahead in the input
6912   ** string looking for the initial match without having to run the whole
6913   ** regex engine over the string.  Do not worry about trying to match
6914   ** unicode characters beyond plane 0 - those are very rare and this is
6915   ** just an optimization. */
6916   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
6917     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
6918       unsigned x = pRe->aArg[i];
6919       if( x<=0x7f ){
6920         pRe->zInit[j++] = (unsigned char)x;
6921       }else if( x<=0x7ff ){
6922         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
6923         pRe->zInit[j++] = 0x80 | (x&0x3f);
6924       }else if( x<=0xffff ){
6925         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
6926         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
6927         pRe->zInit[j++] = 0x80 | (x&0x3f);
6928       }else{
6929         break;
6930       }
6931     }
6932     if( j>0 && pRe->zInit[j-1]==0 ) j--;
6933     pRe->nInit = j;
6934   }
6935   return pRe->zErr;
6936 }
6937 
6938 /*
6939 ** Implementation of the regexp() SQL function.  This function implements
6940 ** the build-in REGEXP operator.  The first argument to the function is the
6941 ** pattern and the second argument is the string.  So, the SQL statements:
6942 **
6943 **       A REGEXP B
6944 **
6945 ** is implemented as regexp(B,A).
6946 */
re_sql_func(sqlite3_context * context,int argc,sqlite3_value ** argv)6947 static void re_sql_func(
6948   sqlite3_context *context,
6949   int argc,
6950   sqlite3_value **argv
6951 ){
6952   ReCompiled *pRe;          /* Compiled regular expression */
6953   const char *zPattern;     /* The regular expression */
6954   const unsigned char *zStr;/* String being searched */
6955   const char *zErr;         /* Compile error message */
6956   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
6957 
6958   (void)argc;  /* Unused */
6959   pRe = sqlite3_get_auxdata(context, 0);
6960   if( pRe==0 ){
6961     zPattern = (const char*)sqlite3_value_text(argv[0]);
6962     if( zPattern==0 ) return;
6963     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
6964     if( zErr ){
6965       re_free(pRe);
6966       sqlite3_result_error(context, zErr, -1);
6967       return;
6968     }
6969     if( pRe==0 ){
6970       sqlite3_result_error_nomem(context);
6971       return;
6972     }
6973     setAux = 1;
6974   }
6975   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
6976   if( zStr!=0 ){
6977     sqlite3_result_int(context, re_match(pRe, zStr, -1));
6978   }
6979   if( setAux ){
6980     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
6981   }
6982 }
6983 
6984 #if defined(SQLITE_DEBUG)
6985 /*
6986 ** This function is used for testing and debugging only.  It is only available
6987 ** if the SQLITE_DEBUG compile-time option is used.
6988 **
6989 ** Compile a regular expression and then convert the compiled expression into
6990 ** text and return that text.
6991 */
re_bytecode_func(sqlite3_context * context,int argc,sqlite3_value ** argv)6992 static void re_bytecode_func(
6993   sqlite3_context *context,
6994   int argc,
6995   sqlite3_value **argv
6996 ){
6997   const char *zPattern;
6998   const char *zErr;
6999   ReCompiled *pRe;
7000   sqlite3_str *pStr;
7001   int i;
7002   int n;
7003   char *z;
7004   (void)argc;
7005 
7006   zPattern = (const char*)sqlite3_value_text(argv[0]);
7007   if( zPattern==0 ) return;
7008   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7009   if( zErr ){
7010     re_free(pRe);
7011     sqlite3_result_error(context, zErr, -1);
7012     return;
7013   }
7014   if( pRe==0 ){
7015     sqlite3_result_error_nomem(context);
7016     return;
7017   }
7018   pStr = sqlite3_str_new(0);
7019   if( pStr==0 ) goto re_bytecode_func_err;
7020   if( pRe->nInit>0 ){
7021     sqlite3_str_appendf(pStr, "INIT     ");
7022     for(i=0; i<pRe->nInit; i++){
7023       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
7024     }
7025     sqlite3_str_appendf(pStr, "\n");
7026   }
7027   for(i=0; (unsigned)i<pRe->nState; i++){
7028     sqlite3_str_appendf(pStr, "%-8s %4d\n",
7029          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
7030   }
7031   n = sqlite3_str_length(pStr);
7032   z = sqlite3_str_finish(pStr);
7033   if( n==0 ){
7034     sqlite3_free(z);
7035   }else{
7036     sqlite3_result_text(context, z, n-1, sqlite3_free);
7037   }
7038 
7039 re_bytecode_func_err:
7040   re_free(pRe);
7041 }
7042 
7043 #endif /* SQLITE_DEBUG */
7044 
7045 
7046 /*
7047 ** Invoke this routine to register the regexp() function with the
7048 ** SQLite database connection.
7049 */
7050 #ifdef _WIN32
7051 
7052 #endif
sqlite3_regexp_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)7053 int sqlite3_regexp_init(
7054   sqlite3 *db,
7055   char **pzErrMsg,
7056   const sqlite3_api_routines *pApi
7057 ){
7058   int rc = SQLITE_OK;
7059   SQLITE_EXTENSION_INIT2(pApi);
7060   (void)pzErrMsg;  /* Unused */
7061   rc = sqlite3_create_function(db, "regexp", 2,
7062                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7063                             0, re_sql_func, 0, 0);
7064   if( rc==SQLITE_OK ){
7065     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
7066     ** of regexp(PATTERN,STRING). */
7067     rc = sqlite3_create_function(db, "regexpi", 2,
7068                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7069                             (void*)db, re_sql_func, 0, 0);
7070 #if defined(SQLITE_DEBUG)
7071     if( rc==SQLITE_OK ){
7072       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
7073                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7074                             0, re_bytecode_func, 0, 0);
7075     }
7076 #endif /* SQLITE_DEBUG */
7077   }
7078   return rc;
7079 }
7080 
7081 /************************* End ../ext/misc/regexp.c ********************/
7082 #ifndef SQLITE_SHELL_FIDDLE
7083 /************************* Begin ../ext/misc/fileio.c ******************/
7084 /*
7085 ** 2014-06-13
7086 **
7087 ** The author disclaims copyright to this source code.  In place of
7088 ** a legal notice, here is a blessing:
7089 **
7090 **    May you do good and not evil.
7091 **    May you find forgiveness for yourself and forgive others.
7092 **    May you share freely, never taking more than you give.
7093 **
7094 ******************************************************************************
7095 **
7096 ** This SQLite extension implements SQL functions readfile() and
7097 ** writefile(), and eponymous virtual type "fsdir".
7098 **
7099 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
7100 **
7101 **   If neither of the optional arguments is present, then this UDF
7102 **   function writes blob DATA to file FILE. If successful, the number
7103 **   of bytes written is returned. If an error occurs, NULL is returned.
7104 **
7105 **   If the first option argument - MODE - is present, then it must
7106 **   be passed an integer value that corresponds to a POSIX mode
7107 **   value (file type + permissions, as returned in the stat.st_mode
7108 **   field by the stat() system call). Three types of files may
7109 **   be written/created:
7110 **
7111 **     regular files:  (mode & 0170000)==0100000
7112 **     symbolic links: (mode & 0170000)==0120000
7113 **     directories:    (mode & 0170000)==0040000
7114 **
7115 **   For a directory, the DATA is ignored. For a symbolic link, it is
7116 **   interpreted as text and used as the target of the link. For a
7117 **   regular file, it is interpreted as a blob and written into the
7118 **   named file. Regardless of the type of file, its permissions are
7119 **   set to (mode & 0777) before returning.
7120 **
7121 **   If the optional MTIME argument is present, then it is interpreted
7122 **   as an integer - the number of seconds since the unix epoch. The
7123 **   modification-time of the target file is set to this value before
7124 **   returning.
7125 **
7126 **   If three or more arguments are passed to this function and an
7127 **   error is encountered, an exception is raised.
7128 **
7129 ** READFILE(FILE):
7130 **
7131 **   Read and return the contents of file FILE (type blob) from disk.
7132 **
7133 ** FSDIR:
7134 **
7135 **   Used as follows:
7136 **
7137 **     SELECT * FROM fsdir($path [, $dir]);
7138 **
7139 **   Parameter $path is an absolute or relative pathname. If the file that it
7140 **   refers to does not exist, it is an error. If the path refers to a regular
7141 **   file or symbolic link, it returns a single row. Or, if the path refers
7142 **   to a directory, it returns one row for the directory, and one row for each
7143 **   file within the hierarchy rooted at $path.
7144 **
7145 **   Each row has the following columns:
7146 **
7147 **     name:  Path to file or directory (text value).
7148 **     mode:  Value of stat.st_mode for directory entry (an integer).
7149 **     mtime: Value of stat.st_mtime for directory entry (an integer).
7150 **     data:  For a regular file, a blob containing the file data. For a
7151 **            symlink, a text value containing the text of the link. For a
7152 **            directory, NULL.
7153 **
7154 **   If a non-NULL value is specified for the optional $dir parameter and
7155 **   $path is a relative path, then $path is interpreted relative to $dir.
7156 **   And the paths returned in the "name" column of the table are also
7157 **   relative to directory $dir.
7158 **
7159 ** Notes on building this extension for Windows:
7160 **   Unless linked statically with the SQLite library, a preprocessor
7161 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
7162 **   DLL form of this extension for WIN32. See its use below for details.
7163 */
7164 /* #include "sqlite3ext.h" */
7165 SQLITE_EXTENSION_INIT1
7166 #include <stdio.h>
7167 #include <string.h>
7168 #include <assert.h>
7169 
7170 #include <sys/types.h>
7171 #include <sys/stat.h>
7172 #include <fcntl.h>
7173 #if !defined(_WIN32) && !defined(WIN32)
7174 #  include <unistd.h>
7175 #  include <dirent.h>
7176 #  include <utime.h>
7177 #  include <sys/time.h>
7178 #else
7179 #  include "windows.h"
7180 #  include <io.h>
7181 #  include <direct.h>
7182 /* #  include "test_windirent.h" */
7183 #  define dirent DIRENT
7184 #  ifndef chmod
7185 #    define chmod _chmod
7186 #  endif
7187 #  ifndef stat
7188 #    define stat _stat
7189 #  endif
7190 #  define mkdir(path,mode) _mkdir(path)
7191 #  define lstat(path,buf) stat(path,buf)
7192 #endif
7193 #include <time.h>
7194 #include <errno.h>
7195 
7196 
7197 /*
7198 ** Structure of the fsdir() table-valued function
7199 */
7200                  /*    0    1    2     3    4           5             */
7201 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
7202 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
7203 #define FSDIR_COLUMN_MODE     1     /* Access mode */
7204 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
7205 #define FSDIR_COLUMN_DATA     3     /* File content */
7206 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
7207 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
7208 
7209 
7210 /*
7211 ** Set the result stored by context ctx to a blob containing the
7212 ** contents of file zName.  Or, leave the result unchanged (NULL)
7213 ** if the file does not exist or is unreadable.
7214 **
7215 ** If the file exceeds the SQLite blob size limit, through an
7216 ** SQLITE_TOOBIG error.
7217 **
7218 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
7219 ** off of disk.
7220 */
readFileContents(sqlite3_context * ctx,const char * zName)7221 static void readFileContents(sqlite3_context *ctx, const char *zName){
7222   FILE *in;
7223   sqlite3_int64 nIn;
7224   void *pBuf;
7225   sqlite3 *db;
7226   int mxBlob;
7227 
7228   in = fopen(zName, "rb");
7229   if( in==0 ){
7230     /* File does not exist or is unreadable. Leave the result set to NULL. */
7231     return;
7232   }
7233   fseek(in, 0, SEEK_END);
7234   nIn = ftell(in);
7235   rewind(in);
7236   db = sqlite3_context_db_handle(ctx);
7237   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
7238   if( nIn>mxBlob ){
7239     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
7240     fclose(in);
7241     return;
7242   }
7243   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
7244   if( pBuf==0 ){
7245     sqlite3_result_error_nomem(ctx);
7246     fclose(in);
7247     return;
7248   }
7249   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
7250     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
7251   }else{
7252     sqlite3_result_error_code(ctx, SQLITE_IOERR);
7253     sqlite3_free(pBuf);
7254   }
7255   fclose(in);
7256 }
7257 
7258 /*
7259 ** Implementation of the "readfile(X)" SQL function.  The entire content
7260 ** of the file named X is read and returned as a BLOB.  NULL is returned
7261 ** if the file does not exist or is unreadable.
7262 */
readfileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7263 static void readfileFunc(
7264   sqlite3_context *context,
7265   int argc,
7266   sqlite3_value **argv
7267 ){
7268   const char *zName;
7269   (void)(argc);  /* Unused parameter */
7270   zName = (const char*)sqlite3_value_text(argv[0]);
7271   if( zName==0 ) return;
7272   readFileContents(context, zName);
7273 }
7274 
7275 /*
7276 ** Set the error message contained in context ctx to the results of
7277 ** vprintf(zFmt, ...).
7278 */
ctxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)7279 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7280   char *zMsg = 0;
7281   va_list ap;
7282   va_start(ap, zFmt);
7283   zMsg = sqlite3_vmprintf(zFmt, ap);
7284   sqlite3_result_error(ctx, zMsg, -1);
7285   sqlite3_free(zMsg);
7286   va_end(ap);
7287 }
7288 
7289 #if defined(_WIN32)
7290 /*
7291 ** This function is designed to convert a Win32 FILETIME structure into the
7292 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
7293 */
fileTimeToUnixTime(LPFILETIME pFileTime)7294 static sqlite3_uint64 fileTimeToUnixTime(
7295   LPFILETIME pFileTime
7296 ){
7297   SYSTEMTIME epochSystemTime;
7298   ULARGE_INTEGER epochIntervals;
7299   FILETIME epochFileTime;
7300   ULARGE_INTEGER fileIntervals;
7301 
7302   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
7303   epochSystemTime.wYear = 1970;
7304   epochSystemTime.wMonth = 1;
7305   epochSystemTime.wDay = 1;
7306   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
7307   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
7308   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
7309 
7310   fileIntervals.LowPart = pFileTime->dwLowDateTime;
7311   fileIntervals.HighPart = pFileTime->dwHighDateTime;
7312 
7313   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
7314 }
7315 
7316 
7317 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
7318 #  /* To allow a standalone DLL, use this next replacement function: */
7319 #  undef sqlite3_win32_utf8_to_unicode
7320 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
7321 #
utf8_to_utf16(const char * z)7322 LPWSTR utf8_to_utf16(const char *z){
7323   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
7324   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
7325   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
7326     return rv;
7327   sqlite3_free(rv);
7328   return 0;
7329 }
7330 #endif
7331 
7332 /*
7333 ** This function attempts to normalize the time values found in the stat()
7334 ** buffer to UTC.  This is necessary on Win32, where the runtime library
7335 ** appears to return these values as local times.
7336 */
statTimesToUtc(const char * zPath,struct stat * pStatBuf)7337 static void statTimesToUtc(
7338   const char *zPath,
7339   struct stat *pStatBuf
7340 ){
7341   HANDLE hFindFile;
7342   WIN32_FIND_DATAW fd;
7343   LPWSTR zUnicodeName;
7344   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7345   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
7346   if( zUnicodeName ){
7347     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
7348     hFindFile = FindFirstFileW(zUnicodeName, &fd);
7349     if( hFindFile!=NULL ){
7350       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
7351       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
7352       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
7353       FindClose(hFindFile);
7354     }
7355     sqlite3_free(zUnicodeName);
7356   }
7357 }
7358 #endif
7359 
7360 /*
7361 ** This function is used in place of stat().  On Windows, special handling
7362 ** is required in order for the included time to be returned as UTC.  On all
7363 ** other systems, this function simply calls stat().
7364 */
fileStat(const char * zPath,struct stat * pStatBuf)7365 static int fileStat(
7366   const char *zPath,
7367   struct stat *pStatBuf
7368 ){
7369 #if defined(_WIN32)
7370   int rc = stat(zPath, pStatBuf);
7371   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7372   return rc;
7373 #else
7374   return stat(zPath, pStatBuf);
7375 #endif
7376 }
7377 
7378 /*
7379 ** This function is used in place of lstat().  On Windows, special handling
7380 ** is required in order for the included time to be returned as UTC.  On all
7381 ** other systems, this function simply calls lstat().
7382 */
fileLinkStat(const char * zPath,struct stat * pStatBuf)7383 static int fileLinkStat(
7384   const char *zPath,
7385   struct stat *pStatBuf
7386 ){
7387 #if defined(_WIN32)
7388   int rc = lstat(zPath, pStatBuf);
7389   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7390   return rc;
7391 #else
7392   return lstat(zPath, pStatBuf);
7393 #endif
7394 }
7395 
7396 /*
7397 ** Argument zFile is the name of a file that will be created and/or written
7398 ** by SQL function writefile(). This function ensures that the directory
7399 ** zFile will be written to exists, creating it if required. The permissions
7400 ** for any path components created by this function are set in accordance
7401 ** with the current umask.
7402 **
7403 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
7404 ** SQLITE_OK is returned if the directory is successfully created, or
7405 ** SQLITE_ERROR otherwise.
7406 */
makeDirectory(const char * zFile)7407 static int makeDirectory(
7408   const char *zFile
7409 ){
7410   char *zCopy = sqlite3_mprintf("%s", zFile);
7411   int rc = SQLITE_OK;
7412 
7413   if( zCopy==0 ){
7414     rc = SQLITE_NOMEM;
7415   }else{
7416     int nCopy = (int)strlen(zCopy);
7417     int i = 1;
7418 
7419     while( rc==SQLITE_OK ){
7420       struct stat sStat;
7421       int rc2;
7422 
7423       for(; zCopy[i]!='/' && i<nCopy; i++);
7424       if( i==nCopy ) break;
7425       zCopy[i] = '\0';
7426 
7427       rc2 = fileStat(zCopy, &sStat);
7428       if( rc2!=0 ){
7429         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
7430       }else{
7431         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
7432       }
7433       zCopy[i] = '/';
7434       i++;
7435     }
7436 
7437     sqlite3_free(zCopy);
7438   }
7439 
7440   return rc;
7441 }
7442 
7443 /*
7444 ** This function does the work for the writefile() UDF. Refer to
7445 ** header comments at the top of this file for details.
7446 */
writeFile(sqlite3_context * pCtx,const char * zFile,sqlite3_value * pData,mode_t mode,sqlite3_int64 mtime)7447 static int writeFile(
7448   sqlite3_context *pCtx,          /* Context to return bytes written in */
7449   const char *zFile,              /* File to write */
7450   sqlite3_value *pData,           /* Data to write */
7451   mode_t mode,                    /* MODE parameter passed to writefile() */
7452   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
7453 ){
7454   if( zFile==0 ) return 1;
7455 #if !defined(_WIN32) && !defined(WIN32)
7456   if( S_ISLNK(mode) ){
7457     const char *zTo = (const char*)sqlite3_value_text(pData);
7458     if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
7459   }else
7460 #endif
7461   {
7462     if( S_ISDIR(mode) ){
7463       if( mkdir(zFile, mode) ){
7464         /* The mkdir() call to create the directory failed. This might not
7465         ** be an error though - if there is already a directory at the same
7466         ** path and either the permissions already match or can be changed
7467         ** to do so using chmod(), it is not an error.  */
7468         struct stat sStat;
7469         if( errno!=EEXIST
7470          || 0!=fileStat(zFile, &sStat)
7471          || !S_ISDIR(sStat.st_mode)
7472          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
7473         ){
7474           return 1;
7475         }
7476       }
7477     }else{
7478       sqlite3_int64 nWrite = 0;
7479       const char *z;
7480       int rc = 0;
7481       FILE *out = fopen(zFile, "wb");
7482       if( out==0 ) return 1;
7483       z = (const char*)sqlite3_value_blob(pData);
7484       if( z ){
7485         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
7486         nWrite = sqlite3_value_bytes(pData);
7487         if( nWrite!=n ){
7488           rc = 1;
7489         }
7490       }
7491       fclose(out);
7492       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
7493         rc = 1;
7494       }
7495       if( rc ) return 2;
7496       sqlite3_result_int64(pCtx, nWrite);
7497     }
7498   }
7499 
7500   if( mtime>=0 ){
7501 #if defined(_WIN32)
7502 #if !SQLITE_OS_WINRT
7503     /* Windows */
7504     FILETIME lastAccess;
7505     FILETIME lastWrite;
7506     SYSTEMTIME currentTime;
7507     LONGLONG intervals;
7508     HANDLE hFile;
7509     LPWSTR zUnicodeName;
7510     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7511 
7512     GetSystemTime(&currentTime);
7513     SystemTimeToFileTime(&currentTime, &lastAccess);
7514     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
7515     lastWrite.dwLowDateTime = (DWORD)intervals;
7516     lastWrite.dwHighDateTime = intervals >> 32;
7517     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
7518     if( zUnicodeName==0 ){
7519       return 1;
7520     }
7521     hFile = CreateFileW(
7522       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
7523       FILE_FLAG_BACKUP_SEMANTICS, NULL
7524     );
7525     sqlite3_free(zUnicodeName);
7526     if( hFile!=INVALID_HANDLE_VALUE ){
7527       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
7528       CloseHandle(hFile);
7529       return !bResult;
7530     }else{
7531       return 1;
7532     }
7533 #endif
7534 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
7535     /* Recent unix */
7536     struct timespec times[2];
7537     times[0].tv_nsec = times[1].tv_nsec = 0;
7538     times[0].tv_sec = time(0);
7539     times[1].tv_sec = mtime;
7540     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
7541       return 1;
7542     }
7543 #else
7544     /* Legacy unix */
7545     struct timeval times[2];
7546     times[0].tv_usec = times[1].tv_usec = 0;
7547     times[0].tv_sec = time(0);
7548     times[1].tv_sec = mtime;
7549     if( utimes(zFile, times) ){
7550       return 1;
7551     }
7552 #endif
7553   }
7554 
7555   return 0;
7556 }
7557 
7558 /*
7559 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
7560 ** Refer to header comments at the top of this file for details.
7561 */
writefileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7562 static void writefileFunc(
7563   sqlite3_context *context,
7564   int argc,
7565   sqlite3_value **argv
7566 ){
7567   const char *zFile;
7568   mode_t mode = 0;
7569   int res;
7570   sqlite3_int64 mtime = -1;
7571 
7572   if( argc<2 || argc>4 ){
7573     sqlite3_result_error(context,
7574         "wrong number of arguments to function writefile()", -1
7575     );
7576     return;
7577   }
7578 
7579   zFile = (const char*)sqlite3_value_text(argv[0]);
7580   if( zFile==0 ) return;
7581   if( argc>=3 ){
7582     mode = (mode_t)sqlite3_value_int(argv[2]);
7583   }
7584   if( argc==4 ){
7585     mtime = sqlite3_value_int64(argv[3]);
7586   }
7587 
7588   res = writeFile(context, zFile, argv[1], mode, mtime);
7589   if( res==1 && errno==ENOENT ){
7590     if( makeDirectory(zFile)==SQLITE_OK ){
7591       res = writeFile(context, zFile, argv[1], mode, mtime);
7592     }
7593   }
7594 
7595   if( argc>2 && res!=0 ){
7596     if( S_ISLNK(mode) ){
7597       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
7598     }else if( S_ISDIR(mode) ){
7599       ctxErrorMsg(context, "failed to create directory: %s", zFile);
7600     }else{
7601       ctxErrorMsg(context, "failed to write file: %s", zFile);
7602     }
7603   }
7604 }
7605 
7606 /*
7607 ** SQL function:   lsmode(MODE)
7608 **
7609 ** Given a numberic st_mode from stat(), convert it into a human-readable
7610 ** text string in the style of "ls -l".
7611 */
lsModeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7612 static void lsModeFunc(
7613   sqlite3_context *context,
7614   int argc,
7615   sqlite3_value **argv
7616 ){
7617   int i;
7618   int iMode = sqlite3_value_int(argv[0]);
7619   char z[16];
7620   (void)argc;
7621   if( S_ISLNK(iMode) ){
7622     z[0] = 'l';
7623   }else if( S_ISREG(iMode) ){
7624     z[0] = '-';
7625   }else if( S_ISDIR(iMode) ){
7626     z[0] = 'd';
7627   }else{
7628     z[0] = '?';
7629   }
7630   for(i=0; i<3; i++){
7631     int m = (iMode >> ((2-i)*3));
7632     char *a = &z[1 + i*3];
7633     a[0] = (m & 0x4) ? 'r' : '-';
7634     a[1] = (m & 0x2) ? 'w' : '-';
7635     a[2] = (m & 0x1) ? 'x' : '-';
7636   }
7637   z[10] = '\0';
7638   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
7639 }
7640 
7641 #ifndef SQLITE_OMIT_VIRTUALTABLE
7642 
7643 /*
7644 ** Cursor type for recursively iterating through a directory structure.
7645 */
7646 typedef struct fsdir_cursor fsdir_cursor;
7647 typedef struct FsdirLevel FsdirLevel;
7648 
7649 struct FsdirLevel {
7650   DIR *pDir;                 /* From opendir() */
7651   char *zDir;                /* Name of directory (nul-terminated) */
7652 };
7653 
7654 struct fsdir_cursor {
7655   sqlite3_vtab_cursor base;  /* Base class - must be first */
7656 
7657   int nLvl;                  /* Number of entries in aLvl[] array */
7658   int iLvl;                  /* Index of current entry */
7659   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
7660 
7661   const char *zBase;
7662   int nBase;
7663 
7664   struct stat sStat;         /* Current lstat() results */
7665   char *zPath;               /* Path to current entry */
7666   sqlite3_int64 iRowid;      /* Current rowid */
7667 };
7668 
7669 typedef struct fsdir_tab fsdir_tab;
7670 struct fsdir_tab {
7671   sqlite3_vtab base;         /* Base class - must be first */
7672 };
7673 
7674 /*
7675 ** Construct a new fsdir virtual table object.
7676 */
fsdirConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)7677 static int fsdirConnect(
7678   sqlite3 *db,
7679   void *pAux,
7680   int argc, const char *const*argv,
7681   sqlite3_vtab **ppVtab,
7682   char **pzErr
7683 ){
7684   fsdir_tab *pNew = 0;
7685   int rc;
7686   (void)pAux;
7687   (void)argc;
7688   (void)argv;
7689   (void)pzErr;
7690   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
7691   if( rc==SQLITE_OK ){
7692     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
7693     if( pNew==0 ) return SQLITE_NOMEM;
7694     memset(pNew, 0, sizeof(*pNew));
7695     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
7696   }
7697   *ppVtab = (sqlite3_vtab*)pNew;
7698   return rc;
7699 }
7700 
7701 /*
7702 ** This method is the destructor for fsdir vtab objects.
7703 */
fsdirDisconnect(sqlite3_vtab * pVtab)7704 static int fsdirDisconnect(sqlite3_vtab *pVtab){
7705   sqlite3_free(pVtab);
7706   return SQLITE_OK;
7707 }
7708 
7709 /*
7710 ** Constructor for a new fsdir_cursor object.
7711 */
fsdirOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)7712 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
7713   fsdir_cursor *pCur;
7714   (void)p;
7715   pCur = sqlite3_malloc( sizeof(*pCur) );
7716   if( pCur==0 ) return SQLITE_NOMEM;
7717   memset(pCur, 0, sizeof(*pCur));
7718   pCur->iLvl = -1;
7719   *ppCursor = &pCur->base;
7720   return SQLITE_OK;
7721 }
7722 
7723 /*
7724 ** Reset a cursor back to the state it was in when first returned
7725 ** by fsdirOpen().
7726 */
fsdirResetCursor(fsdir_cursor * pCur)7727 static void fsdirResetCursor(fsdir_cursor *pCur){
7728   int i;
7729   for(i=0; i<=pCur->iLvl; i++){
7730     FsdirLevel *pLvl = &pCur->aLvl[i];
7731     if( pLvl->pDir ) closedir(pLvl->pDir);
7732     sqlite3_free(pLvl->zDir);
7733   }
7734   sqlite3_free(pCur->zPath);
7735   sqlite3_free(pCur->aLvl);
7736   pCur->aLvl = 0;
7737   pCur->zPath = 0;
7738   pCur->zBase = 0;
7739   pCur->nBase = 0;
7740   pCur->nLvl = 0;
7741   pCur->iLvl = -1;
7742   pCur->iRowid = 1;
7743 }
7744 
7745 /*
7746 ** Destructor for an fsdir_cursor.
7747 */
fsdirClose(sqlite3_vtab_cursor * cur)7748 static int fsdirClose(sqlite3_vtab_cursor *cur){
7749   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7750 
7751   fsdirResetCursor(pCur);
7752   sqlite3_free(pCur);
7753   return SQLITE_OK;
7754 }
7755 
7756 /*
7757 ** Set the error message for the virtual table associated with cursor
7758 ** pCur to the results of vprintf(zFmt, ...).
7759 */
fsdirSetErrmsg(fsdir_cursor * pCur,const char * zFmt,...)7760 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
7761   va_list ap;
7762   va_start(ap, zFmt);
7763   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7764   va_end(ap);
7765 }
7766 
7767 
7768 /*
7769 ** Advance an fsdir_cursor to its next row of output.
7770 */
fsdirNext(sqlite3_vtab_cursor * cur)7771 static int fsdirNext(sqlite3_vtab_cursor *cur){
7772   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7773   mode_t m = pCur->sStat.st_mode;
7774 
7775   pCur->iRowid++;
7776   if( S_ISDIR(m) ){
7777     /* Descend into this directory */
7778     int iNew = pCur->iLvl + 1;
7779     FsdirLevel *pLvl;
7780     if( iNew>=pCur->nLvl ){
7781       int nNew = iNew+1;
7782       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
7783       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
7784       if( aNew==0 ) return SQLITE_NOMEM;
7785       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
7786       pCur->aLvl = aNew;
7787       pCur->nLvl = nNew;
7788     }
7789     pCur->iLvl = iNew;
7790     pLvl = &pCur->aLvl[iNew];
7791 
7792     pLvl->zDir = pCur->zPath;
7793     pCur->zPath = 0;
7794     pLvl->pDir = opendir(pLvl->zDir);
7795     if( pLvl->pDir==0 ){
7796       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
7797       return SQLITE_ERROR;
7798     }
7799   }
7800 
7801   while( pCur->iLvl>=0 ){
7802     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
7803     struct dirent *pEntry = readdir(pLvl->pDir);
7804     if( pEntry ){
7805       if( pEntry->d_name[0]=='.' ){
7806        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
7807        if( pEntry->d_name[1]=='\0' ) continue;
7808       }
7809       sqlite3_free(pCur->zPath);
7810       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
7811       if( pCur->zPath==0 ) return SQLITE_NOMEM;
7812       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7813         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7814         return SQLITE_ERROR;
7815       }
7816       return SQLITE_OK;
7817     }
7818     closedir(pLvl->pDir);
7819     sqlite3_free(pLvl->zDir);
7820     pLvl->pDir = 0;
7821     pLvl->zDir = 0;
7822     pCur->iLvl--;
7823   }
7824 
7825   /* EOF */
7826   sqlite3_free(pCur->zPath);
7827   pCur->zPath = 0;
7828   return SQLITE_OK;
7829 }
7830 
7831 /*
7832 ** Return values of columns for the row at which the series_cursor
7833 ** is currently pointing.
7834 */
fsdirColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)7835 static int fsdirColumn(
7836   sqlite3_vtab_cursor *cur,   /* The cursor */
7837   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7838   int i                       /* Which column to return */
7839 ){
7840   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7841   switch( i ){
7842     case FSDIR_COLUMN_NAME: {
7843       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
7844       break;
7845     }
7846 
7847     case FSDIR_COLUMN_MODE:
7848       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
7849       break;
7850 
7851     case FSDIR_COLUMN_MTIME:
7852       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
7853       break;
7854 
7855     case FSDIR_COLUMN_DATA: {
7856       mode_t m = pCur->sStat.st_mode;
7857       if( S_ISDIR(m) ){
7858         sqlite3_result_null(ctx);
7859 #if !defined(_WIN32) && !defined(WIN32)
7860       }else if( S_ISLNK(m) ){
7861         char aStatic[64];
7862         char *aBuf = aStatic;
7863         sqlite3_int64 nBuf = 64;
7864         int n;
7865 
7866         while( 1 ){
7867           n = readlink(pCur->zPath, aBuf, nBuf);
7868           if( n<nBuf ) break;
7869           if( aBuf!=aStatic ) sqlite3_free(aBuf);
7870           nBuf = nBuf*2;
7871           aBuf = sqlite3_malloc64(nBuf);
7872           if( aBuf==0 ){
7873             sqlite3_result_error_nomem(ctx);
7874             return SQLITE_NOMEM;
7875           }
7876         }
7877 
7878         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
7879         if( aBuf!=aStatic ) sqlite3_free(aBuf);
7880 #endif
7881       }else{
7882         readFileContents(ctx, pCur->zPath);
7883       }
7884     }
7885     case FSDIR_COLUMN_PATH:
7886     default: {
7887       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
7888       ** always return their values as NULL */
7889       break;
7890     }
7891   }
7892   return SQLITE_OK;
7893 }
7894 
7895 /*
7896 ** Return the rowid for the current row. In this implementation, the
7897 ** first row returned is assigned rowid value 1, and each subsequent
7898 ** row a value 1 more than that of the previous.
7899 */
fsdirRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)7900 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7901   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7902   *pRowid = pCur->iRowid;
7903   return SQLITE_OK;
7904 }
7905 
7906 /*
7907 ** Return TRUE if the cursor has been moved off of the last
7908 ** row of output.
7909 */
fsdirEof(sqlite3_vtab_cursor * cur)7910 static int fsdirEof(sqlite3_vtab_cursor *cur){
7911   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7912   return (pCur->zPath==0);
7913 }
7914 
7915 /*
7916 ** xFilter callback.
7917 **
7918 ** idxNum==1   PATH parameter only
7919 ** idxNum==2   Both PATH and DIR supplied
7920 */
fsdirFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)7921 static int fsdirFilter(
7922   sqlite3_vtab_cursor *cur,
7923   int idxNum, const char *idxStr,
7924   int argc, sqlite3_value **argv
7925 ){
7926   const char *zDir = 0;
7927   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7928   (void)idxStr;
7929   fsdirResetCursor(pCur);
7930 
7931   if( idxNum==0 ){
7932     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
7933     return SQLITE_ERROR;
7934   }
7935 
7936   assert( argc==idxNum && (argc==1 || argc==2) );
7937   zDir = (const char*)sqlite3_value_text(argv[0]);
7938   if( zDir==0 ){
7939     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
7940     return SQLITE_ERROR;
7941   }
7942   if( argc==2 ){
7943     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
7944   }
7945   if( pCur->zBase ){
7946     pCur->nBase = (int)strlen(pCur->zBase)+1;
7947     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
7948   }else{
7949     pCur->zPath = sqlite3_mprintf("%s", zDir);
7950   }
7951 
7952   if( pCur->zPath==0 ){
7953     return SQLITE_NOMEM;
7954   }
7955   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7956     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7957     return SQLITE_ERROR;
7958   }
7959 
7960   return SQLITE_OK;
7961 }
7962 
7963 /*
7964 ** SQLite will invoke this method one or more times while planning a query
7965 ** that uses the generate_series virtual table.  This routine needs to create
7966 ** a query plan for each invocation and compute an estimated cost for that
7967 ** plan.
7968 **
7969 ** In this implementation idxNum is used to represent the
7970 ** query plan.  idxStr is unused.
7971 **
7972 ** The query plan is represented by values of idxNum:
7973 **
7974 **  (1)  The path value is supplied by argv[0]
7975 **  (2)  Path is in argv[0] and dir is in argv[1]
7976 */
fsdirBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)7977 static int fsdirBestIndex(
7978   sqlite3_vtab *tab,
7979   sqlite3_index_info *pIdxInfo
7980 ){
7981   int i;                 /* Loop over constraints */
7982   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
7983   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
7984   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
7985   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
7986   const struct sqlite3_index_constraint *pConstraint;
7987 
7988   (void)tab;
7989   pConstraint = pIdxInfo->aConstraint;
7990   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
7991     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
7992     switch( pConstraint->iColumn ){
7993       case FSDIR_COLUMN_PATH: {
7994         if( pConstraint->usable ){
7995           idxPath = i;
7996           seenPath = 0;
7997         }else if( idxPath<0 ){
7998           seenPath = 1;
7999         }
8000         break;
8001       }
8002       case FSDIR_COLUMN_DIR: {
8003         if( pConstraint->usable ){
8004           idxDir = i;
8005           seenDir = 0;
8006         }else if( idxDir<0 ){
8007           seenDir = 1;
8008         }
8009         break;
8010       }
8011     }
8012   }
8013   if( seenPath || seenDir ){
8014     /* If input parameters are unusable, disallow this plan */
8015     return SQLITE_CONSTRAINT;
8016   }
8017 
8018   if( idxPath<0 ){
8019     pIdxInfo->idxNum = 0;
8020     /* The pIdxInfo->estimatedCost should have been initialized to a huge
8021     ** number.  Leave it unchanged. */
8022     pIdxInfo->estimatedRows = 0x7fffffff;
8023   }else{
8024     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
8025     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
8026     if( idxDir>=0 ){
8027       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
8028       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
8029       pIdxInfo->idxNum = 2;
8030       pIdxInfo->estimatedCost = 10.0;
8031     }else{
8032       pIdxInfo->idxNum = 1;
8033       pIdxInfo->estimatedCost = 100.0;
8034     }
8035   }
8036 
8037   return SQLITE_OK;
8038 }
8039 
8040 /*
8041 ** Register the "fsdir" virtual table.
8042 */
fsdirRegister(sqlite3 * db)8043 static int fsdirRegister(sqlite3 *db){
8044   static sqlite3_module fsdirModule = {
8045     0,                         /* iVersion */
8046     0,                         /* xCreate */
8047     fsdirConnect,              /* xConnect */
8048     fsdirBestIndex,            /* xBestIndex */
8049     fsdirDisconnect,           /* xDisconnect */
8050     0,                         /* xDestroy */
8051     fsdirOpen,                 /* xOpen - open a cursor */
8052     fsdirClose,                /* xClose - close a cursor */
8053     fsdirFilter,               /* xFilter - configure scan constraints */
8054     fsdirNext,                 /* xNext - advance a cursor */
8055     fsdirEof,                  /* xEof - check for end of scan */
8056     fsdirColumn,               /* xColumn - read data */
8057     fsdirRowid,                /* xRowid - read data */
8058     0,                         /* xUpdate */
8059     0,                         /* xBegin */
8060     0,                         /* xSync */
8061     0,                         /* xCommit */
8062     0,                         /* xRollback */
8063     0,                         /* xFindMethod */
8064     0,                         /* xRename */
8065     0,                         /* xSavepoint */
8066     0,                         /* xRelease */
8067     0,                         /* xRollbackTo */
8068     0,                         /* xShadowName */
8069     0                          /* xIntegrity */
8070   };
8071 
8072   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
8073   return rc;
8074 }
8075 #else         /* SQLITE_OMIT_VIRTUALTABLE */
8076 # define fsdirRegister(x) SQLITE_OK
8077 #endif
8078 
8079 #ifdef _WIN32
8080 
8081 #endif
sqlite3_fileio_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8082 int sqlite3_fileio_init(
8083   sqlite3 *db,
8084   char **pzErrMsg,
8085   const sqlite3_api_routines *pApi
8086 ){
8087   int rc = SQLITE_OK;
8088   SQLITE_EXTENSION_INIT2(pApi);
8089   (void)pzErrMsg;  /* Unused parameter */
8090   rc = sqlite3_create_function(db, "readfile", 1,
8091                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8092                                readfileFunc, 0, 0);
8093   if( rc==SQLITE_OK ){
8094     rc = sqlite3_create_function(db, "writefile", -1,
8095                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8096                                  writefileFunc, 0, 0);
8097   }
8098   if( rc==SQLITE_OK ){
8099     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
8100                                  lsModeFunc, 0, 0);
8101   }
8102   if( rc==SQLITE_OK ){
8103     rc = fsdirRegister(db);
8104   }
8105   return rc;
8106 }
8107 
8108 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
8109 /* To allow a standalone DLL, make test_windirent.c use the same
8110  * redefined SQLite API calls as the above extension code does.
8111  * Just pull in this .c to accomplish this. As a beneficial side
8112  * effect, this extension becomes a single translation unit. */
8113 #  include "test_windirent.c"
8114 #endif
8115 
8116 /************************* End ../ext/misc/fileio.c ********************/
8117 /************************* Begin ../ext/misc/completion.c ******************/
8118 /*
8119 ** 2017-07-10
8120 **
8121 ** The author disclaims copyright to this source code.  In place of
8122 ** a legal notice, here is a blessing:
8123 **
8124 **    May you do good and not evil.
8125 **    May you find forgiveness for yourself and forgive others.
8126 **    May you share freely, never taking more than you give.
8127 **
8128 *************************************************************************
8129 **
8130 ** This file implements an eponymous virtual table that returns suggested
8131 ** completions for a partial SQL input.
8132 **
8133 ** Suggested usage:
8134 **
8135 **     SELECT DISTINCT candidate COLLATE nocase
8136 **       FROM completion($prefix,$wholeline)
8137 **      ORDER BY 1;
8138 **
8139 ** The two query parameters are optional.  $prefix is the text of the
8140 ** current word being typed and that is to be completed.  $wholeline is
8141 ** the complete input line, used for context.
8142 **
8143 ** The raw completion() table might return the same candidate multiple
8144 ** times, for example if the same column name is used to two or more
8145 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
8146 ** the DISTINCT and ORDER BY are recommended.
8147 **
8148 ** This virtual table operates at the speed of human typing, and so there
8149 ** is no attempt to make it fast.  Even a slow implementation will be much
8150 ** faster than any human can type.
8151 **
8152 */
8153 /* #include "sqlite3ext.h" */
8154 SQLITE_EXTENSION_INIT1
8155 #include <assert.h>
8156 #include <string.h>
8157 #include <ctype.h>
8158 
8159 #ifndef SQLITE_OMIT_VIRTUALTABLE
8160 
8161 /* completion_vtab is a subclass of sqlite3_vtab which will
8162 ** serve as the underlying representation of a completion virtual table
8163 */
8164 typedef struct completion_vtab completion_vtab;
8165 struct completion_vtab {
8166   sqlite3_vtab base;  /* Base class - must be first */
8167   sqlite3 *db;        /* Database connection for this completion vtab */
8168 };
8169 
8170 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
8171 ** serve as the underlying representation of a cursor that scans
8172 ** over rows of the result
8173 */
8174 typedef struct completion_cursor completion_cursor;
8175 struct completion_cursor {
8176   sqlite3_vtab_cursor base;  /* Base class - must be first */
8177   sqlite3 *db;               /* Database connection for this cursor */
8178   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
8179   char *zPrefix;             /* The prefix for the word we want to complete */
8180   char *zLine;               /* The whole that we want to complete */
8181   const char *zCurrentRow;   /* Current output row */
8182   int szRow;                 /* Length of the zCurrentRow string */
8183   sqlite3_stmt *pStmt;       /* Current statement */
8184   sqlite3_int64 iRowid;      /* The rowid */
8185   int ePhase;                /* Current phase */
8186   int j;                     /* inter-phase counter */
8187 };
8188 
8189 /* Values for ePhase:
8190 */
8191 #define COMPLETION_FIRST_PHASE   1
8192 #define COMPLETION_KEYWORDS      1
8193 #define COMPLETION_PRAGMAS       2
8194 #define COMPLETION_FUNCTIONS     3
8195 #define COMPLETION_COLLATIONS    4
8196 #define COMPLETION_INDEXES       5
8197 #define COMPLETION_TRIGGERS      6
8198 #define COMPLETION_DATABASES     7
8199 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
8200 #define COMPLETION_COLUMNS       9
8201 #define COMPLETION_MODULES       10
8202 #define COMPLETION_EOF           11
8203 
8204 /*
8205 ** The completionConnect() method is invoked to create a new
8206 ** completion_vtab that describes the completion virtual table.
8207 **
8208 ** Think of this routine as the constructor for completion_vtab objects.
8209 **
8210 ** All this routine needs to do is:
8211 **
8212 **    (1) Allocate the completion_vtab object and initialize all fields.
8213 **
8214 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
8215 **        result set of queries against completion will look like.
8216 */
completionConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)8217 static int completionConnect(
8218   sqlite3 *db,
8219   void *pAux,
8220   int argc, const char *const*argv,
8221   sqlite3_vtab **ppVtab,
8222   char **pzErr
8223 ){
8224   completion_vtab *pNew;
8225   int rc;
8226 
8227   (void)(pAux);    /* Unused parameter */
8228   (void)(argc);    /* Unused parameter */
8229   (void)(argv);    /* Unused parameter */
8230   (void)(pzErr);   /* Unused parameter */
8231 
8232 /* Column numbers */
8233 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
8234 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
8235 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
8236 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
8237 
8238   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
8239   rc = sqlite3_declare_vtab(db,
8240       "CREATE TABLE x("
8241       "  candidate TEXT,"
8242       "  prefix TEXT HIDDEN,"
8243       "  wholeline TEXT HIDDEN,"
8244       "  phase INT HIDDEN"        /* Used for debugging only */
8245       ")");
8246   if( rc==SQLITE_OK ){
8247     pNew = sqlite3_malloc( sizeof(*pNew) );
8248     *ppVtab = (sqlite3_vtab*)pNew;
8249     if( pNew==0 ) return SQLITE_NOMEM;
8250     memset(pNew, 0, sizeof(*pNew));
8251     pNew->db = db;
8252   }
8253   return rc;
8254 }
8255 
8256 /*
8257 ** This method is the destructor for completion_cursor objects.
8258 */
completionDisconnect(sqlite3_vtab * pVtab)8259 static int completionDisconnect(sqlite3_vtab *pVtab){
8260   sqlite3_free(pVtab);
8261   return SQLITE_OK;
8262 }
8263 
8264 /*
8265 ** Constructor for a new completion_cursor object.
8266 */
completionOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)8267 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
8268   completion_cursor *pCur;
8269   pCur = sqlite3_malloc( sizeof(*pCur) );
8270   if( pCur==0 ) return SQLITE_NOMEM;
8271   memset(pCur, 0, sizeof(*pCur));
8272   pCur->db = ((completion_vtab*)p)->db;
8273   *ppCursor = &pCur->base;
8274   return SQLITE_OK;
8275 }
8276 
8277 /*
8278 ** Reset the completion_cursor.
8279 */
completionCursorReset(completion_cursor * pCur)8280 static void completionCursorReset(completion_cursor *pCur){
8281   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
8282   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
8283   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
8284   pCur->j = 0;
8285 }
8286 
8287 /*
8288 ** Destructor for a completion_cursor.
8289 */
completionClose(sqlite3_vtab_cursor * cur)8290 static int completionClose(sqlite3_vtab_cursor *cur){
8291   completionCursorReset((completion_cursor*)cur);
8292   sqlite3_free(cur);
8293   return SQLITE_OK;
8294 }
8295 
8296 /*
8297 ** Advance a completion_cursor to its next row of output.
8298 **
8299 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
8300 ** record the current state of the scan.  This routine sets ->zCurrentRow
8301 ** to the current row of output and then returns.  If no more rows remain,
8302 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
8303 ** table that has reached the end of its scan.
8304 **
8305 ** The current implementation just lists potential identifiers and
8306 ** keywords and filters them by zPrefix.  Future enhancements should
8307 ** take zLine into account to try to restrict the set of identifiers and
8308 ** keywords based on what would be legal at the current point of input.
8309 */
completionNext(sqlite3_vtab_cursor * cur)8310 static int completionNext(sqlite3_vtab_cursor *cur){
8311   completion_cursor *pCur = (completion_cursor*)cur;
8312   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
8313   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
8314   pCur->iRowid++;
8315   while( pCur->ePhase!=COMPLETION_EOF ){
8316     switch( pCur->ePhase ){
8317       case COMPLETION_KEYWORDS: {
8318         if( pCur->j >= sqlite3_keyword_count() ){
8319           pCur->zCurrentRow = 0;
8320           pCur->ePhase = COMPLETION_DATABASES;
8321         }else{
8322           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
8323         }
8324         iCol = -1;
8325         break;
8326       }
8327       case COMPLETION_DATABASES: {
8328         if( pCur->pStmt==0 ){
8329           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
8330                              &pCur->pStmt, 0);
8331         }
8332         iCol = 1;
8333         eNextPhase = COMPLETION_TABLES;
8334         break;
8335       }
8336       case COMPLETION_TABLES: {
8337         if( pCur->pStmt==0 ){
8338           sqlite3_stmt *pS2;
8339           char *zSql = 0;
8340           const char *zSep = "";
8341           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8342           while( sqlite3_step(pS2)==SQLITE_ROW ){
8343             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8344             zSql = sqlite3_mprintf(
8345                "%z%s"
8346                "SELECT name FROM \"%w\".sqlite_schema",
8347                zSql, zSep, zDb
8348             );
8349             if( zSql==0 ) return SQLITE_NOMEM;
8350             zSep = " UNION ";
8351           }
8352           sqlite3_finalize(pS2);
8353           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8354           sqlite3_free(zSql);
8355         }
8356         iCol = 0;
8357         eNextPhase = COMPLETION_COLUMNS;
8358         break;
8359       }
8360       case COMPLETION_COLUMNS: {
8361         if( pCur->pStmt==0 ){
8362           sqlite3_stmt *pS2;
8363           char *zSql = 0;
8364           const char *zSep = "";
8365           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8366           while( sqlite3_step(pS2)==SQLITE_ROW ){
8367             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8368             zSql = sqlite3_mprintf(
8369                "%z%s"
8370                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
8371                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
8372                " WHERE sm.type='table'",
8373                zSql, zSep, zDb, zDb
8374             );
8375             if( zSql==0 ) return SQLITE_NOMEM;
8376             zSep = " UNION ";
8377           }
8378           sqlite3_finalize(pS2);
8379           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8380           sqlite3_free(zSql);
8381         }
8382         iCol = 0;
8383         eNextPhase = COMPLETION_EOF;
8384         break;
8385       }
8386     }
8387     if( iCol<0 ){
8388       /* This case is when the phase presets zCurrentRow */
8389       if( pCur->zCurrentRow==0 ) continue;
8390     }else{
8391       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
8392         /* Extract the next row of content */
8393         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
8394         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
8395       }else{
8396         /* When all rows are finished, advance to the next phase */
8397         sqlite3_finalize(pCur->pStmt);
8398         pCur->pStmt = 0;
8399         pCur->ePhase = eNextPhase;
8400         continue;
8401       }
8402     }
8403     if( pCur->nPrefix==0 ) break;
8404     if( pCur->nPrefix<=pCur->szRow
8405      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
8406     ){
8407       break;
8408     }
8409   }
8410 
8411   return SQLITE_OK;
8412 }
8413 
8414 /*
8415 ** Return values of columns for the row at which the completion_cursor
8416 ** is currently pointing.
8417 */
completionColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)8418 static int completionColumn(
8419   sqlite3_vtab_cursor *cur,   /* The cursor */
8420   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8421   int i                       /* Which column to return */
8422 ){
8423   completion_cursor *pCur = (completion_cursor*)cur;
8424   switch( i ){
8425     case COMPLETION_COLUMN_CANDIDATE: {
8426       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
8427       break;
8428     }
8429     case COMPLETION_COLUMN_PREFIX: {
8430       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
8431       break;
8432     }
8433     case COMPLETION_COLUMN_WHOLELINE: {
8434       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
8435       break;
8436     }
8437     case COMPLETION_COLUMN_PHASE: {
8438       sqlite3_result_int(ctx, pCur->ePhase);
8439       break;
8440     }
8441   }
8442   return SQLITE_OK;
8443 }
8444 
8445 /*
8446 ** Return the rowid for the current row.  In this implementation, the
8447 ** rowid is the same as the output value.
8448 */
completionRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)8449 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8450   completion_cursor *pCur = (completion_cursor*)cur;
8451   *pRowid = pCur->iRowid;
8452   return SQLITE_OK;
8453 }
8454 
8455 /*
8456 ** Return TRUE if the cursor has been moved off of the last
8457 ** row of output.
8458 */
completionEof(sqlite3_vtab_cursor * cur)8459 static int completionEof(sqlite3_vtab_cursor *cur){
8460   completion_cursor *pCur = (completion_cursor*)cur;
8461   return pCur->ePhase >= COMPLETION_EOF;
8462 }
8463 
8464 /*
8465 ** This method is called to "rewind" the completion_cursor object back
8466 ** to the first row of output.  This method is always called at least
8467 ** once prior to any call to completionColumn() or completionRowid() or
8468 ** completionEof().
8469 */
completionFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)8470 static int completionFilter(
8471   sqlite3_vtab_cursor *pVtabCursor,
8472   int idxNum, const char *idxStr,
8473   int argc, sqlite3_value **argv
8474 ){
8475   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
8476   int iArg = 0;
8477   (void)(idxStr);   /* Unused parameter */
8478   (void)(argc);     /* Unused parameter */
8479   completionCursorReset(pCur);
8480   if( idxNum & 1 ){
8481     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
8482     if( pCur->nPrefix>0 ){
8483       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8484       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8485     }
8486     iArg = 1;
8487   }
8488   if( idxNum & 2 ){
8489     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
8490     if( pCur->nLine>0 ){
8491       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8492       if( pCur->zLine==0 ) return SQLITE_NOMEM;
8493     }
8494   }
8495   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
8496     int i = pCur->nLine;
8497     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
8498       i--;
8499     }
8500     pCur->nPrefix = pCur->nLine - i;
8501     if( pCur->nPrefix>0 ){
8502       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
8503       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8504     }
8505   }
8506   pCur->iRowid = 0;
8507   pCur->ePhase = COMPLETION_FIRST_PHASE;
8508   return completionNext(pVtabCursor);
8509 }
8510 
8511 /*
8512 ** SQLite will invoke this method one or more times while planning a query
8513 ** that uses the completion virtual table.  This routine needs to create
8514 ** a query plan for each invocation and compute an estimated cost for that
8515 ** plan.
8516 **
8517 ** There are two hidden parameters that act as arguments to the table-valued
8518 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
8519 ** is available and bit 1 is set if "wholeline" is available.
8520 */
completionBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)8521 static int completionBestIndex(
8522   sqlite3_vtab *tab,
8523   sqlite3_index_info *pIdxInfo
8524 ){
8525   int i;                 /* Loop over constraints */
8526   int idxNum = 0;        /* The query plan bitmask */
8527   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
8528   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
8529   int nArg = 0;          /* Number of arguments that completeFilter() expects */
8530   const struct sqlite3_index_constraint *pConstraint;
8531 
8532   (void)(tab);    /* Unused parameter */
8533   pConstraint = pIdxInfo->aConstraint;
8534   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8535     if( pConstraint->usable==0 ) continue;
8536     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8537     switch( pConstraint->iColumn ){
8538       case COMPLETION_COLUMN_PREFIX:
8539         prefixIdx = i;
8540         idxNum |= 1;
8541         break;
8542       case COMPLETION_COLUMN_WHOLELINE:
8543         wholelineIdx = i;
8544         idxNum |= 2;
8545         break;
8546     }
8547   }
8548   if( prefixIdx>=0 ){
8549     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
8550     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
8551   }
8552   if( wholelineIdx>=0 ){
8553     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
8554     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
8555   }
8556   pIdxInfo->idxNum = idxNum;
8557   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
8558   pIdxInfo->estimatedRows = 500 - 100*nArg;
8559   return SQLITE_OK;
8560 }
8561 
8562 /*
8563 ** This following structure defines all the methods for the
8564 ** completion virtual table.
8565 */
8566 static sqlite3_module completionModule = {
8567   0,                         /* iVersion */
8568   0,                         /* xCreate */
8569   completionConnect,         /* xConnect */
8570   completionBestIndex,       /* xBestIndex */
8571   completionDisconnect,      /* xDisconnect */
8572   0,                         /* xDestroy */
8573   completionOpen,            /* xOpen - open a cursor */
8574   completionClose,           /* xClose - close a cursor */
8575   completionFilter,          /* xFilter - configure scan constraints */
8576   completionNext,            /* xNext - advance a cursor */
8577   completionEof,             /* xEof - check for end of scan */
8578   completionColumn,          /* xColumn - read data */
8579   completionRowid,           /* xRowid - read data */
8580   0,                         /* xUpdate */
8581   0,                         /* xBegin */
8582   0,                         /* xSync */
8583   0,                         /* xCommit */
8584   0,                         /* xRollback */
8585   0,                         /* xFindMethod */
8586   0,                         /* xRename */
8587   0,                         /* xSavepoint */
8588   0,                         /* xRelease */
8589   0,                         /* xRollbackTo */
8590   0,                         /* xShadowName */
8591   0                          /* xIntegrity */
8592 };
8593 
8594 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8595 
sqlite3CompletionVtabInit(sqlite3 * db)8596 int sqlite3CompletionVtabInit(sqlite3 *db){
8597   int rc = SQLITE_OK;
8598 #ifndef SQLITE_OMIT_VIRTUALTABLE
8599   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
8600 #endif
8601   return rc;
8602 }
8603 
8604 #ifdef _WIN32
8605 
8606 #endif
sqlite3_completion_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8607 int sqlite3_completion_init(
8608   sqlite3 *db,
8609   char **pzErrMsg,
8610   const sqlite3_api_routines *pApi
8611 ){
8612   int rc = SQLITE_OK;
8613   SQLITE_EXTENSION_INIT2(pApi);
8614   (void)(pzErrMsg);  /* Unused parameter */
8615 #ifndef SQLITE_OMIT_VIRTUALTABLE
8616   rc = sqlite3CompletionVtabInit(db);
8617 #endif
8618   return rc;
8619 }
8620 
8621 /************************* End ../ext/misc/completion.c ********************/
8622 /************************* Begin ../ext/misc/appendvfs.c ******************/
8623 /*
8624 ** 2017-10-20
8625 **
8626 ** The author disclaims copyright to this source code.  In place of
8627 ** a legal notice, here is a blessing:
8628 **
8629 **    May you do good and not evil.
8630 **    May you find forgiveness for yourself and forgive others.
8631 **    May you share freely, never taking more than you give.
8632 **
8633 ******************************************************************************
8634 **
8635 ** This file implements a VFS shim that allows an SQLite database to be
8636 ** appended onto the end of some other file, such as an executable.
8637 **
8638 ** A special record must appear at the end of the file that identifies the
8639 ** file as an appended database and provides the offset to the first page
8640 ** of the exposed content. (Or, it is the length of the content prefix.)
8641 ** For best performance page 1 should be located at a disk page boundary,
8642 ** though that is not required.
8643 **
8644 ** When opening a database using this VFS, the connection might treat
8645 ** the file as an ordinary SQLite database, or it might treat it as a
8646 ** database appended onto some other file.  The decision is made by
8647 ** applying the following rules in order:
8648 **
8649 **  (1)  An empty file is an ordinary database.
8650 **
8651 **  (2)  If the file ends with the appendvfs trailer string
8652 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
8653 **
8654 **  (3)  If the file begins with the standard SQLite prefix string
8655 **       "SQLite format 3", that file is an ordinary database.
8656 **
8657 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
8658 **       set, then a new database is appended to the already existing file.
8659 **
8660 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
8661 **
8662 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
8663 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
8664 ** This VFS will not read or write past the 1GiB mark.  This restriction
8665 ** might be lifted in future versions.  For now, if you need a larger
8666 ** database, then keep it in a separate file.
8667 **
8668 ** If the file being opened is a plain database (not an appended one), then
8669 ** this shim is a pass-through into the default underlying VFS. (rule 3)
8670 **/
8671 /* #include "sqlite3ext.h" */
8672 SQLITE_EXTENSION_INIT1
8673 #include <string.h>
8674 #include <assert.h>
8675 
8676 /* The append mark at the end of the database is:
8677 **
8678 **     Start-Of-SQLite3-NNNNNNNN
8679 **     123456789 123456789 12345
8680 **
8681 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
8682 ** the offset to page 1, and also the length of the prefix content.
8683 */
8684 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
8685 #define APND_MARK_PREFIX_SZ  17
8686 #define APND_MARK_FOS_SZ      8
8687 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
8688 
8689 /*
8690 ** Maximum size of the combined prefix + database + append-mark.  This
8691 ** must be less than 0x40000000 to avoid locking issues on Windows.
8692 */
8693 #define APND_MAX_SIZE  (0x40000000)
8694 
8695 /*
8696 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
8697 */
8698 #ifndef APND_ROUNDUP
8699 #define APND_ROUNDUP 4096
8700 #endif
8701 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
8702 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
8703 
8704 /*
8705 ** Forward declaration of objects used by this utility
8706 */
8707 typedef struct sqlite3_vfs ApndVfs;
8708 typedef struct ApndFile ApndFile;
8709 
8710 /* Access to a lower-level VFS that (might) implement dynamic loading,
8711 ** access to randomness, etc.
8712 */
8713 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
8714 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
8715 
8716 /* An open appendvfs file
8717 **
8718 ** An instance of this structure describes the appended database file.
8719 ** A separate sqlite3_file object is always appended. The appended
8720 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
8721 ** the entire file, including the prefix, the database, and the
8722 ** append-mark.
8723 **
8724 ** The structure of an AppendVFS database is like this:
8725 **
8726 **   +-------------+---------+----------+-------------+
8727 **   | prefix-file | padding | database | append-mark |
8728 **   +-------------+---------+----------+-------------+
8729 **                           ^          ^
8730 **                           |          |
8731 **                         iPgOne      iMark
8732 **
8733 **
8734 ** "prefix file" -  file onto which the database has been appended.
8735 ** "padding"     -  zero or more bytes inserted so that "database"
8736 **                  starts on an APND_ROUNDUP boundary
8737 ** "database"    -  The SQLite database file
8738 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8739 **                  the offset from the start of prefix-file to the start
8740 **                  of "database".
8741 **
8742 ** The size of the database is iMark - iPgOne.
8743 **
8744 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8745 ** of iPgOne stored as a big-ending 64-bit integer.
8746 **
8747 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
8748 ** Or, iMark is -1 to indicate that it has not yet been written.
8749 */
8750 struct ApndFile {
8751   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
8752   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
8753   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
8754   /* Always followed by another sqlite3_file that describes the whole file */
8755 };
8756 
8757 /*
8758 ** Methods for ApndFile
8759 */
8760 static int apndClose(sqlite3_file*);
8761 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
8762 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
8763 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
8764 static int apndSync(sqlite3_file*, int flags);
8765 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
8766 static int apndLock(sqlite3_file*, int);
8767 static int apndUnlock(sqlite3_file*, int);
8768 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
8769 static int apndFileControl(sqlite3_file*, int op, void *pArg);
8770 static int apndSectorSize(sqlite3_file*);
8771 static int apndDeviceCharacteristics(sqlite3_file*);
8772 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
8773 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
8774 static void apndShmBarrier(sqlite3_file*);
8775 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
8776 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
8777 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
8778 
8779 /*
8780 ** Methods for ApndVfs
8781 */
8782 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
8783 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
8784 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
8785 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
8786 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
8787 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
8788 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
8789 static void apndDlClose(sqlite3_vfs*, void*);
8790 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
8791 static int apndSleep(sqlite3_vfs*, int microseconds);
8792 static int apndCurrentTime(sqlite3_vfs*, double*);
8793 static int apndGetLastError(sqlite3_vfs*, int, char *);
8794 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
8795 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
8796 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
8797 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
8798 
8799 static sqlite3_vfs apnd_vfs = {
8800   3,                            /* iVersion (set when registered) */
8801   0,                            /* szOsFile (set when registered) */
8802   1024,                         /* mxPathname */
8803   0,                            /* pNext */
8804   "apndvfs",                    /* zName */
8805   0,                            /* pAppData (set when registered) */
8806   apndOpen,                     /* xOpen */
8807   apndDelete,                   /* xDelete */
8808   apndAccess,                   /* xAccess */
8809   apndFullPathname,             /* xFullPathname */
8810   apndDlOpen,                   /* xDlOpen */
8811   apndDlError,                  /* xDlError */
8812   apndDlSym,                    /* xDlSym */
8813   apndDlClose,                  /* xDlClose */
8814   apndRandomness,               /* xRandomness */
8815   apndSleep,                    /* xSleep */
8816   apndCurrentTime,              /* xCurrentTime */
8817   apndGetLastError,             /* xGetLastError */
8818   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
8819   apndSetSystemCall,            /* xSetSystemCall */
8820   apndGetSystemCall,            /* xGetSystemCall */
8821   apndNextSystemCall            /* xNextSystemCall */
8822 };
8823 
8824 static const sqlite3_io_methods apnd_io_methods = {
8825   3,                              /* iVersion */
8826   apndClose,                      /* xClose */
8827   apndRead,                       /* xRead */
8828   apndWrite,                      /* xWrite */
8829   apndTruncate,                   /* xTruncate */
8830   apndSync,                       /* xSync */
8831   apndFileSize,                   /* xFileSize */
8832   apndLock,                       /* xLock */
8833   apndUnlock,                     /* xUnlock */
8834   apndCheckReservedLock,          /* xCheckReservedLock */
8835   apndFileControl,                /* xFileControl */
8836   apndSectorSize,                 /* xSectorSize */
8837   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
8838   apndShmMap,                     /* xShmMap */
8839   apndShmLock,                    /* xShmLock */
8840   apndShmBarrier,                 /* xShmBarrier */
8841   apndShmUnmap,                   /* xShmUnmap */
8842   apndFetch,                      /* xFetch */
8843   apndUnfetch                     /* xUnfetch */
8844 };
8845 
8846 /*
8847 ** Close an apnd-file.
8848 */
apndClose(sqlite3_file * pFile)8849 static int apndClose(sqlite3_file *pFile){
8850   pFile = ORIGFILE(pFile);
8851   return pFile->pMethods->xClose(pFile);
8852 }
8853 
8854 /*
8855 ** Read data from an apnd-file.
8856 */
apndRead(sqlite3_file * pFile,void * zBuf,int iAmt,sqlite_int64 iOfst)8857 static int apndRead(
8858   sqlite3_file *pFile,
8859   void *zBuf,
8860   int iAmt,
8861   sqlite_int64 iOfst
8862 ){
8863   ApndFile *paf = (ApndFile *)pFile;
8864   pFile = ORIGFILE(pFile);
8865   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8866 }
8867 
8868 /*
8869 ** Add the append-mark onto what should become the end of the file.
8870 *  If and only if this succeeds, internal ApndFile.iMark is updated.
8871 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8872 */
apndWriteMark(ApndFile * paf,sqlite3_file * pFile,sqlite_int64 iWriteEnd)8873 static int apndWriteMark(
8874   ApndFile *paf,
8875   sqlite3_file *pFile,
8876   sqlite_int64 iWriteEnd
8877 ){
8878   sqlite_int64 iPgOne = paf->iPgOne;
8879   unsigned char a[APND_MARK_SIZE];
8880   int i = APND_MARK_FOS_SZ;
8881   int rc;
8882   assert(pFile == ORIGFILE(paf));
8883   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
8884   while( --i >= 0 ){
8885     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
8886     iPgOne >>= 8;
8887   }
8888   iWriteEnd += paf->iPgOne;
8889   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
8890                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
8891     paf->iMark = iWriteEnd;
8892   }
8893   return rc;
8894 }
8895 
8896 /*
8897 ** Write data to an apnd-file.
8898 */
apndWrite(sqlite3_file * pFile,const void * zBuf,int iAmt,sqlite_int64 iOfst)8899 static int apndWrite(
8900   sqlite3_file *pFile,
8901   const void *zBuf,
8902   int iAmt,
8903   sqlite_int64 iOfst
8904 ){
8905   ApndFile *paf = (ApndFile *)pFile;
8906   sqlite_int64 iWriteEnd = iOfst + iAmt;
8907   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
8908   pFile = ORIGFILE(pFile);
8909   /* If append-mark is absent or will be overwritten, write it. */
8910   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
8911     int rc = apndWriteMark(paf, pFile, iWriteEnd);
8912     if( SQLITE_OK!=rc ) return rc;
8913   }
8914   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8915 }
8916 
8917 /*
8918 ** Truncate an apnd-file.
8919 */
apndTruncate(sqlite3_file * pFile,sqlite_int64 size)8920 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
8921   ApndFile *paf = (ApndFile *)pFile;
8922   pFile = ORIGFILE(pFile);
8923   /* The append mark goes out first so truncate failure does not lose it. */
8924   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
8925   /* Truncate underlying file just past append mark */
8926   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
8927 }
8928 
8929 /*
8930 ** Sync an apnd-file.
8931 */
apndSync(sqlite3_file * pFile,int flags)8932 static int apndSync(sqlite3_file *pFile, int flags){
8933   pFile = ORIGFILE(pFile);
8934   return pFile->pMethods->xSync(pFile, flags);
8935 }
8936 
8937 /*
8938 ** Return the current file-size of an apnd-file.
8939 ** If the append mark is not yet there, the file-size is 0.
8940 */
apndFileSize(sqlite3_file * pFile,sqlite_int64 * pSize)8941 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
8942   ApndFile *paf = (ApndFile *)pFile;
8943   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
8944   return SQLITE_OK;
8945 }
8946 
8947 /*
8948 ** Lock an apnd-file.
8949 */
apndLock(sqlite3_file * pFile,int eLock)8950 static int apndLock(sqlite3_file *pFile, int eLock){
8951   pFile = ORIGFILE(pFile);
8952   return pFile->pMethods->xLock(pFile, eLock);
8953 }
8954 
8955 /*
8956 ** Unlock an apnd-file.
8957 */
apndUnlock(sqlite3_file * pFile,int eLock)8958 static int apndUnlock(sqlite3_file *pFile, int eLock){
8959   pFile = ORIGFILE(pFile);
8960   return pFile->pMethods->xUnlock(pFile, eLock);
8961 }
8962 
8963 /*
8964 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
8965 */
apndCheckReservedLock(sqlite3_file * pFile,int * pResOut)8966 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
8967   pFile = ORIGFILE(pFile);
8968   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
8969 }
8970 
8971 /*
8972 ** File control method. For custom operations on an apnd-file.
8973 */
apndFileControl(sqlite3_file * pFile,int op,void * pArg)8974 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
8975   ApndFile *paf = (ApndFile *)pFile;
8976   int rc;
8977   pFile = ORIGFILE(pFile);
8978   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
8979   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
8980   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
8981     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
8982   }
8983   return rc;
8984 }
8985 
8986 /*
8987 ** Return the sector-size in bytes for an apnd-file.
8988 */
apndSectorSize(sqlite3_file * pFile)8989 static int apndSectorSize(sqlite3_file *pFile){
8990   pFile = ORIGFILE(pFile);
8991   return pFile->pMethods->xSectorSize(pFile);
8992 }
8993 
8994 /*
8995 ** Return the device characteristic flags supported by an apnd-file.
8996 */
apndDeviceCharacteristics(sqlite3_file * pFile)8997 static int apndDeviceCharacteristics(sqlite3_file *pFile){
8998   pFile = ORIGFILE(pFile);
8999   return pFile->pMethods->xDeviceCharacteristics(pFile);
9000 }
9001 
9002 /* Create a shared memory file mapping */
apndShmMap(sqlite3_file * pFile,int iPg,int pgsz,int bExtend,void volatile ** pp)9003 static int apndShmMap(
9004   sqlite3_file *pFile,
9005   int iPg,
9006   int pgsz,
9007   int bExtend,
9008   void volatile **pp
9009 ){
9010   pFile = ORIGFILE(pFile);
9011   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
9012 }
9013 
9014 /* Perform locking on a shared-memory segment */
apndShmLock(sqlite3_file * pFile,int offset,int n,int flags)9015 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
9016   pFile = ORIGFILE(pFile);
9017   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
9018 }
9019 
9020 /* Memory barrier operation on shared memory */
apndShmBarrier(sqlite3_file * pFile)9021 static void apndShmBarrier(sqlite3_file *pFile){
9022   pFile = ORIGFILE(pFile);
9023   pFile->pMethods->xShmBarrier(pFile);
9024 }
9025 
9026 /* Unmap a shared memory segment */
apndShmUnmap(sqlite3_file * pFile,int deleteFlag)9027 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
9028   pFile = ORIGFILE(pFile);
9029   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
9030 }
9031 
9032 /* Fetch a page of a memory-mapped file */
apndFetch(sqlite3_file * pFile,sqlite3_int64 iOfst,int iAmt,void ** pp)9033 static int apndFetch(
9034   sqlite3_file *pFile,
9035   sqlite3_int64 iOfst,
9036   int iAmt,
9037   void **pp
9038 ){
9039   ApndFile *p = (ApndFile *)pFile;
9040   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
9041     return SQLITE_IOERR; /* Cannot read what is not yet there. */
9042   }
9043   pFile = ORIGFILE(pFile);
9044   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
9045 }
9046 
9047 /* Release a memory-mapped page */
apndUnfetch(sqlite3_file * pFile,sqlite3_int64 iOfst,void * pPage)9048 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
9049   ApndFile *p = (ApndFile *)pFile;
9050   pFile = ORIGFILE(pFile);
9051   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
9052 }
9053 
9054 /*
9055 ** Try to read the append-mark off the end of a file.  Return the
9056 ** start of the appended database if the append-mark is present.
9057 ** If there is no valid append-mark, return -1;
9058 **
9059 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
9060 ** indicates that the appended database contains at least one page.  The
9061 ** start-of-database value must be a multiple of 512.
9062 */
apndReadMark(sqlite3_int64 sz,sqlite3_file * pFile)9063 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
9064   int rc, i;
9065   sqlite3_int64 iMark;
9066   int msbs = 8 * (APND_MARK_FOS_SZ-1);
9067   unsigned char a[APND_MARK_SIZE];
9068 
9069   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
9070   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
9071   if( rc ) return -1;
9072   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
9073   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
9074   for(i=1; i<8; i++){
9075     msbs -= 8;
9076     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
9077   }
9078   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
9079   if( iMark & 0x1ff ) return -1;
9080   return iMark;
9081 }
9082 
9083 static const char apvfsSqliteHdr[] = "SQLite format 3";
9084 /*
9085 ** Check to see if the file is an appendvfs SQLite database file.
9086 ** Return true iff it is such. Parameter sz is the file's size.
9087 */
apndIsAppendvfsDatabase(sqlite3_int64 sz,sqlite3_file * pFile)9088 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
9089   int rc;
9090   char zHdr[16];
9091   sqlite3_int64 iMark = apndReadMark(sz, pFile);
9092   if( iMark>=0 ){
9093     /* If file has the correct end-marker, the expected odd size, and the
9094     ** SQLite DB type marker where the end-marker puts it, then it
9095     ** is an appendvfs database.
9096     */
9097     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
9098     if( SQLITE_OK==rc
9099      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
9100      && (sz & 0x1ff) == APND_MARK_SIZE
9101      && sz>=512+APND_MARK_SIZE
9102     ){
9103       return 1; /* It's an appendvfs database */
9104     }
9105   }
9106   return 0;
9107 }
9108 
9109 /*
9110 ** Check to see if the file is an ordinary SQLite database file.
9111 ** Return true iff so. Parameter sz is the file's size.
9112 */
apndIsOrdinaryDatabaseFile(sqlite3_int64 sz,sqlite3_file * pFile)9113 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
9114   char zHdr[16];
9115   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
9116    || (sz & 0x1ff) != 0
9117    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
9118    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
9119   ){
9120     return 0;
9121   }else{
9122     return 1;
9123   }
9124 }
9125 
9126 /*
9127 ** Open an apnd file handle.
9128 */
apndOpen(sqlite3_vfs * pApndVfs,const char * zName,sqlite3_file * pFile,int flags,int * pOutFlags)9129 static int apndOpen(
9130   sqlite3_vfs *pApndVfs,
9131   const char *zName,
9132   sqlite3_file *pFile,
9133   int flags,
9134   int *pOutFlags
9135 ){
9136   ApndFile *pApndFile = (ApndFile*)pFile;
9137   sqlite3_file *pBaseFile = ORIGFILE(pFile);
9138   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
9139   int rc;
9140   sqlite3_int64 sz = 0;
9141   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
9142     /* The appendvfs is not to be used for transient or temporary databases.
9143     ** Just use the base VFS open to initialize the given file object and
9144     ** open the underlying file. (Appendvfs is then unused for this file.)
9145     */
9146     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
9147   }
9148   memset(pApndFile, 0, sizeof(ApndFile));
9149   pFile->pMethods = &apnd_io_methods;
9150   pApndFile->iMark = -1;    /* Append mark not yet written */
9151 
9152   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
9153   if( rc==SQLITE_OK ){
9154     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
9155     if( rc ){
9156       pBaseFile->pMethods->xClose(pBaseFile);
9157     }
9158   }
9159   if( rc ){
9160     pFile->pMethods = 0;
9161     return rc;
9162   }
9163   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
9164     /* The file being opened appears to be just an ordinary DB. Copy
9165     ** the base dispatch-table so this instance mimics the base VFS.
9166     */
9167     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
9168     return SQLITE_OK;
9169   }
9170   pApndFile->iPgOne = apndReadMark(sz, pFile);
9171   if( pApndFile->iPgOne>=0 ){
9172     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
9173     return SQLITE_OK;
9174   }
9175   if( (flags & SQLITE_OPEN_CREATE)==0 ){
9176     pBaseFile->pMethods->xClose(pBaseFile);
9177     rc = SQLITE_CANTOPEN;
9178     pFile->pMethods = 0;
9179   }else{
9180     /* Round newly added appendvfs location to #define'd page boundary.
9181     ** Note that nothing has yet been written to the underlying file.
9182     ** The append mark will be written along with first content write.
9183     ** Until then, paf->iMark value indicates it is not yet written.
9184     */
9185     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
9186   }
9187   return rc;
9188 }
9189 
9190 /*
9191 ** Delete an apnd file.
9192 ** For an appendvfs, this could mean delete the appendvfs portion,
9193 ** leaving the appendee as it was before it gained an appendvfs.
9194 ** For now, this code deletes the underlying file too.
9195 */
apndDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)9196 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
9197   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
9198 }
9199 
9200 /*
9201 ** All other VFS methods are pass-thrus.
9202 */
apndAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)9203 static int apndAccess(
9204   sqlite3_vfs *pVfs,
9205   const char *zPath,
9206   int flags,
9207   int *pResOut
9208 ){
9209   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
9210 }
apndFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nOut,char * zOut)9211 static int apndFullPathname(
9212   sqlite3_vfs *pVfs,
9213   const char *zPath,
9214   int nOut,
9215   char *zOut
9216 ){
9217   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
9218 }
apndDlOpen(sqlite3_vfs * pVfs,const char * zPath)9219 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
9220   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
9221 }
apndDlError(sqlite3_vfs * pVfs,int nByte,char * zErrMsg)9222 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
9223   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
9224 }
apndDlSym(sqlite3_vfs * pVfs,void * p,const char * zSym)9225 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
9226   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
9227 }
apndDlClose(sqlite3_vfs * pVfs,void * pHandle)9228 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
9229   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
9230 }
apndRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)9231 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
9232   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
9233 }
apndSleep(sqlite3_vfs * pVfs,int nMicro)9234 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
9235   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
9236 }
apndCurrentTime(sqlite3_vfs * pVfs,double * pTimeOut)9237 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
9238   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
9239 }
apndGetLastError(sqlite3_vfs * pVfs,int a,char * b)9240 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
9241   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
9242 }
apndCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * p)9243 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
9244   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
9245 }
apndSetSystemCall(sqlite3_vfs * pVfs,const char * zName,sqlite3_syscall_ptr pCall)9246 static int apndSetSystemCall(
9247   sqlite3_vfs *pVfs,
9248   const char *zName,
9249   sqlite3_syscall_ptr pCall
9250 ){
9251   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
9252 }
apndGetSystemCall(sqlite3_vfs * pVfs,const char * zName)9253 static sqlite3_syscall_ptr apndGetSystemCall(
9254   sqlite3_vfs *pVfs,
9255   const char *zName
9256 ){
9257   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
9258 }
apndNextSystemCall(sqlite3_vfs * pVfs,const char * zName)9259 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
9260   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
9261 }
9262 
9263 
9264 #ifdef _WIN32
9265 
9266 #endif
9267 /*
9268 ** This routine is called when the extension is loaded.
9269 ** Register the new VFS.
9270 */
sqlite3_appendvfs_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)9271 int sqlite3_appendvfs_init(
9272   sqlite3 *db,
9273   char **pzErrMsg,
9274   const sqlite3_api_routines *pApi
9275 ){
9276   int rc = SQLITE_OK;
9277   sqlite3_vfs *pOrig;
9278   SQLITE_EXTENSION_INIT2(pApi);
9279   (void)pzErrMsg;
9280   (void)db;
9281   pOrig = sqlite3_vfs_find(0);
9282   if( pOrig==0 ) return SQLITE_ERROR;
9283   apnd_vfs.iVersion = pOrig->iVersion;
9284   apnd_vfs.pAppData = pOrig;
9285   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
9286   rc = sqlite3_vfs_register(&apnd_vfs, 0);
9287 #ifdef APPENDVFS_TEST
9288   if( rc==SQLITE_OK ){
9289     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
9290   }
9291 #endif
9292   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
9293   return rc;
9294 }
9295 
9296 /************************* End ../ext/misc/appendvfs.c ********************/
9297 #endif
9298 #ifdef SQLITE_HAVE_ZLIB
9299 /************************* Begin ../ext/misc/zipfile.c ******************/
9300 /*
9301 ** 2017-12-26
9302 **
9303 ** The author disclaims copyright to this source code.  In place of
9304 ** a legal notice, here is a blessing:
9305 **
9306 **    May you do good and not evil.
9307 **    May you find forgiveness for yourself and forgive others.
9308 **    May you share freely, never taking more than you give.
9309 **
9310 ******************************************************************************
9311 **
9312 ** This file implements a virtual table for reading and writing ZIP archive
9313 ** files.
9314 **
9315 ** Usage example:
9316 **
9317 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
9318 **
9319 ** Current limitations:
9320 **
9321 **    *  No support for encryption
9322 **    *  No support for ZIP archives spanning multiple files
9323 **    *  No support for zip64 extensions
9324 **    *  Only the "inflate/deflate" (zlib) compression method is supported
9325 */
9326 /* #include "sqlite3ext.h" */
9327 SQLITE_EXTENSION_INIT1
9328 #include <stdio.h>
9329 #include <string.h>
9330 #include <assert.h>
9331 #include <stdint.h>
9332 
9333 #include <zlib.h>
9334 
9335 #ifndef SQLITE_OMIT_VIRTUALTABLE
9336 
9337 #ifndef SQLITE_AMALGAMATION
9338 
9339 #ifndef UINT32_TYPE
9340 # ifdef HAVE_UINT32_T
9341 #  define UINT32_TYPE uint32_t
9342 # else
9343 #  define UINT32_TYPE unsigned int
9344 # endif
9345 #endif
9346 #ifndef UINT16_TYPE
9347 # ifdef HAVE_UINT16_T
9348 #  define UINT16_TYPE uint16_t
9349 # else
9350 #  define UINT16_TYPE unsigned short int
9351 # endif
9352 #endif
9353 /* typedef sqlite3_int64 i64; */
9354 /* typedef unsigned char u8; */
9355 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
9356 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
9357 #define MIN(a,b) ((a)<(b) ? (a) : (b))
9358 
9359 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
9360 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
9361 #endif
9362 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
9363 # define ALWAYS(X)      (1)
9364 # define NEVER(X)       (0)
9365 #elif !defined(NDEBUG)
9366 # define ALWAYS(X)      ((X)?1:(assert(0),0))
9367 # define NEVER(X)       ((X)?(assert(0),1):0)
9368 #else
9369 # define ALWAYS(X)      (X)
9370 # define NEVER(X)       (X)
9371 #endif
9372 
9373 #endif   /* SQLITE_AMALGAMATION */
9374 
9375 /*
9376 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
9377 **
9378 ** In some ways it would be better to obtain these values from system
9379 ** header files. But, the dependency is undesirable and (a) these
9380 ** have been stable for decades, (b) the values are part of POSIX and
9381 ** are also made explicit in [man stat], and (c) are part of the
9382 ** file format for zip archives.
9383 */
9384 #ifndef S_IFDIR
9385 # define S_IFDIR 0040000
9386 #endif
9387 #ifndef S_IFREG
9388 # define S_IFREG 0100000
9389 #endif
9390 #ifndef S_IFLNK
9391 # define S_IFLNK 0120000
9392 #endif
9393 
9394 static const char ZIPFILE_SCHEMA[] =
9395   "CREATE TABLE y("
9396     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
9397     "mode,"              /* 1: POSIX mode for file */
9398     "mtime,"             /* 2: Last modification time (secs since 1970)*/
9399     "sz,"                /* 3: Size of object */
9400     "rawdata,"           /* 4: Raw data */
9401     "data,"              /* 5: Uncompressed data */
9402     "method,"            /* 6: Compression method (integer) */
9403     "z HIDDEN"           /* 7: Name of zip file */
9404   ") WITHOUT ROWID;";
9405 
9406 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
9407 #define ZIPFILE_BUFFER_SIZE (64*1024)
9408 
9409 
9410 /*
9411 ** Magic numbers used to read and write zip files.
9412 **
9413 ** ZIPFILE_NEWENTRY_MADEBY:
9414 **   Use this value for the "version-made-by" field in new zip file
9415 **   entries. The upper byte indicates "unix", and the lower byte
9416 **   indicates that the zip file matches pkzip specification 3.0.
9417 **   This is what info-zip seems to do.
9418 **
9419 ** ZIPFILE_NEWENTRY_REQUIRED:
9420 **   Value for "version-required-to-extract" field of new entries.
9421 **   Version 2.0 is required to support folders and deflate compression.
9422 **
9423 ** ZIPFILE_NEWENTRY_FLAGS:
9424 **   Value for "general-purpose-bit-flags" field of new entries. Bit
9425 **   11 means "utf-8 filename and comment".
9426 **
9427 ** ZIPFILE_SIGNATURE_CDS:
9428 **   First 4 bytes of a valid CDS record.
9429 **
9430 ** ZIPFILE_SIGNATURE_LFH:
9431 **   First 4 bytes of a valid LFH record.
9432 **
9433 ** ZIPFILE_SIGNATURE_EOCD
9434 **   First 4 bytes of a valid EOCD record.
9435 */
9436 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
9437 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
9438 #define ZIPFILE_NEWENTRY_REQUIRED 20
9439 #define ZIPFILE_NEWENTRY_FLAGS    0x800
9440 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
9441 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
9442 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
9443 
9444 /*
9445 ** The sizes of the fixed-size part of each of the three main data
9446 ** structures in a zip archive.
9447 */
9448 #define ZIPFILE_LFH_FIXED_SZ      30
9449 #define ZIPFILE_EOCD_FIXED_SZ     22
9450 #define ZIPFILE_CDS_FIXED_SZ      46
9451 
9452 /*
9453 *** 4.3.16  End of central directory record:
9454 ***
9455 ***   end of central dir signature    4 bytes  (0x06054b50)
9456 ***   number of this disk             2 bytes
9457 ***   number of the disk with the
9458 ***   start of the central directory  2 bytes
9459 ***   total number of entries in the
9460 ***   central directory on this disk  2 bytes
9461 ***   total number of entries in
9462 ***   the central directory           2 bytes
9463 ***   size of the central directory   4 bytes
9464 ***   offset of start of central
9465 ***   directory with respect to
9466 ***   the starting disk number        4 bytes
9467 ***   .ZIP file comment length        2 bytes
9468 ***   .ZIP file comment       (variable size)
9469 */
9470 typedef struct ZipfileEOCD ZipfileEOCD;
9471 struct ZipfileEOCD {
9472   u16 iDisk;
9473   u16 iFirstDisk;
9474   u16 nEntry;
9475   u16 nEntryTotal;
9476   u32 nSize;
9477   u32 iOffset;
9478 };
9479 
9480 /*
9481 *** 4.3.12  Central directory structure:
9482 ***
9483 *** ...
9484 ***
9485 ***   central file header signature   4 bytes  (0x02014b50)
9486 ***   version made by                 2 bytes
9487 ***   version needed to extract       2 bytes
9488 ***   general purpose bit flag        2 bytes
9489 ***   compression method              2 bytes
9490 ***   last mod file time              2 bytes
9491 ***   last mod file date              2 bytes
9492 ***   crc-32                          4 bytes
9493 ***   compressed size                 4 bytes
9494 ***   uncompressed size               4 bytes
9495 ***   file name length                2 bytes
9496 ***   extra field length              2 bytes
9497 ***   file comment length             2 bytes
9498 ***   disk number start               2 bytes
9499 ***   internal file attributes        2 bytes
9500 ***   external file attributes        4 bytes
9501 ***   relative offset of local header 4 bytes
9502 */
9503 typedef struct ZipfileCDS ZipfileCDS;
9504 struct ZipfileCDS {
9505   u16 iVersionMadeBy;
9506   u16 iVersionExtract;
9507   u16 flags;
9508   u16 iCompression;
9509   u16 mTime;
9510   u16 mDate;
9511   u32 crc32;
9512   u32 szCompressed;
9513   u32 szUncompressed;
9514   u16 nFile;
9515   u16 nExtra;
9516   u16 nComment;
9517   u16 iDiskStart;
9518   u16 iInternalAttr;
9519   u32 iExternalAttr;
9520   u32 iOffset;
9521   char *zFile;                    /* Filename (sqlite3_malloc()) */
9522 };
9523 
9524 /*
9525 *** 4.3.7  Local file header:
9526 ***
9527 ***   local file header signature     4 bytes  (0x04034b50)
9528 ***   version needed to extract       2 bytes
9529 ***   general purpose bit flag        2 bytes
9530 ***   compression method              2 bytes
9531 ***   last mod file time              2 bytes
9532 ***   last mod file date              2 bytes
9533 ***   crc-32                          4 bytes
9534 ***   compressed size                 4 bytes
9535 ***   uncompressed size               4 bytes
9536 ***   file name length                2 bytes
9537 ***   extra field length              2 bytes
9538 ***
9539 */
9540 typedef struct ZipfileLFH ZipfileLFH;
9541 struct ZipfileLFH {
9542   u16 iVersionExtract;
9543   u16 flags;
9544   u16 iCompression;
9545   u16 mTime;
9546   u16 mDate;
9547   u32 crc32;
9548   u32 szCompressed;
9549   u32 szUncompressed;
9550   u16 nFile;
9551   u16 nExtra;
9552 };
9553 
9554 typedef struct ZipfileEntry ZipfileEntry;
9555 struct ZipfileEntry {
9556   ZipfileCDS cds;            /* Parsed CDS record */
9557   u32 mUnixTime;             /* Modification time, in UNIX format */
9558   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
9559   i64 iDataOff;              /* Offset to data in file (if aData==0) */
9560   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
9561   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
9562 };
9563 
9564 /*
9565 ** Cursor type for zipfile tables.
9566 */
9567 typedef struct ZipfileCsr ZipfileCsr;
9568 struct ZipfileCsr {
9569   sqlite3_vtab_cursor base;  /* Base class - must be first */
9570   i64 iId;                   /* Cursor ID */
9571   u8 bEof;                   /* True when at EOF */
9572   u8 bNoop;                  /* If next xNext() call is no-op */
9573 
9574   /* Used outside of write transactions */
9575   FILE *pFile;               /* Zip file */
9576   i64 iNextOff;              /* Offset of next record in central directory */
9577   ZipfileEOCD eocd;          /* Parse of central directory record */
9578 
9579   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
9580   ZipfileEntry *pCurrent;    /* Current entry */
9581   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
9582 };
9583 
9584 typedef struct ZipfileTab ZipfileTab;
9585 struct ZipfileTab {
9586   sqlite3_vtab base;         /* Base class - must be first */
9587   char *zFile;               /* Zip file this table accesses (may be NULL) */
9588   sqlite3 *db;               /* Host database connection */
9589   u8 *aBuffer;               /* Temporary buffer used for various tasks */
9590 
9591   ZipfileCsr *pCsrList;      /* List of cursors */
9592   i64 iNextCsrid;
9593 
9594   /* The following are used by write transactions only */
9595   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
9596   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
9597   FILE *pWriteFd;            /* File handle open on zip archive */
9598   i64 szCurrent;             /* Current size of zip archive */
9599   i64 szOrig;                /* Size of archive at start of transaction */
9600 };
9601 
9602 /*
9603 ** Set the error message contained in context ctx to the results of
9604 ** vprintf(zFmt, ...).
9605 */
zipfileCtxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)9606 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
9607   char *zMsg = 0;
9608   va_list ap;
9609   va_start(ap, zFmt);
9610   zMsg = sqlite3_vmprintf(zFmt, ap);
9611   sqlite3_result_error(ctx, zMsg, -1);
9612   sqlite3_free(zMsg);
9613   va_end(ap);
9614 }
9615 
9616 /*
9617 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
9618 ** is not quoted, do nothing.
9619 */
zipfileDequote(char * zIn)9620 static void zipfileDequote(char *zIn){
9621   char q = zIn[0];
9622   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
9623     int iIn = 1;
9624     int iOut = 0;
9625     if( q=='[' ) q = ']';
9626     while( ALWAYS(zIn[iIn]) ){
9627       char c = zIn[iIn++];
9628       if( c==q && zIn[iIn++]!=q ) break;
9629       zIn[iOut++] = c;
9630     }
9631     zIn[iOut] = '\0';
9632   }
9633 }
9634 
9635 /*
9636 ** Construct a new ZipfileTab virtual table object.
9637 **
9638 **   argv[0]   -> module name  ("zipfile")
9639 **   argv[1]   -> database name
9640 **   argv[2]   -> table name
9641 **   argv[...] -> "column name" and other module argument fields.
9642 */
zipfileConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)9643 static int zipfileConnect(
9644   sqlite3 *db,
9645   void *pAux,
9646   int argc, const char *const*argv,
9647   sqlite3_vtab **ppVtab,
9648   char **pzErr
9649 ){
9650   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
9651   int nFile = 0;
9652   const char *zFile = 0;
9653   ZipfileTab *pNew = 0;
9654   int rc;
9655   (void)pAux;
9656 
9657   /* If the table name is not "zipfile", require that the argument be
9658   ** specified. This stops zipfile tables from being created as:
9659   **
9660   **   CREATE VIRTUAL TABLE zzz USING zipfile();
9661   **
9662   ** It does not prevent:
9663   **
9664   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
9665   */
9666   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
9667   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
9668     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
9669     return SQLITE_ERROR;
9670   }
9671 
9672   if( argc>3 ){
9673     zFile = argv[3];
9674     nFile = (int)strlen(zFile)+1;
9675   }
9676 
9677   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
9678   if( rc==SQLITE_OK ){
9679     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
9680     if( pNew==0 ) return SQLITE_NOMEM;
9681     memset(pNew, 0, nByte+nFile);
9682     pNew->db = db;
9683     pNew->aBuffer = (u8*)&pNew[1];
9684     if( zFile ){
9685       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
9686       memcpy(pNew->zFile, zFile, nFile);
9687       zipfileDequote(pNew->zFile);
9688     }
9689   }
9690   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
9691   *ppVtab = (sqlite3_vtab*)pNew;
9692   return rc;
9693 }
9694 
9695 /*
9696 ** Free the ZipfileEntry structure indicated by the only argument.
9697 */
zipfileEntryFree(ZipfileEntry * p)9698 static void zipfileEntryFree(ZipfileEntry *p){
9699   if( p ){
9700     sqlite3_free(p->cds.zFile);
9701     sqlite3_free(p);
9702   }
9703 }
9704 
9705 /*
9706 ** Release resources that should be freed at the end of a write
9707 ** transaction.
9708 */
zipfileCleanupTransaction(ZipfileTab * pTab)9709 static void zipfileCleanupTransaction(ZipfileTab *pTab){
9710   ZipfileEntry *pEntry;
9711   ZipfileEntry *pNext;
9712 
9713   if( pTab->pWriteFd ){
9714     fclose(pTab->pWriteFd);
9715     pTab->pWriteFd = 0;
9716   }
9717   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
9718     pNext = pEntry->pNext;
9719     zipfileEntryFree(pEntry);
9720   }
9721   pTab->pFirstEntry = 0;
9722   pTab->pLastEntry = 0;
9723   pTab->szCurrent = 0;
9724   pTab->szOrig = 0;
9725 }
9726 
9727 /*
9728 ** This method is the destructor for zipfile vtab objects.
9729 */
zipfileDisconnect(sqlite3_vtab * pVtab)9730 static int zipfileDisconnect(sqlite3_vtab *pVtab){
9731   zipfileCleanupTransaction((ZipfileTab*)pVtab);
9732   sqlite3_free(pVtab);
9733   return SQLITE_OK;
9734 }
9735 
9736 /*
9737 ** Constructor for a new ZipfileCsr object.
9738 */
zipfileOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCsr)9739 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
9740   ZipfileTab *pTab = (ZipfileTab*)p;
9741   ZipfileCsr *pCsr;
9742   pCsr = sqlite3_malloc(sizeof(*pCsr));
9743   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
9744   if( pCsr==0 ){
9745     return SQLITE_NOMEM;
9746   }
9747   memset(pCsr, 0, sizeof(*pCsr));
9748   pCsr->iId = ++pTab->iNextCsrid;
9749   pCsr->pCsrNext = pTab->pCsrList;
9750   pTab->pCsrList = pCsr;
9751   return SQLITE_OK;
9752 }
9753 
9754 /*
9755 ** Reset a cursor back to the state it was in when first returned
9756 ** by zipfileOpen().
9757 */
zipfileResetCursor(ZipfileCsr * pCsr)9758 static void zipfileResetCursor(ZipfileCsr *pCsr){
9759   ZipfileEntry *p;
9760   ZipfileEntry *pNext;
9761 
9762   pCsr->bEof = 0;
9763   if( pCsr->pFile ){
9764     fclose(pCsr->pFile);
9765     pCsr->pFile = 0;
9766     zipfileEntryFree(pCsr->pCurrent);
9767     pCsr->pCurrent = 0;
9768   }
9769 
9770   for(p=pCsr->pFreeEntry; p; p=pNext){
9771     pNext = p->pNext;
9772     zipfileEntryFree(p);
9773   }
9774 }
9775 
9776 /*
9777 ** Destructor for an ZipfileCsr.
9778 */
zipfileClose(sqlite3_vtab_cursor * cur)9779 static int zipfileClose(sqlite3_vtab_cursor *cur){
9780   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9781   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
9782   ZipfileCsr **pp;
9783   zipfileResetCursor(pCsr);
9784 
9785   /* Remove this cursor from the ZipfileTab.pCsrList list. */
9786   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
9787   *pp = pCsr->pCsrNext;
9788 
9789   sqlite3_free(pCsr);
9790   return SQLITE_OK;
9791 }
9792 
9793 /*
9794 ** Set the error message for the virtual table associated with cursor
9795 ** pCsr to the results of vprintf(zFmt, ...).
9796 */
zipfileTableErr(ZipfileTab * pTab,const char * zFmt,...)9797 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
9798   va_list ap;
9799   va_start(ap, zFmt);
9800   sqlite3_free(pTab->base.zErrMsg);
9801   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
9802   va_end(ap);
9803 }
zipfileCursorErr(ZipfileCsr * pCsr,const char * zFmt,...)9804 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
9805   va_list ap;
9806   va_start(ap, zFmt);
9807   sqlite3_free(pCsr->base.pVtab->zErrMsg);
9808   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
9809   va_end(ap);
9810 }
9811 
9812 /*
9813 ** Read nRead bytes of data from offset iOff of file pFile into buffer
9814 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
9815 ** otherwise.
9816 **
9817 ** If an error does occur, output variable (*pzErrmsg) may be set to point
9818 ** to an English language error message. It is the responsibility of the
9819 ** caller to eventually free this buffer using
9820 ** sqlite3_free().
9821 */
zipfileReadData(FILE * pFile,u8 * aRead,int nRead,i64 iOff,char ** pzErrmsg)9822 static int zipfileReadData(
9823   FILE *pFile,                    /* Read from this file */
9824   u8 *aRead,                      /* Read into this buffer */
9825   int nRead,                      /* Number of bytes to read */
9826   i64 iOff,                       /* Offset to read from */
9827   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
9828 ){
9829   size_t n;
9830   fseek(pFile, (long)iOff, SEEK_SET);
9831   n = fread(aRead, 1, nRead, pFile);
9832   if( (int)n!=nRead ){
9833     *pzErrmsg = sqlite3_mprintf("error in fread()");
9834     return SQLITE_ERROR;
9835   }
9836   return SQLITE_OK;
9837 }
9838 
zipfileAppendData(ZipfileTab * pTab,const u8 * aWrite,int nWrite)9839 static int zipfileAppendData(
9840   ZipfileTab *pTab,
9841   const u8 *aWrite,
9842   int nWrite
9843 ){
9844   if( nWrite>0 ){
9845     size_t n = nWrite;
9846     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
9847     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
9848     if( (int)n!=nWrite ){
9849       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
9850       return SQLITE_ERROR;
9851     }
9852     pTab->szCurrent += nWrite;
9853   }
9854   return SQLITE_OK;
9855 }
9856 
9857 /*
9858 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9859 */
zipfileGetU16(const u8 * aBuf)9860 static u16 zipfileGetU16(const u8 *aBuf){
9861   return (aBuf[1] << 8) + aBuf[0];
9862 }
9863 
9864 /*
9865 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9866 */
zipfileGetU32(const u8 * aBuf)9867 static u32 zipfileGetU32(const u8 *aBuf){
9868   if( aBuf==0 ) return 0;
9869   return ((u32)(aBuf[3]) << 24)
9870        + ((u32)(aBuf[2]) << 16)
9871        + ((u32)(aBuf[1]) <<  8)
9872        + ((u32)(aBuf[0]) <<  0);
9873 }
9874 
9875 /*
9876 ** Write a 16-bit little endiate integer into buffer aBuf.
9877 */
zipfilePutU16(u8 * aBuf,u16 val)9878 static void zipfilePutU16(u8 *aBuf, u16 val){
9879   aBuf[0] = val & 0xFF;
9880   aBuf[1] = (val>>8) & 0xFF;
9881 }
9882 
9883 /*
9884 ** Write a 32-bit little endiate integer into buffer aBuf.
9885 */
zipfilePutU32(u8 * aBuf,u32 val)9886 static void zipfilePutU32(u8 *aBuf, u32 val){
9887   aBuf[0] = val & 0xFF;
9888   aBuf[1] = (val>>8) & 0xFF;
9889   aBuf[2] = (val>>16) & 0xFF;
9890   aBuf[3] = (val>>24) & 0xFF;
9891 }
9892 
9893 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9894 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9895 
9896 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
9897 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
9898 
9899 /*
9900 ** Magic numbers used to read CDS records.
9901 */
9902 #define ZIPFILE_CDS_NFILE_OFF        28
9903 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
9904 
9905 /*
9906 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
9907 ** if the record is not well-formed, or SQLITE_OK otherwise.
9908 */
zipfileReadCDS(u8 * aBuf,ZipfileCDS * pCDS)9909 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
9910   u8 *aRead = aBuf;
9911   u32 sig = zipfileRead32(aRead);
9912   int rc = SQLITE_OK;
9913   if( sig!=ZIPFILE_SIGNATURE_CDS ){
9914     rc = SQLITE_ERROR;
9915   }else{
9916     pCDS->iVersionMadeBy = zipfileRead16(aRead);
9917     pCDS->iVersionExtract = zipfileRead16(aRead);
9918     pCDS->flags = zipfileRead16(aRead);
9919     pCDS->iCompression = zipfileRead16(aRead);
9920     pCDS->mTime = zipfileRead16(aRead);
9921     pCDS->mDate = zipfileRead16(aRead);
9922     pCDS->crc32 = zipfileRead32(aRead);
9923     pCDS->szCompressed = zipfileRead32(aRead);
9924     pCDS->szUncompressed = zipfileRead32(aRead);
9925     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
9926     pCDS->nFile = zipfileRead16(aRead);
9927     pCDS->nExtra = zipfileRead16(aRead);
9928     pCDS->nComment = zipfileRead16(aRead);
9929     pCDS->iDiskStart = zipfileRead16(aRead);
9930     pCDS->iInternalAttr = zipfileRead16(aRead);
9931     pCDS->iExternalAttr = zipfileRead32(aRead);
9932     pCDS->iOffset = zipfileRead32(aRead);
9933     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
9934   }
9935 
9936   return rc;
9937 }
9938 
9939 /*
9940 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
9941 ** if the record is not well-formed, or SQLITE_OK otherwise.
9942 */
zipfileReadLFH(u8 * aBuffer,ZipfileLFH * pLFH)9943 static int zipfileReadLFH(
9944   u8 *aBuffer,
9945   ZipfileLFH *pLFH
9946 ){
9947   u8 *aRead = aBuffer;
9948   int rc = SQLITE_OK;
9949 
9950   u32 sig = zipfileRead32(aRead);
9951   if( sig!=ZIPFILE_SIGNATURE_LFH ){
9952     rc = SQLITE_ERROR;
9953   }else{
9954     pLFH->iVersionExtract = zipfileRead16(aRead);
9955     pLFH->flags = zipfileRead16(aRead);
9956     pLFH->iCompression = zipfileRead16(aRead);
9957     pLFH->mTime = zipfileRead16(aRead);
9958     pLFH->mDate = zipfileRead16(aRead);
9959     pLFH->crc32 = zipfileRead32(aRead);
9960     pLFH->szCompressed = zipfileRead32(aRead);
9961     pLFH->szUncompressed = zipfileRead32(aRead);
9962     pLFH->nFile = zipfileRead16(aRead);
9963     pLFH->nExtra = zipfileRead16(aRead);
9964   }
9965   return rc;
9966 }
9967 
9968 
9969 /*
9970 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
9971 ** Scan through this buffer to find an "extra-timestamp" field. If one
9972 ** exists, extract the 32-bit modification-timestamp from it and store
9973 ** the value in output parameter *pmTime.
9974 **
9975 ** Zero is returned if no extra-timestamp record could be found (and so
9976 ** *pmTime is left unchanged), or non-zero otherwise.
9977 **
9978 ** The general format of an extra field is:
9979 **
9980 **   Header ID    2 bytes
9981 **   Data Size    2 bytes
9982 **   Data         N bytes
9983 */
zipfileScanExtra(u8 * aExtra,int nExtra,u32 * pmTime)9984 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
9985   int ret = 0;
9986   u8 *p = aExtra;
9987   u8 *pEnd = &aExtra[nExtra];
9988 
9989   while( p<pEnd ){
9990     u16 id = zipfileRead16(p);
9991     u16 nByte = zipfileRead16(p);
9992 
9993     switch( id ){
9994       case ZIPFILE_EXTRA_TIMESTAMP: {
9995         u8 b = p[0];
9996         if( b & 0x01 ){     /* 0x01 -> modtime is present */
9997           *pmTime = zipfileGetU32(&p[1]);
9998           ret = 1;
9999         }
10000         break;
10001       }
10002     }
10003 
10004     p += nByte;
10005   }
10006   return ret;
10007 }
10008 
10009 /*
10010 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10011 ** fields of the CDS structure passed as the only argument to a 32-bit
10012 ** UNIX seconds-since-the-epoch timestamp. Return the result.
10013 **
10014 ** "Standard" MS-DOS time format:
10015 **
10016 **   File modification time:
10017 **     Bits 00-04: seconds divided by 2
10018 **     Bits 05-10: minute
10019 **     Bits 11-15: hour
10020 **   File modification date:
10021 **     Bits 00-04: day
10022 **     Bits 05-08: month (1-12)
10023 **     Bits 09-15: years from 1980
10024 **
10025 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10026 */
zipfileMtime(ZipfileCDS * pCDS)10027 static u32 zipfileMtime(ZipfileCDS *pCDS){
10028   int Y,M,D,X1,X2,A,B,sec,min,hr;
10029   i64 JDsec;
10030   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
10031   M = ((pCDS->mDate >> 5) & 0x0F);
10032   D = (pCDS->mDate & 0x1F);
10033   sec = (pCDS->mTime & 0x1F)*2;
10034   min = (pCDS->mTime >> 5) & 0x3F;
10035   hr = (pCDS->mTime >> 11) & 0x1F;
10036   if( M<=2 ){
10037     Y--;
10038     M += 12;
10039   }
10040   X1 = 36525*(Y+4716)/100;
10041   X2 = 306001*(M+1)/10000;
10042   A = Y/100;
10043   B = 2 - A + (A/4);
10044   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
10045   return (u32)(JDsec - (i64)24405875*(i64)8640);
10046 }
10047 
10048 /*
10049 ** The opposite of zipfileMtime(). This function populates the mTime and
10050 ** mDate fields of the CDS structure passed as the first argument according
10051 ** to the UNIX timestamp value passed as the second.
10052 */
zipfileMtimeToDos(ZipfileCDS * pCds,u32 mUnixTime)10053 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
10054   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
10055   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
10056 
10057   int A, B, C, D, E;
10058   int yr, mon, day;
10059   int hr, min, sec;
10060 
10061   A = (int)((JD - 1867216.25)/36524.25);
10062   A = (int)(JD + 1 + A - (A/4));
10063   B = A + 1524;
10064   C = (int)((B - 122.1)/365.25);
10065   D = (36525*(C&32767))/100;
10066   E = (int)((B-D)/30.6001);
10067 
10068   day = B - D - (int)(30.6001*E);
10069   mon = (E<14 ? E-1 : E-13);
10070   yr = mon>2 ? C-4716 : C-4715;
10071 
10072   hr = (mUnixTime % (24*60*60)) / (60*60);
10073   min = (mUnixTime % (60*60)) / 60;
10074   sec = (mUnixTime % 60);
10075 
10076   if( yr>=1980 ){
10077     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
10078     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
10079   }else{
10080     pCds->mDate = pCds->mTime = 0;
10081   }
10082 
10083   assert( mUnixTime<315507600
10084        || mUnixTime==zipfileMtime(pCds)
10085        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
10086        /* || (mUnixTime % 2) */
10087   );
10088 }
10089 
10090 /*
10091 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
10092 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
10093 ** then pFile is a file-handle open on a zip file. In either case, this
10094 ** function creates a ZipfileEntry object based on the zip archive entry
10095 ** for which the CDS record is at offset iOff.
10096 **
10097 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
10098 ** the new object. Otherwise, an SQLite error code is returned and the
10099 ** final value of (*ppEntry) undefined.
10100 */
zipfileGetEntry(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,i64 iOff,ZipfileEntry ** ppEntry)10101 static int zipfileGetEntry(
10102   ZipfileTab *pTab,               /* Store any error message here */
10103   const u8 *aBlob,                /* Pointer to in-memory file image */
10104   int nBlob,                      /* Size of aBlob[] in bytes */
10105   FILE *pFile,                    /* If aBlob==0, read from this file */
10106   i64 iOff,                       /* Offset of CDS record */
10107   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
10108 ){
10109   u8 *aRead;
10110   char **pzErr = &pTab->base.zErrMsg;
10111   int rc = SQLITE_OK;
10112   (void)nBlob;
10113 
10114   if( aBlob==0 ){
10115     aRead = pTab->aBuffer;
10116     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
10117   }else{
10118     aRead = (u8*)&aBlob[iOff];
10119   }
10120 
10121   if( rc==SQLITE_OK ){
10122     sqlite3_int64 nAlloc;
10123     ZipfileEntry *pNew;
10124 
10125     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
10126     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
10127     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
10128 
10129     nAlloc = sizeof(ZipfileEntry) + nExtra;
10130     if( aBlob ){
10131       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
10132     }
10133 
10134     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
10135     if( pNew==0 ){
10136       rc = SQLITE_NOMEM;
10137     }else{
10138       memset(pNew, 0, sizeof(ZipfileEntry));
10139       rc = zipfileReadCDS(aRead, &pNew->cds);
10140       if( rc!=SQLITE_OK ){
10141         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
10142       }else if( aBlob==0 ){
10143         rc = zipfileReadData(
10144             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
10145         );
10146       }else{
10147         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
10148       }
10149     }
10150 
10151     if( rc==SQLITE_OK ){
10152       u32 *pt = &pNew->mUnixTime;
10153       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
10154       pNew->aExtra = (u8*)&pNew[1];
10155       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
10156       if( pNew->cds.zFile==0 ){
10157         rc = SQLITE_NOMEM;
10158       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
10159         pNew->mUnixTime = zipfileMtime(&pNew->cds);
10160       }
10161     }
10162 
10163     if( rc==SQLITE_OK ){
10164       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
10165       ZipfileLFH lfh;
10166       if( pFile ){
10167         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
10168       }else{
10169         aRead = (u8*)&aBlob[pNew->cds.iOffset];
10170       }
10171 
10172       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
10173       if( rc==SQLITE_OK ){
10174         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
10175         pNew->iDataOff += lfh.nFile + lfh.nExtra;
10176         if( aBlob && pNew->cds.szCompressed ){
10177           pNew->aData = &pNew->aExtra[nExtra];
10178           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
10179         }
10180       }else{
10181         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
10182             (int)pNew->cds.iOffset
10183         );
10184       }
10185     }
10186 
10187     if( rc!=SQLITE_OK ){
10188       zipfileEntryFree(pNew);
10189     }else{
10190       *ppEntry = pNew;
10191     }
10192   }
10193 
10194   return rc;
10195 }
10196 
10197 /*
10198 ** Advance an ZipfileCsr to its next row of output.
10199 */
zipfileNext(sqlite3_vtab_cursor * cur)10200 static int zipfileNext(sqlite3_vtab_cursor *cur){
10201   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10202   int rc = SQLITE_OK;
10203 
10204   if( pCsr->pFile ){
10205     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
10206     zipfileEntryFree(pCsr->pCurrent);
10207     pCsr->pCurrent = 0;
10208     if( pCsr->iNextOff>=iEof ){
10209       pCsr->bEof = 1;
10210     }else{
10211       ZipfileEntry *p = 0;
10212       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
10213       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
10214       if( rc==SQLITE_OK ){
10215         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
10216         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
10217       }
10218       pCsr->pCurrent = p;
10219     }
10220   }else{
10221     if( !pCsr->bNoop ){
10222       pCsr->pCurrent = pCsr->pCurrent->pNext;
10223     }
10224     if( pCsr->pCurrent==0 ){
10225       pCsr->bEof = 1;
10226     }
10227   }
10228 
10229   pCsr->bNoop = 0;
10230   return rc;
10231 }
10232 
zipfileFree(void * p)10233 static void zipfileFree(void *p) {
10234   sqlite3_free(p);
10235 }
10236 
10237 /*
10238 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
10239 ** size is nOut bytes. This function uncompresses the data and sets the
10240 ** return value in context pCtx to the result (a blob).
10241 **
10242 ** If an error occurs, an error code is left in pCtx instead.
10243 */
zipfileInflate(sqlite3_context * pCtx,const u8 * aIn,int nIn,int nOut)10244 static void zipfileInflate(
10245   sqlite3_context *pCtx,          /* Store result here */
10246   const u8 *aIn,                  /* Compressed data */
10247   int nIn,                        /* Size of buffer aIn[] in bytes */
10248   int nOut                        /* Expected output size */
10249 ){
10250   u8 *aRes = sqlite3_malloc(nOut);
10251   if( aRes==0 ){
10252     sqlite3_result_error_nomem(pCtx);
10253   }else{
10254     int err;
10255     z_stream str;
10256     memset(&str, 0, sizeof(str));
10257 
10258     str.next_in = (Byte*)aIn;
10259     str.avail_in = nIn;
10260     str.next_out = (Byte*)aRes;
10261     str.avail_out = nOut;
10262 
10263     err = inflateInit2(&str, -15);
10264     if( err!=Z_OK ){
10265       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
10266     }else{
10267       err = inflate(&str, Z_NO_FLUSH);
10268       if( err!=Z_STREAM_END ){
10269         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
10270       }else{
10271         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
10272         aRes = 0;
10273       }
10274     }
10275     sqlite3_free(aRes);
10276     inflateEnd(&str);
10277   }
10278 }
10279 
10280 /*
10281 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
10282 ** compresses it and sets (*ppOut) to point to a buffer containing the
10283 ** compressed data. The caller is responsible for eventually calling
10284 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
10285 ** is set to the size of buffer (*ppOut) in bytes.
10286 **
10287 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
10288 ** code is returned and an error message left in virtual-table handle
10289 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
10290 ** case.
10291 */
zipfileDeflate(const u8 * aIn,int nIn,u8 ** ppOut,int * pnOut,char ** pzErr)10292 static int zipfileDeflate(
10293   const u8 *aIn, int nIn,         /* Input */
10294   u8 **ppOut, int *pnOut,         /* Output */
10295   char **pzErr                    /* OUT: Error message */
10296 ){
10297   int rc = SQLITE_OK;
10298   sqlite3_int64 nAlloc;
10299   z_stream str;
10300   u8 *aOut;
10301 
10302   memset(&str, 0, sizeof(str));
10303   str.next_in = (Bytef*)aIn;
10304   str.avail_in = nIn;
10305   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
10306 
10307   nAlloc = deflateBound(&str, nIn);
10308   aOut = (u8*)sqlite3_malloc64(nAlloc);
10309   if( aOut==0 ){
10310     rc = SQLITE_NOMEM;
10311   }else{
10312     int res;
10313     str.next_out = aOut;
10314     str.avail_out = nAlloc;
10315     res = deflate(&str, Z_FINISH);
10316     if( res==Z_STREAM_END ){
10317       *ppOut = aOut;
10318       *pnOut = (int)str.total_out;
10319     }else{
10320       sqlite3_free(aOut);
10321       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
10322       rc = SQLITE_ERROR;
10323     }
10324     deflateEnd(&str);
10325   }
10326 
10327   return rc;
10328 }
10329 
10330 
10331 /*
10332 ** Return values of columns for the row at which the series_cursor
10333 ** is currently pointing.
10334 */
zipfileColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)10335 static int zipfileColumn(
10336   sqlite3_vtab_cursor *cur,   /* The cursor */
10337   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
10338   int i                       /* Which column to return */
10339 ){
10340   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10341   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
10342   int rc = SQLITE_OK;
10343   switch( i ){
10344     case 0:   /* name */
10345       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
10346       break;
10347     case 1:   /* mode */
10348       /* TODO: Whether or not the following is correct surely depends on
10349       ** the platform on which the archive was created.  */
10350       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
10351       break;
10352     case 2: { /* mtime */
10353       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
10354       break;
10355     }
10356     case 3: { /* sz */
10357       if( sqlite3_vtab_nochange(ctx)==0 ){
10358         sqlite3_result_int64(ctx, pCDS->szUncompressed);
10359       }
10360       break;
10361     }
10362     case 4:   /* rawdata */
10363       if( sqlite3_vtab_nochange(ctx) ) break;
10364     case 5: { /* data */
10365       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
10366         int sz = pCDS->szCompressed;
10367         int szFinal = pCDS->szUncompressed;
10368         if( szFinal>0 ){
10369           u8 *aBuf;
10370           u8 *aFree = 0;
10371           if( pCsr->pCurrent->aData ){
10372             aBuf = pCsr->pCurrent->aData;
10373           }else{
10374             aBuf = aFree = sqlite3_malloc64(sz);
10375             if( aBuf==0 ){
10376               rc = SQLITE_NOMEM;
10377             }else{
10378               FILE *pFile = pCsr->pFile;
10379               if( pFile==0 ){
10380                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
10381               }
10382               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
10383                   &pCsr->base.pVtab->zErrMsg
10384               );
10385             }
10386           }
10387           if( rc==SQLITE_OK ){
10388             if( i==5 && pCDS->iCompression ){
10389               zipfileInflate(ctx, aBuf, sz, szFinal);
10390             }else{
10391               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
10392             }
10393           }
10394           sqlite3_free(aFree);
10395         }else{
10396           /* Figure out if this is a directory or a zero-sized file. Consider
10397           ** it to be a directory either if the mode suggests so, or if
10398           ** the final character in the name is '/'.  */
10399           u32 mode = pCDS->iExternalAttr >> 16;
10400           if( !(mode & S_IFDIR)
10401            && pCDS->nFile>=1
10402            && pCDS->zFile[pCDS->nFile-1]!='/'
10403           ){
10404             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
10405           }
10406         }
10407       }
10408       break;
10409     }
10410     case 6:   /* method */
10411       sqlite3_result_int(ctx, pCDS->iCompression);
10412       break;
10413     default:  /* z */
10414       assert( i==7 );
10415       sqlite3_result_int64(ctx, pCsr->iId);
10416       break;
10417   }
10418 
10419   return rc;
10420 }
10421 
10422 /*
10423 ** Return TRUE if the cursor is at EOF.
10424 */
zipfileEof(sqlite3_vtab_cursor * cur)10425 static int zipfileEof(sqlite3_vtab_cursor *cur){
10426   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10427   return pCsr->bEof;
10428 }
10429 
10430 /*
10431 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
10432 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
10433 ** is guaranteed to be a file-handle open on a zip file.
10434 **
10435 ** This function attempts to locate the EOCD record within the zip archive
10436 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
10437 ** returned if successful. Otherwise, an SQLite error code is returned and
10438 ** an English language error message may be left in virtual-table pTab.
10439 */
zipfileReadEOCD(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,ZipfileEOCD * pEOCD)10440 static int zipfileReadEOCD(
10441   ZipfileTab *pTab,               /* Return errors here */
10442   const u8 *aBlob,                /* Pointer to in-memory file image */
10443   int nBlob,                      /* Size of aBlob[] in bytes */
10444   FILE *pFile,                    /* Read from this file if aBlob==0 */
10445   ZipfileEOCD *pEOCD              /* Object to populate */
10446 ){
10447   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
10448   int nRead;                      /* Bytes to read from file */
10449   int rc = SQLITE_OK;
10450 
10451   memset(pEOCD, 0, sizeof(ZipfileEOCD));
10452   if( aBlob==0 ){
10453     i64 iOff;                     /* Offset to read from */
10454     i64 szFile;                   /* Total size of file in bytes */
10455     fseek(pFile, 0, SEEK_END);
10456     szFile = (i64)ftell(pFile);
10457     if( szFile==0 ){
10458       return SQLITE_OK;
10459     }
10460     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
10461     iOff = szFile - nRead;
10462     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
10463   }else{
10464     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
10465     aRead = (u8*)&aBlob[nBlob-nRead];
10466   }
10467 
10468   if( rc==SQLITE_OK ){
10469     int i;
10470 
10471     /* Scan backwards looking for the signature bytes */
10472     for(i=nRead-20; i>=0; i--){
10473       if( aRead[i]==0x50 && aRead[i+1]==0x4b
10474        && aRead[i+2]==0x05 && aRead[i+3]==0x06
10475       ){
10476         break;
10477       }
10478     }
10479     if( i<0 ){
10480       pTab->base.zErrMsg = sqlite3_mprintf(
10481           "cannot find end of central directory record"
10482       );
10483       return SQLITE_ERROR;
10484     }
10485 
10486     aRead += i+4;
10487     pEOCD->iDisk = zipfileRead16(aRead);
10488     pEOCD->iFirstDisk = zipfileRead16(aRead);
10489     pEOCD->nEntry = zipfileRead16(aRead);
10490     pEOCD->nEntryTotal = zipfileRead16(aRead);
10491     pEOCD->nSize = zipfileRead32(aRead);
10492     pEOCD->iOffset = zipfileRead32(aRead);
10493   }
10494 
10495   return rc;
10496 }
10497 
10498 /*
10499 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
10500 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
10501 ** to the end of the list. Otherwise, it is added to the list immediately
10502 ** before pBefore (which is guaranteed to be a part of said list).
10503 */
zipfileAddEntry(ZipfileTab * pTab,ZipfileEntry * pBefore,ZipfileEntry * pNew)10504 static void zipfileAddEntry(
10505   ZipfileTab *pTab,
10506   ZipfileEntry *pBefore,
10507   ZipfileEntry *pNew
10508 ){
10509   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
10510   assert( pNew->pNext==0 );
10511   if( pBefore==0 ){
10512     if( pTab->pFirstEntry==0 ){
10513       pTab->pFirstEntry = pTab->pLastEntry = pNew;
10514     }else{
10515       assert( pTab->pLastEntry->pNext==0 );
10516       pTab->pLastEntry->pNext = pNew;
10517       pTab->pLastEntry = pNew;
10518     }
10519   }else{
10520     ZipfileEntry **pp;
10521     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
10522     pNew->pNext = pBefore;
10523     *pp = pNew;
10524   }
10525 }
10526 
zipfileLoadDirectory(ZipfileTab * pTab,const u8 * aBlob,int nBlob)10527 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
10528   ZipfileEOCD eocd;
10529   int rc;
10530   int i;
10531   i64 iOff;
10532 
10533   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
10534   iOff = eocd.iOffset;
10535   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
10536     ZipfileEntry *pNew = 0;
10537     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
10538 
10539     if( rc==SQLITE_OK ){
10540       zipfileAddEntry(pTab, 0, pNew);
10541       iOff += ZIPFILE_CDS_FIXED_SZ;
10542       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
10543     }
10544   }
10545   return rc;
10546 }
10547 
10548 /*
10549 ** xFilter callback.
10550 */
zipfileFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)10551 static int zipfileFilter(
10552   sqlite3_vtab_cursor *cur,
10553   int idxNum, const char *idxStr,
10554   int argc, sqlite3_value **argv
10555 ){
10556   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
10557   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10558   const char *zFile = 0;          /* Zip file to scan */
10559   int rc = SQLITE_OK;             /* Return Code */
10560   int bInMemory = 0;              /* True for an in-memory zipfile */
10561 
10562   (void)idxStr;
10563   (void)argc;
10564 
10565   zipfileResetCursor(pCsr);
10566 
10567   if( pTab->zFile ){
10568     zFile = pTab->zFile;
10569   }else if( idxNum==0 ){
10570     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
10571     return SQLITE_ERROR;
10572   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
10573     static const u8 aEmptyBlob = 0;
10574     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
10575     int nBlob = sqlite3_value_bytes(argv[0]);
10576     assert( pTab->pFirstEntry==0 );
10577     if( aBlob==0 ){
10578       aBlob = &aEmptyBlob;
10579       nBlob = 0;
10580     }
10581     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
10582     pCsr->pFreeEntry = pTab->pFirstEntry;
10583     pTab->pFirstEntry = pTab->pLastEntry = 0;
10584     if( rc!=SQLITE_OK ) return rc;
10585     bInMemory = 1;
10586   }else{
10587     zFile = (const char*)sqlite3_value_text(argv[0]);
10588   }
10589 
10590   if( 0==pTab->pWriteFd && 0==bInMemory ){
10591     pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
10592     if( pCsr->pFile==0 ){
10593       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
10594       rc = SQLITE_ERROR;
10595     }else{
10596       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
10597       if( rc==SQLITE_OK ){
10598         if( pCsr->eocd.nEntry==0 ){
10599           pCsr->bEof = 1;
10600         }else{
10601           pCsr->iNextOff = pCsr->eocd.iOffset;
10602           rc = zipfileNext(cur);
10603         }
10604       }
10605     }
10606   }else{
10607     pCsr->bNoop = 1;
10608     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
10609     rc = zipfileNext(cur);
10610   }
10611 
10612   return rc;
10613 }
10614 
10615 /*
10616 ** xBestIndex callback.
10617 */
zipfileBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)10618 static int zipfileBestIndex(
10619   sqlite3_vtab *tab,
10620   sqlite3_index_info *pIdxInfo
10621 ){
10622   int i;
10623   int idx = -1;
10624   int unusable = 0;
10625   (void)tab;
10626 
10627   for(i=0; i<pIdxInfo->nConstraint; i++){
10628     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
10629     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
10630     if( pCons->usable==0 ){
10631       unusable = 1;
10632     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10633       idx = i;
10634     }
10635   }
10636   pIdxInfo->estimatedCost = 1000.0;
10637   if( idx>=0 ){
10638     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
10639     pIdxInfo->aConstraintUsage[idx].omit = 1;
10640     pIdxInfo->idxNum = 1;
10641   }else if( unusable ){
10642     return SQLITE_CONSTRAINT;
10643   }
10644   return SQLITE_OK;
10645 }
10646 
zipfileNewEntry(const char * zPath)10647 static ZipfileEntry *zipfileNewEntry(const char *zPath){
10648   ZipfileEntry *pNew;
10649   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
10650   if( pNew ){
10651     memset(pNew, 0, sizeof(ZipfileEntry));
10652     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
10653     if( pNew->cds.zFile==0 ){
10654       sqlite3_free(pNew);
10655       pNew = 0;
10656     }
10657   }
10658   return pNew;
10659 }
10660 
zipfileSerializeLFH(ZipfileEntry * pEntry,u8 * aBuf)10661 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
10662   ZipfileCDS *pCds = &pEntry->cds;
10663   u8 *a = aBuf;
10664 
10665   pCds->nExtra = 9;
10666 
10667   /* Write the LFH itself */
10668   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
10669   zipfileWrite16(a, pCds->iVersionExtract);
10670   zipfileWrite16(a, pCds->flags);
10671   zipfileWrite16(a, pCds->iCompression);
10672   zipfileWrite16(a, pCds->mTime);
10673   zipfileWrite16(a, pCds->mDate);
10674   zipfileWrite32(a, pCds->crc32);
10675   zipfileWrite32(a, pCds->szCompressed);
10676   zipfileWrite32(a, pCds->szUncompressed);
10677   zipfileWrite16(a, (u16)pCds->nFile);
10678   zipfileWrite16(a, pCds->nExtra);
10679   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
10680 
10681   /* Add the file name */
10682   memcpy(a, pCds->zFile, (int)pCds->nFile);
10683   a += (int)pCds->nFile;
10684 
10685   /* The "extra" data */
10686   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
10687   zipfileWrite16(a, 5);
10688   *a++ = 0x01;
10689   zipfileWrite32(a, pEntry->mUnixTime);
10690 
10691   return a-aBuf;
10692 }
10693 
zipfileAppendEntry(ZipfileTab * pTab,ZipfileEntry * pEntry,const u8 * pData,int nData)10694 static int zipfileAppendEntry(
10695   ZipfileTab *pTab,
10696   ZipfileEntry *pEntry,
10697   const u8 *pData,
10698   int nData
10699 ){
10700   u8 *aBuf = pTab->aBuffer;
10701   int nBuf;
10702   int rc;
10703 
10704   nBuf = zipfileSerializeLFH(pEntry, aBuf);
10705   rc = zipfileAppendData(pTab, aBuf, nBuf);
10706   if( rc==SQLITE_OK ){
10707     pEntry->iDataOff = pTab->szCurrent;
10708     rc = zipfileAppendData(pTab, pData, nData);
10709   }
10710 
10711   return rc;
10712 }
10713 
zipfileGetMode(sqlite3_value * pVal,int bIsDir,u32 * pMode,char ** pzErr)10714 static int zipfileGetMode(
10715   sqlite3_value *pVal,
10716   int bIsDir,                     /* If true, default to directory */
10717   u32 *pMode,                     /* OUT: Mode value */
10718   char **pzErr                    /* OUT: Error message */
10719 ){
10720   const char *z = (const char*)sqlite3_value_text(pVal);
10721   u32 mode = 0;
10722   if( z==0 ){
10723     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
10724   }else if( z[0]>='0' && z[0]<='9' ){
10725     mode = (unsigned int)sqlite3_value_int(pVal);
10726   }else{
10727     const char zTemplate[11] = "-rwxrwxrwx";
10728     int i;
10729     if( strlen(z)!=10 ) goto parse_error;
10730     switch( z[0] ){
10731       case '-': mode |= S_IFREG; break;
10732       case 'd': mode |= S_IFDIR; break;
10733       case 'l': mode |= S_IFLNK; break;
10734       default: goto parse_error;
10735     }
10736     for(i=1; i<10; i++){
10737       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
10738       else if( z[i]!='-' ) goto parse_error;
10739     }
10740   }
10741   if( ((mode & S_IFDIR)==0)==bIsDir ){
10742     /* The "mode" attribute is a directory, but data has been specified.
10743     ** Or vice-versa - no data but "mode" is a file or symlink.  */
10744     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
10745     return SQLITE_CONSTRAINT;
10746   }
10747   *pMode = mode;
10748   return SQLITE_OK;
10749 
10750  parse_error:
10751   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
10752   return SQLITE_ERROR;
10753 }
10754 
10755 /*
10756 ** Both (const char*) arguments point to nul-terminated strings. Argument
10757 ** nB is the value of strlen(zB). This function returns 0 if the strings are
10758 ** identical, ignoring any trailing '/' character in either path.  */
zipfileComparePath(const char * zA,const char * zB,int nB)10759 static int zipfileComparePath(const char *zA, const char *zB, int nB){
10760   int nA = (int)strlen(zA);
10761   if( nA>0 && zA[nA-1]=='/' ) nA--;
10762   if( nB>0 && zB[nB-1]=='/' ) nB--;
10763   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
10764   return 1;
10765 }
10766 
zipfileBegin(sqlite3_vtab * pVtab)10767 static int zipfileBegin(sqlite3_vtab *pVtab){
10768   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10769   int rc = SQLITE_OK;
10770 
10771   assert( pTab->pWriteFd==0 );
10772   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
10773     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
10774     return SQLITE_ERROR;
10775   }
10776 
10777   /* Open a write fd on the file. Also load the entire central directory
10778   ** structure into memory. During the transaction any new file data is
10779   ** appended to the archive file, but the central directory is accumulated
10780   ** in main-memory until the transaction is committed.  */
10781   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
10782   if( pTab->pWriteFd==0 ){
10783     pTab->base.zErrMsg = sqlite3_mprintf(
10784         "zipfile: failed to open file %s for writing", pTab->zFile
10785         );
10786     rc = SQLITE_ERROR;
10787   }else{
10788     fseek(pTab->pWriteFd, 0, SEEK_END);
10789     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
10790     rc = zipfileLoadDirectory(pTab, 0, 0);
10791   }
10792 
10793   if( rc!=SQLITE_OK ){
10794     zipfileCleanupTransaction(pTab);
10795   }
10796 
10797   return rc;
10798 }
10799 
10800 /*
10801 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10802 ** time(2)).
10803 */
zipfileTime(void)10804 static u32 zipfileTime(void){
10805   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
10806   u32 ret;
10807   if( pVfs==0 ) return 0;
10808   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
10809     i64 ms;
10810     pVfs->xCurrentTimeInt64(pVfs, &ms);
10811     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
10812   }else{
10813     double day;
10814     pVfs->xCurrentTime(pVfs, &day);
10815     ret = (u32)((day - 2440587.5) * 86400);
10816   }
10817   return ret;
10818 }
10819 
10820 /*
10821 ** Return a 32-bit timestamp in UNIX epoch format.
10822 **
10823 ** If the value passed as the only argument is either NULL or an SQL NULL,
10824 ** return the current time. Otherwise, return the value stored in (*pVal)
10825 ** cast to a 32-bit unsigned integer.
10826 */
zipfileGetTime(sqlite3_value * pVal)10827 static u32 zipfileGetTime(sqlite3_value *pVal){
10828   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
10829     return zipfileTime();
10830   }
10831   return (u32)sqlite3_value_int64(pVal);
10832 }
10833 
10834 /*
10835 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10836 ** linked list.  Remove it from the list and free the object.
10837 */
zipfileRemoveEntryFromList(ZipfileTab * pTab,ZipfileEntry * pOld)10838 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
10839   if( pOld ){
10840     if( pTab->pFirstEntry==pOld ){
10841       pTab->pFirstEntry = pOld->pNext;
10842       if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
10843     }else{
10844       ZipfileEntry *p;
10845       for(p=pTab->pFirstEntry; p; p=p->pNext){
10846         if( p->pNext==pOld ){
10847           p->pNext = pOld->pNext;
10848           if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
10849           break;
10850         }
10851       }
10852     }
10853     zipfileEntryFree(pOld);
10854   }
10855 }
10856 
10857 /*
10858 ** xUpdate method.
10859 */
zipfileUpdate(sqlite3_vtab * pVtab,int nVal,sqlite3_value ** apVal,sqlite_int64 * pRowid)10860 static int zipfileUpdate(
10861   sqlite3_vtab *pVtab,
10862   int nVal,
10863   sqlite3_value **apVal,
10864   sqlite_int64 *pRowid
10865 ){
10866   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10867   int rc = SQLITE_OK;             /* Return Code */
10868   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
10869 
10870   u32 mode = 0;                   /* Mode for new entry */
10871   u32 mTime = 0;                  /* Modification time for new entry */
10872   i64 sz = 0;                     /* Uncompressed size */
10873   const char *zPath = 0;          /* Path for new entry */
10874   int nPath = 0;                  /* strlen(zPath) */
10875   const u8 *pData = 0;            /* Pointer to buffer containing content */
10876   int nData = 0;                  /* Size of pData buffer in bytes */
10877   int iMethod = 0;                /* Compression method for new entry */
10878   u8 *pFree = 0;                  /* Free this */
10879   char *zFree = 0;                /* Also free this */
10880   ZipfileEntry *pOld = 0;
10881   ZipfileEntry *pOld2 = 0;
10882   int bUpdate = 0;                /* True for an update that modifies "name" */
10883   int bIsDir = 0;
10884   u32 iCrc32 = 0;
10885 
10886   (void)pRowid;
10887 
10888   if( pTab->pWriteFd==0 ){
10889     rc = zipfileBegin(pVtab);
10890     if( rc!=SQLITE_OK ) return rc;
10891   }
10892 
10893   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
10894   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
10895     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
10896     int nDelete = (int)strlen(zDelete);
10897     if( nVal>1 ){
10898       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
10899       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
10900         bUpdate = 1;
10901       }
10902     }
10903     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
10904       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
10905         break;
10906       }
10907       assert( pOld->pNext );
10908     }
10909   }
10910 
10911   if( nVal>1 ){
10912     /* Check that "sz" and "rawdata" are both NULL: */
10913     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
10914       zipfileTableErr(pTab, "sz must be NULL");
10915       rc = SQLITE_CONSTRAINT;
10916     }
10917     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
10918       zipfileTableErr(pTab, "rawdata must be NULL");
10919       rc = SQLITE_CONSTRAINT;
10920     }
10921 
10922     if( rc==SQLITE_OK ){
10923       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
10924         /* data=NULL. A directory */
10925         bIsDir = 1;
10926       }else{
10927         /* Value specified for "data", and possibly "method". This must be
10928         ** a regular file or a symlink. */
10929         const u8 *aIn = sqlite3_value_blob(apVal[7]);
10930         int nIn = sqlite3_value_bytes(apVal[7]);
10931         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
10932 
10933         iMethod = sqlite3_value_int(apVal[8]);
10934         sz = nIn;
10935         pData = aIn;
10936         nData = nIn;
10937         if( iMethod!=0 && iMethod!=8 ){
10938           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
10939           rc = SQLITE_CONSTRAINT;
10940         }else{
10941           if( bAuto || iMethod ){
10942             int nCmp;
10943             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
10944             if( rc==SQLITE_OK ){
10945               if( iMethod || nCmp<nIn ){
10946                 iMethod = 8;
10947                 pData = pFree;
10948                 nData = nCmp;
10949               }
10950             }
10951           }
10952           iCrc32 = crc32(0, aIn, nIn);
10953         }
10954       }
10955     }
10956 
10957     if( rc==SQLITE_OK ){
10958       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
10959     }
10960 
10961     if( rc==SQLITE_OK ){
10962       zPath = (const char*)sqlite3_value_text(apVal[2]);
10963       if( zPath==0 ) zPath = "";
10964       nPath = (int)strlen(zPath);
10965       mTime = zipfileGetTime(apVal[4]);
10966     }
10967 
10968     if( rc==SQLITE_OK && bIsDir ){
10969       /* For a directory, check that the last character in the path is a
10970       ** '/'. This appears to be required for compatibility with info-zip
10971       ** (the unzip command on unix). It does not create directories
10972       ** otherwise.  */
10973       if( nPath<=0 || zPath[nPath-1]!='/' ){
10974         zFree = sqlite3_mprintf("%s/", zPath);
10975         zPath = (const char*)zFree;
10976         if( zFree==0 ){
10977           rc = SQLITE_NOMEM;
10978           nPath = 0;
10979         }else{
10980           nPath = (int)strlen(zPath);
10981         }
10982       }
10983     }
10984 
10985     /* Check that we're not inserting a duplicate entry -OR- updating an
10986     ** entry with a path, thereby making it into a duplicate. */
10987     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
10988       ZipfileEntry *p;
10989       for(p=pTab->pFirstEntry; p; p=p->pNext){
10990         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
10991           switch( sqlite3_vtab_on_conflict(pTab->db) ){
10992             case SQLITE_IGNORE: {
10993               goto zipfile_update_done;
10994             }
10995             case SQLITE_REPLACE: {
10996               pOld2 = p;
10997               break;
10998             }
10999             default: {
11000               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
11001               rc = SQLITE_CONSTRAINT;
11002               break;
11003             }
11004           }
11005           break;
11006         }
11007       }
11008     }
11009 
11010     if( rc==SQLITE_OK ){
11011       /* Create the new CDS record. */
11012       pNew = zipfileNewEntry(zPath);
11013       if( pNew==0 ){
11014         rc = SQLITE_NOMEM;
11015       }else{
11016         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11017         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11018         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11019         pNew->cds.iCompression = (u16)iMethod;
11020         zipfileMtimeToDos(&pNew->cds, mTime);
11021         pNew->cds.crc32 = iCrc32;
11022         pNew->cds.szCompressed = nData;
11023         pNew->cds.szUncompressed = (u32)sz;
11024         pNew->cds.iExternalAttr = (mode<<16);
11025         pNew->cds.iOffset = (u32)pTab->szCurrent;
11026         pNew->cds.nFile = (u16)nPath;
11027         pNew->mUnixTime = (u32)mTime;
11028         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
11029         zipfileAddEntry(pTab, pOld, pNew);
11030       }
11031     }
11032   }
11033 
11034   if( rc==SQLITE_OK && (pOld || pOld2) ){
11035     ZipfileCsr *pCsr;
11036     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11037       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
11038         pCsr->pCurrent = pCsr->pCurrent->pNext;
11039         pCsr->bNoop = 1;
11040       }
11041     }
11042 
11043     zipfileRemoveEntryFromList(pTab, pOld);
11044     zipfileRemoveEntryFromList(pTab, pOld2);
11045   }
11046 
11047 zipfile_update_done:
11048   sqlite3_free(pFree);
11049   sqlite3_free(zFree);
11050   return rc;
11051 }
11052 
zipfileSerializeEOCD(ZipfileEOCD * p,u8 * aBuf)11053 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
11054   u8 *a = aBuf;
11055   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
11056   zipfileWrite16(a, p->iDisk);
11057   zipfileWrite16(a, p->iFirstDisk);
11058   zipfileWrite16(a, p->nEntry);
11059   zipfileWrite16(a, p->nEntryTotal);
11060   zipfileWrite32(a, p->nSize);
11061   zipfileWrite32(a, p->iOffset);
11062   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
11063 
11064   return a-aBuf;
11065 }
11066 
zipfileAppendEOCD(ZipfileTab * pTab,ZipfileEOCD * p)11067 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
11068   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
11069   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
11070   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
11071 }
11072 
11073 /*
11074 ** Serialize the CDS structure into buffer aBuf[]. Return the number
11075 ** of bytes written.
11076 */
zipfileSerializeCDS(ZipfileEntry * pEntry,u8 * aBuf)11077 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
11078   u8 *a = aBuf;
11079   ZipfileCDS *pCDS = &pEntry->cds;
11080 
11081   if( pEntry->aExtra==0 ){
11082     pCDS->nExtra = 9;
11083   }
11084 
11085   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
11086   zipfileWrite16(a, pCDS->iVersionMadeBy);
11087   zipfileWrite16(a, pCDS->iVersionExtract);
11088   zipfileWrite16(a, pCDS->flags);
11089   zipfileWrite16(a, pCDS->iCompression);
11090   zipfileWrite16(a, pCDS->mTime);
11091   zipfileWrite16(a, pCDS->mDate);
11092   zipfileWrite32(a, pCDS->crc32);
11093   zipfileWrite32(a, pCDS->szCompressed);
11094   zipfileWrite32(a, pCDS->szUncompressed);
11095   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
11096   zipfileWrite16(a, pCDS->nFile);
11097   zipfileWrite16(a, pCDS->nExtra);
11098   zipfileWrite16(a, pCDS->nComment);
11099   zipfileWrite16(a, pCDS->iDiskStart);
11100   zipfileWrite16(a, pCDS->iInternalAttr);
11101   zipfileWrite32(a, pCDS->iExternalAttr);
11102   zipfileWrite32(a, pCDS->iOffset);
11103 
11104   memcpy(a, pCDS->zFile, pCDS->nFile);
11105   a += pCDS->nFile;
11106 
11107   if( pEntry->aExtra ){
11108     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
11109     memcpy(a, pEntry->aExtra, n);
11110     a += n;
11111   }else{
11112     assert( pCDS->nExtra==9 );
11113     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
11114     zipfileWrite16(a, 5);
11115     *a++ = 0x01;
11116     zipfileWrite32(a, pEntry->mUnixTime);
11117   }
11118 
11119   return a-aBuf;
11120 }
11121 
zipfileCommit(sqlite3_vtab * pVtab)11122 static int zipfileCommit(sqlite3_vtab *pVtab){
11123   ZipfileTab *pTab = (ZipfileTab*)pVtab;
11124   int rc = SQLITE_OK;
11125   if( pTab->pWriteFd ){
11126     i64 iOffset = pTab->szCurrent;
11127     ZipfileEntry *p;
11128     ZipfileEOCD eocd;
11129     int nEntry = 0;
11130 
11131     /* Write out all entries */
11132     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
11133       int n = zipfileSerializeCDS(p, pTab->aBuffer);
11134       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
11135       nEntry++;
11136     }
11137 
11138     /* Write out the EOCD record */
11139     eocd.iDisk = 0;
11140     eocd.iFirstDisk = 0;
11141     eocd.nEntry = (u16)nEntry;
11142     eocd.nEntryTotal = (u16)nEntry;
11143     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
11144     eocd.iOffset = (u32)iOffset;
11145     rc = zipfileAppendEOCD(pTab, &eocd);
11146 
11147     zipfileCleanupTransaction(pTab);
11148   }
11149   return rc;
11150 }
11151 
zipfileRollback(sqlite3_vtab * pVtab)11152 static int zipfileRollback(sqlite3_vtab *pVtab){
11153   return zipfileCommit(pVtab);
11154 }
11155 
zipfileFindCursor(ZipfileTab * pTab,i64 iId)11156 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
11157   ZipfileCsr *pCsr;
11158   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11159     if( iId==pCsr->iId ) break;
11160   }
11161   return pCsr;
11162 }
11163 
zipfileFunctionCds(sqlite3_context * context,int argc,sqlite3_value ** argv)11164 static void zipfileFunctionCds(
11165   sqlite3_context *context,
11166   int argc,
11167   sqlite3_value **argv
11168 ){
11169   ZipfileCsr *pCsr;
11170   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
11171   assert( argc>0 );
11172 
11173   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
11174   if( pCsr ){
11175     ZipfileCDS *p = &pCsr->pCurrent->cds;
11176     char *zRes = sqlite3_mprintf("{"
11177         "\"version-made-by\" : %u, "
11178         "\"version-to-extract\" : %u, "
11179         "\"flags\" : %u, "
11180         "\"compression\" : %u, "
11181         "\"time\" : %u, "
11182         "\"date\" : %u, "
11183         "\"crc32\" : %u, "
11184         "\"compressed-size\" : %u, "
11185         "\"uncompressed-size\" : %u, "
11186         "\"file-name-length\" : %u, "
11187         "\"extra-field-length\" : %u, "
11188         "\"file-comment-length\" : %u, "
11189         "\"disk-number-start\" : %u, "
11190         "\"internal-attr\" : %u, "
11191         "\"external-attr\" : %u, "
11192         "\"offset\" : %u }",
11193         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
11194         (u32)p->flags, (u32)p->iCompression,
11195         (u32)p->mTime, (u32)p->mDate,
11196         (u32)p->crc32, (u32)p->szCompressed,
11197         (u32)p->szUncompressed, (u32)p->nFile,
11198         (u32)p->nExtra, (u32)p->nComment,
11199         (u32)p->iDiskStart, (u32)p->iInternalAttr,
11200         (u32)p->iExternalAttr, (u32)p->iOffset
11201     );
11202 
11203     if( zRes==0 ){
11204       sqlite3_result_error_nomem(context);
11205     }else{
11206       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
11207       sqlite3_free(zRes);
11208     }
11209   }
11210 }
11211 
11212 /*
11213 ** xFindFunction method.
11214 */
zipfileFindFunction(sqlite3_vtab * pVtab,int nArg,const char * zName,void (** pxFunc)(sqlite3_context *,int,sqlite3_value **),void ** ppArg)11215 static int zipfileFindFunction(
11216   sqlite3_vtab *pVtab,            /* Virtual table handle */
11217   int nArg,                       /* Number of SQL function arguments */
11218   const char *zName,              /* Name of SQL function */
11219   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
11220   void **ppArg                    /* OUT: User data for *pxFunc */
11221 ){
11222   (void)nArg;
11223   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
11224     *pxFunc = zipfileFunctionCds;
11225     *ppArg = (void*)pVtab;
11226     return 1;
11227   }
11228   return 0;
11229 }
11230 
11231 typedef struct ZipfileBuffer ZipfileBuffer;
11232 struct ZipfileBuffer {
11233   u8 *a;                          /* Pointer to buffer */
11234   int n;                          /* Size of buffer in bytes */
11235   int nAlloc;                     /* Byte allocated at a[] */
11236 };
11237 
11238 typedef struct ZipfileCtx ZipfileCtx;
11239 struct ZipfileCtx {
11240   int nEntry;
11241   ZipfileBuffer body;
11242   ZipfileBuffer cds;
11243 };
11244 
zipfileBufferGrow(ZipfileBuffer * pBuf,int nByte)11245 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
11246   if( pBuf->n+nByte>pBuf->nAlloc ){
11247     u8 *aNew;
11248     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
11249     int nReq = pBuf->n + nByte;
11250 
11251     while( nNew<nReq ) nNew = nNew*2;
11252     aNew = sqlite3_realloc64(pBuf->a, nNew);
11253     if( aNew==0 ) return SQLITE_NOMEM;
11254     pBuf->a = aNew;
11255     pBuf->nAlloc = (int)nNew;
11256   }
11257   return SQLITE_OK;
11258 }
11259 
11260 /*
11261 ** xStep() callback for the zipfile() aggregate. This can be called in
11262 ** any of the following ways:
11263 **
11264 **   SELECT zipfile(name,data) ...
11265 **   SELECT zipfile(name,mode,mtime,data) ...
11266 **   SELECT zipfile(name,mode,mtime,data,method) ...
11267 */
zipfileStep(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)11268 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
11269   ZipfileCtx *p;                  /* Aggregate function context */
11270   ZipfileEntry e;                 /* New entry to add to zip archive */
11271 
11272   sqlite3_value *pName = 0;
11273   sqlite3_value *pMode = 0;
11274   sqlite3_value *pMtime = 0;
11275   sqlite3_value *pData = 0;
11276   sqlite3_value *pMethod = 0;
11277 
11278   int bIsDir = 0;
11279   u32 mode;
11280   int rc = SQLITE_OK;
11281   char *zErr = 0;
11282 
11283   int iMethod = -1;               /* Compression method to use (0 or 8) */
11284 
11285   const u8 *aData = 0;            /* Possibly compressed data for new entry */
11286   int nData = 0;                  /* Size of aData[] in bytes */
11287   int szUncompressed = 0;         /* Size of data before compression */
11288   u8 *aFree = 0;                  /* Free this before returning */
11289   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
11290 
11291   char *zName = 0;                /* Path (name) of new entry */
11292   int nName = 0;                  /* Size of zName in bytes */
11293   char *zFree = 0;                /* Free this before returning */
11294   int nByte;
11295 
11296   memset(&e, 0, sizeof(e));
11297   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11298   if( p==0 ) return;
11299 
11300   /* Martial the arguments into stack variables */
11301   if( nVal!=2 && nVal!=4 && nVal!=5 ){
11302     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
11303     rc = SQLITE_ERROR;
11304     goto zipfile_step_out;
11305   }
11306   pName = apVal[0];
11307   if( nVal==2 ){
11308     pData = apVal[1];
11309   }else{
11310     pMode = apVal[1];
11311     pMtime = apVal[2];
11312     pData = apVal[3];
11313     if( nVal==5 ){
11314       pMethod = apVal[4];
11315     }
11316   }
11317 
11318   /* Check that the 'name' parameter looks ok. */
11319   zName = (char*)sqlite3_value_text(pName);
11320   nName = sqlite3_value_bytes(pName);
11321   if( zName==0 ){
11322     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
11323     rc = SQLITE_ERROR;
11324     goto zipfile_step_out;
11325   }
11326 
11327   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
11328   ** deflate compression) or NULL (choose automatically).  */
11329   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
11330     iMethod = (int)sqlite3_value_int64(pMethod);
11331     if( iMethod!=0 && iMethod!=8 ){
11332       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
11333       rc = SQLITE_ERROR;
11334       goto zipfile_step_out;
11335     }
11336   }
11337 
11338   /* Now inspect the data. If this is NULL, then the new entry must be a
11339   ** directory.  Otherwise, figure out whether or not the data should
11340   ** be deflated or simply stored in the zip archive. */
11341   if( sqlite3_value_type(pData)==SQLITE_NULL ){
11342     bIsDir = 1;
11343     iMethod = 0;
11344   }else{
11345     aData = sqlite3_value_blob(pData);
11346     szUncompressed = nData = sqlite3_value_bytes(pData);
11347     iCrc32 = crc32(0, aData, nData);
11348     if( iMethod<0 || iMethod==8 ){
11349       int nOut = 0;
11350       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
11351       if( rc!=SQLITE_OK ){
11352         goto zipfile_step_out;
11353       }
11354       if( iMethod==8 || nOut<nData ){
11355         aData = aFree;
11356         nData = nOut;
11357         iMethod = 8;
11358       }else{
11359         iMethod = 0;
11360       }
11361     }
11362   }
11363 
11364   /* Decode the "mode" argument. */
11365   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
11366   if( rc ) goto zipfile_step_out;
11367 
11368   /* Decode the "mtime" argument. */
11369   e.mUnixTime = zipfileGetTime(pMtime);
11370 
11371   /* If this is a directory entry, ensure that there is exactly one '/'
11372   ** at the end of the path. Or, if this is not a directory and the path
11373   ** ends in '/' it is an error. */
11374   if( bIsDir==0 ){
11375     if( nName>0 && zName[nName-1]=='/' ){
11376       zErr = sqlite3_mprintf("non-directory name must not end with /");
11377       rc = SQLITE_ERROR;
11378       goto zipfile_step_out;
11379     }
11380   }else{
11381     if( nName==0 || zName[nName-1]!='/' ){
11382       zName = zFree = sqlite3_mprintf("%s/", zName);
11383       if( zName==0 ){
11384         rc = SQLITE_NOMEM;
11385         goto zipfile_step_out;
11386       }
11387       nName = (int)strlen(zName);
11388     }else{
11389       while( nName>1 && zName[nName-2]=='/' ) nName--;
11390     }
11391   }
11392 
11393   /* Assemble the ZipfileEntry object for the new zip archive entry */
11394   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11395   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11396   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11397   e.cds.iCompression = (u16)iMethod;
11398   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
11399   e.cds.crc32 = iCrc32;
11400   e.cds.szCompressed = nData;
11401   e.cds.szUncompressed = szUncompressed;
11402   e.cds.iExternalAttr = (mode<<16);
11403   e.cds.iOffset = p->body.n;
11404   e.cds.nFile = (u16)nName;
11405   e.cds.zFile = zName;
11406 
11407   /* Append the LFH to the body of the new archive */
11408   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
11409   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
11410   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
11411 
11412   /* Append the data to the body of the new archive */
11413   if( nData>0 ){
11414     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
11415     memcpy(&p->body.a[p->body.n], aData, nData);
11416     p->body.n += nData;
11417   }
11418 
11419   /* Append the CDS record to the directory of the new archive */
11420   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
11421   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
11422   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
11423 
11424   /* Increment the count of entries in the archive */
11425   p->nEntry++;
11426 
11427  zipfile_step_out:
11428   sqlite3_free(aFree);
11429   sqlite3_free(zFree);
11430   if( rc ){
11431     if( zErr ){
11432       sqlite3_result_error(pCtx, zErr, -1);
11433     }else{
11434       sqlite3_result_error_code(pCtx, rc);
11435     }
11436   }
11437   sqlite3_free(zErr);
11438 }
11439 
11440 /*
11441 ** xFinalize() callback for zipfile aggregate function.
11442 */
zipfileFinal(sqlite3_context * pCtx)11443 static void zipfileFinal(sqlite3_context *pCtx){
11444   ZipfileCtx *p;
11445   ZipfileEOCD eocd;
11446   sqlite3_int64 nZip;
11447   u8 *aZip;
11448 
11449   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11450   if( p==0 ) return;
11451   if( p->nEntry>0 ){
11452     memset(&eocd, 0, sizeof(eocd));
11453     eocd.nEntry = (u16)p->nEntry;
11454     eocd.nEntryTotal = (u16)p->nEntry;
11455     eocd.nSize = p->cds.n;
11456     eocd.iOffset = p->body.n;
11457 
11458     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
11459     aZip = (u8*)sqlite3_malloc64(nZip);
11460     if( aZip==0 ){
11461       sqlite3_result_error_nomem(pCtx);
11462     }else{
11463       memcpy(aZip, p->body.a, p->body.n);
11464       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
11465       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
11466       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
11467     }
11468   }
11469 
11470   sqlite3_free(p->body.a);
11471   sqlite3_free(p->cds.a);
11472 }
11473 
11474 
11475 /*
11476 ** Register the "zipfile" virtual table.
11477 */
zipfileRegister(sqlite3 * db)11478 static int zipfileRegister(sqlite3 *db){
11479   static sqlite3_module zipfileModule = {
11480     1,                         /* iVersion */
11481     zipfileConnect,            /* xCreate */
11482     zipfileConnect,            /* xConnect */
11483     zipfileBestIndex,          /* xBestIndex */
11484     zipfileDisconnect,         /* xDisconnect */
11485     zipfileDisconnect,         /* xDestroy */
11486     zipfileOpen,               /* xOpen - open a cursor */
11487     zipfileClose,              /* xClose - close a cursor */
11488     zipfileFilter,             /* xFilter - configure scan constraints */
11489     zipfileNext,               /* xNext - advance a cursor */
11490     zipfileEof,                /* xEof - check for end of scan */
11491     zipfileColumn,             /* xColumn - read data */
11492     0,                         /* xRowid - read data */
11493     zipfileUpdate,             /* xUpdate */
11494     zipfileBegin,              /* xBegin */
11495     0,                         /* xSync */
11496     zipfileCommit,             /* xCommit */
11497     zipfileRollback,           /* xRollback */
11498     zipfileFindFunction,       /* xFindMethod */
11499     0,                         /* xRename */
11500     0,                         /* xSavepoint */
11501     0,                         /* xRelease */
11502     0,                         /* xRollback */
11503     0,                         /* xShadowName */
11504     0                          /* xIntegrity */
11505   };
11506 
11507   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
11508   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
11509   if( rc==SQLITE_OK ){
11510     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
11511         zipfileStep, zipfileFinal
11512     );
11513   }
11514   assert( sizeof(i64)==8 );
11515   assert( sizeof(u32)==4 );
11516   assert( sizeof(u16)==2 );
11517   assert( sizeof(u8)==1 );
11518   return rc;
11519 }
11520 #else         /* SQLITE_OMIT_VIRTUALTABLE */
11521 # define zipfileRegister(x) SQLITE_OK
11522 #endif
11523 
11524 #ifdef _WIN32
11525 
11526 #endif
sqlite3_zipfile_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)11527 int sqlite3_zipfile_init(
11528   sqlite3 *db,
11529   char **pzErrMsg,
11530   const sqlite3_api_routines *pApi
11531 ){
11532   SQLITE_EXTENSION_INIT2(pApi);
11533   (void)pzErrMsg;  /* Unused parameter */
11534   return zipfileRegister(db);
11535 }
11536 
11537 /************************* End ../ext/misc/zipfile.c ********************/
11538 /************************* Begin ../ext/misc/sqlar.c ******************/
11539 /*
11540 ** 2017-12-17
11541 **
11542 ** The author disclaims copyright to this source code.  In place of
11543 ** a legal notice, here is a blessing:
11544 **
11545 **    May you do good and not evil.
11546 **    May you find forgiveness for yourself and forgive others.
11547 **    May you share freely, never taking more than you give.
11548 **
11549 ******************************************************************************
11550 **
11551 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
11552 ** for working with sqlar archives and used by the shell tool's built-in
11553 ** sqlar support.
11554 */
11555 /* #include "sqlite3ext.h" */
11556 SQLITE_EXTENSION_INIT1
11557 #include <zlib.h>
11558 #include <assert.h>
11559 
11560 /*
11561 ** Implementation of the "sqlar_compress(X)" SQL function.
11562 **
11563 ** If the type of X is SQLITE_BLOB, and compressing that blob using
11564 ** zlib utility function compress() yields a smaller blob, return the
11565 ** compressed blob. Otherwise, return a copy of X.
11566 **
11567 ** SQLar uses the "zlib format" for compressed content.  The zlib format
11568 ** contains a two-byte identification header and a four-byte checksum at
11569 ** the end.  This is different from ZIP which uses the raw deflate format.
11570 **
11571 ** Future enhancements to SQLar might add support for new compression formats.
11572 ** If so, those new formats will be identified by alternative headers in the
11573 ** compressed data.
11574 */
sqlarCompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)11575 static void sqlarCompressFunc(
11576   sqlite3_context *context,
11577   int argc,
11578   sqlite3_value **argv
11579 ){
11580   assert( argc==1 );
11581   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
11582     const Bytef *pData = sqlite3_value_blob(argv[0]);
11583     uLong nData = sqlite3_value_bytes(argv[0]);
11584     uLongf nOut = compressBound(nData);
11585     Bytef *pOut;
11586 
11587     pOut = (Bytef*)sqlite3_malloc(nOut);
11588     if( pOut==0 ){
11589       sqlite3_result_error_nomem(context);
11590       return;
11591     }else{
11592       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
11593         sqlite3_result_error(context, "error in compress()", -1);
11594       }else if( nOut<nData ){
11595         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
11596       }else{
11597         sqlite3_result_value(context, argv[0]);
11598       }
11599       sqlite3_free(pOut);
11600     }
11601   }else{
11602     sqlite3_result_value(context, argv[0]);
11603   }
11604 }
11605 
11606 /*
11607 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
11608 **
11609 ** Parameter SZ is interpreted as an integer. If it is less than or
11610 ** equal to zero, then this function returns a copy of X. Or, if
11611 ** SZ is equal to the size of X when interpreted as a blob, also
11612 ** return a copy of X. Otherwise, decompress blob X using zlib
11613 ** utility function uncompress() and return the results (another
11614 ** blob).
11615 */
sqlarUncompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)11616 static void sqlarUncompressFunc(
11617   sqlite3_context *context,
11618   int argc,
11619   sqlite3_value **argv
11620 ){
11621   uLong nData;
11622   uLongf sz;
11623 
11624   assert( argc==2 );
11625   sz = sqlite3_value_int(argv[1]);
11626 
11627   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
11628     sqlite3_result_value(context, argv[0]);
11629   }else{
11630     const Bytef *pData= sqlite3_value_blob(argv[0]);
11631     Bytef *pOut = sqlite3_malloc(sz);
11632     if( pOut==0 ){
11633       sqlite3_result_error_nomem(context);
11634     }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
11635       sqlite3_result_error(context, "error in uncompress()", -1);
11636     }else{
11637       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
11638     }
11639     sqlite3_free(pOut);
11640   }
11641 }
11642 
11643 #ifdef _WIN32
11644 
11645 #endif
sqlite3_sqlar_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)11646 int sqlite3_sqlar_init(
11647   sqlite3 *db,
11648   char **pzErrMsg,
11649   const sqlite3_api_routines *pApi
11650 ){
11651   int rc = SQLITE_OK;
11652   SQLITE_EXTENSION_INIT2(pApi);
11653   (void)pzErrMsg;  /* Unused parameter */
11654   rc = sqlite3_create_function(db, "sqlar_compress", 1,
11655                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11656                                sqlarCompressFunc, 0, 0);
11657   if( rc==SQLITE_OK ){
11658     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
11659                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11660                                  sqlarUncompressFunc, 0, 0);
11661   }
11662   return rc;
11663 }
11664 
11665 /************************* End ../ext/misc/sqlar.c ********************/
11666 #endif
11667 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
11668 /*
11669 ** 2017 April 07
11670 **
11671 ** The author disclaims copyright to this source code.  In place of
11672 ** a legal notice, here is a blessing:
11673 **
11674 **    May you do good and not evil.
11675 **    May you find forgiveness for yourself and forgive others.
11676 **    May you share freely, never taking more than you give.
11677 **
11678 *************************************************************************
11679 */
11680 #if !defined(SQLITEEXPERT_H)
11681 #define SQLITEEXPERT_H 1
11682 /* #include "sqlite3.h" */
11683 
11684 typedef struct sqlite3expert sqlite3expert;
11685 
11686 /*
11687 ** Create a new sqlite3expert object.
11688 **
11689 ** If successful, a pointer to the new object is returned and (*pzErr) set
11690 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
11691 ** an English-language error message. In this case it is the responsibility
11692 ** of the caller to eventually free the error message buffer using
11693 ** sqlite3_free().
11694 */
11695 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
11696 
11697 /*
11698 ** Configure an sqlite3expert object.
11699 **
11700 ** EXPERT_CONFIG_SAMPLE:
11701 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
11702 **   each candidate index. This involves scanning and sorting the entire
11703 **   contents of each user database table once for each candidate index
11704 **   associated with the table. For large databases, this can be
11705 **   prohibitively slow. This option allows the sqlite3expert object to
11706 **   be configured so that sqlite_stat1 data is instead generated based on a
11707 **   subset of each table, or so that no sqlite_stat1 data is used at all.
11708 **
11709 **   A single integer argument is passed to this option. If the value is less
11710 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
11711 **   the analysis - indexes are recommended based on the database schema only.
11712 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
11713 **   generated for each candidate index (this is the default). Finally, if the
11714 **   value falls between 0 and 100, then it represents the percentage of user
11715 **   table rows that should be considered when generating sqlite_stat1 data.
11716 **
11717 **   Examples:
11718 **
11719 **     // Do not generate any sqlite_stat1 data
11720 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
11721 **
11722 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
11723 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
11724 */
11725 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
11726 
11727 #define EXPERT_CONFIG_SAMPLE 1    /* int */
11728 
11729 /*
11730 ** Specify zero or more SQL statements to be included in the analysis.
11731 **
11732 ** Buffer zSql must contain zero or more complete SQL statements. This
11733 ** function parses all statements contained in the buffer and adds them
11734 ** to the internal list of statements to analyze. If successful, SQLITE_OK
11735 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11736 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11737 ** may be set to point to an English language error message. In this case
11738 ** the caller is responsible for eventually freeing the error message buffer
11739 ** using sqlite3_free().
11740 **
11741 ** If an error does occur while processing one of the statements in the
11742 ** buffer passed as the second argument, none of the statements in the
11743 ** buffer are added to the analysis.
11744 **
11745 ** This function must be called before sqlite3_expert_analyze(). If a call
11746 ** to this function is made on an sqlite3expert object that has already
11747 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
11748 ** immediately and no statements are added to the analysis.
11749 */
11750 int sqlite3_expert_sql(
11751   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
11752   const char *zSql,               /* SQL statement(s) to add */
11753   char **pzErr                    /* OUT: Error message (if any) */
11754 );
11755 
11756 
11757 /*
11758 ** This function is called after the sqlite3expert object has been configured
11759 ** with all SQL statements using sqlite3_expert_sql() to actually perform
11760 ** the analysis. Once this function has been called, it is not possible to
11761 ** add further SQL statements to the analysis.
11762 **
11763 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
11764 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
11765 ** point to a buffer containing an English language error message. In this
11766 ** case it is the responsibility of the caller to eventually free the buffer
11767 ** using sqlite3_free().
11768 **
11769 ** If an error does occur within this function, the sqlite3expert object
11770 ** is no longer useful for any purpose. At that point it is no longer
11771 ** possible to add further SQL statements to the object or to re-attempt
11772 ** the analysis. The sqlite3expert object must still be freed using a call
11773 ** sqlite3_expert_destroy().
11774 */
11775 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
11776 
11777 /*
11778 ** Return the total number of statements loaded using sqlite3_expert_sql().
11779 ** The total number of SQL statements may be different from the total number
11780 ** to calls to sqlite3_expert_sql().
11781 */
11782 int sqlite3_expert_count(sqlite3expert*);
11783 
11784 /*
11785 ** Return a component of the report.
11786 **
11787 ** This function is called after sqlite3_expert_analyze() to extract the
11788 ** results of the analysis. Each call to this function returns either a
11789 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11790 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
11791 ** #define constants defined below.
11792 **
11793 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
11794 ** information relating to a specific SQL statement. In these cases that
11795 ** SQL statement is identified by the value passed as the second argument.
11796 ** SQL statements are numbered from 0 in the order in which they are parsed.
11797 ** If an out-of-range value (less than zero or equal to or greater than the
11798 ** value returned by sqlite3_expert_count()) is passed as the second argument
11799 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
11800 **
11801 ** EXPERT_REPORT_SQL:
11802 **   Return the text of SQL statement iStmt.
11803 **
11804 ** EXPERT_REPORT_INDEXES:
11805 **   Return a buffer containing the CREATE INDEX statements for all recommended
11806 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
11807 **   is returned.
11808 **
11809 ** EXPERT_REPORT_PLAN:
11810 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
11811 **   iStmt after the proposed indexes have been added to the database schema.
11812 **
11813 ** EXPERT_REPORT_CANDIDATES:
11814 **   Return a pointer to a buffer containing the CREATE INDEX statements
11815 **   for all indexes that were tested (for all SQL statements). The iStmt
11816 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
11817 */
11818 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
11819 
11820 /*
11821 ** Values for the third argument passed to sqlite3_expert_report().
11822 */
11823 #define EXPERT_REPORT_SQL        1
11824 #define EXPERT_REPORT_INDEXES    2
11825 #define EXPERT_REPORT_PLAN       3
11826 #define EXPERT_REPORT_CANDIDATES 4
11827 
11828 /*
11829 ** Free an (sqlite3expert*) handle and all associated resources. There
11830 ** should be one call to this function for each successful call to
11831 ** sqlite3-expert_new().
11832 */
11833 void sqlite3_expert_destroy(sqlite3expert*);
11834 
11835 #endif  /* !defined(SQLITEEXPERT_H) */
11836 
11837 /************************* End ../ext/expert/sqlite3expert.h ********************/
11838 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
11839 /*
11840 ** 2017 April 09
11841 **
11842 ** The author disclaims copyright to this source code.  In place of
11843 ** a legal notice, here is a blessing:
11844 **
11845 **    May you do good and not evil.
11846 **    May you find forgiveness for yourself and forgive others.
11847 **    May you share freely, never taking more than you give.
11848 **
11849 *************************************************************************
11850 */
11851 /* #include "sqlite3expert.h" */
11852 #include <assert.h>
11853 #include <string.h>
11854 #include <stdio.h>
11855 
11856 #if !defined(SQLITE_AMALGAMATION)
11857 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11858 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
11859 #endif
11860 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
11861 # define ALWAYS(X)      (1)
11862 # define NEVER(X)       (0)
11863 #elif !defined(NDEBUG)
11864 # define ALWAYS(X)      ((X)?1:(assert(0),0))
11865 # define NEVER(X)       ((X)?(assert(0),1):0)
11866 #else
11867 # define ALWAYS(X)      (X)
11868 # define NEVER(X)       (X)
11869 #endif
11870 #endif /* !defined(SQLITE_AMALGAMATION) */
11871 
11872 
11873 #ifndef SQLITE_OMIT_VIRTUALTABLE
11874 
11875 /* typedef sqlite3_int64 i64; */
11876 /* typedef sqlite3_uint64 u64; */
11877 
11878 typedef struct IdxColumn IdxColumn;
11879 typedef struct IdxConstraint IdxConstraint;
11880 typedef struct IdxScan IdxScan;
11881 typedef struct IdxStatement IdxStatement;
11882 typedef struct IdxTable IdxTable;
11883 typedef struct IdxWrite IdxWrite;
11884 
11885 #define STRLEN  (int)strlen
11886 
11887 /*
11888 ** A temp table name that we assume no user database will actually use.
11889 ** If this assumption proves incorrect triggers on the table with the
11890 ** conflicting name will be ignored.
11891 */
11892 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
11893 
11894 /*
11895 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
11896 ** any other type of single-ended range constraint on a column).
11897 **
11898 ** pLink:
11899 **   Used to temporarily link IdxConstraint objects into lists while
11900 **   creating candidate indexes.
11901 */
11902 struct IdxConstraint {
11903   char *zColl;                    /* Collation sequence */
11904   int bRange;                     /* True for range, false for eq */
11905   int iCol;                       /* Constrained table column */
11906   int bFlag;                      /* Used by idxFindCompatible() */
11907   int bDesc;                      /* True if ORDER BY <expr> DESC */
11908   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
11909   IdxConstraint *pLink;           /* See above */
11910 };
11911 
11912 /*
11913 ** A single scan of a single table.
11914 */
11915 struct IdxScan {
11916   IdxTable *pTab;                 /* Associated table object */
11917   int iDb;                        /* Database containing table zTable */
11918   i64 covering;                   /* Mask of columns required for cov. index */
11919   IdxConstraint *pOrder;          /* ORDER BY columns */
11920   IdxConstraint *pEq;             /* List of == constraints */
11921   IdxConstraint *pRange;          /* List of < constraints */
11922   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
11923 };
11924 
11925 /*
11926 ** Information regarding a single database table. Extracted from
11927 ** "PRAGMA table_info" by function idxGetTableInfo().
11928 */
11929 struct IdxColumn {
11930   char *zName;
11931   char *zColl;
11932   int iPk;
11933 };
11934 struct IdxTable {
11935   int nCol;
11936   char *zName;                    /* Table name */
11937   IdxColumn *aCol;
11938   IdxTable *pNext;                /* Next table in linked list of all tables */
11939 };
11940 
11941 /*
11942 ** An object of the following type is created for each unique table/write-op
11943 ** seen. The objects are stored in a singly-linked list beginning at
11944 ** sqlite3expert.pWrite.
11945 */
11946 struct IdxWrite {
11947   IdxTable *pTab;
11948   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
11949   IdxWrite *pNext;
11950 };
11951 
11952 /*
11953 ** Each statement being analyzed is represented by an instance of this
11954 ** structure.
11955 */
11956 struct IdxStatement {
11957   int iId;                        /* Statement number */
11958   char *zSql;                     /* SQL statement */
11959   char *zIdx;                     /* Indexes */
11960   char *zEQP;                     /* Plan */
11961   IdxStatement *pNext;
11962 };
11963 
11964 
11965 /*
11966 ** A hash table for storing strings. With space for a payload string
11967 ** with each entry. Methods are:
11968 **
11969 **   idxHashInit()
11970 **   idxHashClear()
11971 **   idxHashAdd()
11972 **   idxHashSearch()
11973 */
11974 #define IDX_HASH_SIZE 1023
11975 typedef struct IdxHashEntry IdxHashEntry;
11976 typedef struct IdxHash IdxHash;
11977 struct IdxHashEntry {
11978   char *zKey;                     /* nul-terminated key */
11979   char *zVal;                     /* nul-terminated value string */
11980   char *zVal2;                    /* nul-terminated value string 2 */
11981   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
11982   IdxHashEntry *pNext;            /* Next entry in hash */
11983 };
11984 struct IdxHash {
11985   IdxHashEntry *pFirst;
11986   IdxHashEntry *aHash[IDX_HASH_SIZE];
11987 };
11988 
11989 /*
11990 ** sqlite3expert object.
11991 */
11992 struct sqlite3expert {
11993   int iSample;                    /* Percentage of tables to sample for stat1 */
11994   sqlite3 *db;                    /* User database */
11995   sqlite3 *dbm;                   /* In-memory db for this analysis */
11996   sqlite3 *dbv;                   /* Vtab schema for this analysis */
11997   IdxTable *pTable;               /* List of all IdxTable objects */
11998   IdxScan *pScan;                 /* List of scan objects */
11999   IdxWrite *pWrite;               /* List of write objects */
12000   IdxStatement *pStatement;       /* List of IdxStatement objects */
12001   int bRun;                       /* True once analysis has run */
12002   char **pzErrmsg;
12003   int rc;                         /* Error code from whereinfo hook */
12004   IdxHash hIdx;                   /* Hash containing all candidate indexes */
12005   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
12006 };
12007 
12008 
12009 /*
12010 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
12011 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
12012 */
idxMalloc(int * pRc,int nByte)12013 static void *idxMalloc(int *pRc, int nByte){
12014   void *pRet;
12015   assert( *pRc==SQLITE_OK );
12016   assert( nByte>0 );
12017   pRet = sqlite3_malloc(nByte);
12018   if( pRet ){
12019     memset(pRet, 0, nByte);
12020   }else{
12021     *pRc = SQLITE_NOMEM;
12022   }
12023   return pRet;
12024 }
12025 
12026 /*
12027 ** Initialize an IdxHash hash table.
12028 */
idxHashInit(IdxHash * pHash)12029 static void idxHashInit(IdxHash *pHash){
12030   memset(pHash, 0, sizeof(IdxHash));
12031 }
12032 
12033 /*
12034 ** Reset an IdxHash hash table.
12035 */
idxHashClear(IdxHash * pHash)12036 static void idxHashClear(IdxHash *pHash){
12037   int i;
12038   for(i=0; i<IDX_HASH_SIZE; i++){
12039     IdxHashEntry *pEntry;
12040     IdxHashEntry *pNext;
12041     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
12042       pNext = pEntry->pHashNext;
12043       sqlite3_free(pEntry->zVal2);
12044       sqlite3_free(pEntry);
12045     }
12046   }
12047   memset(pHash, 0, sizeof(IdxHash));
12048 }
12049 
12050 /*
12051 ** Return the index of the hash bucket that the string specified by the
12052 ** arguments to this function belongs.
12053 */
idxHashString(const char * z,int n)12054 static int idxHashString(const char *z, int n){
12055   unsigned int ret = 0;
12056   int i;
12057   for(i=0; i<n; i++){
12058     ret += (ret<<3) + (unsigned char)(z[i]);
12059   }
12060   return (int)(ret % IDX_HASH_SIZE);
12061 }
12062 
12063 /*
12064 ** If zKey is already present in the hash table, return non-zero and do
12065 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
12066 ** the hash table passed as the second argument.
12067 */
idxHashAdd(int * pRc,IdxHash * pHash,const char * zKey,const char * zVal)12068 static int idxHashAdd(
12069   int *pRc,
12070   IdxHash *pHash,
12071   const char *zKey,
12072   const char *zVal
12073 ){
12074   int nKey = STRLEN(zKey);
12075   int iHash = idxHashString(zKey, nKey);
12076   int nVal = (zVal ? STRLEN(zVal) : 0);
12077   IdxHashEntry *pEntry;
12078   assert( iHash>=0 );
12079   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12080     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12081       return 1;
12082     }
12083   }
12084   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
12085   if( pEntry ){
12086     pEntry->zKey = (char*)&pEntry[1];
12087     memcpy(pEntry->zKey, zKey, nKey);
12088     if( zVal ){
12089       pEntry->zVal = &pEntry->zKey[nKey+1];
12090       memcpy(pEntry->zVal, zVal, nVal);
12091     }
12092     pEntry->pHashNext = pHash->aHash[iHash];
12093     pHash->aHash[iHash] = pEntry;
12094 
12095     pEntry->pNext = pHash->pFirst;
12096     pHash->pFirst = pEntry;
12097   }
12098   return 0;
12099 }
12100 
12101 /*
12102 ** If zKey/nKey is present in the hash table, return a pointer to the
12103 ** hash-entry object.
12104 */
idxHashFind(IdxHash * pHash,const char * zKey,int nKey)12105 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
12106   int iHash;
12107   IdxHashEntry *pEntry;
12108   if( nKey<0 ) nKey = STRLEN(zKey);
12109   iHash = idxHashString(zKey, nKey);
12110   assert( iHash>=0 );
12111   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12112     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12113       return pEntry;
12114     }
12115   }
12116   return 0;
12117 }
12118 
12119 /*
12120 ** If the hash table contains an entry with a key equal to the string
12121 ** passed as the final two arguments to this function, return a pointer
12122 ** to the payload string. Otherwise, if zKey/nKey is not present in the
12123 ** hash table, return NULL.
12124 */
idxHashSearch(IdxHash * pHash,const char * zKey,int nKey)12125 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
12126   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
12127   if( pEntry ) return pEntry->zVal;
12128   return 0;
12129 }
12130 
12131 /*
12132 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
12133 ** variable to point to a copy of nul-terminated string zColl.
12134 */
idxNewConstraint(int * pRc,const char * zColl)12135 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
12136   IdxConstraint *pNew;
12137   int nColl = STRLEN(zColl);
12138 
12139   assert( *pRc==SQLITE_OK );
12140   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
12141   if( pNew ){
12142     pNew->zColl = (char*)&pNew[1];
12143     memcpy(pNew->zColl, zColl, nColl+1);
12144   }
12145   return pNew;
12146 }
12147 
12148 /*
12149 ** An error associated with database handle db has just occurred. Pass
12150 ** the error message to callback function xOut.
12151 */
idxDatabaseError(sqlite3 * db,char ** pzErrmsg)12152 static void idxDatabaseError(
12153   sqlite3 *db,                    /* Database handle */
12154   char **pzErrmsg                 /* Write error here */
12155 ){
12156   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
12157 }
12158 
12159 /*
12160 ** Prepare an SQL statement.
12161 */
idxPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zSql)12162 static int idxPrepareStmt(
12163   sqlite3 *db,                    /* Database handle to compile against */
12164   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12165   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12166   const char *zSql                /* SQL statement to compile */
12167 ){
12168   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12169   if( rc!=SQLITE_OK ){
12170     *ppStmt = 0;
12171     idxDatabaseError(db, pzErrmsg);
12172   }
12173   return rc;
12174 }
12175 
12176 /*
12177 ** Prepare an SQL statement using the results of a printf() formatting.
12178 */
idxPrintfPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zFmt,...)12179 static int idxPrintfPrepareStmt(
12180   sqlite3 *db,                    /* Database handle to compile against */
12181   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12182   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12183   const char *zFmt,               /* printf() format of SQL statement */
12184   ...                             /* Trailing printf() arguments */
12185 ){
12186   va_list ap;
12187   int rc;
12188   char *zSql;
12189   va_start(ap, zFmt);
12190   zSql = sqlite3_vmprintf(zFmt, ap);
12191   if( zSql==0 ){
12192     rc = SQLITE_NOMEM;
12193   }else{
12194     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
12195     sqlite3_free(zSql);
12196   }
12197   va_end(ap);
12198   return rc;
12199 }
12200 
12201 
12202 /*************************************************************************
12203 ** Beginning of virtual table implementation.
12204 */
12205 typedef struct ExpertVtab ExpertVtab;
12206 struct ExpertVtab {
12207   sqlite3_vtab base;
12208   IdxTable *pTab;
12209   sqlite3expert *pExpert;
12210 };
12211 
12212 typedef struct ExpertCsr ExpertCsr;
12213 struct ExpertCsr {
12214   sqlite3_vtab_cursor base;
12215   sqlite3_stmt *pData;
12216 };
12217 
expertDequote(const char * zIn)12218 static char *expertDequote(const char *zIn){
12219   int n = STRLEN(zIn);
12220   char *zRet = sqlite3_malloc(n);
12221 
12222   assert( zIn[0]=='\'' );
12223   assert( zIn[n-1]=='\'' );
12224 
12225   if( zRet ){
12226     int iOut = 0;
12227     int iIn = 0;
12228     for(iIn=1; iIn<(n-1); iIn++){
12229       if( zIn[iIn]=='\'' ){
12230         assert( zIn[iIn+1]=='\'' );
12231         iIn++;
12232       }
12233       zRet[iOut++] = zIn[iIn];
12234     }
12235     zRet[iOut] = '\0';
12236   }
12237 
12238   return zRet;
12239 }
12240 
12241 /*
12242 ** This function is the implementation of both the xConnect and xCreate
12243 ** methods of the r-tree virtual table.
12244 **
12245 **   argv[0]   -> module name
12246 **   argv[1]   -> database name
12247 **   argv[2]   -> table name
12248 **   argv[...] -> column names...
12249 */
expertConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)12250 static int expertConnect(
12251   sqlite3 *db,
12252   void *pAux,
12253   int argc, const char *const*argv,
12254   sqlite3_vtab **ppVtab,
12255   char **pzErr
12256 ){
12257   sqlite3expert *pExpert = (sqlite3expert*)pAux;
12258   ExpertVtab *p = 0;
12259   int rc;
12260 
12261   if( argc!=4 ){
12262     *pzErr = sqlite3_mprintf("internal error!");
12263     rc = SQLITE_ERROR;
12264   }else{
12265     char *zCreateTable = expertDequote(argv[3]);
12266     if( zCreateTable ){
12267       rc = sqlite3_declare_vtab(db, zCreateTable);
12268       if( rc==SQLITE_OK ){
12269         p = idxMalloc(&rc, sizeof(ExpertVtab));
12270       }
12271       if( rc==SQLITE_OK ){
12272         p->pExpert = pExpert;
12273         p->pTab = pExpert->pTable;
12274         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
12275       }
12276       sqlite3_free(zCreateTable);
12277     }else{
12278       rc = SQLITE_NOMEM;
12279     }
12280   }
12281 
12282   *ppVtab = (sqlite3_vtab*)p;
12283   return rc;
12284 }
12285 
expertDisconnect(sqlite3_vtab * pVtab)12286 static int expertDisconnect(sqlite3_vtab *pVtab){
12287   ExpertVtab *p = (ExpertVtab*)pVtab;
12288   sqlite3_free(p);
12289   return SQLITE_OK;
12290 }
12291 
expertBestIndex(sqlite3_vtab * pVtab,sqlite3_index_info * pIdxInfo)12292 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
12293   ExpertVtab *p = (ExpertVtab*)pVtab;
12294   int rc = SQLITE_OK;
12295   int n = 0;
12296   IdxScan *pScan;
12297   const int opmask =
12298     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
12299     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
12300     SQLITE_INDEX_CONSTRAINT_LE;
12301 
12302   pScan = idxMalloc(&rc, sizeof(IdxScan));
12303   if( pScan ){
12304     int i;
12305 
12306     /* Link the new scan object into the list */
12307     pScan->pTab = p->pTab;
12308     pScan->pNextScan = p->pExpert->pScan;
12309     p->pExpert->pScan = pScan;
12310 
12311     /* Add the constraints to the IdxScan object */
12312     for(i=0; i<pIdxInfo->nConstraint; i++){
12313       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
12314       if( pCons->usable
12315        && pCons->iColumn>=0
12316        && p->pTab->aCol[pCons->iColumn].iPk==0
12317        && (pCons->op & opmask)
12318       ){
12319         IdxConstraint *pNew;
12320         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
12321         pNew = idxNewConstraint(&rc, zColl);
12322         if( pNew ){
12323           pNew->iCol = pCons->iColumn;
12324           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
12325             pNew->pNext = pScan->pEq;
12326             pScan->pEq = pNew;
12327           }else{
12328             pNew->bRange = 1;
12329             pNew->pNext = pScan->pRange;
12330             pScan->pRange = pNew;
12331           }
12332         }
12333         n++;
12334         pIdxInfo->aConstraintUsage[i].argvIndex = n;
12335       }
12336     }
12337 
12338     /* Add the ORDER BY to the IdxScan object */
12339     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
12340       int iCol = pIdxInfo->aOrderBy[i].iColumn;
12341       if( iCol>=0 ){
12342         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
12343         if( pNew ){
12344           pNew->iCol = iCol;
12345           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
12346           pNew->pNext = pScan->pOrder;
12347           pNew->pLink = pScan->pOrder;
12348           pScan->pOrder = pNew;
12349           n++;
12350         }
12351       }
12352     }
12353   }
12354 
12355   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
12356   return rc;
12357 }
12358 
expertUpdate(sqlite3_vtab * pVtab,int nData,sqlite3_value ** azData,sqlite_int64 * pRowid)12359 static int expertUpdate(
12360   sqlite3_vtab *pVtab,
12361   int nData,
12362   sqlite3_value **azData,
12363   sqlite_int64 *pRowid
12364 ){
12365   (void)pVtab;
12366   (void)nData;
12367   (void)azData;
12368   (void)pRowid;
12369   return SQLITE_OK;
12370 }
12371 
12372 /*
12373 ** Virtual table module xOpen method.
12374 */
expertOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)12375 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
12376   int rc = SQLITE_OK;
12377   ExpertCsr *pCsr;
12378   (void)pVTab;
12379   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
12380   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
12381   return rc;
12382 }
12383 
12384 /*
12385 ** Virtual table module xClose method.
12386 */
expertClose(sqlite3_vtab_cursor * cur)12387 static int expertClose(sqlite3_vtab_cursor *cur){
12388   ExpertCsr *pCsr = (ExpertCsr*)cur;
12389   sqlite3_finalize(pCsr->pData);
12390   sqlite3_free(pCsr);
12391   return SQLITE_OK;
12392 }
12393 
12394 /*
12395 ** Virtual table module xEof method.
12396 **
12397 ** Return non-zero if the cursor does not currently point to a valid
12398 ** record (i.e if the scan has finished), or zero otherwise.
12399 */
expertEof(sqlite3_vtab_cursor * cur)12400 static int expertEof(sqlite3_vtab_cursor *cur){
12401   ExpertCsr *pCsr = (ExpertCsr*)cur;
12402   return pCsr->pData==0;
12403 }
12404 
12405 /*
12406 ** Virtual table module xNext method.
12407 */
expertNext(sqlite3_vtab_cursor * cur)12408 static int expertNext(sqlite3_vtab_cursor *cur){
12409   ExpertCsr *pCsr = (ExpertCsr*)cur;
12410   int rc = SQLITE_OK;
12411 
12412   assert( pCsr->pData );
12413   rc = sqlite3_step(pCsr->pData);
12414   if( rc!=SQLITE_ROW ){
12415     rc = sqlite3_finalize(pCsr->pData);
12416     pCsr->pData = 0;
12417   }else{
12418     rc = SQLITE_OK;
12419   }
12420 
12421   return rc;
12422 }
12423 
12424 /*
12425 ** Virtual table module xRowid method.
12426 */
expertRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)12427 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
12428   (void)cur;
12429   *pRowid = 0;
12430   return SQLITE_OK;
12431 }
12432 
12433 /*
12434 ** Virtual table module xColumn method.
12435 */
expertColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)12436 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
12437   ExpertCsr *pCsr = (ExpertCsr*)cur;
12438   sqlite3_value *pVal;
12439   pVal = sqlite3_column_value(pCsr->pData, i);
12440   if( pVal ){
12441     sqlite3_result_value(ctx, pVal);
12442   }
12443   return SQLITE_OK;
12444 }
12445 
12446 /*
12447 ** Virtual table module xFilter method.
12448 */
expertFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)12449 static int expertFilter(
12450   sqlite3_vtab_cursor *cur,
12451   int idxNum, const char *idxStr,
12452   int argc, sqlite3_value **argv
12453 ){
12454   ExpertCsr *pCsr = (ExpertCsr*)cur;
12455   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
12456   sqlite3expert *pExpert = pVtab->pExpert;
12457   int rc;
12458 
12459   (void)idxNum;
12460   (void)idxStr;
12461   (void)argc;
12462   (void)argv;
12463   rc = sqlite3_finalize(pCsr->pData);
12464   pCsr->pData = 0;
12465   if( rc==SQLITE_OK ){
12466     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
12467         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
12468     );
12469   }
12470 
12471   if( rc==SQLITE_OK ){
12472     rc = expertNext(cur);
12473   }
12474   return rc;
12475 }
12476 
idxRegisterVtab(sqlite3expert * p)12477 static int idxRegisterVtab(sqlite3expert *p){
12478   static sqlite3_module expertModule = {
12479     2,                            /* iVersion */
12480     expertConnect,                /* xCreate - create a table */
12481     expertConnect,                /* xConnect - connect to an existing table */
12482     expertBestIndex,              /* xBestIndex - Determine search strategy */
12483     expertDisconnect,             /* xDisconnect - Disconnect from a table */
12484     expertDisconnect,             /* xDestroy - Drop a table */
12485     expertOpen,                   /* xOpen - open a cursor */
12486     expertClose,                  /* xClose - close a cursor */
12487     expertFilter,                 /* xFilter - configure scan constraints */
12488     expertNext,                   /* xNext - advance a cursor */
12489     expertEof,                    /* xEof */
12490     expertColumn,                 /* xColumn - read data */
12491     expertRowid,                  /* xRowid - read data */
12492     expertUpdate,                 /* xUpdate - write data */
12493     0,                            /* xBegin - begin transaction */
12494     0,                            /* xSync - sync transaction */
12495     0,                            /* xCommit - commit transaction */
12496     0,                            /* xRollback - rollback transaction */
12497     0,                            /* xFindFunction - function overloading */
12498     0,                            /* xRename - rename the table */
12499     0,                            /* xSavepoint */
12500     0,                            /* xRelease */
12501     0,                            /* xRollbackTo */
12502     0,                            /* xShadowName */
12503     0,                            /* xIntegrity */
12504   };
12505 
12506   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
12507 }
12508 /*
12509 ** End of virtual table implementation.
12510 *************************************************************************/
12511 /*
12512 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
12513 ** is called, set it to the return value of sqlite3_finalize() before
12514 ** returning. Otherwise, discard the sqlite3_finalize() return value.
12515 */
idxFinalize(int * pRc,sqlite3_stmt * pStmt)12516 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
12517   int rc = sqlite3_finalize(pStmt);
12518   if( *pRc==SQLITE_OK ) *pRc = rc;
12519 }
12520 
12521 /*
12522 ** Attempt to allocate an IdxTable structure corresponding to table zTab
12523 ** in the main database of connection db. If successful, set (*ppOut) to
12524 ** point to the new object and return SQLITE_OK. Otherwise, return an
12525 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
12526 ** set to point to an error string.
12527 **
12528 ** It is the responsibility of the caller to eventually free either the
12529 ** IdxTable object or error message using sqlite3_free().
12530 */
idxGetTableInfo(sqlite3 * db,const char * zTab,IdxTable ** ppOut,char ** pzErrmsg)12531 static int idxGetTableInfo(
12532   sqlite3 *db,                    /* Database connection to read details from */
12533   const char *zTab,               /* Table name */
12534   IdxTable **ppOut,               /* OUT: New object (if successful) */
12535   char **pzErrmsg                 /* OUT: Error message (if not) */
12536 ){
12537   sqlite3_stmt *p1 = 0;
12538   int nCol = 0;
12539   int nTab;
12540   int nByte;
12541   IdxTable *pNew = 0;
12542   int rc, rc2;
12543   char *pCsr = 0;
12544   int nPk = 0;
12545 
12546   *ppOut = 0;
12547   if( zTab==0 ) return SQLITE_ERROR;
12548   nTab = STRLEN(zTab);
12549   nByte = sizeof(IdxTable) + nTab + 1;
12550   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
12551   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12552     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12553     const char *zColSeq = 0;
12554     if( zCol==0 ){
12555       rc = SQLITE_ERROR;
12556       break;
12557     }
12558     nByte += 1 + STRLEN(zCol);
12559     rc = sqlite3_table_column_metadata(
12560         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12561     );
12562     if( zColSeq==0 ) zColSeq = "binary";
12563     nByte += 1 + STRLEN(zColSeq);
12564     nCol++;
12565     nPk += (sqlite3_column_int(p1, 5)>0);
12566   }
12567   rc2 = sqlite3_reset(p1);
12568   if( rc==SQLITE_OK ) rc = rc2;
12569 
12570   nByte += sizeof(IdxColumn) * nCol;
12571   if( rc==SQLITE_OK ){
12572     pNew = idxMalloc(&rc, nByte);
12573   }
12574   if( rc==SQLITE_OK ){
12575     pNew->aCol = (IdxColumn*)&pNew[1];
12576     pNew->nCol = nCol;
12577     pCsr = (char*)&pNew->aCol[nCol];
12578   }
12579 
12580   nCol = 0;
12581   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12582     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12583     const char *zColSeq = 0;
12584     int nCopy;
12585     if( zCol==0 ) continue;
12586     nCopy = STRLEN(zCol) + 1;
12587     pNew->aCol[nCol].zName = pCsr;
12588     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
12589     memcpy(pCsr, zCol, nCopy);
12590     pCsr += nCopy;
12591 
12592     rc = sqlite3_table_column_metadata(
12593         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12594     );
12595     if( rc==SQLITE_OK ){
12596       if( zColSeq==0 ) zColSeq = "binary";
12597       nCopy = STRLEN(zColSeq) + 1;
12598       pNew->aCol[nCol].zColl = pCsr;
12599       memcpy(pCsr, zColSeq, nCopy);
12600       pCsr += nCopy;
12601     }
12602 
12603     nCol++;
12604   }
12605   idxFinalize(&rc, p1);
12606 
12607   if( rc!=SQLITE_OK ){
12608     sqlite3_free(pNew);
12609     pNew = 0;
12610   }else if( ALWAYS(pNew!=0) ){
12611     pNew->zName = pCsr;
12612     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
12613   }
12614 
12615   *ppOut = pNew;
12616   return rc;
12617 }
12618 
12619 /*
12620 ** This function is a no-op if *pRc is set to anything other than
12621 ** SQLITE_OK when it is called.
12622 **
12623 ** If *pRc is initially set to SQLITE_OK, then the text specified by
12624 ** the printf() style arguments is appended to zIn and the result returned
12625 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
12626 ** zIn before returning.
12627 */
idxAppendText(int * pRc,char * zIn,const char * zFmt,...)12628 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
12629   va_list ap;
12630   char *zAppend = 0;
12631   char *zRet = 0;
12632   int nIn = zIn ? STRLEN(zIn) : 0;
12633   int nAppend = 0;
12634   va_start(ap, zFmt);
12635   if( *pRc==SQLITE_OK ){
12636     zAppend = sqlite3_vmprintf(zFmt, ap);
12637     if( zAppend ){
12638       nAppend = STRLEN(zAppend);
12639       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
12640     }
12641     if( zAppend && zRet ){
12642       if( nIn ) memcpy(zRet, zIn, nIn);
12643       memcpy(&zRet[nIn], zAppend, nAppend+1);
12644     }else{
12645       sqlite3_free(zRet);
12646       zRet = 0;
12647       *pRc = SQLITE_NOMEM;
12648     }
12649     sqlite3_free(zAppend);
12650     sqlite3_free(zIn);
12651   }
12652   va_end(ap);
12653   return zRet;
12654 }
12655 
12656 /*
12657 ** Return true if zId must be quoted in order to use it as an SQL
12658 ** identifier, or false otherwise.
12659 */
idxIdentifierRequiresQuotes(const char * zId)12660 static int idxIdentifierRequiresQuotes(const char *zId){
12661   int i;
12662   int nId = STRLEN(zId);
12663 
12664   if( sqlite3_keyword_check(zId, nId) ) return 1;
12665 
12666   for(i=0; zId[i]; i++){
12667     if( !(zId[i]=='_')
12668      && !(zId[i]>='0' && zId[i]<='9')
12669      && !(zId[i]>='a' && zId[i]<='z')
12670      && !(zId[i]>='A' && zId[i]<='Z')
12671     ){
12672       return 1;
12673     }
12674   }
12675   return 0;
12676 }
12677 
12678 /*
12679 ** This function appends an index column definition suitable for constraint
12680 ** pCons to the string passed as zIn and returns the result.
12681 */
idxAppendColDefn(int * pRc,char * zIn,IdxTable * pTab,IdxConstraint * pCons)12682 static char *idxAppendColDefn(
12683   int *pRc,                       /* IN/OUT: Error code */
12684   char *zIn,                      /* Column defn accumulated so far */
12685   IdxTable *pTab,                 /* Table index will be created on */
12686   IdxConstraint *pCons
12687 ){
12688   char *zRet = zIn;
12689   IdxColumn *p = &pTab->aCol[pCons->iCol];
12690   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
12691 
12692   if( idxIdentifierRequiresQuotes(p->zName) ){
12693     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
12694   }else{
12695     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
12696   }
12697 
12698   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
12699     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
12700       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
12701     }else{
12702       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
12703     }
12704   }
12705 
12706   if( pCons->bDesc ){
12707     zRet = idxAppendText(pRc, zRet, " DESC");
12708   }
12709   return zRet;
12710 }
12711 
12712 /*
12713 ** Search database dbm for an index compatible with the one idxCreateFromCons()
12714 ** would create from arguments pScan, pEq and pTail. If no error occurs and
12715 ** such an index is found, return non-zero. Or, if no such index is found,
12716 ** return zero.
12717 **
12718 ** If an error occurs, set *pRc to an SQLite error code and return zero.
12719 */
idxFindCompatible(int * pRc,sqlite3 * dbm,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)12720 static int idxFindCompatible(
12721   int *pRc,                       /* OUT: Error code */
12722   sqlite3* dbm,                   /* Database to search */
12723   IdxScan *pScan,                 /* Scan for table to search for index on */
12724   IdxConstraint *pEq,             /* List of == constraints */
12725   IdxConstraint *pTail            /* List of range constraints */
12726 ){
12727   const char *zTbl = pScan->pTab->zName;
12728   sqlite3_stmt *pIdxList = 0;
12729   IdxConstraint *pIter;
12730   int nEq = 0;                    /* Number of elements in pEq */
12731   int rc;
12732 
12733   /* Count the elements in list pEq */
12734   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
12735 
12736   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
12737   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
12738     int bMatch = 1;
12739     IdxConstraint *pT = pTail;
12740     sqlite3_stmt *pInfo = 0;
12741     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
12742     if( zIdx==0 ) continue;
12743 
12744     /* Zero the IdxConstraint.bFlag values in the pEq list */
12745     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
12746 
12747     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
12748     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
12749       int iIdx = sqlite3_column_int(pInfo, 0);
12750       int iCol = sqlite3_column_int(pInfo, 1);
12751       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
12752 
12753       if( iIdx<nEq ){
12754         for(pIter=pEq; pIter; pIter=pIter->pLink){
12755           if( pIter->bFlag ) continue;
12756           if( pIter->iCol!=iCol ) continue;
12757           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
12758           pIter->bFlag = 1;
12759           break;
12760         }
12761         if( pIter==0 ){
12762           bMatch = 0;
12763           break;
12764         }
12765       }else{
12766         if( pT ){
12767           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
12768             bMatch = 0;
12769             break;
12770           }
12771           pT = pT->pLink;
12772         }
12773       }
12774     }
12775     idxFinalize(&rc, pInfo);
12776 
12777     if( rc==SQLITE_OK && bMatch ){
12778       sqlite3_finalize(pIdxList);
12779       return 1;
12780     }
12781   }
12782   idxFinalize(&rc, pIdxList);
12783 
12784   *pRc = rc;
12785   return 0;
12786 }
12787 
12788 /* Callback for sqlite3_exec() with query with leading count(*) column.
12789  * The first argument is expected to be an int*, referent to be incremented
12790  * if that leading column is not exactly '0'.
12791  */
countNonzeros(void * pCount,int nc,char * azResults[],char * azColumns[])12792 static int countNonzeros(void* pCount, int nc,
12793                          char* azResults[], char* azColumns[]){
12794   (void)azColumns;  /* Suppress unused parameter warning */
12795   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
12796     *((int *)pCount) += 1;
12797   }
12798   return 0;
12799 }
12800 
idxCreateFromCons(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)12801 static int idxCreateFromCons(
12802   sqlite3expert *p,
12803   IdxScan *pScan,
12804   IdxConstraint *pEq,
12805   IdxConstraint *pTail
12806 ){
12807   sqlite3 *dbm = p->dbm;
12808   int rc = SQLITE_OK;
12809   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
12810     IdxTable *pTab = pScan->pTab;
12811     char *zCols = 0;
12812     char *zIdx = 0;
12813     IdxConstraint *pCons;
12814     unsigned int h = 0;
12815     const char *zFmt;
12816 
12817     for(pCons=pEq; pCons; pCons=pCons->pLink){
12818       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12819     }
12820     for(pCons=pTail; pCons; pCons=pCons->pLink){
12821       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12822     }
12823 
12824     if( rc==SQLITE_OK ){
12825       /* Hash the list of columns to come up with a name for the index */
12826       const char *zTable = pScan->pTab->zName;
12827       int quoteTable = idxIdentifierRequiresQuotes(zTable);
12828       char *zName = 0;          /* Index name */
12829       int collisions = 0;
12830       do{
12831         int i;
12832         char *zFind;
12833         for(i=0; zCols[i]; i++){
12834           h += ((h<<3) + zCols[i]);
12835         }
12836         sqlite3_free(zName);
12837         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
12838         if( zName==0 ) break;
12839         /* Is is unique among table, view and index names? */
12840         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
12841           " AND type in ('index','table','view')";
12842         zFind = sqlite3_mprintf(zFmt, zName);
12843         i = 0;
12844         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
12845         assert(rc==SQLITE_OK);
12846         sqlite3_free(zFind);
12847         if( i==0 ){
12848           collisions = 0;
12849           break;
12850         }
12851         ++collisions;
12852       }while( collisions<50 && zName!=0 );
12853       if( collisions ){
12854         /* This return means "Gave up trying to find a unique index name." */
12855         rc = SQLITE_BUSY_TIMEOUT;
12856       }else if( zName==0 ){
12857         rc = SQLITE_NOMEM;
12858       }else{
12859         if( quoteTable ){
12860           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
12861         }else{
12862           zFmt = "CREATE INDEX %s ON %s(%s)";
12863         }
12864         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
12865         if( !zIdx ){
12866           rc = SQLITE_NOMEM;
12867         }else{
12868           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
12869           if( rc!=SQLITE_OK ){
12870             rc = SQLITE_BUSY_TIMEOUT;
12871           }else{
12872             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
12873           }
12874         }
12875         sqlite3_free(zName);
12876         sqlite3_free(zIdx);
12877       }
12878     }
12879 
12880     sqlite3_free(zCols);
12881   }
12882   return rc;
12883 }
12884 
12885 /*
12886 ** Return true if list pList (linked by IdxConstraint.pLink) contains
12887 ** a constraint compatible with *p. Otherwise return false.
12888 */
idxFindConstraint(IdxConstraint * pList,IdxConstraint * p)12889 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
12890   IdxConstraint *pCmp;
12891   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
12892     if( p->iCol==pCmp->iCol ) return 1;
12893   }
12894   return 0;
12895 }
12896 
idxCreateFromWhere(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pTail)12897 static int idxCreateFromWhere(
12898   sqlite3expert *p,
12899   IdxScan *pScan,                 /* Create indexes for this scan */
12900   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
12901 ){
12902   IdxConstraint *p1 = 0;
12903   IdxConstraint *pCon;
12904   int rc;
12905 
12906   /* Gather up all the == constraints. */
12907   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
12908     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12909       pCon->pLink = p1;
12910       p1 = pCon;
12911     }
12912   }
12913 
12914   /* Create an index using the == constraints collected above. And the
12915   ** range constraint/ORDER BY terms passed in by the caller, if any. */
12916   rc = idxCreateFromCons(p, pScan, p1, pTail);
12917 
12918   /* If no range/ORDER BY passed by the caller, create a version of the
12919   ** index for each range constraint.  */
12920   if( pTail==0 ){
12921     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
12922       assert( pCon->pLink==0 );
12923       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12924         rc = idxCreateFromCons(p, pScan, p1, pCon);
12925       }
12926     }
12927   }
12928 
12929   return rc;
12930 }
12931 
12932 /*
12933 ** Create candidate indexes in database [dbm] based on the data in
12934 ** linked-list pScan.
12935 */
idxCreateCandidates(sqlite3expert * p)12936 static int idxCreateCandidates(sqlite3expert *p){
12937   int rc = SQLITE_OK;
12938   IdxScan *pIter;
12939 
12940   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
12941     rc = idxCreateFromWhere(p, pIter, 0);
12942     if( rc==SQLITE_OK && pIter->pOrder ){
12943       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
12944     }
12945   }
12946 
12947   return rc;
12948 }
12949 
12950 /*
12951 ** Free all elements of the linked list starting at pConstraint.
12952 */
idxConstraintFree(IdxConstraint * pConstraint)12953 static void idxConstraintFree(IdxConstraint *pConstraint){
12954   IdxConstraint *pNext;
12955   IdxConstraint *p;
12956 
12957   for(p=pConstraint; p; p=pNext){
12958     pNext = p->pNext;
12959     sqlite3_free(p);
12960   }
12961 }
12962 
12963 /*
12964 ** Free all elements of the linked list starting from pScan up until pLast
12965 ** (pLast is not freed).
12966 */
idxScanFree(IdxScan * pScan,IdxScan * pLast)12967 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
12968   IdxScan *p;
12969   IdxScan *pNext;
12970   for(p=pScan; p!=pLast; p=pNext){
12971     pNext = p->pNextScan;
12972     idxConstraintFree(p->pOrder);
12973     idxConstraintFree(p->pEq);
12974     idxConstraintFree(p->pRange);
12975     sqlite3_free(p);
12976   }
12977 }
12978 
12979 /*
12980 ** Free all elements of the linked list starting from pStatement up
12981 ** until pLast (pLast is not freed).
12982 */
idxStatementFree(IdxStatement * pStatement,IdxStatement * pLast)12983 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
12984   IdxStatement *p;
12985   IdxStatement *pNext;
12986   for(p=pStatement; p!=pLast; p=pNext){
12987     pNext = p->pNext;
12988     sqlite3_free(p->zEQP);
12989     sqlite3_free(p->zIdx);
12990     sqlite3_free(p);
12991   }
12992 }
12993 
12994 /*
12995 ** Free the linked list of IdxTable objects starting at pTab.
12996 */
idxTableFree(IdxTable * pTab)12997 static void idxTableFree(IdxTable *pTab){
12998   IdxTable *pIter;
12999   IdxTable *pNext;
13000   for(pIter=pTab; pIter; pIter=pNext){
13001     pNext = pIter->pNext;
13002     sqlite3_free(pIter);
13003   }
13004 }
13005 
13006 /*
13007 ** Free the linked list of IdxWrite objects starting at pTab.
13008 */
idxWriteFree(IdxWrite * pTab)13009 static void idxWriteFree(IdxWrite *pTab){
13010   IdxWrite *pIter;
13011   IdxWrite *pNext;
13012   for(pIter=pTab; pIter; pIter=pNext){
13013     pNext = pIter->pNext;
13014     sqlite3_free(pIter);
13015   }
13016 }
13017 
13018 
13019 
13020 /*
13021 ** This function is called after candidate indexes have been created. It
13022 ** runs all the queries to see which indexes they prefer, and populates
13023 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
13024 */
idxFindIndexes(sqlite3expert * p,char ** pzErr)13025 static int idxFindIndexes(
13026   sqlite3expert *p,
13027   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
13028 ){
13029   IdxStatement *pStmt;
13030   sqlite3 *dbm = p->dbm;
13031   int rc = SQLITE_OK;
13032 
13033   IdxHash hIdx;
13034   idxHashInit(&hIdx);
13035 
13036   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
13037     IdxHashEntry *pEntry;
13038     sqlite3_stmt *pExplain = 0;
13039     idxHashClear(&hIdx);
13040     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
13041         "EXPLAIN QUERY PLAN %s", pStmt->zSql
13042     );
13043     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
13044       /* int iId = sqlite3_column_int(pExplain, 0); */
13045       /* int iParent = sqlite3_column_int(pExplain, 1); */
13046       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
13047       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
13048       int nDetail;
13049       int i;
13050 
13051       if( !zDetail ) continue;
13052       nDetail = STRLEN(zDetail);
13053 
13054       for(i=0; i<nDetail; i++){
13055         const char *zIdx = 0;
13056         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
13057           zIdx = &zDetail[i+13];
13058         }else if( i+22<nDetail
13059             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
13060         ){
13061           zIdx = &zDetail[i+22];
13062         }
13063         if( zIdx ){
13064           const char *zSql;
13065           int nIdx = 0;
13066           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
13067             nIdx++;
13068           }
13069           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
13070           if( zSql ){
13071             idxHashAdd(&rc, &hIdx, zSql, 0);
13072             if( rc ) goto find_indexes_out;
13073           }
13074           break;
13075         }
13076       }
13077 
13078       if( zDetail[0]!='-' ){
13079         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
13080       }
13081     }
13082 
13083     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13084       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
13085     }
13086 
13087     idxFinalize(&rc, pExplain);
13088   }
13089 
13090  find_indexes_out:
13091   idxHashClear(&hIdx);
13092   return rc;
13093 }
13094 
idxAuthCallback(void * pCtx,int eOp,const char * z3,const char * z4,const char * zDb,const char * zTrigger)13095 static int idxAuthCallback(
13096   void *pCtx,
13097   int eOp,
13098   const char *z3,
13099   const char *z4,
13100   const char *zDb,
13101   const char *zTrigger
13102 ){
13103   int rc = SQLITE_OK;
13104   (void)z4;
13105   (void)zTrigger;
13106   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
13107     if( sqlite3_stricmp(zDb, "main")==0 ){
13108       sqlite3expert *p = (sqlite3expert*)pCtx;
13109       IdxTable *pTab;
13110       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
13111         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
13112       }
13113       if( pTab ){
13114         IdxWrite *pWrite;
13115         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
13116           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
13117         }
13118         if( pWrite==0 ){
13119           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
13120           if( rc==SQLITE_OK ){
13121             pWrite->pTab = pTab;
13122             pWrite->eOp = eOp;
13123             pWrite->pNext = p->pWrite;
13124             p->pWrite = pWrite;
13125           }
13126         }
13127       }
13128     }
13129   }
13130   return rc;
13131 }
13132 
idxProcessOneTrigger(sqlite3expert * p,IdxWrite * pWrite,char ** pzErr)13133 static int idxProcessOneTrigger(
13134   sqlite3expert *p,
13135   IdxWrite *pWrite,
13136   char **pzErr
13137 ){
13138   static const char *zInt = UNIQUE_TABLE_NAME;
13139   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
13140   IdxTable *pTab = pWrite->pTab;
13141   const char *zTab = pTab->zName;
13142   const char *zSql =
13143     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
13144     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
13145     "ORDER BY type;";
13146   sqlite3_stmt *pSelect = 0;
13147   int rc = SQLITE_OK;
13148   char *zWrite = 0;
13149 
13150   /* Create the table and its triggers in the temp schema */
13151   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
13152   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
13153     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
13154     if( zCreate==0 ) continue;
13155     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
13156   }
13157   idxFinalize(&rc, pSelect);
13158 
13159   /* Rename the table in the temp schema to zInt */
13160   if( rc==SQLITE_OK ){
13161     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
13162     if( z==0 ){
13163       rc = SQLITE_NOMEM;
13164     }else{
13165       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
13166       sqlite3_free(z);
13167     }
13168   }
13169 
13170   switch( pWrite->eOp ){
13171     case SQLITE_INSERT: {
13172       int i;
13173       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
13174       for(i=0; i<pTab->nCol; i++){
13175         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
13176       }
13177       zWrite = idxAppendText(&rc, zWrite, ")");
13178       break;
13179     }
13180     case SQLITE_UPDATE: {
13181       int i;
13182       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
13183       for(i=0; i<pTab->nCol; i++){
13184         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
13185             pTab->aCol[i].zName
13186         );
13187       }
13188       break;
13189     }
13190     default: {
13191       assert( pWrite->eOp==SQLITE_DELETE );
13192       if( rc==SQLITE_OK ){
13193         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
13194         if( zWrite==0 ) rc = SQLITE_NOMEM;
13195       }
13196     }
13197   }
13198 
13199   if( rc==SQLITE_OK ){
13200     sqlite3_stmt *pX = 0;
13201     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
13202     idxFinalize(&rc, pX);
13203     if( rc!=SQLITE_OK ){
13204       idxDatabaseError(p->dbv, pzErr);
13205     }
13206   }
13207   sqlite3_free(zWrite);
13208 
13209   if( rc==SQLITE_OK ){
13210     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
13211   }
13212 
13213   return rc;
13214 }
13215 
idxProcessTriggers(sqlite3expert * p,char ** pzErr)13216 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
13217   int rc = SQLITE_OK;
13218   IdxWrite *pEnd = 0;
13219   IdxWrite *pFirst = p->pWrite;
13220 
13221   while( rc==SQLITE_OK && pFirst!=pEnd ){
13222     IdxWrite *pIter;
13223     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
13224       rc = idxProcessOneTrigger(p, pIter, pzErr);
13225     }
13226     pEnd = pFirst;
13227     pFirst = p->pWrite;
13228   }
13229 
13230   return rc;
13231 }
13232 
13233 
idxCreateVtabSchema(sqlite3expert * p,char ** pzErrmsg)13234 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
13235   int rc = idxRegisterVtab(p);
13236   sqlite3_stmt *pSchema = 0;
13237 
13238   /* For each table in the main db schema:
13239   **
13240   **   1) Add an entry to the p->pTable list, and
13241   **   2) Create the equivalent virtual table in dbv.
13242   */
13243   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
13244       "SELECT type, name, sql, 1 FROM sqlite_schema "
13245       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
13246       " UNION ALL "
13247       "SELECT type, name, sql, 2 FROM sqlite_schema "
13248       "WHERE type = 'trigger'"
13249       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
13250       "ORDER BY 4, 1"
13251   );
13252   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
13253     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
13254     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
13255     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
13256 
13257     if( zType==0 || zName==0 ) continue;
13258     if( zType[0]=='v' || zType[1]=='r' ){
13259       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
13260     }else{
13261       IdxTable *pTab;
13262       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
13263       if( rc==SQLITE_OK ){
13264         int i;
13265         char *zInner = 0;
13266         char *zOuter = 0;
13267         pTab->pNext = p->pTable;
13268         p->pTable = pTab;
13269 
13270         /* The statement the vtab will pass to sqlite3_declare_vtab() */
13271         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
13272         for(i=0; i<pTab->nCol; i++){
13273           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
13274               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
13275           );
13276         }
13277         zInner = idxAppendText(&rc, zInner, ")");
13278 
13279         /* The CVT statement to create the vtab */
13280         zOuter = idxAppendText(&rc, 0,
13281             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
13282         );
13283         if( rc==SQLITE_OK ){
13284           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
13285         }
13286         sqlite3_free(zInner);
13287         sqlite3_free(zOuter);
13288       }
13289     }
13290   }
13291   idxFinalize(&rc, pSchema);
13292   return rc;
13293 }
13294 
13295 struct IdxSampleCtx {
13296   int iTarget;
13297   double target;                  /* Target nRet/nRow value */
13298   double nRow;                    /* Number of rows seen */
13299   double nRet;                    /* Number of rows returned */
13300 };
13301 
idxSampleFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)13302 static void idxSampleFunc(
13303   sqlite3_context *pCtx,
13304   int argc,
13305   sqlite3_value **argv
13306 ){
13307   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
13308   int bRet;
13309 
13310   (void)argv;
13311   assert( argc==0 );
13312   if( p->nRow==0.0 ){
13313     bRet = 1;
13314   }else{
13315     bRet = (p->nRet / p->nRow) <= p->target;
13316     if( bRet==0 ){
13317       unsigned short rnd;
13318       sqlite3_randomness(2, (void*)&rnd);
13319       bRet = ((int)rnd % 100) <= p->iTarget;
13320     }
13321   }
13322 
13323   sqlite3_result_int(pCtx, bRet);
13324   p->nRow += 1.0;
13325   p->nRet += (double)bRet;
13326 }
13327 
13328 struct IdxRemCtx {
13329   int nSlot;
13330   struct IdxRemSlot {
13331     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
13332     i64 iVal;                     /* SQLITE_INTEGER value */
13333     double rVal;                  /* SQLITE_FLOAT value */
13334     int nByte;                    /* Bytes of space allocated at z */
13335     int n;                        /* Size of buffer z */
13336     char *z;                      /* SQLITE_TEXT/BLOB value */
13337   } aSlot[1];
13338 };
13339 
13340 /*
13341 ** Implementation of scalar function rem().
13342 */
idxRemFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)13343 static void idxRemFunc(
13344   sqlite3_context *pCtx,
13345   int argc,
13346   sqlite3_value **argv
13347 ){
13348   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
13349   struct IdxRemSlot *pSlot;
13350   int iSlot;
13351   assert( argc==2 );
13352 
13353   iSlot = sqlite3_value_int(argv[0]);
13354   assert( iSlot<=p->nSlot );
13355   pSlot = &p->aSlot[iSlot];
13356 
13357   switch( pSlot->eType ){
13358     case SQLITE_NULL:
13359       /* no-op */
13360       break;
13361 
13362     case SQLITE_INTEGER:
13363       sqlite3_result_int64(pCtx, pSlot->iVal);
13364       break;
13365 
13366     case SQLITE_FLOAT:
13367       sqlite3_result_double(pCtx, pSlot->rVal);
13368       break;
13369 
13370     case SQLITE_BLOB:
13371       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13372       break;
13373 
13374     case SQLITE_TEXT:
13375       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13376       break;
13377   }
13378 
13379   pSlot->eType = sqlite3_value_type(argv[1]);
13380   switch( pSlot->eType ){
13381     case SQLITE_NULL:
13382       /* no-op */
13383       break;
13384 
13385     case SQLITE_INTEGER:
13386       pSlot->iVal = sqlite3_value_int64(argv[1]);
13387       break;
13388 
13389     case SQLITE_FLOAT:
13390       pSlot->rVal = sqlite3_value_double(argv[1]);
13391       break;
13392 
13393     case SQLITE_BLOB:
13394     case SQLITE_TEXT: {
13395       int nByte = sqlite3_value_bytes(argv[1]);
13396       const void *pData = 0;
13397       if( nByte>pSlot->nByte ){
13398         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
13399         if( zNew==0 ){
13400           sqlite3_result_error_nomem(pCtx);
13401           return;
13402         }
13403         pSlot->nByte = nByte*2;
13404         pSlot->z = zNew;
13405       }
13406       pSlot->n = nByte;
13407       if( pSlot->eType==SQLITE_BLOB ){
13408         pData = sqlite3_value_blob(argv[1]);
13409         if( pData ) memcpy(pSlot->z, pData, nByte);
13410       }else{
13411         pData = sqlite3_value_text(argv[1]);
13412         memcpy(pSlot->z, pData, nByte);
13413       }
13414       break;
13415     }
13416   }
13417 }
13418 
idxLargestIndex(sqlite3 * db,int * pnMax,char ** pzErr)13419 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
13420   int rc = SQLITE_OK;
13421   const char *zMax =
13422     "SELECT max(i.seqno) FROM "
13423     "  sqlite_schema AS s, "
13424     "  pragma_index_list(s.name) AS l, "
13425     "  pragma_index_info(l.name) AS i "
13426     "WHERE s.type = 'table'";
13427   sqlite3_stmt *pMax = 0;
13428 
13429   *pnMax = 0;
13430   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
13431   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
13432     *pnMax = sqlite3_column_int(pMax, 0) + 1;
13433   }
13434   idxFinalize(&rc, pMax);
13435 
13436   return rc;
13437 }
13438 
idxPopulateOneStat1(sqlite3expert * p,sqlite3_stmt * pIndexXInfo,sqlite3_stmt * pWriteStat,const char * zTab,const char * zIdx,char ** pzErr)13439 static int idxPopulateOneStat1(
13440   sqlite3expert *p,
13441   sqlite3_stmt *pIndexXInfo,
13442   sqlite3_stmt *pWriteStat,
13443   const char *zTab,
13444   const char *zIdx,
13445   char **pzErr
13446 ){
13447   char *zCols = 0;
13448   char *zOrder = 0;
13449   char *zQuery = 0;
13450   int nCol = 0;
13451   int i;
13452   sqlite3_stmt *pQuery = 0;
13453   int *aStat = 0;
13454   int rc = SQLITE_OK;
13455 
13456   assert( p->iSample>0 );
13457 
13458   /* Formulate the query text */
13459   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
13460   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
13461     const char *zComma = zCols==0 ? "" : ", ";
13462     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
13463     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
13464     zCols = idxAppendText(&rc, zCols,
13465         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
13466     );
13467     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
13468   }
13469   sqlite3_reset(pIndexXInfo);
13470   if( rc==SQLITE_OK ){
13471     if( p->iSample==100 ){
13472       zQuery = sqlite3_mprintf(
13473           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
13474       );
13475     }else{
13476       zQuery = sqlite3_mprintf(
13477           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
13478       );
13479     }
13480   }
13481   sqlite3_free(zCols);
13482   sqlite3_free(zOrder);
13483 
13484   /* Formulate the query text */
13485   if( rc==SQLITE_OK ){
13486     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13487     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
13488   }
13489   sqlite3_free(zQuery);
13490 
13491   if( rc==SQLITE_OK ){
13492     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
13493   }
13494   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13495     IdxHashEntry *pEntry;
13496     char *zStat = 0;
13497     for(i=0; i<=nCol; i++) aStat[i] = 1;
13498     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13499       aStat[0]++;
13500       for(i=0; i<nCol; i++){
13501         if( sqlite3_column_int(pQuery, i)==0 ) break;
13502       }
13503       for(/*no-op*/; i<nCol; i++){
13504         aStat[i+1]++;
13505       }
13506     }
13507 
13508     if( rc==SQLITE_OK ){
13509       int s0 = aStat[0];
13510       zStat = sqlite3_mprintf("%d", s0);
13511       if( zStat==0 ) rc = SQLITE_NOMEM;
13512       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
13513         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
13514       }
13515     }
13516 
13517     if( rc==SQLITE_OK ){
13518       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
13519       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
13520       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
13521       sqlite3_step(pWriteStat);
13522       rc = sqlite3_reset(pWriteStat);
13523     }
13524 
13525     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
13526     if( pEntry ){
13527       assert( pEntry->zVal2==0 );
13528       pEntry->zVal2 = zStat;
13529     }else{
13530       sqlite3_free(zStat);
13531     }
13532   }
13533   sqlite3_free(aStat);
13534   idxFinalize(&rc, pQuery);
13535 
13536   return rc;
13537 }
13538 
idxBuildSampleTable(sqlite3expert * p,const char * zTab)13539 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
13540   int rc;
13541   char *zSql;
13542 
13543   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13544   if( rc!=SQLITE_OK ) return rc;
13545 
13546   zSql = sqlite3_mprintf(
13547       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
13548   );
13549   if( zSql==0 ) return SQLITE_NOMEM;
13550   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
13551   sqlite3_free(zSql);
13552 
13553   return rc;
13554 }
13555 
13556 /*
13557 ** This function is called as part of sqlite3_expert_analyze(). Candidate
13558 ** indexes have already been created in database sqlite3expert.dbm, this
13559 ** function populates sqlite_stat1 table in the same database.
13560 **
13561 ** The stat1 data is generated by querying the
13562 */
idxPopulateStat1(sqlite3expert * p,char ** pzErr)13563 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
13564   int rc = SQLITE_OK;
13565   int nMax =0;
13566   struct IdxRemCtx *pCtx = 0;
13567   struct IdxSampleCtx samplectx;
13568   int i;
13569   i64 iPrev = -100000;
13570   sqlite3_stmt *pAllIndex = 0;
13571   sqlite3_stmt *pIndexXInfo = 0;
13572   sqlite3_stmt *pWrite = 0;
13573 
13574   const char *zAllIndex =
13575     "SELECT s.rowid, s.name, l.name FROM "
13576     "  sqlite_schema AS s, "
13577     "  pragma_index_list(s.name) AS l "
13578     "WHERE s.type = 'table'";
13579   const char *zIndexXInfo =
13580     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
13581   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
13582 
13583   /* If iSample==0, no sqlite_stat1 data is required. */
13584   if( p->iSample==0 ) return SQLITE_OK;
13585 
13586   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
13587   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
13588 
13589   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
13590 
13591   if( rc==SQLITE_OK ){
13592     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
13593     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
13594   }
13595 
13596   if( rc==SQLITE_OK ){
13597     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13598     rc = sqlite3_create_function(
13599         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
13600     );
13601   }
13602   if( rc==SQLITE_OK ){
13603     rc = sqlite3_create_function(
13604         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
13605     );
13606   }
13607 
13608   if( rc==SQLITE_OK ){
13609     pCtx->nSlot = nMax+1;
13610     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
13611   }
13612   if( rc==SQLITE_OK ){
13613     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
13614   }
13615   if( rc==SQLITE_OK ){
13616     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
13617   }
13618 
13619   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
13620     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
13621     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
13622     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
13623     if( zTab==0 || zIdx==0 ) continue;
13624     if( p->iSample<100 && iPrev!=iRowid ){
13625       samplectx.target = (double)p->iSample / 100.0;
13626       samplectx.iTarget = p->iSample;
13627       samplectx.nRow = 0.0;
13628       samplectx.nRet = 0.0;
13629       rc = idxBuildSampleTable(p, zTab);
13630       if( rc!=SQLITE_OK ) break;
13631     }
13632     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
13633     iPrev = iRowid;
13634   }
13635   if( rc==SQLITE_OK && p->iSample<100 ){
13636     rc = sqlite3_exec(p->dbv,
13637         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
13638     );
13639   }
13640 
13641   idxFinalize(&rc, pAllIndex);
13642   idxFinalize(&rc, pIndexXInfo);
13643   idxFinalize(&rc, pWrite);
13644 
13645   if( pCtx ){
13646     for(i=0; i<pCtx->nSlot; i++){
13647       sqlite3_free(pCtx->aSlot[i].z);
13648     }
13649     sqlite3_free(pCtx);
13650   }
13651 
13652   if( rc==SQLITE_OK ){
13653     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
13654   }
13655 
13656   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13657   return rc;
13658 }
13659 
13660 /*
13661 ** Define and possibly pretend to use a useless collation sequence.
13662 ** This pretense allows expert to accept SQL using custom collations.
13663 */
dummyCompare(void * up1,int up2,const void * up3,int up4,const void * up5)13664 int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
13665   (void)up1;
13666   (void)up2;
13667   (void)up3;
13668   (void)up4;
13669   (void)up5;
13670   assert(0); /* VDBE should never be run. */
13671   return 0;
13672 }
13673 /* And a callback to register above upon actual need */
useDummyCS(void * up1,sqlite3 * db,int etr,const char * zName)13674 void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
13675   (void)up1;
13676   sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
13677 }
13678 
13679 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13680   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13681 /*
13682 ** dummy functions for no-op implementation of UDFs during expert's work
13683 */
dummyUDF(sqlite3_context * up1,int up2,sqlite3_value ** up3)13684 void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
13685   (void)up1;
13686   (void)up2;
13687   (void)up3;
13688   assert(0); /* VDBE should never be run. */
13689 }
dummyUDFvalue(sqlite3_context * up1)13690 void dummyUDFvalue(sqlite3_context *up1){
13691   (void)up1;
13692   assert(0); /* VDBE should never be run. */
13693 }
13694 
13695 /*
13696 ** Register UDFs from user database with another.
13697 */
registerUDFs(sqlite3 * dbSrc,sqlite3 * dbDst)13698 int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
13699   sqlite3_stmt *pStmt;
13700   int rc = sqlite3_prepare_v2(dbSrc,
13701             "SELECT name,type,enc,narg,flags "
13702             "FROM pragma_function_list() "
13703             "WHERE builtin==0", -1, &pStmt, 0);
13704   if( rc==SQLITE_OK ){
13705     while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
13706       int nargs = sqlite3_column_int(pStmt,3);
13707       int flags = sqlite3_column_int(pStmt,4);
13708       const char *name = (char*)sqlite3_column_text(pStmt,0);
13709       const char *type = (char*)sqlite3_column_text(pStmt,1);
13710       const char *enc = (char*)sqlite3_column_text(pStmt,2);
13711       if( name==0 || type==0 || enc==0 ){
13712         /* no-op.  Only happens on OOM */
13713       }else{
13714         int ienc = SQLITE_UTF8;
13715         int rcf = SQLITE_ERROR;
13716         if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
13717         else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
13718         ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
13719         if( strcmp(type,"w")==0 ){
13720           rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
13721                                                dummyUDF,dummyUDFvalue,0,0,0);
13722         }else if( strcmp(type,"a")==0 ){
13723           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13724                                         0,dummyUDF,dummyUDFvalue);
13725         }else if( strcmp(type,"s")==0 ){
13726           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13727                                         dummyUDF,0,0);
13728         }
13729         if( rcf!=SQLITE_OK ){
13730           rc = rcf;
13731           break;
13732         }
13733       }
13734     }
13735     sqlite3_finalize(pStmt);
13736     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
13737   }
13738   return rc;
13739 }
13740 #endif
13741 
13742 /*
13743 ** Allocate a new sqlite3expert object.
13744 */
sqlite3_expert_new(sqlite3 * db,char ** pzErrmsg)13745 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
13746   int rc = SQLITE_OK;
13747   sqlite3expert *pNew;
13748 
13749   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
13750 
13751   /* Open two in-memory databases to work with. The "vtab database" (dbv)
13752   ** will contain a virtual table corresponding to each real table in
13753   ** the user database schema, and a copy of each view. It is used to
13754   ** collect information regarding the WHERE, ORDER BY and other clauses
13755   ** of the user's query.
13756   */
13757   if( rc==SQLITE_OK ){
13758     pNew->db = db;
13759     pNew->iSample = 100;
13760     rc = sqlite3_open(":memory:", &pNew->dbv);
13761   }
13762   if( rc==SQLITE_OK ){
13763     rc = sqlite3_open(":memory:", &pNew->dbm);
13764     if( rc==SQLITE_OK ){
13765       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
13766     }
13767   }
13768 
13769   /* Allow custom collations to be dealt with through prepare. */
13770   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
13771   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
13772 
13773 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13774   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13775   /* Register UDFs from database [db] with [dbm] and [dbv]. */
13776   if( rc==SQLITE_OK ){
13777     rc = registerUDFs(pNew->db, pNew->dbm);
13778   }
13779   if( rc==SQLITE_OK ){
13780     rc = registerUDFs(pNew->db, pNew->dbv);
13781   }
13782 #endif
13783 
13784   /* Copy the entire schema of database [db] into [dbm]. */
13785   if( rc==SQLITE_OK ){
13786     sqlite3_stmt *pSql = 0;
13787     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
13788         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
13789         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
13790     );
13791     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
13792       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
13793       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
13794     }
13795     idxFinalize(&rc, pSql);
13796   }
13797 
13798   /* Create the vtab schema */
13799   if( rc==SQLITE_OK ){
13800     rc = idxCreateVtabSchema(pNew, pzErrmsg);
13801   }
13802 
13803   /* Register the auth callback with dbv */
13804   if( rc==SQLITE_OK ){
13805     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
13806   }
13807 
13808   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
13809   ** return the new sqlite3expert handle.  */
13810   if( rc!=SQLITE_OK ){
13811     sqlite3_expert_destroy(pNew);
13812     pNew = 0;
13813   }
13814   return pNew;
13815 }
13816 
13817 /*
13818 ** Configure an sqlite3expert object.
13819 */
sqlite3_expert_config(sqlite3expert * p,int op,...)13820 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
13821   int rc = SQLITE_OK;
13822   va_list ap;
13823   va_start(ap, op);
13824   switch( op ){
13825     case EXPERT_CONFIG_SAMPLE: {
13826       int iVal = va_arg(ap, int);
13827       if( iVal<0 ) iVal = 0;
13828       if( iVal>100 ) iVal = 100;
13829       p->iSample = iVal;
13830       break;
13831     }
13832     default:
13833       rc = SQLITE_NOTFOUND;
13834       break;
13835   }
13836 
13837   va_end(ap);
13838   return rc;
13839 }
13840 
13841 /*
13842 ** Add an SQL statement to the analysis.
13843 */
sqlite3_expert_sql(sqlite3expert * p,const char * zSql,char ** pzErr)13844 int sqlite3_expert_sql(
13845   sqlite3expert *p,               /* From sqlite3_expert_new() */
13846   const char *zSql,               /* SQL statement to add */
13847   char **pzErr                    /* OUT: Error message (if any) */
13848 ){
13849   IdxScan *pScanOrig = p->pScan;
13850   IdxStatement *pStmtOrig = p->pStatement;
13851   int rc = SQLITE_OK;
13852   const char *zStmt = zSql;
13853 
13854   if( p->bRun ) return SQLITE_MISUSE;
13855 
13856   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
13857     sqlite3_stmt *pStmt = 0;
13858     /* Ensure that the provided statement compiles against user's DB. */
13859     rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
13860     if( rc!=SQLITE_OK ) break;
13861     sqlite3_finalize(pStmt);
13862     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
13863     if( rc==SQLITE_OK ){
13864       if( pStmt ){
13865         IdxStatement *pNew;
13866         const char *z = sqlite3_sql(pStmt);
13867         int n = STRLEN(z);
13868         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
13869         if( rc==SQLITE_OK ){
13870           pNew->zSql = (char*)&pNew[1];
13871           memcpy(pNew->zSql, z, n+1);
13872           pNew->pNext = p->pStatement;
13873           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
13874           p->pStatement = pNew;
13875         }
13876         sqlite3_finalize(pStmt);
13877       }
13878     }else{
13879       idxDatabaseError(p->dbv, pzErr);
13880     }
13881   }
13882 
13883   if( rc!=SQLITE_OK ){
13884     idxScanFree(p->pScan, pScanOrig);
13885     idxStatementFree(p->pStatement, pStmtOrig);
13886     p->pScan = pScanOrig;
13887     p->pStatement = pStmtOrig;
13888   }
13889 
13890   return rc;
13891 }
13892 
sqlite3_expert_analyze(sqlite3expert * p,char ** pzErr)13893 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
13894   int rc;
13895   IdxHashEntry *pEntry;
13896 
13897   /* Do trigger processing to collect any extra IdxScan structures */
13898   rc = idxProcessTriggers(p, pzErr);
13899 
13900   /* Create candidate indexes within the in-memory database file */
13901   if( rc==SQLITE_OK ){
13902     rc = idxCreateCandidates(p);
13903   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
13904     if( pzErr )
13905       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
13906     return rc;
13907   }
13908 
13909   /* Generate the stat1 data */
13910   if( rc==SQLITE_OK ){
13911     rc = idxPopulateStat1(p, pzErr);
13912   }
13913 
13914   /* Formulate the EXPERT_REPORT_CANDIDATES text */
13915   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13916     p->zCandidates = idxAppendText(&rc, p->zCandidates,
13917         "%s;%s%s\n", pEntry->zVal,
13918         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
13919     );
13920   }
13921 
13922   /* Figure out which of the candidate indexes are preferred by the query
13923   ** planner and report the results to the user.  */
13924   if( rc==SQLITE_OK ){
13925     rc = idxFindIndexes(p, pzErr);
13926   }
13927 
13928   if( rc==SQLITE_OK ){
13929     p->bRun = 1;
13930   }
13931   return rc;
13932 }
13933 
13934 /*
13935 ** Return the total number of statements that have been added to this
13936 ** sqlite3expert using sqlite3_expert_sql().
13937 */
sqlite3_expert_count(sqlite3expert * p)13938 int sqlite3_expert_count(sqlite3expert *p){
13939   int nRet = 0;
13940   if( p->pStatement ) nRet = p->pStatement->iId+1;
13941   return nRet;
13942 }
13943 
13944 /*
13945 ** Return a component of the report.
13946 */
sqlite3_expert_report(sqlite3expert * p,int iStmt,int eReport)13947 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
13948   const char *zRet = 0;
13949   IdxStatement *pStmt;
13950 
13951   if( p->bRun==0 ) return 0;
13952   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
13953   switch( eReport ){
13954     case EXPERT_REPORT_SQL:
13955       if( pStmt ) zRet = pStmt->zSql;
13956       break;
13957     case EXPERT_REPORT_INDEXES:
13958       if( pStmt ) zRet = pStmt->zIdx;
13959       break;
13960     case EXPERT_REPORT_PLAN:
13961       if( pStmt ) zRet = pStmt->zEQP;
13962       break;
13963     case EXPERT_REPORT_CANDIDATES:
13964       zRet = p->zCandidates;
13965       break;
13966   }
13967   return zRet;
13968 }
13969 
13970 /*
13971 ** Free an sqlite3expert object.
13972 */
sqlite3_expert_destroy(sqlite3expert * p)13973 void sqlite3_expert_destroy(sqlite3expert *p){
13974   if( p ){
13975     sqlite3_close(p->dbm);
13976     sqlite3_close(p->dbv);
13977     idxScanFree(p->pScan, 0);
13978     idxStatementFree(p->pStatement, 0);
13979     idxTableFree(p->pTable);
13980     idxWriteFree(p->pWrite);
13981     idxHashClear(&p->hIdx);
13982     sqlite3_free(p->zCandidates);
13983     sqlite3_free(p);
13984   }
13985 }
13986 
13987 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13988 
13989 /************************* End ../ext/expert/sqlite3expert.c ********************/
13990 
13991 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
13992 #define SQLITE_SHELL_HAVE_RECOVER 1
13993 #else
13994 #define SQLITE_SHELL_HAVE_RECOVER 0
13995 #endif
13996 #if SQLITE_SHELL_HAVE_RECOVER
13997 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
13998 /*
13999 ** 2022-08-27
14000 **
14001 ** The author disclaims copyright to this source code.  In place of
14002 ** a legal notice, here is a blessing:
14003 **
14004 **    May you do good and not evil.
14005 **    May you find forgiveness for yourself and forgive others.
14006 **    May you share freely, never taking more than you give.
14007 **
14008 *************************************************************************
14009 **
14010 ** This file contains the public interface to the "recover" extension -
14011 ** an SQLite extension designed to recover data from corrupted database
14012 ** files.
14013 */
14014 
14015 /*
14016 ** OVERVIEW:
14017 **
14018 ** To use the API to recover data from a corrupted database, an
14019 ** application:
14020 **
14021 **   1) Creates an sqlite3_recover handle by calling either
14022 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
14023 **
14024 **   2) Configures the new handle using one or more calls to
14025 **      sqlite3_recover_config().
14026 **
14027 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
14028 **      the handle until it returns something other than SQLITE_OK. If it
14029 **      returns SQLITE_DONE, then the recovery operation completed without
14030 **      error. If it returns some other non-SQLITE_OK value, then an error
14031 **      has occurred.
14032 **
14033 **   4) Retrieves any error code and English language error message using the
14034 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
14035 **      respectively.
14036 **
14037 **   5) Destroys the sqlite3_recover handle and frees all resources
14038 **      using sqlite3_recover_finish().
14039 **
14040 ** The application may abandon the recovery operation at any point
14041 ** before it is finished by passing the sqlite3_recover handle to
14042 ** sqlite3_recover_finish(). This is not an error, but the final state
14043 ** of the output database, or the results of running the partial script
14044 ** delivered to the SQL callback, are undefined.
14045 */
14046 
14047 #ifndef _SQLITE_RECOVER_H
14048 #define _SQLITE_RECOVER_H
14049 
14050 /* #include "sqlite3.h" */
14051 
14052 #ifdef __cplusplus
14053 extern "C" {
14054 #endif
14055 
14056 /*
14057 ** An instance of the sqlite3_recover object represents a recovery
14058 ** operation in progress.
14059 **
14060 ** Constructors:
14061 **
14062 **    sqlite3_recover_init()
14063 **    sqlite3_recover_init_sql()
14064 **
14065 ** Destructor:
14066 **
14067 **    sqlite3_recover_finish()
14068 **
14069 ** Methods:
14070 **
14071 **    sqlite3_recover_config()
14072 **    sqlite3_recover_errcode()
14073 **    sqlite3_recover_errmsg()
14074 **    sqlite3_recover_run()
14075 **    sqlite3_recover_step()
14076 */
14077 typedef struct sqlite3_recover sqlite3_recover;
14078 
14079 /*
14080 ** These two APIs attempt to create and return a new sqlite3_recover object.
14081 ** In both cases the first two arguments identify the (possibly
14082 ** corrupt) database to recover data from. The first argument is an open
14083 ** database handle and the second the name of a database attached to that
14084 ** handle (i.e. "main", "temp" or the name of an attached database).
14085 **
14086 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
14087 ** handle, then data is recovered into a new database, identified by
14088 ** string parameter zUri. zUri may be an absolute or relative file path,
14089 ** or may be an SQLite URI. If the identified database file already exists,
14090 ** it is overwritten.
14091 **
14092 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
14093 ** be returned to the user as a series of SQL statements. Executing these
14094 ** SQL statements results in the same database as would have been created
14095 ** had sqlite3_recover_init() been used. For each SQL statement in the
14096 ** output, the callback function passed as the third argument (xSql) is
14097 ** invoked once. The first parameter is a passed a copy of the fourth argument
14098 ** to this function (pCtx) as its first parameter, and a pointer to a
14099 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
14100 ** the second. If the xSql callback returns any value other than SQLITE_OK,
14101 ** then processing is immediately abandoned and the value returned used as
14102 ** the recover handle error code (see below).
14103 **
14104 ** If an out-of-memory error occurs, NULL may be returned instead of
14105 ** a valid handle. In all other cases, it is the responsibility of the
14106 ** application to avoid resource leaks by ensuring that
14107 ** sqlite3_recover_finish() is called on all allocated handles.
14108 */
14109 sqlite3_recover *sqlite3_recover_init(
14110   sqlite3* db,
14111   const char *zDb,
14112   const char *zUri
14113 );
14114 sqlite3_recover *sqlite3_recover_init_sql(
14115   sqlite3* db,
14116   const char *zDb,
14117   int (*xSql)(void*, const char*),
14118   void *pCtx
14119 );
14120 
14121 /*
14122 ** Configure an sqlite3_recover object that has just been created using
14123 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
14124 ** may only be called before the first call to sqlite3_recover_step()
14125 ** or sqlite3_recover_run() on the object.
14126 **
14127 ** The second argument passed to this function must be one of the
14128 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
14129 ** depend on the specific SQLITE_RECOVER_* symbol in use.
14130 **
14131 ** SQLITE_OK is returned if the configuration operation was successful,
14132 ** or an SQLite error code otherwise.
14133 */
14134 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
14135 
14136 /*
14137 ** SQLITE_RECOVER_LOST_AND_FOUND:
14138 **   The pArg argument points to a string buffer containing the name
14139 **   of a "lost-and-found" table in the output database, or NULL. If
14140 **   the argument is non-NULL and the database contains seemingly
14141 **   valid pages that cannot be associated with any table in the
14142 **   recovered part of the schema, data is extracted from these
14143 **   pages to add to the lost-and-found table.
14144 **
14145 ** SQLITE_RECOVER_FREELIST_CORRUPT:
14146 **   The pArg value must actually be a pointer to a value of type
14147 **   int containing value 0 or 1 cast as a (void*). If this option is set
14148 **   (argument is 1) and a lost-and-found table has been configured using
14149 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
14150 **   corrupt and an attempt is made to recover records from pages that
14151 **   appear to be linked into the freelist. Otherwise, pages on the freelist
14152 **   are ignored. Setting this option can recover more data from the
14153 **   database, but often ends up "recovering" deleted records. The default
14154 **   value is 0 (clear).
14155 **
14156 ** SQLITE_RECOVER_ROWIDS:
14157 **   The pArg value must actually be a pointer to a value of type
14158 **   int containing value 0 or 1 cast as a (void*). If this option is set
14159 **   (argument is 1), then an attempt is made to recover rowid values
14160 **   that are not also INTEGER PRIMARY KEY values. If this option is
14161 **   clear, then new rowids are assigned to all recovered rows. The
14162 **   default value is 1 (set).
14163 **
14164 ** SQLITE_RECOVER_SLOWINDEXES:
14165 **   The pArg value must actually be a pointer to a value of type
14166 **   int containing value 0 or 1 cast as a (void*). If this option is clear
14167 **   (argument is 0), then when creating an output database, the recover
14168 **   module creates and populates non-UNIQUE indexes right at the end of the
14169 **   recovery operation - after all recoverable data has been inserted
14170 **   into the new database. This is faster overall, but means that the
14171 **   final call to sqlite3_recover_step() for a recovery operation may
14172 **   be need to create a large number of indexes, which may be very slow.
14173 **
14174 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
14175 **   are created in the output database before it is populated with
14176 **   recovered data. This is slower overall, but avoids the slow call
14177 **   to sqlite3_recover_step() at the end of the recovery operation.
14178 **
14179 **   The default option value is 0.
14180 */
14181 #define SQLITE_RECOVER_LOST_AND_FOUND   1
14182 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
14183 #define SQLITE_RECOVER_ROWIDS           3
14184 #define SQLITE_RECOVER_SLOWINDEXES      4
14185 
14186 /*
14187 ** Perform a unit of work towards the recovery operation. This function
14188 ** must normally be called multiple times to complete database recovery.
14189 **
14190 ** If no error occurs but the recovery operation is not completed, this
14191 ** function returns SQLITE_OK. If recovery has been completed successfully
14192 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
14193 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
14194 ** considered an error if some or all of the data cannot be recovered
14195 ** due to database corruption.
14196 **
14197 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
14198 ** all further such calls on the same recover handle are no-ops that return
14199 ** the same non-SQLITE_OK value.
14200 */
14201 int sqlite3_recover_step(sqlite3_recover*);
14202 
14203 /*
14204 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
14205 ** or an SQLite error code otherwise. Calling this function is the same
14206 ** as executing:
14207 **
14208 **     while( SQLITE_OK==sqlite3_recover_step(p) );
14209 **     return sqlite3_recover_errcode(p);
14210 */
14211 int sqlite3_recover_run(sqlite3_recover*);
14212 
14213 /*
14214 ** If an error has been encountered during a prior call to
14215 ** sqlite3_recover_step(), then this function attempts to return a
14216 ** pointer to a buffer containing an English language explanation of
14217 ** the error. If no error message is available, or if an out-of memory
14218 ** error occurs while attempting to allocate a buffer in which to format
14219 ** the error message, NULL is returned.
14220 **
14221 ** The returned buffer remains valid until the sqlite3_recover handle is
14222 ** destroyed using sqlite3_recover_finish().
14223 */
14224 const char *sqlite3_recover_errmsg(sqlite3_recover*);
14225 
14226 /*
14227 ** If this function is called on an sqlite3_recover handle after
14228 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
14229 */
14230 int sqlite3_recover_errcode(sqlite3_recover*);
14231 
14232 /*
14233 ** Clean up a recovery object created by a call to sqlite3_recover_init().
14234 ** The results of using a recovery object with any API after it has been
14235 ** passed to this function are undefined.
14236 **
14237 ** This function returns the same value as sqlite3_recover_errcode().
14238 */
14239 int sqlite3_recover_finish(sqlite3_recover*);
14240 
14241 
14242 #ifdef __cplusplus
14243 }  /* end of the 'extern "C"' block */
14244 #endif
14245 
14246 #endif /* ifndef _SQLITE_RECOVER_H */
14247 
14248 /************************* End ../ext/recover/sqlite3recover.h ********************/
14249 # ifndef SQLITE_HAVE_SQLITE3R
14250 /************************* Begin ../ext/recover/dbdata.c ******************/
14251 /*
14252 ** 2019-04-17
14253 **
14254 ** The author disclaims copyright to this source code.  In place of
14255 ** a legal notice, here is a blessing:
14256 **
14257 **    May you do good and not evil.
14258 **    May you find forgiveness for yourself and forgive others.
14259 **    May you share freely, never taking more than you give.
14260 **
14261 ******************************************************************************
14262 **
14263 ** This file contains an implementation of two eponymous virtual tables,
14264 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
14265 ** "sqlite_dbpage" eponymous virtual table be available.
14266 **
14267 ** SQLITE_DBDATA:
14268 **   sqlite_dbdata is used to extract data directly from a database b-tree
14269 **   page and its associated overflow pages, bypassing the b-tree layer.
14270 **   The table schema is equivalent to:
14271 **
14272 **     CREATE TABLE sqlite_dbdata(
14273 **       pgno INTEGER,
14274 **       cell INTEGER,
14275 **       field INTEGER,
14276 **       value ANY,
14277 **       schema TEXT HIDDEN
14278 **     );
14279 **
14280 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
14281 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
14282 **   "schema".
14283 **
14284 **   Each page of the database is inspected. If it cannot be interpreted as
14285 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
14286 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
14287 **   table contains one row for each field in the record associated with
14288 **   each cell on the page. For intkey b-trees, the key value is stored in
14289 **   field -1.
14290 **
14291 **   For example, for the database:
14292 **
14293 **     CREATE TABLE t1(a, b);     -- root page is page 2
14294 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
14295 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
14296 **
14297 **   the sqlite_dbdata table contains, as well as from entries related to
14298 **   page 1, content equivalent to:
14299 **
14300 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
14301 **         (2, 0, -1, 5     ),
14302 **         (2, 0,  0, 'v'   ),
14303 **         (2, 0,  1, 'five'),
14304 **         (2, 1, -1, 10    ),
14305 **         (2, 1,  0, 'x'   ),
14306 **         (2, 1,  1, 'ten' );
14307 **
14308 **   If database corruption is encountered, this module does not report an
14309 **   error. Instead, it attempts to extract as much data as possible and
14310 **   ignores the corruption.
14311 **
14312 ** SQLITE_DBPTR:
14313 **   The sqlite_dbptr table has the following schema:
14314 **
14315 **     CREATE TABLE sqlite_dbptr(
14316 **       pgno INTEGER,
14317 **       child INTEGER,
14318 **       schema TEXT HIDDEN
14319 **     );
14320 **
14321 **   It contains one entry for each b-tree pointer between a parent and
14322 **   child page in the database.
14323 */
14324 
14325 #if !defined(SQLITEINT_H)
14326 /* #include "sqlite3.h" */
14327 
14328 /* typedef unsigned char u8; */
14329 /* typedef unsigned int u32; */
14330 
14331 #endif
14332 #include <string.h>
14333 #include <assert.h>
14334 
14335 #ifndef SQLITE_OMIT_VIRTUALTABLE
14336 
14337 #define DBDATA_PADDING_BYTES 100
14338 
14339 typedef struct DbdataTable DbdataTable;
14340 typedef struct DbdataCursor DbdataCursor;
14341 
14342 /* Cursor object */
14343 struct DbdataCursor {
14344   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
14345   sqlite3_stmt *pStmt;            /* For fetching database pages */
14346 
14347   int iPgno;                      /* Current page number */
14348   u8 *aPage;                      /* Buffer containing page */
14349   int nPage;                      /* Size of aPage[] in bytes */
14350   int nCell;                      /* Number of cells on aPage[] */
14351   int iCell;                      /* Current cell number */
14352   int bOnePage;                   /* True to stop after one page */
14353   int szDb;
14354   sqlite3_int64 iRowid;
14355 
14356   /* Only for the sqlite_dbdata table */
14357   u8 *pRec;                       /* Buffer containing current record */
14358   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
14359   sqlite3_int64 nHdr;             /* Size of header in bytes */
14360   int iField;                     /* Current field number */
14361   u8 *pHdrPtr;
14362   u8 *pPtr;
14363   u32 enc;                        /* Text encoding */
14364 
14365   sqlite3_int64 iIntkey;          /* Integer key value */
14366 };
14367 
14368 /* Table object */
14369 struct DbdataTable {
14370   sqlite3_vtab base;              /* Base class.  Must be first */
14371   sqlite3 *db;                    /* The database connection */
14372   sqlite3_stmt *pStmt;            /* For fetching database pages */
14373   int bPtr;                       /* True for sqlite3_dbptr table */
14374 };
14375 
14376 /* Column and schema definitions for sqlite_dbdata */
14377 #define DBDATA_COLUMN_PGNO        0
14378 #define DBDATA_COLUMN_CELL        1
14379 #define DBDATA_COLUMN_FIELD       2
14380 #define DBDATA_COLUMN_VALUE       3
14381 #define DBDATA_COLUMN_SCHEMA      4
14382 #define DBDATA_SCHEMA             \
14383       "CREATE TABLE x("           \
14384       "  pgno INTEGER,"           \
14385       "  cell INTEGER,"           \
14386       "  field INTEGER,"          \
14387       "  value ANY,"              \
14388       "  schema TEXT HIDDEN"      \
14389       ")"
14390 
14391 /* Column and schema definitions for sqlite_dbptr */
14392 #define DBPTR_COLUMN_PGNO         0
14393 #define DBPTR_COLUMN_CHILD        1
14394 #define DBPTR_COLUMN_SCHEMA       2
14395 #define DBPTR_SCHEMA              \
14396       "CREATE TABLE x("           \
14397       "  pgno INTEGER,"           \
14398       "  child INTEGER,"          \
14399       "  schema TEXT HIDDEN"      \
14400       ")"
14401 
14402 /*
14403 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
14404 ** table.
14405 */
dbdataConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)14406 static int dbdataConnect(
14407   sqlite3 *db,
14408   void *pAux,
14409   int argc, const char *const*argv,
14410   sqlite3_vtab **ppVtab,
14411   char **pzErr
14412 ){
14413   DbdataTable *pTab = 0;
14414   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
14415 
14416   (void)argc;
14417   (void)argv;
14418   (void)pzErr;
14419   sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
14420   if( rc==SQLITE_OK ){
14421     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
14422     if( pTab==0 ){
14423       rc = SQLITE_NOMEM;
14424     }else{
14425       memset(pTab, 0, sizeof(DbdataTable));
14426       pTab->db = db;
14427       pTab->bPtr = (pAux!=0);
14428     }
14429   }
14430 
14431   *ppVtab = (sqlite3_vtab*)pTab;
14432   return rc;
14433 }
14434 
14435 /*
14436 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
14437 */
dbdataDisconnect(sqlite3_vtab * pVtab)14438 static int dbdataDisconnect(sqlite3_vtab *pVtab){
14439   DbdataTable *pTab = (DbdataTable*)pVtab;
14440   if( pTab ){
14441     sqlite3_finalize(pTab->pStmt);
14442     sqlite3_free(pVtab);
14443   }
14444   return SQLITE_OK;
14445 }
14446 
14447 /*
14448 ** This function interprets two types of constraints:
14449 **
14450 **       schema=?
14451 **       pgno=?
14452 **
14453 ** If neither are present, idxNum is set to 0. If schema=? is present,
14454 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
14455 ** in idxNum is set.
14456 **
14457 ** If both parameters are present, schema is in position 0 and pgno in
14458 ** position 1.
14459 */
dbdataBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdx)14460 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
14461   DbdataTable *pTab = (DbdataTable*)tab;
14462   int i;
14463   int iSchema = -1;
14464   int iPgno = -1;
14465   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
14466 
14467   for(i=0; i<pIdx->nConstraint; i++){
14468     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
14469     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
14470       if( p->iColumn==colSchema ){
14471         if( p->usable==0 ) return SQLITE_CONSTRAINT;
14472         iSchema = i;
14473       }
14474       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
14475         iPgno = i;
14476       }
14477     }
14478   }
14479 
14480   if( iSchema>=0 ){
14481     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
14482     pIdx->aConstraintUsage[iSchema].omit = 1;
14483   }
14484   if( iPgno>=0 ){
14485     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
14486     pIdx->aConstraintUsage[iPgno].omit = 1;
14487     pIdx->estimatedCost = 100;
14488     pIdx->estimatedRows =  50;
14489 
14490     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
14491       int iCol = pIdx->aOrderBy[0].iColumn;
14492       if( pIdx->nOrderBy==1 ){
14493         pIdx->orderByConsumed = (iCol==0 || iCol==1);
14494       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
14495         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
14496       }
14497     }
14498 
14499   }else{
14500     pIdx->estimatedCost = 100000000;
14501     pIdx->estimatedRows = 1000000000;
14502   }
14503   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
14504   return SQLITE_OK;
14505 }
14506 
14507 /*
14508 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
14509 */
dbdataOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)14510 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
14511   DbdataCursor *pCsr;
14512 
14513   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
14514   if( pCsr==0 ){
14515     return SQLITE_NOMEM;
14516   }else{
14517     memset(pCsr, 0, sizeof(DbdataCursor));
14518     pCsr->base.pVtab = pVTab;
14519   }
14520 
14521   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
14522   return SQLITE_OK;
14523 }
14524 
14525 /*
14526 ** Restore a cursor object to the state it was in when first allocated
14527 ** by dbdataOpen().
14528 */
dbdataResetCursor(DbdataCursor * pCsr)14529 static void dbdataResetCursor(DbdataCursor *pCsr){
14530   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
14531   if( pTab->pStmt==0 ){
14532     pTab->pStmt = pCsr->pStmt;
14533   }else{
14534     sqlite3_finalize(pCsr->pStmt);
14535   }
14536   pCsr->pStmt = 0;
14537   pCsr->iPgno = 1;
14538   pCsr->iCell = 0;
14539   pCsr->iField = 0;
14540   pCsr->bOnePage = 0;
14541   sqlite3_free(pCsr->aPage);
14542   sqlite3_free(pCsr->pRec);
14543   pCsr->pRec = 0;
14544   pCsr->aPage = 0;
14545 }
14546 
14547 /*
14548 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
14549 */
dbdataClose(sqlite3_vtab_cursor * pCursor)14550 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
14551   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14552   dbdataResetCursor(pCsr);
14553   sqlite3_free(pCsr);
14554   return SQLITE_OK;
14555 }
14556 
14557 /*
14558 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
14559 */
get_uint16(unsigned char * a)14560 static u32 get_uint16(unsigned char *a){
14561   return (a[0]<<8)|a[1];
14562 }
get_uint32(unsigned char * a)14563 static u32 get_uint32(unsigned char *a){
14564   return ((u32)a[0]<<24)
14565        | ((u32)a[1]<<16)
14566        | ((u32)a[2]<<8)
14567        | ((u32)a[3]);
14568 }
14569 
14570 /*
14571 ** Load page pgno from the database via the sqlite_dbpage virtual table.
14572 ** If successful, set (*ppPage) to point to a buffer containing the page
14573 ** data, (*pnPage) to the size of that buffer in bytes and return
14574 ** SQLITE_OK. In this case it is the responsibility of the caller to
14575 ** eventually free the buffer using sqlite3_free().
14576 **
14577 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
14578 ** return an SQLite error code.
14579 */
dbdataLoadPage(DbdataCursor * pCsr,u32 pgno,u8 ** ppPage,int * pnPage)14580 static int dbdataLoadPage(
14581   DbdataCursor *pCsr,             /* Cursor object */
14582   u32 pgno,                       /* Page number of page to load */
14583   u8 **ppPage,                    /* OUT: pointer to page buffer */
14584   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
14585 ){
14586   int rc2;
14587   int rc = SQLITE_OK;
14588   sqlite3_stmt *pStmt = pCsr->pStmt;
14589 
14590   *ppPage = 0;
14591   *pnPage = 0;
14592   if( pgno>0 ){
14593     sqlite3_bind_int64(pStmt, 2, pgno);
14594     if( SQLITE_ROW==sqlite3_step(pStmt) ){
14595       int nCopy = sqlite3_column_bytes(pStmt, 0);
14596       if( nCopy>0 ){
14597         u8 *pPage;
14598         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
14599         if( pPage==0 ){
14600           rc = SQLITE_NOMEM;
14601         }else{
14602           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
14603           memcpy(pPage, pCopy, nCopy);
14604           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
14605         }
14606         *ppPage = pPage;
14607         *pnPage = nCopy;
14608       }
14609     }
14610     rc2 = sqlite3_reset(pStmt);
14611     if( rc==SQLITE_OK ) rc = rc2;
14612   }
14613 
14614   return rc;
14615 }
14616 
14617 /*
14618 ** Read a varint.  Put the value in *pVal and return the number of bytes.
14619 */
dbdataGetVarint(const u8 * z,sqlite3_int64 * pVal)14620 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
14621   sqlite3_uint64 u = 0;
14622   int i;
14623   for(i=0; i<8; i++){
14624     u = (u<<7) + (z[i]&0x7f);
14625     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
14626   }
14627   u = (u<<8) + (z[i]&0xff);
14628   *pVal = (sqlite3_int64)u;
14629   return 9;
14630 }
14631 
14632 /*
14633 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
14634 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
14635 ** SQLite database except for key values in intkey tables.
14636 */
dbdataGetVarintU32(const u8 * z,sqlite3_int64 * pVal)14637 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
14638   sqlite3_int64 val;
14639   int nRet = dbdataGetVarint(z, &val);
14640   if( val<0 || val>0xFFFFFFFF ) val = 0;
14641   *pVal = val;
14642   return nRet;
14643 }
14644 
14645 /*
14646 ** Return the number of bytes of space used by an SQLite value of type
14647 ** eType.
14648 */
dbdataValueBytes(int eType)14649 static int dbdataValueBytes(int eType){
14650   switch( eType ){
14651     case 0: case 8: case 9:
14652     case 10: case 11:
14653       return 0;
14654     case 1:
14655       return 1;
14656     case 2:
14657       return 2;
14658     case 3:
14659       return 3;
14660     case 4:
14661       return 4;
14662     case 5:
14663       return 6;
14664     case 6:
14665     case 7:
14666       return 8;
14667     default:
14668       if( eType>0 ){
14669         return ((eType-12) / 2);
14670       }
14671       return 0;
14672   }
14673 }
14674 
14675 /*
14676 ** Load a value of type eType from buffer pData and use it to set the
14677 ** result of context object pCtx.
14678 */
dbdataValue(sqlite3_context * pCtx,u32 enc,int eType,u8 * pData,sqlite3_int64 nData)14679 static void dbdataValue(
14680   sqlite3_context *pCtx,
14681   u32 enc,
14682   int eType,
14683   u8 *pData,
14684   sqlite3_int64 nData
14685 ){
14686   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
14687     switch( eType ){
14688       case 0:
14689       case 10:
14690       case 11:
14691         sqlite3_result_null(pCtx);
14692         break;
14693 
14694       case 8:
14695         sqlite3_result_int(pCtx, 0);
14696         break;
14697       case 9:
14698         sqlite3_result_int(pCtx, 1);
14699         break;
14700 
14701       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
14702         sqlite3_uint64 v = (signed char)pData[0];
14703         pData++;
14704         switch( eType ){
14705           case 7:
14706           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
14707           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
14708           case 4:  v = (v<<8) + pData[0];  pData++;
14709           case 3:  v = (v<<8) + pData[0];  pData++;
14710           case 2:  v = (v<<8) + pData[0];  pData++;
14711         }
14712 
14713         if( eType==7 ){
14714           double r;
14715           memcpy(&r, &v, sizeof(r));
14716           sqlite3_result_double(pCtx, r);
14717         }else{
14718           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
14719         }
14720         break;
14721       }
14722 
14723       default: {
14724         int n = ((eType-12) / 2);
14725         if( eType % 2 ){
14726           switch( enc ){
14727 #ifndef SQLITE_OMIT_UTF16
14728             case SQLITE_UTF16BE:
14729               sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14730               break;
14731             case SQLITE_UTF16LE:
14732               sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14733               break;
14734 #endif
14735             default:
14736               sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
14737               break;
14738           }
14739         }else{
14740           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
14741         }
14742       }
14743     }
14744   }
14745 }
14746 
14747 /*
14748 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
14749 */
dbdataNext(sqlite3_vtab_cursor * pCursor)14750 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
14751   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14752   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
14753 
14754   pCsr->iRowid++;
14755   while( 1 ){
14756     int rc;
14757     int iOff = (pCsr->iPgno==1 ? 100 : 0);
14758     int bNextPage = 0;
14759 
14760     if( pCsr->aPage==0 ){
14761       while( 1 ){
14762         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
14763         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
14764         if( rc!=SQLITE_OK ) return rc;
14765         if( pCsr->aPage && pCsr->nPage>=256 ) break;
14766         sqlite3_free(pCsr->aPage);
14767         pCsr->aPage = 0;
14768         if( pCsr->bOnePage ) return SQLITE_OK;
14769         pCsr->iPgno++;
14770       }
14771 
14772       assert( iOff+3+2<=pCsr->nPage );
14773       pCsr->iCell = pTab->bPtr ? -2 : 0;
14774       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
14775     }
14776 
14777     if( pTab->bPtr ){
14778       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
14779         pCsr->iCell = pCsr->nCell;
14780       }
14781       pCsr->iCell++;
14782       if( pCsr->iCell>=pCsr->nCell ){
14783         sqlite3_free(pCsr->aPage);
14784         pCsr->aPage = 0;
14785         if( pCsr->bOnePage ) return SQLITE_OK;
14786         pCsr->iPgno++;
14787       }else{
14788         return SQLITE_OK;
14789       }
14790     }else{
14791       /* If there is no record loaded, load it now. */
14792       if( pCsr->pRec==0 ){
14793         int bHasRowid = 0;
14794         int nPointer = 0;
14795         sqlite3_int64 nPayload = 0;
14796         sqlite3_int64 nHdr = 0;
14797         int iHdr;
14798         int U, X;
14799         int nLocal;
14800 
14801         switch( pCsr->aPage[iOff] ){
14802           case 0x02:
14803             nPointer = 4;
14804             break;
14805           case 0x0a:
14806             break;
14807           case 0x0d:
14808             bHasRowid = 1;
14809             break;
14810           default:
14811             /* This is not a b-tree page with records on it. Continue. */
14812             pCsr->iCell = pCsr->nCell;
14813             break;
14814         }
14815 
14816         if( pCsr->iCell>=pCsr->nCell ){
14817           bNextPage = 1;
14818         }else{
14819 
14820           iOff += 8 + nPointer + pCsr->iCell*2;
14821           if( iOff>pCsr->nPage ){
14822             bNextPage = 1;
14823           }else{
14824             iOff = get_uint16(&pCsr->aPage[iOff]);
14825           }
14826 
14827           /* For an interior node cell, skip past the child-page number */
14828           iOff += nPointer;
14829 
14830           /* Load the "byte of payload including overflow" field */
14831           if( bNextPage || iOff>pCsr->nPage ){
14832             bNextPage = 1;
14833           }else{
14834             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
14835           }
14836 
14837           /* If this is a leaf intkey cell, load the rowid */
14838           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
14839             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
14840           }
14841 
14842           /* Figure out how much data to read from the local page */
14843           U = pCsr->nPage;
14844           if( bHasRowid ){
14845             X = U-35;
14846           }else{
14847             X = ((U-12)*64/255)-23;
14848           }
14849           if( nPayload<=X ){
14850             nLocal = nPayload;
14851           }else{
14852             int M, K;
14853             M = ((U-12)*32/255)-23;
14854             K = M+((nPayload-M)%(U-4));
14855             if( K<=X ){
14856               nLocal = K;
14857             }else{
14858               nLocal = M;
14859             }
14860           }
14861 
14862           if( bNextPage || nLocal+iOff>pCsr->nPage ){
14863             bNextPage = 1;
14864           }else{
14865 
14866             /* Allocate space for payload. And a bit more to catch small buffer
14867             ** overruns caused by attempting to read a varint or similar from
14868             ** near the end of a corrupt record.  */
14869             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
14870             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
14871             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
14872             pCsr->nRec = nPayload;
14873 
14874             /* Load the nLocal bytes of payload */
14875             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
14876             iOff += nLocal;
14877 
14878             /* Load content from overflow pages */
14879             if( nPayload>nLocal ){
14880               sqlite3_int64 nRem = nPayload - nLocal;
14881               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
14882               while( nRem>0 ){
14883                 u8 *aOvfl = 0;
14884                 int nOvfl = 0;
14885                 int nCopy;
14886                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
14887                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
14888                 if( rc!=SQLITE_OK ) return rc;
14889                 if( aOvfl==0 ) break;
14890 
14891                 nCopy = U-4;
14892                 if( nCopy>nRem ) nCopy = nRem;
14893                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
14894                 nRem -= nCopy;
14895 
14896                 pgnoOvfl = get_uint32(aOvfl);
14897                 sqlite3_free(aOvfl);
14898               }
14899             }
14900 
14901             iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
14902             if( nHdr>nPayload ) nHdr = 0;
14903             pCsr->nHdr = nHdr;
14904             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
14905             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
14906             pCsr->iField = (bHasRowid ? -1 : 0);
14907           }
14908         }
14909       }else{
14910         pCsr->iField++;
14911         if( pCsr->iField>0 ){
14912           sqlite3_int64 iType;
14913           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
14914             bNextPage = 1;
14915           }else{
14916             int szField = 0;
14917             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
14918             szField = dbdataValueBytes(iType);
14919             if( (pCsr->nRec - (pCsr->pPtr - pCsr->pRec))<szField ){
14920               pCsr->pPtr = &pCsr->pRec[pCsr->nRec];
14921             }else{
14922               pCsr->pPtr += szField;
14923             }
14924           }
14925         }
14926       }
14927 
14928       if( bNextPage ){
14929         sqlite3_free(pCsr->aPage);
14930         sqlite3_free(pCsr->pRec);
14931         pCsr->aPage = 0;
14932         pCsr->pRec = 0;
14933         if( pCsr->bOnePage ) return SQLITE_OK;
14934         pCsr->iPgno++;
14935       }else{
14936         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
14937           return SQLITE_OK;
14938         }
14939 
14940         /* Advance to the next cell. The next iteration of the loop will load
14941         ** the record and so on. */
14942         sqlite3_free(pCsr->pRec);
14943         pCsr->pRec = 0;
14944         pCsr->iCell++;
14945       }
14946     }
14947   }
14948 
14949   assert( !"can't get here" );
14950   return SQLITE_OK;
14951 }
14952 
14953 /*
14954 ** Return true if the cursor is at EOF.
14955 */
dbdataEof(sqlite3_vtab_cursor * pCursor)14956 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
14957   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14958   return pCsr->aPage==0;
14959 }
14960 
14961 /*
14962 ** Return true if nul-terminated string zSchema ends in "()". Or false
14963 ** otherwise.
14964 */
dbdataIsFunction(const char * zSchema)14965 static int dbdataIsFunction(const char *zSchema){
14966   size_t n = strlen(zSchema);
14967   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
14968     return (int)n-2;
14969   }
14970   return 0;
14971 }
14972 
14973 /*
14974 ** Determine the size in pages of database zSchema (where zSchema is
14975 ** "main", "temp" or the name of an attached database) and set
14976 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
14977 ** an SQLite error code.
14978 */
dbdataDbsize(DbdataCursor * pCsr,const char * zSchema)14979 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
14980   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
14981   char *zSql = 0;
14982   int rc, rc2;
14983   int nFunc = 0;
14984   sqlite3_stmt *pStmt = 0;
14985 
14986   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
14987     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
14988   }else{
14989     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
14990   }
14991   if( zSql==0 ) return SQLITE_NOMEM;
14992 
14993   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
14994   sqlite3_free(zSql);
14995   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
14996     pCsr->szDb = sqlite3_column_int(pStmt, 0);
14997   }
14998   rc2 = sqlite3_finalize(pStmt);
14999   if( rc==SQLITE_OK ) rc = rc2;
15000   return rc;
15001 }
15002 
15003 /*
15004 ** Attempt to figure out the encoding of the database by retrieving page 1
15005 ** and inspecting the header field. If successful, set the pCsr->enc variable
15006 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
15007 */
dbdataGetEncoding(DbdataCursor * pCsr)15008 static int dbdataGetEncoding(DbdataCursor *pCsr){
15009   int rc = SQLITE_OK;
15010   int nPg1 = 0;
15011   u8 *aPg1 = 0;
15012   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
15013   if( rc==SQLITE_OK && nPg1>=(56+4) ){
15014     pCsr->enc = get_uint32(&aPg1[56]);
15015   }
15016   sqlite3_free(aPg1);
15017   return rc;
15018 }
15019 
15020 
15021 /*
15022 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
15023 */
dbdataFilter(sqlite3_vtab_cursor * pCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)15024 static int dbdataFilter(
15025   sqlite3_vtab_cursor *pCursor,
15026   int idxNum, const char *idxStr,
15027   int argc, sqlite3_value **argv
15028 ){
15029   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15030   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
15031   int rc = SQLITE_OK;
15032   const char *zSchema = "main";
15033   (void)idxStr;
15034   (void)argc;
15035 
15036   dbdataResetCursor(pCsr);
15037   assert( pCsr->iPgno==1 );
15038   if( idxNum & 0x01 ){
15039     zSchema = (const char*)sqlite3_value_text(argv[0]);
15040     if( zSchema==0 ) zSchema = "";
15041   }
15042   if( idxNum & 0x02 ){
15043     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
15044     pCsr->bOnePage = 1;
15045   }else{
15046     rc = dbdataDbsize(pCsr, zSchema);
15047   }
15048 
15049   if( rc==SQLITE_OK ){
15050     int nFunc = 0;
15051     if( pTab->pStmt ){
15052       pCsr->pStmt = pTab->pStmt;
15053       pTab->pStmt = 0;
15054     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
15055       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
15056       if( zSql==0 ){
15057         rc = SQLITE_NOMEM;
15058       }else{
15059         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
15060         sqlite3_free(zSql);
15061       }
15062     }else{
15063       rc = sqlite3_prepare_v2(pTab->db,
15064           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
15065           &pCsr->pStmt, 0
15066       );
15067     }
15068   }
15069   if( rc==SQLITE_OK ){
15070     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
15071   }
15072 
15073   /* Try to determine the encoding of the db by inspecting the header
15074   ** field on page 1. */
15075   if( rc==SQLITE_OK ){
15076     rc = dbdataGetEncoding(pCsr);
15077   }
15078 
15079   if( rc!=SQLITE_OK ){
15080     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
15081   }
15082 
15083   if( rc==SQLITE_OK ){
15084     rc = dbdataNext(pCursor);
15085   }
15086   return rc;
15087 }
15088 
15089 /*
15090 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
15091 */
dbdataColumn(sqlite3_vtab_cursor * pCursor,sqlite3_context * ctx,int i)15092 static int dbdataColumn(
15093   sqlite3_vtab_cursor *pCursor,
15094   sqlite3_context *ctx,
15095   int i
15096 ){
15097   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15098   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
15099   if( pTab->bPtr ){
15100     switch( i ){
15101       case DBPTR_COLUMN_PGNO:
15102         sqlite3_result_int64(ctx, pCsr->iPgno);
15103         break;
15104       case DBPTR_COLUMN_CHILD: {
15105         int iOff = pCsr->iPgno==1 ? 100 : 0;
15106         if( pCsr->iCell<0 ){
15107           iOff += 8;
15108         }else{
15109           iOff += 12 + pCsr->iCell*2;
15110           if( iOff>pCsr->nPage ) return SQLITE_OK;
15111           iOff = get_uint16(&pCsr->aPage[iOff]);
15112         }
15113         if( iOff<=pCsr->nPage ){
15114           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
15115         }
15116         break;
15117       }
15118     }
15119   }else{
15120     switch( i ){
15121       case DBDATA_COLUMN_PGNO:
15122         sqlite3_result_int64(ctx, pCsr->iPgno);
15123         break;
15124       case DBDATA_COLUMN_CELL:
15125         sqlite3_result_int(ctx, pCsr->iCell);
15126         break;
15127       case DBDATA_COLUMN_FIELD:
15128         sqlite3_result_int(ctx, pCsr->iField);
15129         break;
15130       case DBDATA_COLUMN_VALUE: {
15131         if( pCsr->iField<0 ){
15132           sqlite3_result_int64(ctx, pCsr->iIntkey);
15133         }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
15134           sqlite3_int64 iType;
15135           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
15136           dbdataValue(
15137               ctx, pCsr->enc, iType, pCsr->pPtr,
15138               &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
15139           );
15140         }
15141         break;
15142       }
15143     }
15144   }
15145   return SQLITE_OK;
15146 }
15147 
15148 /*
15149 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
15150 */
dbdataRowid(sqlite3_vtab_cursor * pCursor,sqlite_int64 * pRowid)15151 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
15152   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15153   *pRowid = pCsr->iRowid;
15154   return SQLITE_OK;
15155 }
15156 
15157 
15158 /*
15159 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
15160 */
sqlite3DbdataRegister(sqlite3 * db)15161 static int sqlite3DbdataRegister(sqlite3 *db){
15162   static sqlite3_module dbdata_module = {
15163     0,                            /* iVersion */
15164     0,                            /* xCreate */
15165     dbdataConnect,                /* xConnect */
15166     dbdataBestIndex,              /* xBestIndex */
15167     dbdataDisconnect,             /* xDisconnect */
15168     0,                            /* xDestroy */
15169     dbdataOpen,                   /* xOpen - open a cursor */
15170     dbdataClose,                  /* xClose - close a cursor */
15171     dbdataFilter,                 /* xFilter - configure scan constraints */
15172     dbdataNext,                   /* xNext - advance a cursor */
15173     dbdataEof,                    /* xEof - check for end of scan */
15174     dbdataColumn,                 /* xColumn - read data */
15175     dbdataRowid,                  /* xRowid - read data */
15176     0,                            /* xUpdate */
15177     0,                            /* xBegin */
15178     0,                            /* xSync */
15179     0,                            /* xCommit */
15180     0,                            /* xRollback */
15181     0,                            /* xFindMethod */
15182     0,                            /* xRename */
15183     0,                            /* xSavepoint */
15184     0,                            /* xRelease */
15185     0,                            /* xRollbackTo */
15186     0,                            /* xShadowName */
15187     0                             /* xIntegrity */
15188   };
15189 
15190   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
15191   if( rc==SQLITE_OK ){
15192     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
15193   }
15194   return rc;
15195 }
15196 
sqlite3_dbdata_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)15197 int sqlite3_dbdata_init(
15198   sqlite3 *db,
15199   char **pzErrMsg,
15200   const sqlite3_api_routines *pApi
15201 ){
15202   (void)pzErrMsg;
15203   return sqlite3DbdataRegister(db);
15204 }
15205 
15206 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
15207 
15208 /************************* End ../ext/recover/dbdata.c ********************/
15209 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
15210 /*
15211 ** 2022-08-27
15212 **
15213 ** The author disclaims copyright to this source code.  In place of
15214 ** a legal notice, here is a blessing:
15215 **
15216 **    May you do good and not evil.
15217 **    May you find forgiveness for yourself and forgive others.
15218 **    May you share freely, never taking more than you give.
15219 **
15220 *************************************************************************
15221 **
15222 */
15223 
15224 
15225 /* #include "sqlite3recover.h" */
15226 #include <assert.h>
15227 #include <string.h>
15228 
15229 #ifndef SQLITE_OMIT_VIRTUALTABLE
15230 
15231 /*
15232 ** Declaration for public API function in file dbdata.c. This may be called
15233 ** with NULL as the final two arguments to register the sqlite_dbptr and
15234 ** sqlite_dbdata virtual tables with a database handle.
15235 */
15236 #ifdef _WIN32
15237 
15238 #endif
15239 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
15240 
15241 /* typedef unsigned int u32; */
15242 /* typedef unsigned char u8; */
15243 /* typedef sqlite3_int64 i64; */
15244 
15245 typedef struct RecoverTable RecoverTable;
15246 typedef struct RecoverColumn RecoverColumn;
15247 
15248 /*
15249 ** When recovering rows of data that can be associated with table
15250 ** definitions recovered from the sqlite_schema table, each table is
15251 ** represented by an instance of the following object.
15252 **
15253 ** iRoot:
15254 **   The root page in the original database. Not necessarily (and usually
15255 **   not) the same in the recovered database.
15256 **
15257 ** zTab:
15258 **   Name of the table.
15259 **
15260 ** nCol/aCol[]:
15261 **   aCol[] is an array of nCol columns. In the order in which they appear
15262 **   in the table.
15263 **
15264 ** bIntkey:
15265 **   Set to true for intkey tables, false for WITHOUT ROWID.
15266 **
15267 ** iRowidBind:
15268 **   Each column in the aCol[] array has associated with it the index of
15269 **   the bind parameter its values will be bound to in the INSERT statement
15270 **   used to construct the output database. If the table does has a rowid
15271 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
15272 **   index of the bind paramater to which the rowid value should be bound.
15273 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
15274 **   KEY column, then the rowid value should be bound to the index associated
15275 **   with the column.
15276 **
15277 ** pNext:
15278 **   All RecoverTable objects used by the recovery operation are allocated
15279 **   and populated as part of creating the recovered database schema in
15280 **   the output database, before any non-schema data are recovered. They
15281 **   are then stored in a singly-linked list linked by this variable beginning
15282 **   at sqlite3_recover.pTblList.
15283 */
15284 struct RecoverTable {
15285   u32 iRoot;                      /* Root page in original database */
15286   char *zTab;                     /* Name of table */
15287   int nCol;                       /* Number of columns in table */
15288   RecoverColumn *aCol;            /* Array of columns */
15289   int bIntkey;                    /* True for intkey, false for without rowid */
15290   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
15291   RecoverTable *pNext;
15292 };
15293 
15294 /*
15295 ** Each database column is represented by an instance of the following object
15296 ** stored in the RecoverTable.aCol[] array of the associated table.
15297 **
15298 ** iField:
15299 **   The index of the associated field within database records. Or -1 if
15300 **   there is no associated field (e.g. for virtual generated columns).
15301 **
15302 ** iBind:
15303 **   The bind index of the INSERT statement to bind this columns values
15304 **   to. Or 0 if there is no such index (iff (iField<0)).
15305 **
15306 ** bIPK:
15307 **   True if this is the INTEGER PRIMARY KEY column.
15308 **
15309 ** zCol:
15310 **   Name of column.
15311 **
15312 ** eHidden:
15313 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
15314 */
15315 struct RecoverColumn {
15316   int iField;                     /* Field in record on disk */
15317   int iBind;                      /* Binding to use in INSERT */
15318   int bIPK;                       /* True for IPK column */
15319   char *zCol;
15320   int eHidden;
15321 };
15322 
15323 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
15324 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
15325 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
15326 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
15327 
15328 /*
15329 ** Bitmap object used to track pages in the input database. Allocated
15330 ** and manipulated only by the following functions:
15331 **
15332 **     recoverBitmapAlloc()
15333 **     recoverBitmapFree()
15334 **     recoverBitmapSet()
15335 **     recoverBitmapQuery()
15336 **
15337 ** nPg:
15338 **   Largest page number that may be stored in the bitmap. The range
15339 **   of valid keys is 1 to nPg, inclusive.
15340 **
15341 ** aElem[]:
15342 **   Array large enough to contain a bit for each key. For key value
15343 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
15344 **   In other words, the following is true if bit iKey is set, or
15345 **   false if it is clear:
15346 **
15347 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
15348 */
15349 typedef struct RecoverBitmap RecoverBitmap;
15350 struct RecoverBitmap {
15351   i64 nPg;                        /* Size of bitmap */
15352   u32 aElem[1];                   /* Array of 32-bit bitmasks */
15353 };
15354 
15355 /*
15356 ** State variables (part of the sqlite3_recover structure) used while
15357 ** recovering data for tables identified in the recovered schema (state
15358 ** RECOVER_STATE_WRITING).
15359 */
15360 typedef struct RecoverStateW1 RecoverStateW1;
15361 struct RecoverStateW1 {
15362   sqlite3_stmt *pTbls;
15363   sqlite3_stmt *pSel;
15364   sqlite3_stmt *pInsert;
15365   int nInsert;
15366 
15367   RecoverTable *pTab;             /* Table currently being written */
15368   int nMax;                       /* Max column count in any schema table */
15369   sqlite3_value **apVal;          /* Array of nMax values */
15370   int nVal;                       /* Number of valid entries in apVal[] */
15371   int bHaveRowid;
15372   i64 iRowid;
15373   i64 iPrevPage;
15374   int iPrevCell;
15375 };
15376 
15377 /*
15378 ** State variables (part of the sqlite3_recover structure) used while
15379 ** recovering data destined for the lost and found table (states
15380 ** RECOVER_STATE_LOSTANDFOUND[123]).
15381 */
15382 typedef struct RecoverStateLAF RecoverStateLAF;
15383 struct RecoverStateLAF {
15384   RecoverBitmap *pUsed;
15385   i64 nPg;                        /* Size of db in pages */
15386   sqlite3_stmt *pAllAndParent;
15387   sqlite3_stmt *pMapInsert;
15388   sqlite3_stmt *pMaxField;
15389   sqlite3_stmt *pUsedPages;
15390   sqlite3_stmt *pFindRoot;
15391   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
15392   sqlite3_stmt *pAllPage;
15393   sqlite3_stmt *pPageData;
15394   sqlite3_value **apVal;
15395   int nMaxField;
15396 };
15397 
15398 /*
15399 ** Main recover handle structure.
15400 */
15401 struct sqlite3_recover {
15402   /* Copies of sqlite3_recover_init[_sql]() parameters */
15403   sqlite3 *dbIn;                  /* Input database */
15404   char *zDb;                      /* Name of input db ("main" etc.) */
15405   char *zUri;                     /* URI for output database */
15406   void *pSqlCtx;                  /* SQL callback context */
15407   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
15408 
15409   /* Values configured by sqlite3_recover_config() */
15410   char *zStateDb;                 /* State database to use (or NULL) */
15411   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
15412   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
15413   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
15414   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
15415 
15416   int pgsz;
15417   int detected_pgsz;
15418   int nReserve;
15419   u8 *pPage1Disk;
15420   u8 *pPage1Cache;
15421 
15422   /* Error code and error message */
15423   int errCode;                    /* For sqlite3_recover_errcode() */
15424   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
15425 
15426   int eState;
15427   int bCloseTransaction;
15428 
15429   /* Variables used with eState==RECOVER_STATE_WRITING */
15430   RecoverStateW1 w1;
15431 
15432   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
15433   RecoverStateLAF laf;
15434 
15435   /* Fields used within sqlite3_recover_run() */
15436   sqlite3 *dbOut;                 /* Output database */
15437   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
15438   RecoverTable *pTblList;         /* List of tables recovered from schema */
15439 };
15440 
15441 /*
15442 ** The various states in which an sqlite3_recover object may exist:
15443 **
15444 **   RECOVER_STATE_INIT:
15445 **    The object is initially created in this state. sqlite3_recover_step()
15446 **    has yet to be called. This is the only state in which it is permitted
15447 **    to call sqlite3_recover_config().
15448 **
15449 **   RECOVER_STATE_WRITING:
15450 **
15451 **   RECOVER_STATE_LOSTANDFOUND1:
15452 **    State to populate the bitmap of pages used by other tables or the
15453 **    database freelist.
15454 **
15455 **   RECOVER_STATE_LOSTANDFOUND2:
15456 **    Populate the recovery.map table - used to figure out a "root" page
15457 **    for each lost page from in the database from which records are
15458 **    extracted.
15459 **
15460 **   RECOVER_STATE_LOSTANDFOUND3:
15461 **    Populate the lost-and-found table itself.
15462 */
15463 #define RECOVER_STATE_INIT           0
15464 #define RECOVER_STATE_WRITING        1
15465 #define RECOVER_STATE_LOSTANDFOUND1  2
15466 #define RECOVER_STATE_LOSTANDFOUND2  3
15467 #define RECOVER_STATE_LOSTANDFOUND3  4
15468 #define RECOVER_STATE_SCHEMA2        5
15469 #define RECOVER_STATE_DONE           6
15470 
15471 
15472 /*
15473 ** Global variables used by this extension.
15474 */
15475 typedef struct RecoverGlobal RecoverGlobal;
15476 struct RecoverGlobal {
15477   const sqlite3_io_methods *pMethods;
15478   sqlite3_recover *p;
15479 };
15480 static RecoverGlobal recover_g;
15481 
15482 /*
15483 ** Use this static SQLite mutex to protect the globals during the
15484 ** first call to sqlite3_recover_step().
15485 */
15486 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
15487 
15488 
15489 /*
15490 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
15491 */
15492 #define RECOVER_ROWID_DEFAULT 1
15493 
15494 /*
15495 ** Mutex handling:
15496 **
15497 **    recoverEnterMutex()       -   Enter the recovery mutex
15498 **    recoverLeaveMutex()       -   Leave the recovery mutex
15499 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
15500 */
15501 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
15502 # define recoverEnterMutex()
15503 # define recoverLeaveMutex()
15504 #else
recoverEnterMutex(void)15505 static void recoverEnterMutex(void){
15506   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
15507 }
recoverLeaveMutex(void)15508 static void recoverLeaveMutex(void){
15509   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
15510 }
15511 #endif
15512 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
recoverAssertMutexHeld(void)15513 static void recoverAssertMutexHeld(void){
15514   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
15515 }
15516 #else
15517 # define recoverAssertMutexHeld()
15518 #endif
15519 
15520 
15521 /*
15522 ** Like strlen(). But handles NULL pointer arguments.
15523 */
recoverStrlen(const char * zStr)15524 static int recoverStrlen(const char *zStr){
15525   if( zStr==0 ) return 0;
15526   return (int)(strlen(zStr)&0x7fffffff);
15527 }
15528 
15529 /*
15530 ** This function is a no-op if the recover handle passed as the first
15531 ** argument already contains an error (if p->errCode!=SQLITE_OK).
15532 **
15533 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
15534 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
15535 ** if an OOM error occurs, NULL is returned and the handle error code
15536 ** (p->errCode) set to SQLITE_NOMEM.
15537 */
recoverMalloc(sqlite3_recover * p,i64 nByte)15538 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
15539   void *pRet = 0;
15540   assert( nByte>0 );
15541   if( p->errCode==SQLITE_OK ){
15542     pRet = sqlite3_malloc64(nByte);
15543     if( pRet ){
15544       memset(pRet, 0, nByte);
15545     }else{
15546       p->errCode = SQLITE_NOMEM;
15547     }
15548   }
15549   return pRet;
15550 }
15551 
15552 /*
15553 ** Set the error code and error message for the recover handle passed as
15554 ** the first argument. The error code is set to the value of parameter
15555 ** errCode.
15556 **
15557 ** Parameter zFmt must be a printf() style formatting string. The handle
15558 ** error message is set to the result of using any trailing arguments for
15559 ** parameter substitutions in the formatting string.
15560 **
15561 ** For example:
15562 **
15563 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
15564 */
recoverError(sqlite3_recover * p,int errCode,const char * zFmt,...)15565 static int recoverError(
15566   sqlite3_recover *p,
15567   int errCode,
15568   const char *zFmt, ...
15569 ){
15570   char *z = 0;
15571   va_list ap;
15572   va_start(ap, zFmt);
15573   if( zFmt ){
15574     z = sqlite3_vmprintf(zFmt, ap);
15575     va_end(ap);
15576   }
15577   sqlite3_free(p->zErrMsg);
15578   p->zErrMsg = z;
15579   p->errCode = errCode;
15580   return errCode;
15581 }
15582 
15583 
15584 /*
15585 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
15586 ** In this case it returns NULL.
15587 **
15588 ** Otherwise, an attempt is made to allocate and return a bitmap object
15589 ** large enough to store a bit for all page numbers between 1 and nPg,
15590 ** inclusive. The bitmap is initially zeroed.
15591 */
recoverBitmapAlloc(sqlite3_recover * p,i64 nPg)15592 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
15593   int nElem = (nPg+1+31) / 32;
15594   int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
15595   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
15596 
15597   if( pRet ){
15598     pRet->nPg = nPg;
15599   }
15600   return pRet;
15601 }
15602 
15603 /*
15604 ** Free a bitmap object allocated by recoverBitmapAlloc().
15605 */
recoverBitmapFree(RecoverBitmap * pMap)15606 static void recoverBitmapFree(RecoverBitmap *pMap){
15607   sqlite3_free(pMap);
15608 }
15609 
15610 /*
15611 ** Set the bit associated with page iPg in bitvec pMap.
15612 */
recoverBitmapSet(RecoverBitmap * pMap,i64 iPg)15613 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
15614   if( iPg<=pMap->nPg ){
15615     int iElem = (iPg / 32);
15616     int iBit = (iPg % 32);
15617     pMap->aElem[iElem] |= (((u32)1) << iBit);
15618   }
15619 }
15620 
15621 /*
15622 ** Query bitmap object pMap for the state of the bit associated with page
15623 ** iPg. Return 1 if it is set, or 0 otherwise.
15624 */
recoverBitmapQuery(RecoverBitmap * pMap,i64 iPg)15625 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
15626   int ret = 1;
15627   if( iPg<=pMap->nPg && iPg>0 ){
15628     int iElem = (iPg / 32);
15629     int iBit = (iPg % 32);
15630     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
15631   }
15632   return ret;
15633 }
15634 
15635 /*
15636 ** Set the recover handle error to the error code and message returned by
15637 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
15638 ** handle db.
15639 */
recoverDbError(sqlite3_recover * p,sqlite3 * db)15640 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
15641   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
15642 }
15643 
15644 /*
15645 ** This function is a no-op if recover handle p already contains an error
15646 ** (if p->errCode!=SQLITE_OK).
15647 **
15648 ** Otherwise, it attempts to prepare the SQL statement in zSql against
15649 ** database handle db. If successful, the statement handle is returned.
15650 ** Or, if an error occurs, NULL is returned and an error left in the
15651 ** recover handle.
15652 */
recoverPrepare(sqlite3_recover * p,sqlite3 * db,const char * zSql)15653 static sqlite3_stmt *recoverPrepare(
15654   sqlite3_recover *p,
15655   sqlite3 *db,
15656   const char *zSql
15657 ){
15658   sqlite3_stmt *pStmt = 0;
15659   if( p->errCode==SQLITE_OK ){
15660     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
15661       recoverDbError(p, db);
15662     }
15663   }
15664   return pStmt;
15665 }
15666 
15667 /*
15668 ** This function is a no-op if recover handle p already contains an error
15669 ** (if p->errCode!=SQLITE_OK).
15670 **
15671 ** Otherwise, argument zFmt is used as a printf() style format string,
15672 ** along with any trailing arguments, to create an SQL statement. This
15673 ** SQL statement is prepared against database handle db and, if successful,
15674 ** the statment handle returned. Or, if an error occurs - either during
15675 ** the printf() formatting or when preparing the resulting SQL - an
15676 ** error code and message are left in the recover handle.
15677 */
recoverPreparePrintf(sqlite3_recover * p,sqlite3 * db,const char * zFmt,...)15678 static sqlite3_stmt *recoverPreparePrintf(
15679   sqlite3_recover *p,
15680   sqlite3 *db,
15681   const char *zFmt, ...
15682 ){
15683   sqlite3_stmt *pStmt = 0;
15684   if( p->errCode==SQLITE_OK ){
15685     va_list ap;
15686     char *z;
15687     va_start(ap, zFmt);
15688     z = sqlite3_vmprintf(zFmt, ap);
15689     va_end(ap);
15690     if( z==0 ){
15691       p->errCode = SQLITE_NOMEM;
15692     }else{
15693       pStmt = recoverPrepare(p, db, z);
15694       sqlite3_free(z);
15695     }
15696   }
15697   return pStmt;
15698 }
15699 
15700 /*
15701 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
15702 ** indicates that an error occurred, and there is not already an error
15703 ** in the recover handle passed as the first argument, set the error
15704 ** code and error message appropriately.
15705 **
15706 ** This function returns a copy of the statement handle pointer passed
15707 ** as the second argument.
15708 */
recoverReset(sqlite3_recover * p,sqlite3_stmt * pStmt)15709 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
15710   int rc = sqlite3_reset(pStmt);
15711   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
15712     recoverDbError(p, sqlite3_db_handle(pStmt));
15713   }
15714   return pStmt;
15715 }
15716 
15717 /*
15718 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
15719 ** indicates that an error occurred, and there is not already an error
15720 ** in the recover handle passed as the first argument, set the error
15721 ** code and error message appropriately.
15722 */
recoverFinalize(sqlite3_recover * p,sqlite3_stmt * pStmt)15723 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
15724   sqlite3 *db = sqlite3_db_handle(pStmt);
15725   int rc = sqlite3_finalize(pStmt);
15726   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
15727     recoverDbError(p, db);
15728   }
15729 }
15730 
15731 /*
15732 ** This function is a no-op if recover handle p already contains an error
15733 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
15734 ** case.
15735 **
15736 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
15737 ** Or, if an error occurs, leave an error code and message in the recover
15738 ** handle and return a copy of the error code.
15739 */
recoverExec(sqlite3_recover * p,sqlite3 * db,const char * zSql)15740 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
15741   if( p->errCode==SQLITE_OK ){
15742     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
15743     if( rc ){
15744       recoverDbError(p, db);
15745     }
15746   }
15747   return p->errCode;
15748 }
15749 
15750 /*
15751 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
15752 ** error in the recover handle passed as the first argument if an error
15753 ** (e.g. an OOM) occurs.
15754 */
recoverBindValue(sqlite3_recover * p,sqlite3_stmt * pStmt,int iBind,sqlite3_value * pVal)15755 static void recoverBindValue(
15756   sqlite3_recover *p,
15757   sqlite3_stmt *pStmt,
15758   int iBind,
15759   sqlite3_value *pVal
15760 ){
15761   if( p->errCode==SQLITE_OK ){
15762     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
15763     if( rc ) recoverError(p, rc, 0);
15764   }
15765 }
15766 
15767 /*
15768 ** This function is a no-op if recover handle p already contains an error
15769 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
15770 **
15771 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
15772 ** formatting string and the result of using the trailing arguments for
15773 ** parameter substitution with it written into a buffer obtained from
15774 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
15775 ** It is the responsibility of the caller to eventually free the buffer
15776 ** using sqlite3_free().
15777 **
15778 ** Or, if an error occurs, an error code and message is left in the recover
15779 ** handle and NULL returned.
15780 */
recoverMPrintf(sqlite3_recover * p,const char * zFmt,...)15781 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
15782   va_list ap;
15783   char *z;
15784   va_start(ap, zFmt);
15785   z = sqlite3_vmprintf(zFmt, ap);
15786   va_end(ap);
15787   if( p->errCode==SQLITE_OK ){
15788     if( z==0 ) p->errCode = SQLITE_NOMEM;
15789   }else{
15790     sqlite3_free(z);
15791     z = 0;
15792   }
15793   return z;
15794 }
15795 
15796 /*
15797 ** This function is a no-op if recover handle p already contains an error
15798 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
15799 **
15800 ** Otherwise, execute "PRAGMA page_count" against the input database. If
15801 ** successful, return the integer result. Or, if an error occurs, leave an
15802 ** error code and error message in the sqlite3_recover handle and return
15803 ** zero.
15804 */
recoverPageCount(sqlite3_recover * p)15805 static i64 recoverPageCount(sqlite3_recover *p){
15806   i64 nPg = 0;
15807   if( p->errCode==SQLITE_OK ){
15808     sqlite3_stmt *pStmt = 0;
15809     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
15810     if( pStmt ){
15811       sqlite3_step(pStmt);
15812       nPg = sqlite3_column_int64(pStmt, 0);
15813     }
15814     recoverFinalize(p, pStmt);
15815   }
15816   return nPg;
15817 }
15818 
15819 /*
15820 ** Implementation of SQL scalar function "read_i32". The first argument to
15821 ** this function must be a blob. The second a non-negative integer. This
15822 ** function reads and returns a 32-bit big-endian integer from byte
15823 ** offset (4*<arg2>) of the blob.
15824 **
15825 **     SELECT read_i32(<blob>, <idx>)
15826 */
recoverReadI32(sqlite3_context * context,int argc,sqlite3_value ** argv)15827 static void recoverReadI32(
15828   sqlite3_context *context,
15829   int argc,
15830   sqlite3_value **argv
15831 ){
15832   const unsigned char *pBlob;
15833   int nBlob;
15834   int iInt;
15835 
15836   assert( argc==2 );
15837   nBlob = sqlite3_value_bytes(argv[0]);
15838   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
15839   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
15840 
15841   if( (iInt+1)*4<=nBlob ){
15842     const unsigned char *a = &pBlob[iInt*4];
15843     i64 iVal = ((i64)a[0]<<24)
15844              + ((i64)a[1]<<16)
15845              + ((i64)a[2]<< 8)
15846              + ((i64)a[3]<< 0);
15847     sqlite3_result_int64(context, iVal);
15848   }
15849 }
15850 
15851 /*
15852 ** Implementation of SQL scalar function "page_is_used". This function
15853 ** is used as part of the procedure for locating orphan rows for the
15854 ** lost-and-found table, and it depends on those routines having populated
15855 ** the sqlite3_recover.laf.pUsed variable.
15856 **
15857 ** The only argument to this function is a page-number. It returns true
15858 ** if the page has already been used somehow during data recovery, or false
15859 ** otherwise.
15860 **
15861 **     SELECT page_is_used(<pgno>);
15862 */
recoverPageIsUsed(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)15863 static void recoverPageIsUsed(
15864   sqlite3_context *pCtx,
15865   int nArg,
15866   sqlite3_value **apArg
15867 ){
15868   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15869   i64 pgno = sqlite3_value_int64(apArg[0]);
15870   assert( nArg==1 );
15871   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
15872 }
15873 
15874 /*
15875 ** The implementation of a user-defined SQL function invoked by the
15876 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
15877 ** of the database being recovered.
15878 **
15879 ** This function always takes a single integer argument. If the argument
15880 ** is zero, then the value returned is the number of pages in the db being
15881 ** recovered. If the argument is greater than zero, it is a page number.
15882 ** The value returned in this case is an SQL blob containing the data for
15883 ** the identified page of the db being recovered. e.g.
15884 **
15885 **     SELECT getpage(0);       -- return number of pages in db
15886 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
15887 */
recoverGetPage(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)15888 static void recoverGetPage(
15889   sqlite3_context *pCtx,
15890   int nArg,
15891   sqlite3_value **apArg
15892 ){
15893   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15894   i64 pgno = sqlite3_value_int64(apArg[0]);
15895   sqlite3_stmt *pStmt = 0;
15896 
15897   assert( nArg==1 );
15898   if( pgno==0 ){
15899     i64 nPg = recoverPageCount(p);
15900     sqlite3_result_int64(pCtx, nPg);
15901     return;
15902   }else{
15903     if( p->pGetPage==0 ){
15904       pStmt = p->pGetPage = recoverPreparePrintf(
15905           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
15906       );
15907     }else if( p->errCode==SQLITE_OK ){
15908       pStmt = p->pGetPage;
15909     }
15910 
15911     if( pStmt ){
15912       sqlite3_bind_int64(pStmt, 1, pgno);
15913       if( SQLITE_ROW==sqlite3_step(pStmt) ){
15914         const u8 *aPg;
15915         int nPg;
15916         assert( p->errCode==SQLITE_OK );
15917         aPg = sqlite3_column_blob(pStmt, 0);
15918         nPg = sqlite3_column_bytes(pStmt, 0);
15919         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
15920           aPg = p->pPage1Disk;
15921         }
15922         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
15923       }
15924       recoverReset(p, pStmt);
15925     }
15926   }
15927 
15928   if( p->errCode ){
15929     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
15930     sqlite3_result_error_code(pCtx, p->errCode);
15931   }
15932 }
15933 
15934 /*
15935 ** Find a string that is not found anywhere in z[].  Return a pointer
15936 ** to that string.
15937 **
15938 ** Try to use zA and zB first.  If both of those are already found in z[]
15939 ** then make up some string and store it in the buffer zBuf.
15940 */
recoverUnusedString(const char * z,const char * zA,const char * zB,char * zBuf)15941 static const char *recoverUnusedString(
15942   const char *z,                    /* Result must not appear anywhere in z */
15943   const char *zA, const char *zB,   /* Try these first */
15944   char *zBuf                        /* Space to store a generated string */
15945 ){
15946   unsigned i = 0;
15947   if( strstr(z, zA)==0 ) return zA;
15948   if( strstr(z, zB)==0 ) return zB;
15949   do{
15950     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
15951   }while( strstr(z,zBuf)!=0 );
15952   return zBuf;
15953 }
15954 
15955 /*
15956 ** Implementation of scalar SQL function "escape_crnl".  The argument passed to
15957 ** this function is the output of built-in function quote(). If the first
15958 ** character of the input is "'", indicating that the value passed to quote()
15959 ** was a text value, then this function searches the input for "\n" and "\r"
15960 ** characters and adds a wrapper similar to the following:
15961 **
15962 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
15963 **
15964 ** Or, if the first character of the input is not "'", then a copy of the input
15965 ** is returned.
15966 */
recoverEscapeCrnl(sqlite3_context * context,int argc,sqlite3_value ** argv)15967 static void recoverEscapeCrnl(
15968   sqlite3_context *context,
15969   int argc,
15970   sqlite3_value **argv
15971 ){
15972   const char *zText = (const char*)sqlite3_value_text(argv[0]);
15973   (void)argc;
15974   if( zText && zText[0]=='\'' ){
15975     int nText = sqlite3_value_bytes(argv[0]);
15976     int i;
15977     char zBuf1[20];
15978     char zBuf2[20];
15979     const char *zNL = 0;
15980     const char *zCR = 0;
15981     int nCR = 0;
15982     int nNL = 0;
15983 
15984     for(i=0; zText[i]; i++){
15985       if( zNL==0 && zText[i]=='\n' ){
15986         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
15987         nNL = (int)strlen(zNL);
15988       }
15989       if( zCR==0 && zText[i]=='\r' ){
15990         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
15991         nCR = (int)strlen(zCR);
15992       }
15993     }
15994 
15995     if( zNL || zCR ){
15996       int iOut = 0;
15997       i64 nMax = (nNL > nCR) ? nNL : nCR;
15998       i64 nAlloc = nMax * nText + (nMax+64)*2;
15999       char *zOut = (char*)sqlite3_malloc64(nAlloc);
16000       if( zOut==0 ){
16001         sqlite3_result_error_nomem(context);
16002         return;
16003       }
16004 
16005       if( zNL && zCR ){
16006         memcpy(&zOut[iOut], "replace(replace(", 16);
16007         iOut += 16;
16008       }else{
16009         memcpy(&zOut[iOut], "replace(", 8);
16010         iOut += 8;
16011       }
16012       for(i=0; zText[i]; i++){
16013         if( zText[i]=='\n' ){
16014           memcpy(&zOut[iOut], zNL, nNL);
16015           iOut += nNL;
16016         }else if( zText[i]=='\r' ){
16017           memcpy(&zOut[iOut], zCR, nCR);
16018           iOut += nCR;
16019         }else{
16020           zOut[iOut] = zText[i];
16021           iOut++;
16022         }
16023       }
16024 
16025       if( zNL ){
16026         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16027         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
16028         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
16029       }
16030       if( zCR ){
16031         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16032         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
16033         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
16034       }
16035 
16036       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
16037       sqlite3_free(zOut);
16038       return;
16039     }
16040   }
16041 
16042   sqlite3_result_value(context, argv[0]);
16043 }
16044 
16045 /*
16046 ** This function is a no-op if recover handle p already contains an error
16047 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16048 ** this case.
16049 **
16050 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
16051 ** parts of the database schema that can be extracted from the input database.
16052 **
16053 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
16054 ** and error message are left in the recover handle and a copy of the
16055 ** error code returned. It is not considered an error if part of all of
16056 ** the database schema cannot be recovered due to corruption.
16057 */
recoverCacheSchema(sqlite3_recover * p)16058 static int recoverCacheSchema(sqlite3_recover *p){
16059   return recoverExec(p, p->dbOut,
16060     "WITH RECURSIVE pages(p) AS ("
16061     "  SELECT 1"
16062     "    UNION"
16063     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
16064     ")"
16065     "INSERT INTO recovery.schema SELECT"
16066     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
16067     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
16068     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
16069     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
16070     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
16071     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
16072     "  SELECT p FROM pages"
16073     ") GROUP BY pgno, cell"
16074   );
16075 }
16076 
16077 /*
16078 ** If this recover handle is not in SQL callback mode (i.e. was not created
16079 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
16080 ** this function is a no-op. Otherwise, issue a callback with SQL statement
16081 ** zSql as the parameter.
16082 **
16083 ** If the callback returns non-zero, set the recover handle error code to
16084 ** the value returned (so that the caller will abandon processing).
16085 */
recoverSqlCallback(sqlite3_recover * p,const char * zSql)16086 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
16087   if( p->errCode==SQLITE_OK && p->xSql ){
16088     int res = p->xSql(p->pSqlCtx, zSql);
16089     if( res ){
16090       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
16091     }
16092   }
16093 }
16094 
16095 /*
16096 ** Transfer the following settings from the input database to the output
16097 ** database:
16098 **
16099 **   + page-size,
16100 **   + auto-vacuum settings,
16101 **   + database encoding,
16102 **   + user-version (PRAGMA user_version), and
16103 **   + application-id (PRAGMA application_id), and
16104 */
recoverTransferSettings(sqlite3_recover * p)16105 static void recoverTransferSettings(sqlite3_recover *p){
16106   const char *aPragma[] = {
16107     "encoding",
16108     "page_size",
16109     "auto_vacuum",
16110     "user_version",
16111     "application_id"
16112   };
16113   int ii;
16114 
16115   /* Truncate the output database to 0 pages in size. This is done by
16116   ** opening a new, empty, temp db, then using the backup API to clobber
16117   ** any existing output db with a copy of it. */
16118   if( p->errCode==SQLITE_OK ){
16119     sqlite3 *db2 = 0;
16120     int rc = sqlite3_open("", &db2);
16121     if( rc!=SQLITE_OK ){
16122       recoverDbError(p, db2);
16123       return;
16124     }
16125 
16126     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
16127       const char *zPrag = aPragma[ii];
16128       sqlite3_stmt *p1 = 0;
16129       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
16130       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
16131         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
16132         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
16133         recoverSqlCallback(p, z2);
16134         recoverExec(p, db2, z2);
16135         sqlite3_free(z2);
16136         if( zArg==0 ){
16137           recoverError(p, SQLITE_NOMEM, 0);
16138         }
16139       }
16140       recoverFinalize(p, p1);
16141     }
16142     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
16143 
16144     if( p->errCode==SQLITE_OK ){
16145       sqlite3 *db = p->dbOut;
16146       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
16147       if( pBackup ){
16148         sqlite3_backup_step(pBackup, -1);
16149         p->errCode = sqlite3_backup_finish(pBackup);
16150       }else{
16151         recoverDbError(p, db);
16152       }
16153     }
16154 
16155     sqlite3_close(db2);
16156   }
16157 }
16158 
16159 /*
16160 ** This function is a no-op if recover handle p already contains an error
16161 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16162 ** this case.
16163 **
16164 ** Otherwise, an attempt is made to open the output database, attach
16165 ** and create the schema of the temporary database used to store
16166 ** intermediate data, and to register all required user functions and
16167 ** virtual table modules with the output handle.
16168 **
16169 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
16170 ** and error message are left in the recover handle and a copy of the
16171 ** error code returned.
16172 */
recoverOpenOutput(sqlite3_recover * p)16173 static int recoverOpenOutput(sqlite3_recover *p){
16174   struct Func {
16175     const char *zName;
16176     int nArg;
16177     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
16178   } aFunc[] = {
16179     { "getpage", 1, recoverGetPage },
16180     { "page_is_used", 1, recoverPageIsUsed },
16181     { "read_i32", 2, recoverReadI32 },
16182     { "escape_crnl", 1, recoverEscapeCrnl },
16183   };
16184 
16185   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
16186   sqlite3 *db = 0;                /* New database handle */
16187   int ii;                         /* For iterating through aFunc[] */
16188 
16189   assert( p->dbOut==0 );
16190 
16191   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
16192     recoverDbError(p, db);
16193   }
16194 
16195   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
16196   ** These two are registered with the output database handle - this
16197   ** module depends on the input handle supporting the sqlite_dbpage
16198   ** virtual table only.  */
16199   if( p->errCode==SQLITE_OK ){
16200     p->errCode = sqlite3_dbdata_init(db, 0, 0);
16201   }
16202 
16203   /* Register the custom user-functions with the output handle. */
16204   for(ii=0;
16205       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
16206       ii++){
16207     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
16208         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
16209     );
16210   }
16211 
16212   p->dbOut = db;
16213   return p->errCode;
16214 }
16215 
16216 /*
16217 ** Attach the auxiliary database 'recovery' to the output database handle.
16218 ** This temporary database is used during the recovery process and then
16219 ** discarded.
16220 */
recoverOpenRecovery(sqlite3_recover * p)16221 static void recoverOpenRecovery(sqlite3_recover *p){
16222   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
16223   recoverExec(p, p->dbOut, zSql);
16224   recoverExec(p, p->dbOut,
16225       "PRAGMA writable_schema = 1;"
16226       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
16227       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
16228   );
16229   sqlite3_free(zSql);
16230 }
16231 
16232 
16233 /*
16234 ** This function is a no-op if recover handle p already contains an error
16235 ** (if p->errCode!=SQLITE_OK).
16236 **
16237 ** Otherwise, argument zName must be the name of a table that has just been
16238 ** created in the output database. This function queries the output db
16239 ** for the schema of said table, and creates a RecoverTable object to
16240 ** store the schema in memory. The new RecoverTable object is linked into
16241 ** the list at sqlite3_recover.pTblList.
16242 **
16243 ** Parameter iRoot must be the root page of table zName in the INPUT
16244 ** database.
16245 */
recoverAddTable(sqlite3_recover * p,const char * zName,i64 iRoot)16246 static void recoverAddTable(
16247   sqlite3_recover *p,
16248   const char *zName,              /* Name of table created in output db */
16249   i64 iRoot                       /* Root page of same table in INPUT db */
16250 ){
16251   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
16252       "PRAGMA table_xinfo(%Q)", zName
16253   );
16254 
16255   if( pStmt ){
16256     int iPk = -1;
16257     int iBind = 1;
16258     RecoverTable *pNew = 0;
16259     int nCol = 0;
16260     int nName = recoverStrlen(zName);
16261     int nByte = 0;
16262     while( sqlite3_step(pStmt)==SQLITE_ROW ){
16263       nCol++;
16264       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
16265     }
16266     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
16267     recoverReset(p, pStmt);
16268 
16269     pNew = recoverMalloc(p, nByte);
16270     if( pNew ){
16271       int i = 0;
16272       int iField = 0;
16273       char *csr = 0;
16274       pNew->aCol = (RecoverColumn*)&pNew[1];
16275       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
16276       pNew->nCol = nCol;
16277       pNew->iRoot = iRoot;
16278       memcpy(csr, zName, nName);
16279       csr += nName+1;
16280 
16281       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
16282         int iPKF = sqlite3_column_int(pStmt, 5);
16283         int n = sqlite3_column_bytes(pStmt, 1);
16284         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
16285         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
16286         int eHidden = sqlite3_column_int(pStmt, 6);
16287 
16288         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
16289         if( iPKF>1 ) iPk = -2;
16290         pNew->aCol[i].zCol = csr;
16291         pNew->aCol[i].eHidden = eHidden;
16292         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
16293           pNew->aCol[i].iField = -1;
16294         }else{
16295           pNew->aCol[i].iField = iField++;
16296         }
16297         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
16298          && eHidden!=RECOVER_EHIDDEN_STORED
16299         ){
16300           pNew->aCol[i].iBind = iBind++;
16301         }
16302         memcpy(csr, z, n);
16303         csr += (n+1);
16304       }
16305 
16306       pNew->pNext = p->pTblList;
16307       p->pTblList = pNew;
16308       pNew->bIntkey = 1;
16309     }
16310 
16311     recoverFinalize(p, pStmt);
16312 
16313     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
16314     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
16315       int iField = sqlite3_column_int(pStmt, 0);
16316       int iCol = sqlite3_column_int(pStmt, 1);
16317 
16318       assert( iCol<pNew->nCol );
16319       pNew->aCol[iCol].iField = iField;
16320 
16321       pNew->bIntkey = 0;
16322       iPk = -2;
16323     }
16324     recoverFinalize(p, pStmt);
16325 
16326     if( p->errCode==SQLITE_OK ){
16327       if( iPk>=0 ){
16328         pNew->aCol[iPk].bIPK = 1;
16329       }else if( pNew->bIntkey ){
16330         pNew->iRowidBind = iBind++;
16331       }
16332     }
16333   }
16334 }
16335 
16336 /*
16337 ** This function is called after recoverCacheSchema() has cached those parts
16338 ** of the input database schema that could be recovered in temporary table
16339 ** "recovery.schema". This function creates in the output database copies
16340 ** of all parts of that schema that must be created before the tables can
16341 ** be populated. Specifically, this means:
16342 **
16343 **     * all tables that are not VIRTUAL, and
16344 **     * UNIQUE indexes.
16345 **
16346 ** If the recovery handle uses SQL callbacks, then callbacks containing
16347 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
16348 **
16349 ** Additionally, records are added to the sqlite_schema table of the
16350 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
16351 ** records are written directly to sqlite_schema, not actually executed.
16352 ** If the handle is in SQL callback mode, then callbacks are invoked
16353 ** with equivalent SQL statements.
16354 */
recoverWriteSchema1(sqlite3_recover * p)16355 static int recoverWriteSchema1(sqlite3_recover *p){
16356   sqlite3_stmt *pSelect = 0;
16357   sqlite3_stmt *pTblname = 0;
16358 
16359   pSelect = recoverPrepare(p, p->dbOut,
16360       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
16361       "  SELECT rootpage, name, sql, "
16362       "    type='table', "
16363       "    sql LIKE 'create virtual%',"
16364       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
16365       "  FROM recovery.schema"
16366       ")"
16367       "SELECT rootpage, tbl, isVirtual, name, sql"
16368       " FROM dbschema "
16369       "  WHERE tbl OR isIndex"
16370       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
16371   );
16372 
16373   pTblname = recoverPrepare(p, p->dbOut,
16374       "SELECT name FROM sqlite_schema "
16375       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
16376   );
16377 
16378   if( pSelect ){
16379     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
16380     while( sqlite3_step(pSelect)==SQLITE_ROW ){
16381       i64 iRoot = sqlite3_column_int64(pSelect, 0);
16382       int bTable = sqlite3_column_int(pSelect, 1);
16383       int bVirtual = sqlite3_column_int(pSelect, 2);
16384       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
16385       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
16386       char *zFree = 0;
16387       int rc = SQLITE_OK;
16388 
16389       if( bVirtual ){
16390         zSql = (const char*)(zFree = recoverMPrintf(p,
16391             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
16392             zName, zName, zSql
16393         ));
16394       }
16395       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
16396       if( rc==SQLITE_OK ){
16397         recoverSqlCallback(p, zSql);
16398         if( bTable && !bVirtual ){
16399           if( SQLITE_ROW==sqlite3_step(pTblname) ){
16400             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
16401             recoverAddTable(p, zTbl, iRoot);
16402           }
16403           recoverReset(p, pTblname);
16404         }
16405       }else if( rc!=SQLITE_ERROR ){
16406         recoverDbError(p, p->dbOut);
16407       }
16408       sqlite3_free(zFree);
16409     }
16410   }
16411   recoverFinalize(p, pSelect);
16412   recoverFinalize(p, pTblname);
16413 
16414   return p->errCode;
16415 }
16416 
16417 /*
16418 ** This function is called after the output database has been populated. It
16419 ** adds all recovered schema elements that were not created in the output
16420 ** database by recoverWriteSchema1() - everything except for tables and
16421 ** UNIQUE indexes. Specifically:
16422 **
16423 **     * views,
16424 **     * triggers,
16425 **     * non-UNIQUE indexes.
16426 **
16427 ** If the recover handle is in SQL callback mode, then equivalent callbacks
16428 ** are issued to create the schema elements.
16429 */
recoverWriteSchema2(sqlite3_recover * p)16430 static int recoverWriteSchema2(sqlite3_recover *p){
16431   sqlite3_stmt *pSelect = 0;
16432 
16433   pSelect = recoverPrepare(p, p->dbOut,
16434       p->bSlowIndexes ?
16435       "SELECT rootpage, sql FROM recovery.schema "
16436       "  WHERE type!='table' AND type!='index'"
16437       :
16438       "SELECT rootpage, sql FROM recovery.schema "
16439       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
16440   );
16441 
16442   if( pSelect ){
16443     while( sqlite3_step(pSelect)==SQLITE_ROW ){
16444       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
16445       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
16446       if( rc==SQLITE_OK ){
16447         recoverSqlCallback(p, zSql);
16448       }else if( rc!=SQLITE_ERROR ){
16449         recoverDbError(p, p->dbOut);
16450       }
16451     }
16452   }
16453   recoverFinalize(p, pSelect);
16454 
16455   return p->errCode;
16456 }
16457 
16458 /*
16459 ** This function is a no-op if recover handle p already contains an error
16460 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
16461 **
16462 ** Otherwise, if the recover handle is configured to create an output
16463 ** database (was created by sqlite3_recover_init()), then this function
16464 ** prepares and returns an SQL statement to INSERT a new record into table
16465 ** pTab, assuming the first nField fields of a record extracted from disk
16466 ** are valid.
16467 **
16468 ** For example, if table pTab is:
16469 **
16470 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
16471 **
16472 ** And nField is 4, then the SQL statement prepared and returned is:
16473 **
16474 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
16475 **
16476 ** In this case even though 4 values were extracted from the input db,
16477 ** only 3 are written to the output, as the generated STORED column
16478 ** cannot be written.
16479 **
16480 ** If the recover handle is in SQL callback mode, then the SQL statement
16481 ** prepared is such that evaluating it returns a single row containing
16482 ** a single text value - itself an SQL statement similar to the above,
16483 ** except with SQL literals in place of the variables. For example:
16484 **
16485 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
16486 **          || quote(?1) || ', '
16487 **          || quote(?2) || ', '
16488 **          || quote(?3) || ')';
16489 **
16490 ** In either case, it is the responsibility of the caller to eventually
16491 ** free the statement handle using sqlite3_finalize().
16492 */
recoverInsertStmt(sqlite3_recover * p,RecoverTable * pTab,int nField)16493 static sqlite3_stmt *recoverInsertStmt(
16494   sqlite3_recover *p,
16495   RecoverTable *pTab,
16496   int nField
16497 ){
16498   sqlite3_stmt *pRet = 0;
16499   const char *zSep = "";
16500   const char *zSqlSep = "";
16501   char *zSql = 0;
16502   char *zFinal = 0;
16503   char *zBind = 0;
16504   int ii;
16505   int bSql = p->xSql ? 1 : 0;
16506 
16507   if( nField<=0 ) return 0;
16508 
16509   assert( nField<=pTab->nCol );
16510 
16511   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
16512 
16513   if( pTab->iRowidBind ){
16514     assert( pTab->bIntkey );
16515     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
16516     if( bSql ){
16517       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
16518     }else{
16519       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
16520     }
16521     zSqlSep = "||', '||";
16522     zSep = ", ";
16523   }
16524 
16525   for(ii=0; ii<nField; ii++){
16526     int eHidden = pTab->aCol[ii].eHidden;
16527     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
16528      && eHidden!=RECOVER_EHIDDEN_STORED
16529     ){
16530       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
16531       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
16532 
16533       if( bSql ){
16534         zBind = recoverMPrintf(p,
16535             "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
16536         );
16537         zSqlSep = "||', '||";
16538       }else{
16539         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
16540       }
16541       zSep = ", ";
16542     }
16543   }
16544 
16545   if( bSql ){
16546     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
16547         zSql, zBind
16548     );
16549   }else{
16550     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
16551   }
16552 
16553   pRet = recoverPrepare(p, p->dbOut, zFinal);
16554   sqlite3_free(zSql);
16555   sqlite3_free(zBind);
16556   sqlite3_free(zFinal);
16557 
16558   return pRet;
16559 }
16560 
16561 
16562 /*
16563 ** Search the list of RecoverTable objects at p->pTblList for one that
16564 ** has root page iRoot in the input database. If such an object is found,
16565 ** return a pointer to it. Otherwise, return NULL.
16566 */
recoverFindTable(sqlite3_recover * p,u32 iRoot)16567 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
16568   RecoverTable *pRet = 0;
16569   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
16570   return pRet;
16571 }
16572 
16573 /*
16574 ** This function attempts to create a lost and found table within the
16575 ** output db. If successful, it returns a pointer to a buffer containing
16576 ** the name of the new table. It is the responsibility of the caller to
16577 ** eventually free this buffer using sqlite3_free().
16578 **
16579 ** If an error occurs, NULL is returned and an error code and error
16580 ** message left in the recover handle.
16581 */
recoverLostAndFoundCreate(sqlite3_recover * p,int nField)16582 static char *recoverLostAndFoundCreate(
16583   sqlite3_recover *p,             /* Recover object */
16584   int nField                      /* Number of column fields in new table */
16585 ){
16586   char *zTbl = 0;
16587   sqlite3_stmt *pProbe = 0;
16588   int ii = 0;
16589 
16590   pProbe = recoverPrepare(p, p->dbOut,
16591     "SELECT 1 FROM sqlite_schema WHERE name=?"
16592   );
16593   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
16594     int bFail = 0;
16595     if( ii<0 ){
16596       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
16597     }else{
16598       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
16599     }
16600 
16601     if( p->errCode==SQLITE_OK ){
16602       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
16603       if( SQLITE_ROW==sqlite3_step(pProbe) ){
16604         bFail = 1;
16605       }
16606       recoverReset(p, pProbe);
16607     }
16608 
16609     if( bFail ){
16610       sqlite3_clear_bindings(pProbe);
16611       sqlite3_free(zTbl);
16612       zTbl = 0;
16613     }
16614   }
16615   recoverFinalize(p, pProbe);
16616 
16617   if( zTbl ){
16618     const char *zSep = 0;
16619     char *zField = 0;
16620     char *zSql = 0;
16621 
16622     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
16623     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
16624       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
16625       zSep = ", ";
16626     }
16627 
16628     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
16629     sqlite3_free(zField);
16630 
16631     recoverExec(p, p->dbOut, zSql);
16632     recoverSqlCallback(p, zSql);
16633     sqlite3_free(zSql);
16634   }else if( p->errCode==SQLITE_OK ){
16635     recoverError(
16636         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
16637     );
16638   }
16639 
16640   return zTbl;
16641 }
16642 
16643 /*
16644 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
16645 ** table in the output database. The name of the table is zTab, and it has
16646 ** nField c* fields.
16647 */
recoverLostAndFoundInsert(sqlite3_recover * p,const char * zTab,int nField)16648 static sqlite3_stmt *recoverLostAndFoundInsert(
16649   sqlite3_recover *p,
16650   const char *zTab,
16651   int nField
16652 ){
16653   int nTotal = nField + 4;
16654   int ii;
16655   char *zBind = 0;
16656   sqlite3_stmt *pRet = 0;
16657 
16658   if( p->xSql==0 ){
16659     for(ii=0; ii<nTotal; ii++){
16660       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
16661     }
16662     pRet = recoverPreparePrintf(
16663         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
16664     );
16665   }else{
16666     const char *zSep = "";
16667     for(ii=0; ii<nTotal; ii++){
16668       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
16669       zSep = "|| ', ' ||";
16670     }
16671     pRet = recoverPreparePrintf(
16672         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
16673     );
16674   }
16675 
16676   sqlite3_free(zBind);
16677   return pRet;
16678 }
16679 
16680 /*
16681 ** Input database page iPg contains data that will be written to the
16682 ** lost-and-found table of the output database. This function attempts
16683 ** to identify the root page of the tree that page iPg belonged to.
16684 ** If successful, it sets output variable (*piRoot) to the page number
16685 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
16686 ** an SQLite error code is returned and the final value of *piRoot
16687 ** undefined.
16688 */
recoverLostAndFoundFindRoot(sqlite3_recover * p,i64 iPg,i64 * piRoot)16689 static int recoverLostAndFoundFindRoot(
16690   sqlite3_recover *p,
16691   i64 iPg,
16692   i64 *piRoot
16693 ){
16694   RecoverStateLAF *pLaf = &p->laf;
16695 
16696   if( pLaf->pFindRoot==0 ){
16697     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
16698         "WITH RECURSIVE p(pgno) AS ("
16699         "  SELECT ?"
16700         "    UNION"
16701         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
16702         ") "
16703         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
16704         "    AND m.parent IS NULL"
16705     );
16706   }
16707   if( p->errCode==SQLITE_OK ){
16708     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
16709     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
16710       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
16711     }else{
16712       *piRoot = iPg;
16713     }
16714     recoverReset(p, pLaf->pFindRoot);
16715   }
16716   return p->errCode;
16717 }
16718 
16719 /*
16720 ** Recover data from page iPage of the input database and write it to
16721 ** the lost-and-found table in the output database.
16722 */
recoverLostAndFoundOnePage(sqlite3_recover * p,i64 iPage)16723 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
16724   RecoverStateLAF *pLaf = &p->laf;
16725   sqlite3_value **apVal = pLaf->apVal;
16726   sqlite3_stmt *pPageData = pLaf->pPageData;
16727   sqlite3_stmt *pInsert = pLaf->pInsert;
16728 
16729   int nVal = -1;
16730   int iPrevCell = 0;
16731   i64 iRoot = 0;
16732   int bHaveRowid = 0;
16733   i64 iRowid = 0;
16734   int ii = 0;
16735 
16736   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
16737   sqlite3_bind_int64(pPageData, 1, iPage);
16738   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
16739     int iCell = sqlite3_column_int64(pPageData, 0);
16740     int iField = sqlite3_column_int64(pPageData, 1);
16741 
16742     if( iPrevCell!=iCell && nVal>=0 ){
16743       /* Insert the new row */
16744       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
16745       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
16746       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
16747       if( bHaveRowid ){
16748         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
16749       }
16750       for(ii=0; ii<nVal; ii++){
16751         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
16752       }
16753       if( sqlite3_step(pInsert)==SQLITE_ROW ){
16754         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
16755       }
16756       recoverReset(p, pInsert);
16757 
16758       /* Discard the accumulated row data */
16759       for(ii=0; ii<nVal; ii++){
16760         sqlite3_value_free(apVal[ii]);
16761         apVal[ii] = 0;
16762       }
16763       sqlite3_clear_bindings(pInsert);
16764       bHaveRowid = 0;
16765       nVal = -1;
16766     }
16767 
16768     if( iCell<0 ) break;
16769 
16770     if( iField<0 ){
16771       assert( nVal==-1 );
16772       iRowid = sqlite3_column_int64(pPageData, 2);
16773       bHaveRowid = 1;
16774       nVal = 0;
16775     }else if( iField<pLaf->nMaxField ){
16776       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
16777       apVal[iField] = sqlite3_value_dup(pVal);
16778       assert( iField==nVal || (nVal==-1 && iField==0) );
16779       nVal = iField+1;
16780       if( apVal[iField]==0 ){
16781         recoverError(p, SQLITE_NOMEM, 0);
16782       }
16783     }
16784 
16785     iPrevCell = iCell;
16786   }
16787   recoverReset(p, pPageData);
16788 
16789   for(ii=0; ii<nVal; ii++){
16790     sqlite3_value_free(apVal[ii]);
16791     apVal[ii] = 0;
16792   }
16793 }
16794 
16795 /*
16796 ** Perform one step (sqlite3_recover_step()) of work for the connection
16797 ** passed as the only argument, which is guaranteed to be in
16798 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
16799 ** table of the output database is populated with recovered data that can
16800 ** not be assigned to any recovered schema object.
16801 */
recoverLostAndFound3Step(sqlite3_recover * p)16802 static int recoverLostAndFound3Step(sqlite3_recover *p){
16803   RecoverStateLAF *pLaf = &p->laf;
16804   if( p->errCode==SQLITE_OK ){
16805     if( pLaf->pInsert==0 ){
16806       return SQLITE_DONE;
16807     }else{
16808       if( p->errCode==SQLITE_OK ){
16809         int res = sqlite3_step(pLaf->pAllPage);
16810         if( res==SQLITE_ROW ){
16811           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
16812           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
16813             recoverLostAndFoundOnePage(p, iPage);
16814           }
16815         }else{
16816           recoverReset(p, pLaf->pAllPage);
16817           return SQLITE_DONE;
16818         }
16819       }
16820     }
16821   }
16822   return SQLITE_OK;
16823 }
16824 
16825 /*
16826 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
16827 ** state - during which the lost-and-found table of the output database
16828 ** is populated with recovered data that can not be assigned to any
16829 ** recovered schema object.
16830 */
recoverLostAndFound3Init(sqlite3_recover * p)16831 static void recoverLostAndFound3Init(sqlite3_recover *p){
16832   RecoverStateLAF *pLaf = &p->laf;
16833 
16834   if( pLaf->nMaxField>0 ){
16835     char *zTab = 0;               /* Name of lost_and_found table */
16836 
16837     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
16838     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
16839     sqlite3_free(zTab);
16840 
16841     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
16842         "WITH RECURSIVE seq(ii) AS ("
16843         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
16844         ")"
16845         "SELECT ii FROM seq" , p->laf.nPg
16846     );
16847     pLaf->pPageData = recoverPrepare(p, p->dbOut,
16848         "SELECT cell, field, value "
16849         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
16850         "UNION ALL "
16851         "SELECT -1, -1, -1"
16852     );
16853 
16854     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
16855         pLaf->nMaxField*sizeof(sqlite3_value*)
16856     );
16857   }
16858 }
16859 
16860 /*
16861 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
16862 ** tables recovered from the schema of the input database are populated with
16863 ** recovered data.
16864 */
recoverWriteDataInit(sqlite3_recover * p)16865 static int recoverWriteDataInit(sqlite3_recover *p){
16866   RecoverStateW1 *p1 = &p->w1;
16867   RecoverTable *pTbl = 0;
16868   int nByte = 0;
16869 
16870   /* Figure out the maximum number of columns for any table in the schema */
16871   assert( p1->nMax==0 );
16872   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
16873     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
16874   }
16875 
16876   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
16877   ** that will be written to the output database in a single row. */
16878   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
16879   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
16880   if( p1->apVal==0 ) return p->errCode;
16881 
16882   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
16883   ** to loop through cells that appear to belong to a single table (pSel). */
16884   p1->pTbls = recoverPrepare(p, p->dbOut,
16885       "SELECT rootpage FROM recovery.schema "
16886       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
16887       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
16888   );
16889   p1->pSel = recoverPrepare(p, p->dbOut,
16890       "WITH RECURSIVE pages(page) AS ("
16891       "  SELECT ?1"
16892       "    UNION"
16893       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
16894       "    WHERE pgno=page"
16895       ") "
16896       "SELECT page, cell, field, value "
16897       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
16898       "UNION ALL "
16899       "SELECT 0, 0, 0, 0"
16900   );
16901 
16902   return p->errCode;
16903 }
16904 
16905 /*
16906 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
16907 ** sqlite3_recover.w1).
16908 */
recoverWriteDataCleanup(sqlite3_recover * p)16909 static void recoverWriteDataCleanup(sqlite3_recover *p){
16910   RecoverStateW1 *p1 = &p->w1;
16911   int ii;
16912   for(ii=0; ii<p1->nVal; ii++){
16913     sqlite3_value_free(p1->apVal[ii]);
16914   }
16915   sqlite3_free(p1->apVal);
16916   recoverFinalize(p, p1->pInsert);
16917   recoverFinalize(p, p1->pTbls);
16918   recoverFinalize(p, p1->pSel);
16919   memset(p1, 0, sizeof(*p1));
16920 }
16921 
16922 /*
16923 ** Perform one step (sqlite3_recover_step()) of work for the connection
16924 ** passed as the only argument, which is guaranteed to be in
16925 ** RECOVER_STATE_WRITING state - during which tables recovered from the
16926 ** schema of the input database are populated with recovered data.
16927 */
recoverWriteDataStep(sqlite3_recover * p)16928 static int recoverWriteDataStep(sqlite3_recover *p){
16929   RecoverStateW1 *p1 = &p->w1;
16930   sqlite3_stmt *pSel = p1->pSel;
16931   sqlite3_value **apVal = p1->apVal;
16932 
16933   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
16934     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
16935       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
16936       p1->pTab = recoverFindTable(p, iRoot);
16937 
16938       recoverFinalize(p, p1->pInsert);
16939       p1->pInsert = 0;
16940 
16941       /* If this table is unknown, return early. The caller will invoke this
16942       ** function again and it will move on to the next table.  */
16943       if( p1->pTab==0 ) return p->errCode;
16944 
16945       /* If this is the sqlite_sequence table, delete any rows added by
16946       ** earlier INSERT statements on tables with AUTOINCREMENT primary
16947       ** keys before recovering its contents. The p1->pTbls SELECT statement
16948       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
16949       ** worry about it being modified after it is recovered. */
16950       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
16951         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
16952         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
16953       }
16954 
16955       /* Bind the root page of this table within the original database to
16956       ** SELECT statement p1->pSel. The SELECT statement will then iterate
16957       ** through cells that look like they belong to table pTab.  */
16958       sqlite3_bind_int64(pSel, 1, iRoot);
16959 
16960       p1->nVal = 0;
16961       p1->bHaveRowid = 0;
16962       p1->iPrevPage = -1;
16963       p1->iPrevCell = -1;
16964     }else{
16965       return SQLITE_DONE;
16966     }
16967   }
16968   assert( p->errCode!=SQLITE_OK || p1->pTab );
16969 
16970   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
16971     RecoverTable *pTab = p1->pTab;
16972 
16973     i64 iPage = sqlite3_column_int64(pSel, 0);
16974     int iCell = sqlite3_column_int(pSel, 1);
16975     int iField = sqlite3_column_int(pSel, 2);
16976     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
16977     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
16978 
16979     assert( bNewCell==0 || (iField==-1 || iField==0) );
16980     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
16981 
16982     if( bNewCell ){
16983       int ii = 0;
16984       if( p1->nVal>=0 ){
16985         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
16986           recoverFinalize(p, p1->pInsert);
16987           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
16988           p1->nInsert = p1->nVal;
16989         }
16990         if( p1->nVal>0 ){
16991           sqlite3_stmt *pInsert = p1->pInsert;
16992           for(ii=0; ii<pTab->nCol; ii++){
16993             RecoverColumn *pCol = &pTab->aCol[ii];
16994             int iBind = pCol->iBind;
16995             if( iBind>0 ){
16996               if( pCol->bIPK ){
16997                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
16998               }else if( pCol->iField<p1->nVal ){
16999                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
17000               }
17001             }
17002           }
17003           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
17004             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
17005           }
17006           if( SQLITE_ROW==sqlite3_step(pInsert) ){
17007             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
17008             recoverSqlCallback(p, z);
17009           }
17010           recoverReset(p, pInsert);
17011           assert( p->errCode || pInsert );
17012           if( pInsert ) sqlite3_clear_bindings(pInsert);
17013         }
17014       }
17015 
17016       for(ii=0; ii<p1->nVal; ii++){
17017         sqlite3_value_free(apVal[ii]);
17018         apVal[ii] = 0;
17019       }
17020       p1->nVal = -1;
17021       p1->bHaveRowid = 0;
17022     }
17023 
17024     if( iPage!=0 ){
17025       if( iField<0 ){
17026         p1->iRowid = sqlite3_column_int64(pSel, 3);
17027         assert( p1->nVal==-1 );
17028         p1->nVal = 0;
17029         p1->bHaveRowid = 1;
17030       }else if( iField<pTab->nCol ){
17031         assert( apVal[iField]==0 );
17032         apVal[iField] = sqlite3_value_dup( pVal );
17033         if( apVal[iField]==0 ){
17034           recoverError(p, SQLITE_NOMEM, 0);
17035         }
17036         p1->nVal = iField+1;
17037       }
17038       p1->iPrevCell = iCell;
17039       p1->iPrevPage = iPage;
17040     }
17041   }else{
17042     recoverReset(p, pSel);
17043     p1->pTab = 0;
17044   }
17045 
17046   return p->errCode;
17047 }
17048 
17049 /*
17050 ** Initialize resources required by sqlite3_recover_step() in
17051 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17052 ** already allocated to a recovered schema element is determined.
17053 */
recoverLostAndFound1Init(sqlite3_recover * p)17054 static void recoverLostAndFound1Init(sqlite3_recover *p){
17055   RecoverStateLAF *pLaf = &p->laf;
17056   sqlite3_stmt *pStmt = 0;
17057 
17058   assert( p->laf.pUsed==0 );
17059   pLaf->nPg = recoverPageCount(p);
17060   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
17061 
17062   /* Prepare a statement to iterate through all pages that are part of any tree
17063   ** in the recoverable part of the input database schema to the bitmap. And,
17064   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
17065   ** freelist.  */
17066   pStmt = recoverPrepare(
17067       p, p->dbOut,
17068       "WITH trunk(pgno) AS ("
17069       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
17070       "    UNION"
17071       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
17072       "),"
17073       "trunkdata(pgno, data) AS ("
17074       "  SELECT pgno, getpage(pgno) FROM trunk"
17075       "),"
17076       "freelist(data, n, freepgno) AS ("
17077       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
17078       "    UNION ALL"
17079       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
17080       "),"
17081       ""
17082       "roots(r) AS ("
17083       "  SELECT 1 UNION ALL"
17084       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
17085       "),"
17086       "used(page) AS ("
17087       "  SELECT r FROM roots"
17088       "    UNION"
17089       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
17090       "    WHERE pgno=page"
17091       ") "
17092       "SELECT page FROM used"
17093       " UNION ALL "
17094       "SELECT freepgno FROM freelist WHERE NOT ?"
17095   );
17096   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
17097   pLaf->pUsedPages = pStmt;
17098 }
17099 
17100 /*
17101 ** Perform one step (sqlite3_recover_step()) of work for the connection
17102 ** passed as the only argument, which is guaranteed to be in
17103 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17104 ** already allocated to a recovered schema element is determined.
17105 */
recoverLostAndFound1Step(sqlite3_recover * p)17106 static int recoverLostAndFound1Step(sqlite3_recover *p){
17107   RecoverStateLAF *pLaf = &p->laf;
17108   int rc = p->errCode;
17109   if( rc==SQLITE_OK ){
17110     rc = sqlite3_step(pLaf->pUsedPages);
17111     if( rc==SQLITE_ROW ){
17112       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
17113       recoverBitmapSet(pLaf->pUsed, iPg);
17114       rc = SQLITE_OK;
17115     }else{
17116       recoverFinalize(p, pLaf->pUsedPages);
17117       pLaf->pUsedPages = 0;
17118     }
17119   }
17120   return rc;
17121 }
17122 
17123 /*
17124 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
17125 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
17126 ** are sorted into sets that likely belonged to the same database tree.
17127 */
recoverLostAndFound2Init(sqlite3_recover * p)17128 static void recoverLostAndFound2Init(sqlite3_recover *p){
17129   RecoverStateLAF *pLaf = &p->laf;
17130 
17131   assert( p->laf.pAllAndParent==0 );
17132   assert( p->laf.pMapInsert==0 );
17133   assert( p->laf.pMaxField==0 );
17134   assert( p->laf.nMaxField==0 );
17135 
17136   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
17137       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
17138   );
17139   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
17140       "WITH RECURSIVE seq(ii) AS ("
17141       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
17142       ")"
17143       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
17144       " UNION ALL "
17145       "SELECT NULL, ii FROM seq", p->laf.nPg
17146   );
17147   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
17148       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
17149   );
17150 }
17151 
17152 /*
17153 ** Perform one step (sqlite3_recover_step()) of work for the connection
17154 ** passed as the only argument, which is guaranteed to be in
17155 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
17156 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
17157 ** to the same database tree.
17158 */
recoverLostAndFound2Step(sqlite3_recover * p)17159 static int recoverLostAndFound2Step(sqlite3_recover *p){
17160   RecoverStateLAF *pLaf = &p->laf;
17161   if( p->errCode==SQLITE_OK ){
17162     int res = sqlite3_step(pLaf->pAllAndParent);
17163     if( res==SQLITE_ROW ){
17164       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
17165       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
17166         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
17167         sqlite3_bind_value(pLaf->pMapInsert, 2,
17168             sqlite3_column_value(pLaf->pAllAndParent, 0)
17169         );
17170         sqlite3_step(pLaf->pMapInsert);
17171         recoverReset(p, pLaf->pMapInsert);
17172         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
17173         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
17174           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
17175           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
17176         }
17177         recoverReset(p, pLaf->pMaxField);
17178       }
17179     }else{
17180       recoverFinalize(p, pLaf->pAllAndParent);
17181       pLaf->pAllAndParent =0;
17182       return SQLITE_DONE;
17183     }
17184   }
17185   return p->errCode;
17186 }
17187 
17188 /*
17189 ** Free all resources allocated as part of sqlite3_recover_step() calls
17190 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
17191 */
recoverLostAndFoundCleanup(sqlite3_recover * p)17192 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
17193   recoverBitmapFree(p->laf.pUsed);
17194   p->laf.pUsed = 0;
17195   sqlite3_finalize(p->laf.pUsedPages);
17196   sqlite3_finalize(p->laf.pAllAndParent);
17197   sqlite3_finalize(p->laf.pMapInsert);
17198   sqlite3_finalize(p->laf.pMaxField);
17199   sqlite3_finalize(p->laf.pFindRoot);
17200   sqlite3_finalize(p->laf.pInsert);
17201   sqlite3_finalize(p->laf.pAllPage);
17202   sqlite3_finalize(p->laf.pPageData);
17203   p->laf.pUsedPages = 0;
17204   p->laf.pAllAndParent = 0;
17205   p->laf.pMapInsert = 0;
17206   p->laf.pMaxField = 0;
17207   p->laf.pFindRoot = 0;
17208   p->laf.pInsert = 0;
17209   p->laf.pAllPage = 0;
17210   p->laf.pPageData = 0;
17211   sqlite3_free(p->laf.apVal);
17212   p->laf.apVal = 0;
17213 }
17214 
17215 /*
17216 ** Free all resources allocated as part of sqlite3_recover_step() calls.
17217 */
recoverFinalCleanup(sqlite3_recover * p)17218 static void recoverFinalCleanup(sqlite3_recover *p){
17219   RecoverTable *pTab = 0;
17220   RecoverTable *pNext = 0;
17221 
17222   recoverWriteDataCleanup(p);
17223   recoverLostAndFoundCleanup(p);
17224 
17225   for(pTab=p->pTblList; pTab; pTab=pNext){
17226     pNext = pTab->pNext;
17227     sqlite3_free(pTab);
17228   }
17229   p->pTblList = 0;
17230   sqlite3_finalize(p->pGetPage);
17231   p->pGetPage = 0;
17232   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
17233 
17234   {
17235 #ifndef NDEBUG
17236     int res =
17237 #endif
17238        sqlite3_close(p->dbOut);
17239     assert( res==SQLITE_OK );
17240   }
17241   p->dbOut = 0;
17242 }
17243 
17244 /*
17245 ** Decode and return an unsigned 16-bit big-endian integer value from
17246 ** buffer a[].
17247 */
recoverGetU16(const u8 * a)17248 static u32 recoverGetU16(const u8 *a){
17249   return (((u32)a[0])<<8) + ((u32)a[1]);
17250 }
17251 
17252 /*
17253 ** Decode and return an unsigned 32-bit big-endian integer value from
17254 ** buffer a[].
17255 */
recoverGetU32(const u8 * a)17256 static u32 recoverGetU32(const u8 *a){
17257   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
17258 }
17259 
17260 /*
17261 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
17262 ** and return the number of bytes consumed.
17263 */
recoverGetVarint(const u8 * a,i64 * pVal)17264 static int recoverGetVarint(const u8 *a, i64 *pVal){
17265   sqlite3_uint64 u = 0;
17266   int i;
17267   for(i=0; i<8; i++){
17268     u = (u<<7) + (a[i]&0x7f);
17269     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
17270   }
17271   u = (u<<8) + (a[i]&0xff);
17272   *pVal = (sqlite3_int64)u;
17273   return 9;
17274 }
17275 
17276 /*
17277 ** The second argument points to a buffer n bytes in size. If this buffer
17278 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
17279 ** return the page-size in bytes. Otherwise, if the buffer does not
17280 ** appear to contain a well-formed b-tree page, return 0.
17281 */
recoverIsValidPage(u8 * aTmp,const u8 * a,int n)17282 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
17283   u8 *aUsed = aTmp;
17284   int nFrag = 0;
17285   int nActual = 0;
17286   int iFree = 0;
17287   int nCell = 0;                  /* Number of cells on page */
17288   int iCellOff = 0;               /* Offset of cell array in page */
17289   int iContent = 0;
17290   int eType = 0;
17291   int ii = 0;
17292 
17293   eType = (int)a[0];
17294   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
17295 
17296   iFree = (int)recoverGetU16(&a[1]);
17297   nCell = (int)recoverGetU16(&a[3]);
17298   iContent = (int)recoverGetU16(&a[5]);
17299   if( iContent==0 ) iContent = 65536;
17300   nFrag = (int)a[7];
17301 
17302   if( iContent>n ) return 0;
17303 
17304   memset(aUsed, 0, n);
17305   memset(aUsed, 0xFF, iContent);
17306 
17307   /* Follow the free-list. This is the same format for all b-tree pages. */
17308   if( iFree && iFree<=iContent ) return 0;
17309   while( iFree ){
17310     int iNext = 0;
17311     int nByte = 0;
17312     if( iFree>(n-4) ) return 0;
17313     iNext = recoverGetU16(&a[iFree]);
17314     nByte = recoverGetU16(&a[iFree+2]);
17315     if( iFree+nByte>n || nByte<4 ) return 0;
17316     if( iNext && iNext<iFree+nByte ) return 0;
17317     memset(&aUsed[iFree], 0xFF, nByte);
17318     iFree = iNext;
17319   }
17320 
17321   /* Run through the cells */
17322   if( eType==0x02 || eType==0x05 ){
17323     iCellOff = 12;
17324   }else{
17325     iCellOff = 8;
17326   }
17327   if( (iCellOff + 2*nCell)>iContent ) return 0;
17328   for(ii=0; ii<nCell; ii++){
17329     int iByte;
17330     i64 nPayload = 0;
17331     int nByte = 0;
17332     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
17333     if( iOff<iContent || iOff>n ){
17334       return 0;
17335     }
17336     if( eType==0x05 || eType==0x02 ) nByte += 4;
17337     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
17338     if( eType==0x0D ){
17339       i64 dummy = 0;
17340       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
17341     }
17342     if( eType!=0x05 ){
17343       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
17344       int M = ((n-12)*32/255)-23;
17345       int K = M+((nPayload-M)%(n-4));
17346 
17347       if( nPayload<X ){
17348         nByte += nPayload;
17349       }else if( K<=X ){
17350         nByte += K+4;
17351       }else{
17352         nByte += M+4;
17353       }
17354     }
17355 
17356     if( iOff+nByte>n ){
17357       return 0;
17358     }
17359     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
17360       if( aUsed[iByte]!=0 ){
17361         return 0;
17362       }
17363       aUsed[iByte] = 0xFF;
17364     }
17365   }
17366 
17367   nActual = 0;
17368   for(ii=0; ii<n; ii++){
17369     if( aUsed[ii]==0 ) nActual++;
17370   }
17371   return (nActual==nFrag);
17372 }
17373 
17374 
17375 static int recoverVfsClose(sqlite3_file*);
17376 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
17377 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
17378 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
17379 static int recoverVfsSync(sqlite3_file*, int flags);
17380 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
17381 static int recoverVfsLock(sqlite3_file*, int);
17382 static int recoverVfsUnlock(sqlite3_file*, int);
17383 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
17384 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
17385 static int recoverVfsSectorSize(sqlite3_file*);
17386 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
17387 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
17388 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
17389 static void recoverVfsShmBarrier(sqlite3_file*);
17390 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
17391 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
17392 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
17393 
17394 static sqlite3_io_methods recover_methods = {
17395   2, /* iVersion */
17396   recoverVfsClose,
17397   recoverVfsRead,
17398   recoverVfsWrite,
17399   recoverVfsTruncate,
17400   recoverVfsSync,
17401   recoverVfsFileSize,
17402   recoverVfsLock,
17403   recoverVfsUnlock,
17404   recoverVfsCheckReservedLock,
17405   recoverVfsFileControl,
17406   recoverVfsSectorSize,
17407   recoverVfsDeviceCharacteristics,
17408   recoverVfsShmMap,
17409   recoverVfsShmLock,
17410   recoverVfsShmBarrier,
17411   recoverVfsShmUnmap,
17412   recoverVfsFetch,
17413   recoverVfsUnfetch
17414 };
17415 
recoverVfsClose(sqlite3_file * pFd)17416 static int recoverVfsClose(sqlite3_file *pFd){
17417   assert( pFd->pMethods!=&recover_methods );
17418   return pFd->pMethods->xClose(pFd);
17419 }
17420 
17421 /*
17422 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
17423 */
recoverPutU16(u8 * a,u32 v)17424 static void recoverPutU16(u8 *a, u32 v){
17425   a[0] = (v>>8) & 0x00FF;
17426   a[1] = (v>>0) & 0x00FF;
17427 }
17428 
17429 /*
17430 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
17431 */
recoverPutU32(u8 * a,u32 v)17432 static void recoverPutU32(u8 *a, u32 v){
17433   a[0] = (v>>24) & 0x00FF;
17434   a[1] = (v>>16) & 0x00FF;
17435   a[2] = (v>>8) & 0x00FF;
17436   a[3] = (v>>0) & 0x00FF;
17437 }
17438 
17439 /*
17440 ** Detect the page-size of the database opened by file-handle pFd by
17441 ** searching the first part of the file for a well-formed SQLite b-tree
17442 ** page. If parameter nReserve is non-zero, then as well as searching for
17443 ** a b-tree page with zero reserved bytes, this function searches for one
17444 ** with nReserve reserved bytes at the end of it.
17445 **
17446 ** If successful, set variable p->detected_pgsz to the detected page-size
17447 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
17448 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
17449 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
17450 ** is returned. The final value of p->detected_pgsz is undefined in this
17451 ** case.
17452 */
recoverVfsDetectPagesize(sqlite3_recover * p,sqlite3_file * pFd,u32 nReserve,i64 nSz)17453 static int recoverVfsDetectPagesize(
17454   sqlite3_recover *p,             /* Recover handle */
17455   sqlite3_file *pFd,              /* File-handle open on input database */
17456   u32 nReserve,                   /* Possible nReserve value */
17457   i64 nSz                         /* Size of database file in bytes */
17458 ){
17459   int rc = SQLITE_OK;
17460   const int nMin = 512;
17461   const int nMax = 65536;
17462   const int nMaxBlk = 4;
17463   u32 pgsz = 0;
17464   int iBlk = 0;
17465   u8 *aPg = 0;
17466   u8 *aTmp = 0;
17467   int nBlk = 0;
17468 
17469   aPg = (u8*)sqlite3_malloc(2*nMax);
17470   if( aPg==0 ) return SQLITE_NOMEM;
17471   aTmp = &aPg[nMax];
17472 
17473   nBlk = (nSz+nMax-1)/nMax;
17474   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
17475 
17476   do {
17477     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
17478       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
17479       memset(aPg, 0, nMax);
17480       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
17481       if( rc==SQLITE_OK ){
17482         int pgsz2;
17483         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
17484           int iOff;
17485           for(iOff=0; iOff<nMax; iOff+=pgsz2){
17486             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
17487               pgsz = pgsz2;
17488               break;
17489             }
17490           }
17491         }
17492       }
17493     }
17494     if( pgsz>(u32)p->detected_pgsz ){
17495       p->detected_pgsz = pgsz;
17496       p->nReserve = nReserve;
17497     }
17498     if( nReserve==0 ) break;
17499     nReserve = 0;
17500   }while( 1 );
17501 
17502   p->detected_pgsz = pgsz;
17503   sqlite3_free(aPg);
17504   return rc;
17505 }
17506 
17507 /*
17508 ** The xRead() method of the wrapper VFS. This is used to intercept calls
17509 ** to read page 1 of the input database.
17510 */
recoverVfsRead(sqlite3_file * pFd,void * aBuf,int nByte,i64 iOff)17511 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
17512   int rc = SQLITE_OK;
17513   if( pFd->pMethods==&recover_methods ){
17514     pFd->pMethods = recover_g.pMethods;
17515     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
17516     if( nByte==16 ){
17517       sqlite3_randomness(16, aBuf);
17518     }else
17519     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
17520       /* Ensure that the database has a valid header file. The only fields
17521       ** that really matter to recovery are:
17522       **
17523       **   + Database page size (16-bits at offset 16)
17524       **   + Size of db in pages (32-bits at offset 28)
17525       **   + Database encoding (32-bits at offset 56)
17526       **
17527       ** Also preserved are:
17528       **
17529       **   + first freelist page (32-bits at offset 32)
17530       **   + size of freelist (32-bits at offset 36)
17531       **   + the wal-mode flags (16-bits at offset 18)
17532       **
17533       ** We also try to preserve the auto-vacuum, incr-value, user-version
17534       ** and application-id fields - all 32 bit quantities at offsets
17535       ** 52, 60, 64 and 68. All other fields are set to known good values.
17536       **
17537       ** Byte offset 105 should also contain the page-size as a 16-bit
17538       ** integer.
17539       */
17540       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
17541       u8 aHdr[108] = {
17542         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
17543         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
17544         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
17545         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
17546         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17547         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
17548         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
17549         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17550         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17551         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17552         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17553         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17554         0x00, 0x2e, 0x5b, 0x30,
17555 
17556         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
17557       };
17558       u8 *a = (u8*)aBuf;
17559 
17560       u32 pgsz = recoverGetU16(&a[16]);
17561       u32 nReserve = a[20];
17562       u32 enc = recoverGetU32(&a[56]);
17563       u32 dbsz = 0;
17564       i64 dbFileSize = 0;
17565       int ii;
17566       sqlite3_recover *p = recover_g.p;
17567 
17568       if( pgsz==0x01 ) pgsz = 65536;
17569       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
17570 
17571       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
17572         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
17573       }
17574       if( p->detected_pgsz ){
17575         pgsz = p->detected_pgsz;
17576         nReserve = p->nReserve;
17577       }
17578 
17579       if( pgsz ){
17580         dbsz = dbFileSize / pgsz;
17581       }
17582       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
17583         enc = SQLITE_UTF8;
17584       }
17585 
17586       sqlite3_free(p->pPage1Cache);
17587       p->pPage1Cache = 0;
17588       p->pPage1Disk = 0;
17589 
17590       p->pgsz = nByte;
17591       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
17592       if( p->pPage1Cache ){
17593         p->pPage1Disk = &p->pPage1Cache[nByte];
17594         memcpy(p->pPage1Disk, aBuf, nByte);
17595         aHdr[18] = a[18];
17596         aHdr[19] = a[19];
17597         recoverPutU32(&aHdr[28], dbsz);
17598         recoverPutU32(&aHdr[56], enc);
17599         recoverPutU16(&aHdr[105], pgsz-nReserve);
17600         if( pgsz==65536 ) pgsz = 1;
17601         recoverPutU16(&aHdr[16], pgsz);
17602         aHdr[20] = nReserve;
17603         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
17604           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
17605         }
17606         memcpy(aBuf, aHdr, sizeof(aHdr));
17607         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
17608 
17609         memcpy(p->pPage1Cache, aBuf, nByte);
17610       }else{
17611         rc = p->errCode;
17612       }
17613 
17614     }
17615     pFd->pMethods = &recover_methods;
17616   }else{
17617     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
17618   }
17619   return rc;
17620 }
17621 
17622 /*
17623 ** Used to make sqlite3_io_methods wrapper methods less verbose.
17624 */
17625 #define RECOVER_VFS_WRAPPER(code)                         \
17626   int rc = SQLITE_OK;                                     \
17627   if( pFd->pMethods==&recover_methods ){                  \
17628     pFd->pMethods = recover_g.pMethods;                   \
17629     rc = code;                                            \
17630     pFd->pMethods = &recover_methods;                     \
17631   }else{                                                  \
17632     rc = code;                                            \
17633   }                                                       \
17634   return rc;
17635 
17636 /*
17637 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
17638 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
17639 ** method on the lower level VFS, then reinstall the wrapper before returning.
17640 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
17641 */
recoverVfsWrite(sqlite3_file * pFd,const void * aBuf,int nByte,i64 iOff)17642 static int recoverVfsWrite(
17643   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
17644 ){
17645   RECOVER_VFS_WRAPPER (
17646       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
17647   );
17648 }
recoverVfsTruncate(sqlite3_file * pFd,sqlite3_int64 size)17649 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
17650   RECOVER_VFS_WRAPPER (
17651       pFd->pMethods->xTruncate(pFd, size)
17652   );
17653 }
recoverVfsSync(sqlite3_file * pFd,int flags)17654 static int recoverVfsSync(sqlite3_file *pFd, int flags){
17655   RECOVER_VFS_WRAPPER (
17656       pFd->pMethods->xSync(pFd, flags)
17657   );
17658 }
recoverVfsFileSize(sqlite3_file * pFd,sqlite3_int64 * pSize)17659 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
17660   RECOVER_VFS_WRAPPER (
17661       pFd->pMethods->xFileSize(pFd, pSize)
17662   );
17663 }
recoverVfsLock(sqlite3_file * pFd,int eLock)17664 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
17665   RECOVER_VFS_WRAPPER (
17666       pFd->pMethods->xLock(pFd, eLock)
17667   );
17668 }
recoverVfsUnlock(sqlite3_file * pFd,int eLock)17669 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
17670   RECOVER_VFS_WRAPPER (
17671       pFd->pMethods->xUnlock(pFd, eLock)
17672   );
17673 }
recoverVfsCheckReservedLock(sqlite3_file * pFd,int * pResOut)17674 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
17675   RECOVER_VFS_WRAPPER (
17676       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
17677   );
17678 }
recoverVfsFileControl(sqlite3_file * pFd,int op,void * pArg)17679 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
17680   RECOVER_VFS_WRAPPER (
17681     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
17682   );
17683 }
recoverVfsSectorSize(sqlite3_file * pFd)17684 static int recoverVfsSectorSize(sqlite3_file *pFd){
17685   RECOVER_VFS_WRAPPER (
17686       pFd->pMethods->xSectorSize(pFd)
17687   );
17688 }
recoverVfsDeviceCharacteristics(sqlite3_file * pFd)17689 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
17690   RECOVER_VFS_WRAPPER (
17691       pFd->pMethods->xDeviceCharacteristics(pFd)
17692   );
17693 }
recoverVfsShmMap(sqlite3_file * pFd,int iPg,int pgsz,int bExtend,void volatile ** pp)17694 static int recoverVfsShmMap(
17695   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
17696 ){
17697   RECOVER_VFS_WRAPPER (
17698       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
17699   );
17700 }
recoverVfsShmLock(sqlite3_file * pFd,int offset,int n,int flags)17701 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
17702   RECOVER_VFS_WRAPPER (
17703       pFd->pMethods->xShmLock(pFd, offset, n, flags)
17704   );
17705 }
recoverVfsShmBarrier(sqlite3_file * pFd)17706 static void recoverVfsShmBarrier(sqlite3_file *pFd){
17707   if( pFd->pMethods==&recover_methods ){
17708     pFd->pMethods = recover_g.pMethods;
17709     pFd->pMethods->xShmBarrier(pFd);
17710     pFd->pMethods = &recover_methods;
17711   }else{
17712     pFd->pMethods->xShmBarrier(pFd);
17713   }
17714 }
recoverVfsShmUnmap(sqlite3_file * pFd,int deleteFlag)17715 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
17716   RECOVER_VFS_WRAPPER (
17717       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
17718   );
17719 }
17720 
recoverVfsFetch(sqlite3_file * pFd,sqlite3_int64 iOff,int iAmt,void ** pp)17721 static int recoverVfsFetch(
17722   sqlite3_file *pFd,
17723   sqlite3_int64 iOff,
17724   int iAmt,
17725   void **pp
17726 ){
17727   (void)pFd;
17728   (void)iOff;
17729   (void)iAmt;
17730   *pp = 0;
17731   return SQLITE_OK;
17732 }
recoverVfsUnfetch(sqlite3_file * pFd,sqlite3_int64 iOff,void * p)17733 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
17734   (void)pFd;
17735   (void)iOff;
17736   (void)p;
17737   return SQLITE_OK;
17738 }
17739 
17740 /*
17741 ** Install the VFS wrapper around the file-descriptor open on the input
17742 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
17743 ** when this function is called.
17744 */
recoverInstallWrapper(sqlite3_recover * p)17745 static void recoverInstallWrapper(sqlite3_recover *p){
17746   sqlite3_file *pFd = 0;
17747   assert( recover_g.pMethods==0 );
17748   recoverAssertMutexHeld();
17749   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
17750   assert( pFd==0 || pFd->pMethods!=&recover_methods );
17751   if( pFd && pFd->pMethods ){
17752     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
17753     recover_g.pMethods = pFd->pMethods;
17754     recover_g.p = p;
17755     recover_methods.iVersion = iVersion;
17756     pFd->pMethods = &recover_methods;
17757   }
17758 }
17759 
17760 /*
17761 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
17762 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
17763 ** held when this function is called.
17764 */
recoverUninstallWrapper(sqlite3_recover * p)17765 static void recoverUninstallWrapper(sqlite3_recover *p){
17766   sqlite3_file *pFd = 0;
17767   recoverAssertMutexHeld();
17768   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
17769   if( pFd && pFd->pMethods ){
17770     pFd->pMethods = recover_g.pMethods;
17771     recover_g.pMethods = 0;
17772     recover_g.p = 0;
17773   }
17774 }
17775 
17776 /*
17777 ** This function does the work of a single sqlite3_recover_step() call. It
17778 ** is guaranteed that the handle is not in an error state when this
17779 ** function is called.
17780 */
recoverStep(sqlite3_recover * p)17781 static void recoverStep(sqlite3_recover *p){
17782   assert( p && p->errCode==SQLITE_OK );
17783   switch( p->eState ){
17784     case RECOVER_STATE_INIT:
17785       /* This is the very first call to sqlite3_recover_step() on this object.
17786       */
17787       recoverSqlCallback(p, "BEGIN");
17788       recoverSqlCallback(p, "PRAGMA writable_schema = on");
17789 
17790       recoverEnterMutex();
17791       recoverInstallWrapper(p);
17792 
17793       /* Open the output database. And register required virtual tables and
17794       ** user functions with the new handle. */
17795       recoverOpenOutput(p);
17796 
17797       /* Open transactions on both the input and output databases. */
17798       sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
17799       recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
17800       recoverExec(p, p->dbIn, "BEGIN");
17801       if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
17802       recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
17803       recoverTransferSettings(p);
17804       recoverOpenRecovery(p);
17805       recoverCacheSchema(p);
17806 
17807       recoverUninstallWrapper(p);
17808       recoverLeaveMutex();
17809 
17810       recoverExec(p, p->dbOut, "BEGIN");
17811 
17812       recoverWriteSchema1(p);
17813       p->eState = RECOVER_STATE_WRITING;
17814       break;
17815 
17816     case RECOVER_STATE_WRITING: {
17817       if( p->w1.pTbls==0 ){
17818         recoverWriteDataInit(p);
17819       }
17820       if( SQLITE_DONE==recoverWriteDataStep(p) ){
17821         recoverWriteDataCleanup(p);
17822         if( p->zLostAndFound ){
17823           p->eState = RECOVER_STATE_LOSTANDFOUND1;
17824         }else{
17825           p->eState = RECOVER_STATE_SCHEMA2;
17826         }
17827       }
17828       break;
17829     }
17830 
17831     case RECOVER_STATE_LOSTANDFOUND1: {
17832       if( p->laf.pUsed==0 ){
17833         recoverLostAndFound1Init(p);
17834       }
17835       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
17836         p->eState = RECOVER_STATE_LOSTANDFOUND2;
17837       }
17838       break;
17839     }
17840     case RECOVER_STATE_LOSTANDFOUND2: {
17841       if( p->laf.pAllAndParent==0 ){
17842         recoverLostAndFound2Init(p);
17843       }
17844       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
17845         p->eState = RECOVER_STATE_LOSTANDFOUND3;
17846       }
17847       break;
17848     }
17849 
17850     case RECOVER_STATE_LOSTANDFOUND3: {
17851       if( p->laf.pInsert==0 ){
17852         recoverLostAndFound3Init(p);
17853       }
17854       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
17855         p->eState = RECOVER_STATE_SCHEMA2;
17856       }
17857       break;
17858     }
17859 
17860     case RECOVER_STATE_SCHEMA2: {
17861       int rc = SQLITE_OK;
17862 
17863       recoverWriteSchema2(p);
17864       p->eState = RECOVER_STATE_DONE;
17865 
17866       /* If no error has occurred, commit the write transaction on the output
17867       ** database. Regardless of whether or not an error has occurred, make
17868       ** an attempt to end the read transaction on the input database.  */
17869       recoverExec(p, p->dbOut, "COMMIT");
17870       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
17871       if( p->errCode==SQLITE_OK ) p->errCode = rc;
17872 
17873       recoverSqlCallback(p, "PRAGMA writable_schema = off");
17874       recoverSqlCallback(p, "COMMIT");
17875       p->eState = RECOVER_STATE_DONE;
17876       recoverFinalCleanup(p);
17877       break;
17878     };
17879 
17880     case RECOVER_STATE_DONE: {
17881       /* no-op */
17882       break;
17883     };
17884   }
17885 }
17886 
17887 
17888 /*
17889 ** This is a worker function that does the heavy lifting for both init
17890 ** functions:
17891 **
17892 **     sqlite3_recover_init()
17893 **     sqlite3_recover_init_sql()
17894 **
17895 ** All this function does is allocate space for the recover handle and
17896 ** take copies of the input parameters. All the real work is done within
17897 ** sqlite3_recover_run().
17898 */
recoverInit(sqlite3 * db,const char * zDb,const char * zUri,int (* xSql)(void *,const char *),void * pSqlCtx)17899 sqlite3_recover *recoverInit(
17900   sqlite3* db,
17901   const char *zDb,
17902   const char *zUri,               /* Output URI for _recover_init() */
17903   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
17904   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
17905 ){
17906   sqlite3_recover *pRet = 0;
17907   int nDb = 0;
17908   int nUri = 0;
17909   int nByte = 0;
17910 
17911   if( zDb==0 ){ zDb = "main"; }
17912 
17913   nDb = recoverStrlen(zDb);
17914   nUri = recoverStrlen(zUri);
17915 
17916   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
17917   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
17918   if( pRet ){
17919     memset(pRet, 0, nByte);
17920     pRet->dbIn = db;
17921     pRet->zDb = (char*)&pRet[1];
17922     pRet->zUri = &pRet->zDb[nDb+1];
17923     memcpy(pRet->zDb, zDb, nDb);
17924     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
17925     pRet->xSql = xSql;
17926     pRet->pSqlCtx = pSqlCtx;
17927     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
17928   }
17929 
17930   return pRet;
17931 }
17932 
17933 /*
17934 ** Initialize a recovery handle that creates a new database containing
17935 ** the recovered data.
17936 */
sqlite3_recover_init(sqlite3 * db,const char * zDb,const char * zUri)17937 sqlite3_recover *sqlite3_recover_init(
17938   sqlite3* db,
17939   const char *zDb,
17940   const char *zUri
17941 ){
17942   return recoverInit(db, zDb, zUri, 0, 0);
17943 }
17944 
17945 /*
17946 ** Initialize a recovery handle that returns recovered data in the
17947 ** form of SQL statements via a callback.
17948 */
sqlite3_recover_init_sql(sqlite3 * db,const char * zDb,int (* xSql)(void *,const char *),void * pSqlCtx)17949 sqlite3_recover *sqlite3_recover_init_sql(
17950   sqlite3* db,
17951   const char *zDb,
17952   int (*xSql)(void*, const char*),
17953   void *pSqlCtx
17954 ){
17955   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
17956 }
17957 
17958 /*
17959 ** Return the handle error message, if any.
17960 */
sqlite3_recover_errmsg(sqlite3_recover * p)17961 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
17962   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
17963 }
17964 
17965 /*
17966 ** Return the handle error code.
17967 */
sqlite3_recover_errcode(sqlite3_recover * p)17968 int sqlite3_recover_errcode(sqlite3_recover *p){
17969   return p ? p->errCode : SQLITE_NOMEM;
17970 }
17971 
17972 /*
17973 ** Configure the handle.
17974 */
sqlite3_recover_config(sqlite3_recover * p,int op,void * pArg)17975 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
17976   int rc = SQLITE_OK;
17977   if( p==0 ){
17978     rc = SQLITE_NOMEM;
17979   }else if( p->eState!=RECOVER_STATE_INIT ){
17980     rc = SQLITE_MISUSE;
17981   }else{
17982     switch( op ){
17983       case 789:
17984         /* This undocumented magic configuration option is used to set the
17985         ** name of the auxiliary database that is ATTACH-ed to the database
17986         ** connection and used to hold state information during the
17987         ** recovery process.  This option is for debugging use only and
17988         ** is subject to change or removal at any time. */
17989         sqlite3_free(p->zStateDb);
17990         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
17991         break;
17992 
17993       case SQLITE_RECOVER_LOST_AND_FOUND: {
17994         const char *zArg = (const char*)pArg;
17995         sqlite3_free(p->zLostAndFound);
17996         if( zArg ){
17997           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
17998         }else{
17999           p->zLostAndFound = 0;
18000         }
18001         break;
18002       }
18003 
18004       case SQLITE_RECOVER_FREELIST_CORRUPT:
18005         p->bFreelistCorrupt = *(int*)pArg;
18006         break;
18007 
18008       case SQLITE_RECOVER_ROWIDS:
18009         p->bRecoverRowid = *(int*)pArg;
18010         break;
18011 
18012       case SQLITE_RECOVER_SLOWINDEXES:
18013         p->bSlowIndexes = *(int*)pArg;
18014         break;
18015 
18016       default:
18017         rc = SQLITE_NOTFOUND;
18018         break;
18019     }
18020   }
18021 
18022   return rc;
18023 }
18024 
18025 /*
18026 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
18027 ** no error has occurred but database recovery is not finished, SQLITE_DONE
18028 ** if database recovery has been successfully completed, or an SQLite
18029 ** error code if an error has occurred.
18030 */
sqlite3_recover_step(sqlite3_recover * p)18031 int sqlite3_recover_step(sqlite3_recover *p){
18032   if( p==0 ) return SQLITE_NOMEM;
18033   if( p->errCode==SQLITE_OK ) recoverStep(p);
18034   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
18035     return SQLITE_DONE;
18036   }
18037   return p->errCode;
18038 }
18039 
18040 /*
18041 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
18042 ** else an SQLite error code.
18043 */
sqlite3_recover_run(sqlite3_recover * p)18044 int sqlite3_recover_run(sqlite3_recover *p){
18045   while( SQLITE_OK==sqlite3_recover_step(p) );
18046   return sqlite3_recover_errcode(p);
18047 }
18048 
18049 
18050 /*
18051 ** Free all resources associated with the recover handle passed as the only
18052 ** argument. The results of using a handle with any sqlite3_recover_**
18053 ** API function after it has been passed to this function are undefined.
18054 **
18055 ** A copy of the value returned by the first call made to sqlite3_recover_run()
18056 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
18057 ** not been called on this handle.
18058 */
sqlite3_recover_finish(sqlite3_recover * p)18059 int sqlite3_recover_finish(sqlite3_recover *p){
18060   int rc;
18061   if( p==0 ){
18062     rc = SQLITE_NOMEM;
18063   }else{
18064     recoverFinalCleanup(p);
18065     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
18066       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
18067       if( p->errCode==SQLITE_OK ) p->errCode = rc;
18068     }
18069     rc = p->errCode;
18070     sqlite3_free(p->zErrMsg);
18071     sqlite3_free(p->zStateDb);
18072     sqlite3_free(p->zLostAndFound);
18073     sqlite3_free(p->pPage1Cache);
18074     sqlite3_free(p);
18075   }
18076   return rc;
18077 }
18078 
18079 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
18080 
18081 /************************* End ../ext/recover/sqlite3recover.c ********************/
18082 # endif /* SQLITE_HAVE_SQLITE3R */
18083 #endif
18084 #ifdef SQLITE_SHELL_EXTSRC
18085 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
18086 #endif
18087 
18088 #if defined(SQLITE_ENABLE_SESSION)
18089 /*
18090 ** State information for a single open session
18091 */
18092 typedef struct OpenSession OpenSession;
18093 struct OpenSession {
18094   char *zName;             /* Symbolic name for this session */
18095   int nFilter;             /* Number of xFilter rejection GLOB patterns */
18096   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
18097   sqlite3_session *p;      /* The open session */
18098 };
18099 #endif
18100 
18101 typedef struct ExpertInfo ExpertInfo;
18102 struct ExpertInfo {
18103   sqlite3expert *pExpert;
18104   int bVerbose;
18105 };
18106 
18107 /* A single line in the EQP output */
18108 typedef struct EQPGraphRow EQPGraphRow;
18109 struct EQPGraphRow {
18110   int iEqpId;           /* ID for this row */
18111   int iParentId;        /* ID of the parent row */
18112   EQPGraphRow *pNext;   /* Next row in sequence */
18113   char zText[1];        /* Text to display for this row */
18114 };
18115 
18116 /* All EQP output is collected into an instance of the following */
18117 typedef struct EQPGraph EQPGraph;
18118 struct EQPGraph {
18119   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
18120   EQPGraphRow *pLast;   /* Last element of the pRow list */
18121   char zPrefix[100];    /* Graph prefix */
18122 };
18123 
18124 /* Parameters affecting columnar mode result display (defaulting together) */
18125 typedef struct ColModeOpts {
18126   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
18127   u8 bQuote;            /* Quote results for .mode box and table */
18128   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
18129 } ColModeOpts;
18130 #define ColModeOpts_default { 60, 0, 0 }
18131 #define ColModeOpts_default_qbox { 60, 1, 0 }
18132 
18133 /*
18134 ** State information about the database connection is contained in an
18135 ** instance of the following structure.
18136 */
18137 typedef struct ShellState ShellState;
18138 struct ShellState {
18139   sqlite3 *db;           /* The database */
18140   u8 autoExplain;        /* Automatically turn on .explain mode */
18141   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
18142   u8 autoEQPtest;        /* autoEQP is in test mode */
18143   u8 autoEQPtrace;       /* autoEQP is in trace mode */
18144   u8 scanstatsOn;        /* True to display scan stats before each finalize */
18145   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
18146   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
18147   u8 nEqpLevel;          /* Depth of the EQP output graph */
18148   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
18149   u8 bSafeMode;          /* True to prohibit unsafe operations */
18150   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
18151   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
18152   unsigned statsOn;      /* True to display memory stats before each finalize */
18153   unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
18154   int inputNesting;      /* Track nesting level of .read and other redirects */
18155   int outCount;          /* Revert to stdout when reaching zero */
18156   int cnt;               /* Number of records displayed so far */
18157   int lineno;            /* Line number of last line read from in */
18158   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
18159   FILE *in;              /* Read commands from this stream */
18160   FILE *out;             /* Write results here */
18161   FILE *traceOut;        /* Output for sqlite3_trace() */
18162   int nErr;              /* Number of errors seen */
18163   int mode;              /* An output mode setting */
18164   int modePrior;         /* Saved mode */
18165   int cMode;             /* temporary output mode for the current query */
18166   int normalMode;        /* Output mode before ".explain on" */
18167   int writableSchema;    /* True if PRAGMA writable_schema=ON */
18168   int showHeader;        /* True to show column names in List or Column mode */
18169   int nCheck;            /* Number of ".check" commands run */
18170   unsigned nProgress;    /* Number of progress callbacks encountered */
18171   unsigned mxProgress;   /* Maximum progress callbacks before failing */
18172   unsigned flgProgress;  /* Flags for the progress callback */
18173   unsigned shellFlgs;    /* Various flags */
18174   unsigned priorShFlgs;  /* Saved copy of flags */
18175   sqlite3_int64 szMax;   /* --maxsize argument to .open */
18176   char *zDestTable;      /* Name of destination table when MODE_Insert */
18177   char *zTempFile;       /* Temporary file that might need deleting */
18178   char zTestcase[30];    /* Name of current test case */
18179   char colSeparator[20]; /* Column separator character for several modes */
18180   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
18181   char colSepPrior[20];  /* Saved column separator */
18182   char rowSepPrior[20];  /* Saved row separator */
18183   int *colWidth;         /* Requested width of each column in columnar modes */
18184   int *actualWidth;      /* Actual width of each column */
18185   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
18186   char nullValue[20];    /* The text to print when a NULL comes back from
18187                          ** the database */
18188   char outfile[FILENAME_MAX]; /* Filename for *out */
18189   sqlite3_stmt *pStmt;   /* Current statement if any. */
18190   FILE *pLog;            /* Write log output here */
18191   struct AuxDb {         /* Storage space for auxiliary database connections */
18192     sqlite3 *db;               /* Connection pointer */
18193     const char *zDbFilename;   /* Filename used to open the connection */
18194     char *zFreeOnClose;        /* Free this memory allocation on close */
18195 #if defined(SQLITE_ENABLE_SESSION)
18196     int nSession;              /* Number of active sessions */
18197     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
18198 #endif
18199   } aAuxDb[5],           /* Array of all database connections */
18200     *pAuxDb;             /* Currently active database connection */
18201   int *aiIndent;         /* Array of indents used in MODE_Explain */
18202   int nIndent;           /* Size of array aiIndent[] */
18203   int iIndent;           /* Index of current op in aiIndent[] */
18204   char *zNonce;          /* Nonce for temporary safe-mode escapes */
18205   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
18206   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
18207 #ifdef SQLITE_SHELL_FIDDLE
18208   struct {
18209     const char * zInput; /* Input string from wasm/JS proxy */
18210     const char * zPos;   /* Cursor pos into zInput */
18211     const char * zDefaultDbName; /* Default name for db file */
18212   } wasm;
18213 #endif
18214 };
18215 
18216 #ifdef SQLITE_SHELL_FIDDLE
18217 static ShellState shellState;
18218 #endif
18219 
18220 
18221 /* Allowed values for ShellState.autoEQP
18222 */
18223 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
18224 #define AUTOEQP_on       1           /* Automatic EQP is on */
18225 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
18226 #define AUTOEQP_full     3           /* Show full EXPLAIN */
18227 
18228 /* Allowed values for ShellState.openMode
18229 */
18230 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
18231 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
18232 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
18233 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
18234 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
18235 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
18236 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
18237 
18238 /* Allowed values for ShellState.eTraceType
18239 */
18240 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
18241 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
18242 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
18243 
18244 /* Bits in the ShellState.flgProgress variable */
18245 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
18246 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
18247                                    ** callback limit is reached, and for each
18248                                    ** top-level SQL statement */
18249 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
18250 
18251 /*
18252 ** These are the allowed shellFlgs values
18253 */
18254 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
18255 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
18256 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
18257 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
18258 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
18259 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
18260 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
18261 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
18262 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
18263 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
18264 #define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
18265 
18266 /*
18267 ** Macros for testing and setting shellFlgs
18268 */
18269 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
18270 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
18271 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
18272 
18273 /*
18274 ** These are the allowed modes.
18275 */
18276 #define MODE_Line     0  /* One column per line.  Blank line between records */
18277 #define MODE_Column   1  /* One record per line in neat columns */
18278 #define MODE_List     2  /* One record per line with a separator */
18279 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
18280 #define MODE_Html     4  /* Generate an XHTML table */
18281 #define MODE_Insert   5  /* Generate SQL "insert" statements */
18282 #define MODE_Quote    6  /* Quote values as for SQL */
18283 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
18284 #define MODE_Csv      8  /* Quote strings, numbers are plain */
18285 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
18286 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
18287 #define MODE_Pretty  11  /* Pretty-print schemas */
18288 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
18289 #define MODE_Json    13  /* Output JSON */
18290 #define MODE_Markdown 14 /* Markdown formatting */
18291 #define MODE_Table   15  /* MySQL-style table formatting */
18292 #define MODE_Box     16  /* Unicode box-drawing characters */
18293 #define MODE_Count   17  /* Output only a count of the rows of output */
18294 #define MODE_Off     18  /* No query output shown */
18295 #define MODE_ScanExp 19  /* Like MODE_Explain, but for ".scanstats vm" */
18296 
18297 static const char *modeDescr[] = {
18298   "line",
18299   "column",
18300   "list",
18301   "semi",
18302   "html",
18303   "insert",
18304   "quote",
18305   "tcl",
18306   "csv",
18307   "explain",
18308   "ascii",
18309   "prettyprint",
18310   "eqp",
18311   "json",
18312   "markdown",
18313   "table",
18314   "box",
18315   "count",
18316   "off"
18317 };
18318 
18319 /*
18320 ** These are the column/row/line separators used by the various
18321 ** import/export modes.
18322 */
18323 #define SEP_Column    "|"
18324 #define SEP_Row       "\n"
18325 #define SEP_Tab       "\t"
18326 #define SEP_Space     " "
18327 #define SEP_Comma     ","
18328 #define SEP_CrLf      "\r\n"
18329 #define SEP_Unit      "\x1F"
18330 #define SEP_Record    "\x1E"
18331 
18332 /*
18333 ** Limit input nesting via .read or any other input redirect.
18334 ** It's not too expensive, so a generous allowance can be made.
18335 */
18336 #define MAX_INPUT_NESTING 25
18337 
18338 /*
18339 ** A callback for the sqlite3_log() interface.
18340 */
shellLog(void * pArg,int iErrCode,const char * zMsg)18341 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
18342   ShellState *p = (ShellState*)pArg;
18343   if( p->pLog==0 ) return;
18344   sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
18345   fflush(p->pLog);
18346 }
18347 
18348 /*
18349 ** SQL function:  shell_putsnl(X)
18350 **
18351 ** Write the text X to the screen (or whatever output is being directed)
18352 ** adding a newline at the end, and then return X.
18353 */
shellPutsFunc(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)18354 static void shellPutsFunc(
18355   sqlite3_context *pCtx,
18356   int nVal,
18357   sqlite3_value **apVal
18358 ){
18359   /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
18360   (void)nVal;
18361   oputf("%s\n", sqlite3_value_text(apVal[0]));
18362   sqlite3_result_value(pCtx, apVal[0]);
18363 }
18364 
18365 /*
18366 ** If in safe mode, print an error message described by the arguments
18367 ** and exit immediately.
18368 */
failIfSafeMode(ShellState * p,const char * zErrMsg,...)18369 static void failIfSafeMode(
18370   ShellState *p,
18371   const char *zErrMsg,
18372   ...
18373 ){
18374   if( p->bSafeMode ){
18375     va_list ap;
18376     char *zMsg;
18377     va_start(ap, zErrMsg);
18378     zMsg = sqlite3_vmprintf(zErrMsg, ap);
18379     va_end(ap);
18380     eputf("line %d: %s\n", p->lineno, zMsg);
18381     exit(1);
18382   }
18383 }
18384 
18385 /*
18386 ** SQL function:   edit(VALUE)
18387 **                 edit(VALUE,EDITOR)
18388 **
18389 ** These steps:
18390 **
18391 **     (1) Write VALUE into a temporary file.
18392 **     (2) Run program EDITOR on that temporary file.
18393 **     (3) Read the temporary file back and return its content as the result.
18394 **     (4) Delete the temporary file
18395 **
18396 ** If the EDITOR argument is omitted, use the value in the VISUAL
18397 ** environment variable.  If still there is no EDITOR, through an error.
18398 **
18399 ** Also throw an error if the EDITOR program returns a non-zero exit code.
18400 */
18401 #ifndef SQLITE_NOHAVE_SYSTEM
editFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)18402 static void editFunc(
18403   sqlite3_context *context,
18404   int argc,
18405   sqlite3_value **argv
18406 ){
18407   const char *zEditor;
18408   char *zTempFile = 0;
18409   sqlite3 *db;
18410   char *zCmd = 0;
18411   int bBin;
18412   int rc;
18413   int hasCRNL = 0;
18414   FILE *f = 0;
18415   sqlite3_int64 sz;
18416   sqlite3_int64 x;
18417   unsigned char *p = 0;
18418 
18419   if( argc==2 ){
18420     zEditor = (const char*)sqlite3_value_text(argv[1]);
18421   }else{
18422     zEditor = getenv("VISUAL");
18423   }
18424   if( zEditor==0 ){
18425     sqlite3_result_error(context, "no editor for edit()", -1);
18426     return;
18427   }
18428   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
18429     sqlite3_result_error(context, "NULL input to edit()", -1);
18430     return;
18431   }
18432   db = sqlite3_context_db_handle(context);
18433   zTempFile = 0;
18434   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
18435   if( zTempFile==0 ){
18436     sqlite3_uint64 r = 0;
18437     sqlite3_randomness(sizeof(r), &r);
18438     zTempFile = sqlite3_mprintf("temp%llx", r);
18439     if( zTempFile==0 ){
18440       sqlite3_result_error_nomem(context);
18441       return;
18442     }
18443   }
18444   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
18445   /* When writing the file to be edited, do \n to \r\n conversions on systems
18446   ** that want \r\n line endings */
18447   f = fopen(zTempFile, bBin ? "wb" : "w");
18448   if( f==0 ){
18449     sqlite3_result_error(context, "edit() cannot open temp file", -1);
18450     goto edit_func_end;
18451   }
18452   sz = sqlite3_value_bytes(argv[0]);
18453   if( bBin ){
18454     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
18455   }else{
18456     const char *z = (const char*)sqlite3_value_text(argv[0]);
18457     /* Remember whether or not the value originally contained \r\n */
18458     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
18459     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
18460   }
18461   fclose(f);
18462   f = 0;
18463   if( x!=sz ){
18464     sqlite3_result_error(context, "edit() could not write the whole file", -1);
18465     goto edit_func_end;
18466   }
18467   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
18468   if( zCmd==0 ){
18469     sqlite3_result_error_nomem(context);
18470     goto edit_func_end;
18471   }
18472   rc = system(zCmd);
18473   sqlite3_free(zCmd);
18474   if( rc ){
18475     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
18476     goto edit_func_end;
18477   }
18478   f = fopen(zTempFile, "rb");
18479   if( f==0 ){
18480     sqlite3_result_error(context,
18481       "edit() cannot reopen temp file after edit", -1);
18482     goto edit_func_end;
18483   }
18484   fseek(f, 0, SEEK_END);
18485   sz = ftell(f);
18486   rewind(f);
18487   p = sqlite3_malloc64( sz+1 );
18488   if( p==0 ){
18489     sqlite3_result_error_nomem(context);
18490     goto edit_func_end;
18491   }
18492   x = fread(p, 1, (size_t)sz, f);
18493   fclose(f);
18494   f = 0;
18495   if( x!=sz ){
18496     sqlite3_result_error(context, "could not read back the whole file", -1);
18497     goto edit_func_end;
18498   }
18499   if( bBin ){
18500     sqlite3_result_blob64(context, p, sz, sqlite3_free);
18501   }else{
18502     sqlite3_int64 i, j;
18503     if( hasCRNL ){
18504       /* If the original contains \r\n then do no conversions back to \n */
18505     }else{
18506       /* If the file did not originally contain \r\n then convert any new
18507       ** \r\n back into \n */
18508       p[sz] = 0;
18509       for(i=j=0; i<sz; i++){
18510         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
18511         p[j++] = p[i];
18512       }
18513       sz = j;
18514       p[sz] = 0;
18515     }
18516     sqlite3_result_text64(context, (const char*)p, sz,
18517                           sqlite3_free, SQLITE_UTF8);
18518   }
18519   p = 0;
18520 
18521 edit_func_end:
18522   if( f ) fclose(f);
18523   unlink(zTempFile);
18524   sqlite3_free(zTempFile);
18525   sqlite3_free(p);
18526 }
18527 #endif /* SQLITE_NOHAVE_SYSTEM */
18528 
18529 /*
18530 ** Save or restore the current output mode
18531 */
outputModePush(ShellState * p)18532 static void outputModePush(ShellState *p){
18533   p->modePrior = p->mode;
18534   p->priorShFlgs = p->shellFlgs;
18535   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
18536   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
18537 }
outputModePop(ShellState * p)18538 static void outputModePop(ShellState *p){
18539   p->mode = p->modePrior;
18540   p->shellFlgs = p->priorShFlgs;
18541   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
18542   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
18543 }
18544 
18545 /*
18546 ** Output the given string as a hex-encoded blob (eg. X'1234' )
18547 */
output_hex_blob(const void * pBlob,int nBlob)18548 static void output_hex_blob(const void *pBlob, int nBlob){
18549   int i;
18550   unsigned char *aBlob = (unsigned char*)pBlob;
18551 
18552   char *zStr = sqlite3_malloc(nBlob*2 + 1);
18553   shell_check_oom(zStr);
18554 
18555   for(i=0; i<nBlob; i++){
18556     static const char aHex[] = {
18557         '0', '1', '2', '3', '4', '5', '6', '7',
18558         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
18559     };
18560     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
18561     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
18562   }
18563   zStr[i*2] = '\0';
18564 
18565   oputf("X'%s'", zStr);
18566   sqlite3_free(zStr);
18567 }
18568 
18569 /*
18570 ** Find a string that is not found anywhere in z[].  Return a pointer
18571 ** to that string.
18572 **
18573 ** Try to use zA and zB first.  If both of those are already found in z[]
18574 ** then make up some string and store it in the buffer zBuf.
18575 */
unused_string(const char * z,const char * zA,const char * zB,char * zBuf)18576 static const char *unused_string(
18577   const char *z,                    /* Result must not appear anywhere in z */
18578   const char *zA, const char *zB,   /* Try these first */
18579   char *zBuf                        /* Space to store a generated string */
18580 ){
18581   unsigned i = 0;
18582   if( strstr(z, zA)==0 ) return zA;
18583   if( strstr(z, zB)==0 ) return zB;
18584   do{
18585     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
18586   }while( strstr(z,zBuf)!=0 );
18587   return zBuf;
18588 }
18589 
18590 /*
18591 ** Output the given string as a quoted string using SQL quoting conventions.
18592 **
18593 ** See also: output_quoted_escaped_string()
18594 */
output_quoted_string(const char * z)18595 static void output_quoted_string(const char *z){
18596   int i;
18597   char c;
18598 #ifndef SQLITE_SHELL_FIDDLE
18599   FILE *pfO = setOutputStream(invalidFileStream);
18600   setBinaryMode(pfO, 1);
18601 #endif
18602   if( z==0 ) return;
18603   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
18604   if( c==0 ){
18605     oputf("'%s'",z);
18606   }else{
18607     oputz("'");
18608     while( *z ){
18609       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
18610       if( c=='\'' ) i++;
18611       if( i ){
18612         oputf("%.*s", i, z);
18613         z += i;
18614       }
18615       if( c=='\'' ){
18616         oputz("'");
18617         continue;
18618       }
18619       if( c==0 ){
18620         break;
18621       }
18622       z++;
18623     }
18624     oputz("'");
18625   }
18626 #ifndef SQLITE_SHELL_FIDDLE
18627   setTextMode(pfO, 1);
18628 #else
18629   setTextMode(stdout, 1);
18630 #endif
18631 }
18632 
18633 /*
18634 ** Output the given string as a quoted string using SQL quoting conventions.
18635 ** Additionallly , escape the "\n" and "\r" characters so that they do not
18636 ** get corrupted by end-of-line translation facilities in some operating
18637 ** systems.
18638 **
18639 ** This is like output_quoted_string() but with the addition of the \r\n
18640 ** escape mechanism.
18641 */
output_quoted_escaped_string(const char * z)18642 static void output_quoted_escaped_string(const char *z){
18643   int i;
18644   char c;
18645 #ifndef SQLITE_SHELL_FIDDLE
18646   FILE *pfO = setOutputStream(invalidFileStream);
18647   setBinaryMode(pfO, 1);
18648 #endif
18649   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
18650   if( c==0 ){
18651     oputf("'%s'",z);
18652   }else{
18653     const char *zNL = 0;
18654     const char *zCR = 0;
18655     int nNL = 0;
18656     int nCR = 0;
18657     char zBuf1[20], zBuf2[20];
18658     for(i=0; z[i]; i++){
18659       if( z[i]=='\n' ) nNL++;
18660       if( z[i]=='\r' ) nCR++;
18661     }
18662     if( nNL ){
18663       oputz("replace(");
18664       zNL = unused_string(z, "\\n", "\\012", zBuf1);
18665     }
18666     if( nCR ){
18667       oputz("replace(");
18668       zCR = unused_string(z, "\\r", "\\015", zBuf2);
18669     }
18670     oputz("'");
18671     while( *z ){
18672       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
18673       if( c=='\'' ) i++;
18674       if( i ){
18675         oputf("%.*s", i, z);
18676         z += i;
18677       }
18678       if( c=='\'' ){
18679         oputz("'");
18680         continue;
18681       }
18682       if( c==0 ){
18683         break;
18684       }
18685       z++;
18686       if( c=='\n' ){
18687         oputz(zNL);
18688         continue;
18689       }
18690       oputz(zCR);
18691     }
18692     oputz("'");
18693     if( nCR ){
18694       oputf(",'%s',char(13))", zCR);
18695     }
18696     if( nNL ){
18697       oputf(",'%s',char(10))", zNL);
18698     }
18699   }
18700 #ifndef SQLITE_SHELL_FIDDLE
18701   setTextMode(pfO, 1);
18702 #else
18703   setTextMode(stdout, 1);
18704 #endif
18705 }
18706 
18707 /*
18708 ** Find earliest of chars within s specified in zAny.
18709 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
18710 */
anyOfInStr(const char * s,const char * zAny,size_t ns)18711 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
18712   const char *pcFirst = 0;
18713   if( ns == ~(size_t)0 ) ns = strlen(s);
18714   while(*zAny){
18715     const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
18716     if( pc ){
18717       pcFirst = pc;
18718       ns = pcFirst - s;
18719     }
18720     ++zAny;
18721   }
18722   return pcFirst;
18723 }
18724 /*
18725 ** Output the given string as a quoted according to C or TCL quoting rules.
18726 */
output_c_string(const char * z)18727 static void output_c_string(const char *z){
18728   char c;
18729   static const char *zq = "\"";
18730   static long ctrlMask = ~0L;
18731   static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
18732   char ace[3] = "\\?";
18733   char cbsSay;
18734   oputz(zq);
18735   while( *z!=0 ){
18736     const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
18737     const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
18738     const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
18739     if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
18740     if( (c = *pcEnd)==0 ) break;
18741     ++pcEnd;
18742     switch( c ){
18743     case '\\': case '"':
18744       cbsSay = (char)c;
18745       break;
18746     case '\t': cbsSay = 't'; break;
18747     case '\n': cbsSay = 'n'; break;
18748     case '\r': cbsSay = 'r'; break;
18749     case '\f': cbsSay = 'f'; break;
18750     default: cbsSay = 0; break;
18751     }
18752     if( cbsSay ){
18753       ace[1] = cbsSay;
18754       oputz(ace);
18755     }else if( !isprint(c&0xff) ){
18756       oputf("\\%03o", c&0xff);
18757     }else{
18758       ace[1] = (char)c;
18759       oputz(ace+1);
18760     }
18761     z = pcEnd;
18762   }
18763   oputz(zq);
18764 }
18765 
18766 /*
18767 ** Output the given string as a quoted according to JSON quoting rules.
18768 */
output_json_string(const char * z,i64 n)18769 static void output_json_string(const char *z, i64 n){
18770   char c;
18771   static const char *zq = "\"";
18772   static long ctrlMask = ~0L;
18773   static const char *zDQBS = "\"\\";
18774   const char *pcLimit;
18775   char ace[3] = "\\?";
18776   char cbsSay;
18777 
18778   if( z==0 ) z = "";
18779   pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
18780   oputz(zq);
18781   while( z < pcLimit ){
18782     const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
18783     const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
18784     const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
18785     if( pcEnd > z ){
18786       oputb(z, (int)(pcEnd-z));
18787       z = pcEnd;
18788     }
18789     if( z >= pcLimit ) break;
18790     c = *(z++);
18791     switch( c ){
18792     case '"': case '\\':
18793       cbsSay = (char)c;
18794       break;
18795     case '\b': cbsSay = 'b'; break;
18796     case '\f': cbsSay = 'f'; break;
18797     case '\n': cbsSay = 'n'; break;
18798     case '\r': cbsSay = 'r'; break;
18799     case '\t': cbsSay = 't'; break;
18800     default: cbsSay = 0; break;
18801     }
18802     if( cbsSay ){
18803       ace[1] = cbsSay;
18804       oputz(ace);
18805     }else if( c<=0x1f ){
18806       oputf("u%04x", c);
18807     }else{
18808       ace[1] = (char)c;
18809       oputz(ace+1);
18810     }
18811   }
18812   oputz(zq);
18813 }
18814 
18815 /*
18816 ** Output the given string with characters that are special to
18817 ** HTML escaped.
18818 */
output_html_string(const char * z)18819 static void output_html_string(const char *z){
18820   int i;
18821   if( z==0 ) z = "";
18822   while( *z ){
18823     for(i=0;   z[i]
18824             && z[i]!='<'
18825             && z[i]!='&'
18826             && z[i]!='>'
18827             && z[i]!='\"'
18828             && z[i]!='\'';
18829         i++){}
18830     if( i>0 ){
18831       oputf("%.*s",i,z);
18832     }
18833     if( z[i]=='<' ){
18834       oputz("&lt;");
18835     }else if( z[i]=='&' ){
18836       oputz("&amp;");
18837     }else if( z[i]=='>' ){
18838       oputz("&gt;");
18839     }else if( z[i]=='\"' ){
18840       oputz("&quot;");
18841     }else if( z[i]=='\'' ){
18842       oputz("&#39;");
18843     }else{
18844       break;
18845     }
18846     z += i + 1;
18847   }
18848 }
18849 
18850 /*
18851 ** If a field contains any character identified by a 1 in the following
18852 ** array, then the string must be quoted for CSV.
18853 */
18854 static const char needCsvQuote[] = {
18855   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18856   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18857   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
18858   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18859   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18860   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18861   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18862   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 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   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18867   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18868   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18869   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18870   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18871 };
18872 
18873 /*
18874 ** Output a single term of CSV.  Actually, p->colSeparator is used for
18875 ** the separator, which may or may not be a comma.  p->nullValue is
18876 ** the null value.  Strings are quoted if necessary.  The separator
18877 ** is only issued if bSep is true.
18878 */
output_csv(ShellState * p,const char * z,int bSep)18879 static void output_csv(ShellState *p, const char *z, int bSep){
18880   if( z==0 ){
18881     oputf("%s",p->nullValue);
18882   }else{
18883     unsigned i;
18884     for(i=0; z[i]; i++){
18885       if( needCsvQuote[((unsigned char*)z)[i]] ){
18886         i = 0;
18887         break;
18888       }
18889     }
18890     if( i==0 || strstr(z, p->colSeparator)!=0 ){
18891       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
18892       shell_check_oom(zQuoted);
18893       oputz(zQuoted);
18894       sqlite3_free(zQuoted);
18895     }else{
18896       oputz(z);
18897     }
18898   }
18899   if( bSep ){
18900     oputz(p->colSeparator);
18901   }
18902 }
18903 
18904 /*
18905 ** This routine runs when the user presses Ctrl-C
18906 */
interrupt_handler(int NotUsed)18907 static void interrupt_handler(int NotUsed){
18908   UNUSED_PARAMETER(NotUsed);
18909   if( ++seenInterrupt>1 ) exit(1);
18910   if( globalDb ) sqlite3_interrupt(globalDb);
18911 }
18912 
18913 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
18914 /*
18915 ** This routine runs for console events (e.g. Ctrl-C) on Win32
18916 */
ConsoleCtrlHandler(DWORD dwCtrlType)18917 static BOOL WINAPI ConsoleCtrlHandler(
18918   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
18919 ){
18920   if( dwCtrlType==CTRL_C_EVENT ){
18921     interrupt_handler(0);
18922     return TRUE;
18923   }
18924   return FALSE;
18925 }
18926 #endif
18927 
18928 #ifndef SQLITE_OMIT_AUTHORIZATION
18929 /*
18930 ** This authorizer runs in safe mode.
18931 */
safeModeAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)18932 static int safeModeAuth(
18933   void *pClientData,
18934   int op,
18935   const char *zA1,
18936   const char *zA2,
18937   const char *zA3,
18938   const char *zA4
18939 ){
18940   ShellState *p = (ShellState*)pClientData;
18941   static const char *azProhibitedFunctions[] = {
18942     "edit",
18943     "fts3_tokenizer",
18944     "load_extension",
18945     "readfile",
18946     "writefile",
18947     "zipfile",
18948     "zipfile_cds",
18949   };
18950   UNUSED_PARAMETER(zA1);
18951   UNUSED_PARAMETER(zA3);
18952   UNUSED_PARAMETER(zA4);
18953   switch( op ){
18954     case SQLITE_ATTACH: {
18955 #ifndef SQLITE_SHELL_FIDDLE
18956       /* In WASM builds the filesystem is a virtual sandbox, so
18957       ** there's no harm in using ATTACH. */
18958       failIfSafeMode(p, "cannot run ATTACH in safe mode");
18959 #endif
18960       break;
18961     }
18962     case SQLITE_FUNCTION: {
18963       int i;
18964       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
18965         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
18966           failIfSafeMode(p, "cannot use the %s() function in safe mode",
18967                          azProhibitedFunctions[i]);
18968         }
18969       }
18970       break;
18971     }
18972   }
18973   return SQLITE_OK;
18974 }
18975 
18976 /*
18977 ** When the ".auth ON" is set, the following authorizer callback is
18978 ** invoked.  It always returns SQLITE_OK.
18979 */
shellAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)18980 static int shellAuth(
18981   void *pClientData,
18982   int op,
18983   const char *zA1,
18984   const char *zA2,
18985   const char *zA3,
18986   const char *zA4
18987 ){
18988   ShellState *p = (ShellState*)pClientData;
18989   static const char *azAction[] = { 0,
18990      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
18991      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
18992      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
18993      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
18994      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
18995      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
18996      "PRAGMA",               "READ",                 "SELECT",
18997      "TRANSACTION",          "UPDATE",               "ATTACH",
18998      "DETACH",               "ALTER_TABLE",          "REINDEX",
18999      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
19000      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
19001   };
19002   int i;
19003   const char *az[4];
19004   az[0] = zA1;
19005   az[1] = zA2;
19006   az[2] = zA3;
19007   az[3] = zA4;
19008   oputf("authorizer: %s", azAction[op]);
19009   for(i=0; i<4; i++){
19010     oputz(" ");
19011     if( az[i] ){
19012       output_c_string(az[i]);
19013     }else{
19014       oputz("NULL");
19015     }
19016   }
19017   oputz("\n");
19018   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
19019   return SQLITE_OK;
19020 }
19021 #endif
19022 
19023 /*
19024 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
19025 **
19026 ** This routine converts some CREATE TABLE statements for shadow tables
19027 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
19028 **
19029 ** If the schema statement in z[] contains a start-of-comment and if
19030 ** sqlite3_complete() returns false, try to terminate the comment before
19031 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
19032 */
printSchemaLine(const char * z,const char * zTail)19033 static void printSchemaLine(const char *z, const char *zTail){
19034   char *zToFree = 0;
19035   if( z==0 ) return;
19036   if( zTail==0 ) return;
19037   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
19038     const char *zOrig = z;
19039     static const char *azTerm[] = { "", "*/", "\n" };
19040     int i;
19041     for(i=0; i<ArraySize(azTerm); i++){
19042       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
19043       shell_check_oom(zNew);
19044       if( sqlite3_complete(zNew) ){
19045         size_t n = strlen(zNew);
19046         zNew[n-1] = 0;
19047         zToFree = zNew;
19048         z = zNew;
19049         break;
19050       }
19051       sqlite3_free(zNew);
19052     }
19053   }
19054   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
19055     oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
19056   }else{
19057     oputf("%s%s", z, zTail);
19058   }
19059   sqlite3_free(zToFree);
19060 }
printSchemaLineN(char * z,int n,const char * zTail)19061 static void printSchemaLineN(char *z, int n, const char *zTail){
19062   char c = z[n];
19063   z[n] = 0;
19064   printSchemaLine(z, zTail);
19065   z[n] = c;
19066 }
19067 
19068 /*
19069 ** Return true if string z[] has nothing but whitespace and comments to the
19070 ** end of the first line.
19071 */
wsToEol(const char * z)19072 static int wsToEol(const char *z){
19073   int i;
19074   for(i=0; z[i]; i++){
19075     if( z[i]=='\n' ) return 1;
19076     if( IsSpace(z[i]) ) continue;
19077     if( z[i]=='-' && z[i+1]=='-' ) return 1;
19078     return 0;
19079   }
19080   return 1;
19081 }
19082 
19083 /*
19084 ** Add a new entry to the EXPLAIN QUERY PLAN data
19085 */
eqp_append(ShellState * p,int iEqpId,int p2,const char * zText)19086 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
19087   EQPGraphRow *pNew;
19088   i64 nText;
19089   if( zText==0 ) return;
19090   nText = strlen(zText);
19091   if( p->autoEQPtest ){
19092     oputf("%d,%d,%s\n", iEqpId, p2, zText);
19093   }
19094   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
19095   shell_check_oom(pNew);
19096   pNew->iEqpId = iEqpId;
19097   pNew->iParentId = p2;
19098   memcpy(pNew->zText, zText, nText+1);
19099   pNew->pNext = 0;
19100   if( p->sGraph.pLast ){
19101     p->sGraph.pLast->pNext = pNew;
19102   }else{
19103     p->sGraph.pRow = pNew;
19104   }
19105   p->sGraph.pLast = pNew;
19106 }
19107 
19108 /*
19109 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
19110 ** in p->sGraph.
19111 */
eqp_reset(ShellState * p)19112 static void eqp_reset(ShellState *p){
19113   EQPGraphRow *pRow, *pNext;
19114   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
19115     pNext = pRow->pNext;
19116     sqlite3_free(pRow);
19117   }
19118   memset(&p->sGraph, 0, sizeof(p->sGraph));
19119 }
19120 
19121 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
19122 ** pOld, or return the first such line if pOld is NULL
19123 */
eqp_next_row(ShellState * p,int iEqpId,EQPGraphRow * pOld)19124 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
19125   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
19126   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
19127   return pRow;
19128 }
19129 
19130 /* Render a single level of the graph that has iEqpId as its parent.  Called
19131 ** recursively to render sublevels.
19132 */
eqp_render_level(ShellState * p,int iEqpId)19133 static void eqp_render_level(ShellState *p, int iEqpId){
19134   EQPGraphRow *pRow, *pNext;
19135   i64 n = strlen(p->sGraph.zPrefix);
19136   char *z;
19137   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
19138     pNext = eqp_next_row(p, iEqpId, pRow);
19139     z = pRow->zText;
19140     oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
19141     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
19142       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
19143       eqp_render_level(p, pRow->iEqpId);
19144       p->sGraph.zPrefix[n] = 0;
19145     }
19146   }
19147 }
19148 
19149 /*
19150 ** Display and reset the EXPLAIN QUERY PLAN data
19151 */
eqp_render(ShellState * p,i64 nCycle)19152 static void eqp_render(ShellState *p, i64 nCycle){
19153   EQPGraphRow *pRow = p->sGraph.pRow;
19154   if( pRow ){
19155     if( pRow->zText[0]=='-' ){
19156       if( pRow->pNext==0 ){
19157         eqp_reset(p);
19158         return;
19159       }
19160       oputf("%s\n", pRow->zText+3);
19161       p->sGraph.pRow = pRow->pNext;
19162       sqlite3_free(pRow);
19163     }else if( nCycle>0 ){
19164       oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
19165     }else{
19166       oputz("QUERY PLAN\n");
19167     }
19168     p->sGraph.zPrefix[0] = 0;
19169     eqp_render_level(p, 0);
19170     eqp_reset(p);
19171   }
19172 }
19173 
19174 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19175 /*
19176 ** Progress handler callback.
19177 */
progress_handler(void * pClientData)19178 static int progress_handler(void *pClientData) {
19179   ShellState *p = (ShellState*)pClientData;
19180   p->nProgress++;
19181   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
19182     oputf("Progress limit reached (%u)\n", p->nProgress);
19183     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
19184     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
19185     return 1;
19186   }
19187   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
19188     oputf("Progress %u\n", p->nProgress);
19189   }
19190   return 0;
19191 }
19192 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
19193 
19194 /*
19195 ** Print N dashes
19196 */
print_dashes(int N)19197 static void print_dashes(int N){
19198   const char zDash[] = "--------------------------------------------------";
19199   const int nDash = sizeof(zDash) - 1;
19200   while( N>nDash ){
19201     oputz(zDash);
19202     N -= nDash;
19203   }
19204   oputf("%.*s", N, zDash);
19205 }
19206 
19207 /*
19208 ** Print a markdown or table-style row separator using ascii-art
19209 */
print_row_separator(ShellState * p,int nArg,const char * zSep)19210 static void print_row_separator(
19211   ShellState *p,
19212   int nArg,
19213   const char *zSep
19214 ){
19215   int i;
19216   if( nArg>0 ){
19217     oputz(zSep);
19218     print_dashes(p->actualWidth[0]+2);
19219     for(i=1; i<nArg; i++){
19220       oputz(zSep);
19221       print_dashes(p->actualWidth[i]+2);
19222     }
19223     oputz(zSep);
19224   }
19225   oputz("\n");
19226 }
19227 
19228 /*
19229 ** This is the callback routine that the shell
19230 ** invokes for each row of a query result.
19231 */
shell_callback(void * pArg,int nArg,char ** azArg,char ** azCol,int * aiType)19232 static int shell_callback(
19233   void *pArg,
19234   int nArg,        /* Number of result columns */
19235   char **azArg,    /* Text of each result column */
19236   char **azCol,    /* Column names */
19237   int *aiType      /* Column types.  Might be NULL */
19238 ){
19239   int i;
19240   ShellState *p = (ShellState*)pArg;
19241 
19242   if( azArg==0 ) return 0;
19243   switch( p->cMode ){
19244     case MODE_Count:
19245     case MODE_Off: {
19246       break;
19247     }
19248     case MODE_Line: {
19249       int w = 5;
19250       if( azArg==0 ) break;
19251       for(i=0; i<nArg; i++){
19252         int len = strlen30(azCol[i] ? azCol[i] : "");
19253         if( len>w ) w = len;
19254       }
19255       if( p->cnt++>0 ) oputz(p->rowSeparator);
19256       for(i=0; i<nArg; i++){
19257         oputf("%*s = %s%s", w, azCol[i],
19258               azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
19259       }
19260       break;
19261     }
19262     case MODE_ScanExp:
19263     case MODE_Explain: {
19264       static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
19265       static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
19266       static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
19267       static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
19268 
19269       const int *aWidth = aExplainWidth;
19270       const int *aMap = aExplainMap;
19271       int nWidth = ArraySize(aExplainWidth);
19272       int iIndent = 1;
19273 
19274       if( p->cMode==MODE_ScanExp ){
19275         aWidth = aScanExpWidth;
19276         aMap = aScanExpMap;
19277         nWidth = ArraySize(aScanExpWidth);
19278         iIndent = 3;
19279       }
19280       if( nArg>nWidth ) nArg = nWidth;
19281 
19282       /* If this is the first row seen, print out the headers */
19283       if( p->cnt++==0 ){
19284         for(i=0; i<nArg; i++){
19285           utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
19286           oputz(i==nArg-1 ? "\n" : "  ");
19287         }
19288         for(i=0; i<nArg; i++){
19289           print_dashes(aWidth[i]);
19290           oputz(i==nArg-1 ? "\n" : "  ");
19291         }
19292       }
19293 
19294       /* If there is no data, exit early. */
19295       if( azArg==0 ) break;
19296 
19297       for(i=0; i<nArg; i++){
19298         const char *zSep = "  ";
19299         int w = aWidth[i];
19300         const char *zVal = azArg[ aMap[i] ];
19301         if( i==nArg-1 ) w = 0;
19302         if( zVal && strlenChar(zVal)>w ){
19303           w = strlenChar(zVal);
19304           zSep = " ";
19305         }
19306         if( i==iIndent && p->aiIndent && p->pStmt ){
19307           if( p->iIndent<p->nIndent ){
19308             oputf("%*.s", p->aiIndent[p->iIndent], "");
19309           }
19310           p->iIndent++;
19311         }
19312         utf8_width_print(w, zVal ? zVal : p->nullValue);
19313         oputz(i==nArg-1 ? "\n" : zSep);
19314       }
19315       break;
19316     }
19317     case MODE_Semi: {   /* .schema and .fullschema output */
19318       printSchemaLine(azArg[0], ";\n");
19319       break;
19320     }
19321     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
19322       char *z;
19323       int j;
19324       int nParen = 0;
19325       char cEnd = 0;
19326       char c;
19327       int nLine = 0;
19328       assert( nArg==1 );
19329       if( azArg[0]==0 ) break;
19330       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
19331        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
19332       ){
19333         oputf("%s;\n", azArg[0]);
19334         break;
19335       }
19336       z = sqlite3_mprintf("%s", azArg[0]);
19337       shell_check_oom(z);
19338       j = 0;
19339       for(i=0; IsSpace(z[i]); i++){}
19340       for(; (c = z[i])!=0; i++){
19341         if( IsSpace(c) ){
19342           if( z[j-1]=='\r' ) z[j-1] = '\n';
19343           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
19344         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
19345           j--;
19346         }
19347         z[j++] = c;
19348       }
19349       while( j>0 && IsSpace(z[j-1]) ){ j--; }
19350       z[j] = 0;
19351       if( strlen30(z)>=79 ){
19352         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
19353           if( c==cEnd ){
19354             cEnd = 0;
19355           }else if( c=='"' || c=='\'' || c=='`' ){
19356             cEnd = c;
19357           }else if( c=='[' ){
19358             cEnd = ']';
19359           }else if( c=='-' && z[i+1]=='-' ){
19360             cEnd = '\n';
19361           }else if( c=='(' ){
19362             nParen++;
19363           }else if( c==')' ){
19364             nParen--;
19365             if( nLine>0 && nParen==0 && j>0 ){
19366               printSchemaLineN(z, j, "\n");
19367               j = 0;
19368             }
19369           }
19370           z[j++] = c;
19371           if( nParen==1 && cEnd==0
19372            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
19373           ){
19374             if( c=='\n' ) j--;
19375             printSchemaLineN(z, j, "\n  ");
19376             j = 0;
19377             nLine++;
19378             while( IsSpace(z[i+1]) ){ i++; }
19379           }
19380         }
19381         z[j] = 0;
19382       }
19383       printSchemaLine(z, ";\n");
19384       sqlite3_free(z);
19385       break;
19386     }
19387     case MODE_List: {
19388       if( p->cnt++==0 && p->showHeader ){
19389         for(i=0; i<nArg; i++){
19390           oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
19391         }
19392       }
19393       if( azArg==0 ) break;
19394       for(i=0; i<nArg; i++){
19395         char *z = azArg[i];
19396         if( z==0 ) z = p->nullValue;
19397         oputz(z);
19398         oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
19399       }
19400       break;
19401     }
19402     case MODE_Html: {
19403       if( p->cnt++==0 && p->showHeader ){
19404         oputz("<TR>");
19405         for(i=0; i<nArg; i++){
19406           oputz("<TH>");
19407           output_html_string(azCol[i]);
19408           oputz("</TH>\n");
19409         }
19410         oputz("</TR>\n");
19411       }
19412       if( azArg==0 ) break;
19413       oputz("<TR>");
19414       for(i=0; i<nArg; i++){
19415         oputz("<TD>");
19416         output_html_string(azArg[i] ? azArg[i] : p->nullValue);
19417         oputz("</TD>\n");
19418       }
19419       oputz("</TR>\n");
19420       break;
19421     }
19422     case MODE_Tcl: {
19423       if( p->cnt++==0 && p->showHeader ){
19424         for(i=0; i<nArg; i++){
19425           output_c_string(azCol[i] ? azCol[i] : "");
19426           if(i<nArg-1) oputz(p->colSeparator);
19427         }
19428         oputz(p->rowSeparator);
19429       }
19430       if( azArg==0 ) break;
19431       for(i=0; i<nArg; i++){
19432         output_c_string(azArg[i] ? azArg[i] : p->nullValue);
19433         if(i<nArg-1) oputz(p->colSeparator);
19434       }
19435       oputz(p->rowSeparator);
19436       break;
19437     }
19438     case MODE_Csv: {
19439       setBinaryMode(p->out, 1);
19440       if( p->cnt++==0 && p->showHeader ){
19441         for(i=0; i<nArg; i++){
19442           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
19443         }
19444         oputz(p->rowSeparator);
19445       }
19446       if( nArg>0 ){
19447         for(i=0; i<nArg; i++){
19448           output_csv(p, azArg[i], i<nArg-1);
19449         }
19450         oputz(p->rowSeparator);
19451       }
19452       setTextMode(p->out, 1);
19453       break;
19454     }
19455     case MODE_Insert: {
19456       if( azArg==0 ) break;
19457       oputf("INSERT INTO %s",p->zDestTable);
19458       if( p->showHeader ){
19459         oputz("(");
19460         for(i=0; i<nArg; i++){
19461           if( i>0 ) oputz(",");
19462           if( quoteChar(azCol[i]) ){
19463             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
19464             shell_check_oom(z);
19465             oputz(z);
19466             sqlite3_free(z);
19467           }else{
19468             oputf("%s", azCol[i]);
19469           }
19470         }
19471         oputz(")");
19472       }
19473       p->cnt++;
19474       for(i=0; i<nArg; i++){
19475         oputz(i>0 ? "," : " VALUES(");
19476         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19477           oputz("NULL");
19478         }else if( aiType && aiType[i]==SQLITE_TEXT ){
19479           if( ShellHasFlag(p, SHFLG_Newlines) ){
19480             output_quoted_string(azArg[i]);
19481           }else{
19482             output_quoted_escaped_string(azArg[i]);
19483           }
19484         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
19485           oputz(azArg[i]);
19486         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19487           char z[50];
19488           double r = sqlite3_column_double(p->pStmt, i);
19489           sqlite3_uint64 ur;
19490           memcpy(&ur,&r,sizeof(r));
19491           if( ur==0x7ff0000000000000LL ){
19492             oputz("9.0e+999");
19493           }else if( ur==0xfff0000000000000LL ){
19494             oputz("-9.0e+999");
19495           }else{
19496             sqlite3_int64 ir = (sqlite3_int64)r;
19497             if( r==(double)ir ){
19498               sqlite3_snprintf(50,z,"%lld.0", ir);
19499             }else{
19500               sqlite3_snprintf(50,z,"%!.20g", r);
19501             }
19502             oputz(z);
19503           }
19504         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19505           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19506           int nBlob = sqlite3_column_bytes(p->pStmt, i);
19507           output_hex_blob(pBlob, nBlob);
19508         }else if( isNumber(azArg[i], 0) ){
19509           oputz(azArg[i]);
19510         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
19511           output_quoted_string(azArg[i]);
19512         }else{
19513           output_quoted_escaped_string(azArg[i]);
19514         }
19515       }
19516       oputz(");\n");
19517       break;
19518     }
19519     case MODE_Json: {
19520       if( azArg==0 ) break;
19521       if( p->cnt==0 ){
19522         fputs("[{", p->out);
19523       }else{
19524         fputs(",\n{", p->out);
19525       }
19526       p->cnt++;
19527       for(i=0; i<nArg; i++){
19528         output_json_string(azCol[i], -1);
19529         oputz(":");
19530         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19531           oputz("null");
19532         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19533           char z[50];
19534           double r = sqlite3_column_double(p->pStmt, i);
19535           sqlite3_uint64 ur;
19536           memcpy(&ur,&r,sizeof(r));
19537           if( ur==0x7ff0000000000000LL ){
19538             oputz("9.0e+999");
19539           }else if( ur==0xfff0000000000000LL ){
19540             oputz("-9.0e+999");
19541           }else{
19542             sqlite3_snprintf(50,z,"%!.20g", r);
19543             oputz(z);
19544           }
19545         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19546           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19547           int nBlob = sqlite3_column_bytes(p->pStmt, i);
19548           output_json_string(pBlob, nBlob);
19549         }else if( aiType && aiType[i]==SQLITE_TEXT ){
19550           output_json_string(azArg[i], -1);
19551         }else{
19552           oputz(azArg[i]);
19553         }
19554         if( i<nArg-1 ){
19555           oputz(",");
19556         }
19557       }
19558       oputz("}");
19559       break;
19560     }
19561     case MODE_Quote: {
19562       if( azArg==0 ) break;
19563       if( p->cnt==0 && p->showHeader ){
19564         for(i=0; i<nArg; i++){
19565           if( i>0 ) fputs(p->colSeparator, p->out);
19566           output_quoted_string(azCol[i]);
19567         }
19568         fputs(p->rowSeparator, p->out);
19569       }
19570       p->cnt++;
19571       for(i=0; i<nArg; i++){
19572         if( i>0 ) fputs(p->colSeparator, p->out);
19573         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19574           oputz("NULL");
19575         }else if( aiType && aiType[i]==SQLITE_TEXT ){
19576           output_quoted_string(azArg[i]);
19577         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
19578           oputz(azArg[i]);
19579         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19580           char z[50];
19581           double r = sqlite3_column_double(p->pStmt, i);
19582           sqlite3_snprintf(50,z,"%!.20g", r);
19583           oputz(z);
19584         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19585           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19586           int nBlob = sqlite3_column_bytes(p->pStmt, i);
19587           output_hex_blob(pBlob, nBlob);
19588         }else if( isNumber(azArg[i], 0) ){
19589           oputz(azArg[i]);
19590         }else{
19591           output_quoted_string(azArg[i]);
19592         }
19593       }
19594       fputs(p->rowSeparator, p->out);
19595       break;
19596     }
19597     case MODE_Ascii: {
19598       if( p->cnt++==0 && p->showHeader ){
19599         for(i=0; i<nArg; i++){
19600           if( i>0 ) oputz(p->colSeparator);
19601           oputz(azCol[i] ? azCol[i] : "");
19602         }
19603         oputz(p->rowSeparator);
19604       }
19605       if( azArg==0 ) break;
19606       for(i=0; i<nArg; i++){
19607         if( i>0 ) oputz(p->colSeparator);
19608         oputz(azArg[i] ? azArg[i] : p->nullValue);
19609       }
19610       oputz(p->rowSeparator);
19611       break;
19612     }
19613     case MODE_EQP: {
19614       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
19615       break;
19616     }
19617   }
19618   return 0;
19619 }
19620 
19621 /*
19622 ** This is the callback routine that the SQLite library
19623 ** invokes for each row of a query result.
19624 */
callback(void * pArg,int nArg,char ** azArg,char ** azCol)19625 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
19626   /* since we don't have type info, call the shell_callback with a NULL value */
19627   return shell_callback(pArg, nArg, azArg, azCol, NULL);
19628 }
19629 
19630 /*
19631 ** This is the callback routine from sqlite3_exec() that appends all
19632 ** output onto the end of a ShellText object.
19633 */
captureOutputCallback(void * pArg,int nArg,char ** azArg,char ** az)19634 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
19635   ShellText *p = (ShellText*)pArg;
19636   int i;
19637   UNUSED_PARAMETER(az);
19638   if( azArg==0 ) return 0;
19639   if( p->n ) appendText(p, "|", 0);
19640   for(i=0; i<nArg; i++){
19641     if( i ) appendText(p, ",", 0);
19642     if( azArg[i] ) appendText(p, azArg[i], 0);
19643   }
19644   return 0;
19645 }
19646 
19647 /*
19648 ** Generate an appropriate SELFTEST table in the main database.
19649 */
createSelftestTable(ShellState * p)19650 static void createSelftestTable(ShellState *p){
19651   char *zErrMsg = 0;
19652   sqlite3_exec(p->db,
19653     "SAVEPOINT selftest_init;\n"
19654     "CREATE TABLE IF NOT EXISTS selftest(\n"
19655     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
19656     "  op TEXT,\n"                   /* Operator:  memo run */
19657     "  cmd TEXT,\n"                  /* Command text */
19658     "  ans TEXT\n"                   /* Desired answer */
19659     ");"
19660     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
19661     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
19662     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
19663     "         'memo','Tests generated by --init');\n"
19664     "INSERT INTO [_shell$self]\n"
19665     "  SELECT 'run',\n"
19666     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
19667                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
19668     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
19669                           "FROM sqlite_schema ORDER BY 2',224));\n"
19670     "INSERT INTO [_shell$self]\n"
19671     "  SELECT 'run',"
19672     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
19673     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
19674     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
19675     "  FROM (\n"
19676     "    SELECT name FROM sqlite_schema\n"
19677     "     WHERE type='table'\n"
19678     "       AND name<>'selftest'\n"
19679     "       AND coalesce(rootpage,0)>0\n"
19680     "  )\n"
19681     " ORDER BY name;\n"
19682     "INSERT INTO [_shell$self]\n"
19683     "  VALUES('run','PRAGMA integrity_check','ok');\n"
19684     "INSERT INTO selftest(tno,op,cmd,ans)"
19685     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
19686     "DROP TABLE [_shell$self];"
19687     ,0,0,&zErrMsg);
19688   if( zErrMsg ){
19689     eputf("SELFTEST initialization failure: %s\n", zErrMsg);
19690     sqlite3_free(zErrMsg);
19691   }
19692   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
19693 }
19694 
19695 
19696 /*
19697 ** Set the destination table field of the ShellState structure to
19698 ** the name of the table given.  Escape any quote characters in the
19699 ** table name.
19700 */
set_table_name(ShellState * p,const char * zName)19701 static void set_table_name(ShellState *p, const char *zName){
19702   int i, n;
19703   char cQuote;
19704   char *z;
19705 
19706   if( p->zDestTable ){
19707     free(p->zDestTable);
19708     p->zDestTable = 0;
19709   }
19710   if( zName==0 ) return;
19711   cQuote = quoteChar(zName);
19712   n = strlen30(zName);
19713   if( cQuote ) n += n+2;
19714   z = p->zDestTable = malloc( n+1 );
19715   shell_check_oom(z);
19716   n = 0;
19717   if( cQuote ) z[n++] = cQuote;
19718   for(i=0; zName[i]; i++){
19719     z[n++] = zName[i];
19720     if( zName[i]==cQuote ) z[n++] = cQuote;
19721   }
19722   if( cQuote ) z[n++] = cQuote;
19723   z[n] = 0;
19724 }
19725 
19726 /*
19727 ** Maybe construct two lines of text that point out the position of a
19728 ** syntax error.  Return a pointer to the text, in memory obtained from
19729 ** sqlite3_malloc().  Or, if the most recent error does not involve a
19730 ** specific token that we can point to, return an empty string.
19731 **
19732 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
19733 ** and should be released by the caller invoking sqlite3_free().
19734 */
shell_error_context(const char * zSql,sqlite3 * db)19735 static char *shell_error_context(const char *zSql, sqlite3 *db){
19736   int iOffset;
19737   size_t len;
19738   char *zCode;
19739   char *zMsg;
19740   int i;
19741   if( db==0
19742    || zSql==0
19743    || (iOffset = sqlite3_error_offset(db))<0
19744    || iOffset>=(int)strlen(zSql)
19745   ){
19746     return sqlite3_mprintf("");
19747   }
19748   while( iOffset>50 ){
19749     iOffset--;
19750     zSql++;
19751     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
19752   }
19753   len = strlen(zSql);
19754   if( len>78 ){
19755     len = 78;
19756     while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
19757   }
19758   zCode = sqlite3_mprintf("%.*s", len, zSql);
19759   shell_check_oom(zCode);
19760   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
19761   if( iOffset<25 ){
19762     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
19763   }else{
19764     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
19765   }
19766   return zMsg;
19767 }
19768 
19769 
19770 /*
19771 ** Execute a query statement that will generate SQL output.  Print
19772 ** the result columns, comma-separated, on a line and then add a
19773 ** semicolon terminator to the end of that line.
19774 **
19775 ** If the number of columns is 1 and that column contains text "--"
19776 ** then write the semicolon on a separate line.  That way, if a
19777 ** "--" comment occurs at the end of the statement, the comment
19778 ** won't consume the semicolon terminator.
19779 */
run_table_dump_query(ShellState * p,const char * zSelect)19780 static int run_table_dump_query(
19781   ShellState *p,           /* Query context */
19782   const char *zSelect      /* SELECT statement to extract content */
19783 ){
19784   sqlite3_stmt *pSelect;
19785   int rc;
19786   int nResult;
19787   int i;
19788   const char *z;
19789   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
19790   if( rc!=SQLITE_OK || !pSelect ){
19791     char *zContext = shell_error_context(zSelect, p->db);
19792     oputf("/**** ERROR: (%d) %s *****/\n%s",
19793           rc, sqlite3_errmsg(p->db), zContext);
19794     sqlite3_free(zContext);
19795     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19796     return rc;
19797   }
19798   rc = sqlite3_step(pSelect);
19799   nResult = sqlite3_column_count(pSelect);
19800   while( rc==SQLITE_ROW ){
19801     z = (const char*)sqlite3_column_text(pSelect, 0);
19802     oputf("%s", z);
19803     for(i=1; i<nResult; i++){
19804       oputf(",%s", sqlite3_column_text(pSelect, i));
19805     }
19806     if( z==0 ) z = "";
19807     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
19808     if( z[0] ){
19809       oputz("\n;\n");
19810     }else{
19811       oputz(";\n");
19812     }
19813     rc = sqlite3_step(pSelect);
19814   }
19815   rc = sqlite3_finalize(pSelect);
19816   if( rc!=SQLITE_OK ){
19817     oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
19818     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19819   }
19820   return rc;
19821 }
19822 
19823 /*
19824 ** Allocate space and save off string indicating current error.
19825 */
save_err_msg(sqlite3 * db,const char * zPhase,int rc,const char * zSql)19826 static char *save_err_msg(
19827   sqlite3 *db,           /* Database to query */
19828   const char *zPhase,    /* When the error occurs */
19829   int rc,                /* Error code returned from API */
19830   const char *zSql       /* SQL string, or NULL */
19831 ){
19832   char *zErr;
19833   char *zContext;
19834   sqlite3_str *pStr = sqlite3_str_new(0);
19835   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
19836   if( rc>1 ){
19837     sqlite3_str_appendf(pStr, " (%d)", rc);
19838   }
19839   zContext = shell_error_context(zSql, db);
19840   if( zContext ){
19841     sqlite3_str_appendall(pStr, zContext);
19842     sqlite3_free(zContext);
19843   }
19844   zErr = sqlite3_str_finish(pStr);
19845   shell_check_oom(zErr);
19846   return zErr;
19847 }
19848 
19849 #ifdef __linux__
19850 /*
19851 ** Attempt to display I/O stats on Linux using /proc/PID/io
19852 */
displayLinuxIoStats(void)19853 static void displayLinuxIoStats(void){
19854   FILE *in;
19855   char z[200];
19856   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
19857   in = fopen(z, "rb");
19858   if( in==0 ) return;
19859   while( fgets(z, sizeof(z), in)!=0 ){
19860     static const struct {
19861       const char *zPattern;
19862       const char *zDesc;
19863     } aTrans[] = {
19864       { "rchar: ",                  "Bytes received by read():" },
19865       { "wchar: ",                  "Bytes sent to write():"    },
19866       { "syscr: ",                  "Read() system calls:"      },
19867       { "syscw: ",                  "Write() system calls:"     },
19868       { "read_bytes: ",             "Bytes read from storage:"  },
19869       { "write_bytes: ",            "Bytes written to storage:" },
19870       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
19871     };
19872     int i;
19873     for(i=0; i<ArraySize(aTrans); i++){
19874       int n = strlen30(aTrans[i].zPattern);
19875       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
19876         oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
19877         break;
19878       }
19879     }
19880   }
19881   fclose(in);
19882 }
19883 #endif
19884 
19885 /*
19886 ** Display a single line of status using 64-bit values.
19887 */
displayStatLine(char * zLabel,char * zFormat,int iStatusCtrl,int bReset)19888 static void displayStatLine(
19889   char *zLabel,             /* Label for this one line */
19890   char *zFormat,            /* Format for the result */
19891   int iStatusCtrl,          /* Which status to display */
19892   int bReset                /* True to reset the stats */
19893 ){
19894   sqlite3_int64 iCur = -1;
19895   sqlite3_int64 iHiwtr = -1;
19896   int i, nPercent;
19897   char zLine[200];
19898   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
19899   for(i=0, nPercent=0; zFormat[i]; i++){
19900     if( zFormat[i]=='%' ) nPercent++;
19901   }
19902   if( nPercent>1 ){
19903     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
19904   }else{
19905     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
19906   }
19907   oputf("%-36s %s\n", zLabel, zLine);
19908 }
19909 
19910 /*
19911 ** Display memory stats.
19912 */
display_stats(sqlite3 * db,ShellState * pArg,int bReset)19913 static int display_stats(
19914   sqlite3 *db,                /* Database to query */
19915   ShellState *pArg,           /* Pointer to ShellState */
19916   int bReset                  /* True to reset the stats */
19917 ){
19918   int iCur;
19919   int iHiwtr;
19920   if( pArg==0 || pArg->out==0 ) return 0;
19921 
19922   if( pArg->pStmt && pArg->statsOn==2 ){
19923     int nCol, i, x;
19924     sqlite3_stmt *pStmt = pArg->pStmt;
19925     char z[100];
19926     nCol = sqlite3_column_count(pStmt);
19927     oputf("%-36s %d\n", "Number of output columns:", nCol);
19928     for(i=0; i<nCol; i++){
19929       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
19930       oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
19931 #ifndef SQLITE_OMIT_DECLTYPE
19932       sqlite3_snprintf(30, z+x, "declared type:");
19933       oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
19934 #endif
19935 #ifdef SQLITE_ENABLE_COLUMN_METADATA
19936       sqlite3_snprintf(30, z+x, "database name:");
19937       oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
19938       sqlite3_snprintf(30, z+x, "table name:");
19939       oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
19940       sqlite3_snprintf(30, z+x, "origin name:");
19941       oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
19942 #endif
19943     }
19944   }
19945 
19946   if( pArg->statsOn==3 ){
19947     if( pArg->pStmt ){
19948       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
19949       oputf("VM-steps: %d\n", iCur);
19950     }
19951     return 0;
19952   }
19953 
19954   displayStatLine("Memory Used:",
19955      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
19956   displayStatLine("Number of Outstanding Allocations:",
19957      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
19958   if( pArg->shellFlgs & SHFLG_Pagecache ){
19959     displayStatLine("Number of Pcache Pages Used:",
19960        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
19961   }
19962   displayStatLine("Number of Pcache Overflow Bytes:",
19963      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
19964   displayStatLine("Largest Allocation:",
19965      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
19966   displayStatLine("Largest Pcache Allocation:",
19967      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
19968 #ifdef YYTRACKMAXSTACKDEPTH
19969   displayStatLine("Deepest Parser Stack:",
19970      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
19971 #endif
19972 
19973   if( db ){
19974     if( pArg->shellFlgs & SHFLG_Lookaside ){
19975       iHiwtr = iCur = -1;
19976       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
19977                         &iCur, &iHiwtr, bReset);
19978       oputf("Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
19979       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
19980                         &iCur, &iHiwtr, bReset);
19981       oputf("Successful lookaside attempts:       %d\n", iHiwtr);
19982       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
19983                         &iCur, &iHiwtr, bReset);
19984       oputf("Lookaside failures due to size:      %d\n", iHiwtr);
19985       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
19986                         &iCur, &iHiwtr, bReset);
19987       oputf("Lookaside failures due to OOM:       %d\n", iHiwtr);
19988     }
19989     iHiwtr = iCur = -1;
19990     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
19991     oputf("Pager Heap Usage:                    %d bytes\n", iCur);
19992     iHiwtr = iCur = -1;
19993     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
19994     oputf("Page cache hits:                     %d\n", iCur);
19995     iHiwtr = iCur = -1;
19996     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
19997     oputf("Page cache misses:                   %d\n", iCur);
19998     iHiwtr = iCur = -1;
19999     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
20000     oputf("Page cache writes:                   %d\n", iCur);
20001     iHiwtr = iCur = -1;
20002     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
20003     oputf("Page cache spills:                   %d\n", iCur);
20004     iHiwtr = iCur = -1;
20005     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
20006     oputf("Schema Heap Usage:                   %d bytes\n", iCur);
20007     iHiwtr = iCur = -1;
20008     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
20009     oputf("Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
20010   }
20011 
20012   if( pArg->pStmt ){
20013     int iHit, iMiss;
20014     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
20015                                bReset);
20016     oputf("Fullscan Steps:                      %d\n", iCur);
20017     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
20018     oputf("Sort Operations:                     %d\n", iCur);
20019     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
20020     oputf("Autoindex Inserts:                   %d\n", iCur);
20021     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
20022                                bReset);
20023     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
20024                                 bReset);
20025     if( iHit || iMiss ){
20026       oputf("Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
20027     }
20028     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
20029     oputf("Virtual Machine Steps:               %d\n", iCur);
20030     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
20031     oputf("Reprepare operations:                %d\n", iCur);
20032     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
20033     oputf("Number of times run:                 %d\n", iCur);
20034     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
20035     oputf("Memory used by prepared stmt:        %d\n", iCur);
20036   }
20037 
20038 #ifdef __linux__
20039   displayLinuxIoStats();
20040 #endif
20041 
20042   /* Do not remove this machine readable comment: extra-stats-output-here */
20043 
20044   return 0;
20045 }
20046 
20047 
20048 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
scanStatsHeight(sqlite3_stmt * p,int iEntry)20049 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
20050   int iPid = 0;
20051   int ret = 1;
20052   sqlite3_stmt_scanstatus_v2(p, iEntry,
20053       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
20054   );
20055   while( iPid!=0 ){
20056     int ii;
20057     for(ii=0; 1; ii++){
20058       int iId;
20059       int res;
20060       res = sqlite3_stmt_scanstatus_v2(p, ii,
20061           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
20062       );
20063       if( res ) break;
20064       if( iId==iPid ){
20065         sqlite3_stmt_scanstatus_v2(p, ii,
20066             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
20067         );
20068       }
20069     }
20070     ret++;
20071   }
20072   return ret;
20073 }
20074 #endif
20075 
20076 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
display_explain_scanstats(sqlite3 * db,ShellState * pArg)20077 static void display_explain_scanstats(
20078   sqlite3 *db,                    /* Database to query */
20079   ShellState *pArg                /* Pointer to ShellState */
20080 ){
20081   static const int f = SQLITE_SCANSTAT_COMPLEX;
20082   sqlite3_stmt *p = pArg->pStmt;
20083   int ii = 0;
20084   i64 nTotal = 0;
20085   int nWidth = 0;
20086   eqp_reset(pArg);
20087 
20088   for(ii=0; 1; ii++){
20089     const char *z = 0;
20090     int n = 0;
20091     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
20092       break;
20093     }
20094     n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
20095     if( n>nWidth ) nWidth = n;
20096   }
20097   nWidth += 4;
20098 
20099   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
20100   for(ii=0; 1; ii++){
20101     i64 nLoop = 0;
20102     i64 nRow = 0;
20103     i64 nCycle = 0;
20104     int iId = 0;
20105     int iPid = 0;
20106     const char *zo = 0;
20107     const char *zName = 0;
20108     char *zText = 0;
20109     double rEst = 0.0;
20110 
20111     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
20112       break;
20113     }
20114     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
20115     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
20116     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
20117     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
20118     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
20119     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
20120     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
20121 
20122     zText = sqlite3_mprintf("%s", zo);
20123     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
20124       char *z = 0;
20125       if( nCycle>=0 && nTotal>0 ){
20126         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
20127             nCycle, ((nCycle*100)+nTotal/2) / nTotal
20128         );
20129       }
20130       if( nLoop>=0 ){
20131         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
20132       }
20133       if( nRow>=0 ){
20134         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
20135       }
20136 
20137       if( zName && pArg->scanstatsOn>1 ){
20138         double rpl = (double)nRow / (double)nLoop;
20139         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
20140       }
20141 
20142       zText = sqlite3_mprintf(
20143           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
20144       );
20145     }
20146 
20147     eqp_append(pArg, iId, iPid, zText);
20148     sqlite3_free(zText);
20149   }
20150 
20151   eqp_render(pArg, nTotal);
20152 }
20153 #endif
20154 
20155 
20156 /*
20157 ** Parameter azArray points to a zero-terminated array of strings. zStr
20158 ** points to a single nul-terminated string. Return non-zero if zStr
20159 ** is equal, according to strcmp(), to any of the strings in the array.
20160 ** Otherwise, return zero.
20161 */
str_in_array(const char * zStr,const char ** azArray)20162 static int str_in_array(const char *zStr, const char **azArray){
20163   int i;
20164   for(i=0; azArray[i]; i++){
20165     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
20166   }
20167   return 0;
20168 }
20169 
20170 /*
20171 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
20172 ** and populate the ShellState.aiIndent[] array with the number of
20173 ** spaces each opcode should be indented before it is output.
20174 **
20175 ** The indenting rules are:
20176 **
20177 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
20178 **       all opcodes that occur between the p2 jump destination and the opcode
20179 **       itself by 2 spaces.
20180 **
20181 **     * Do the previous for "Return" instructions for when P2 is positive.
20182 **       See tag-20220407a in wherecode.c and vdbe.c.
20183 **
20184 **     * For each "Goto", if the jump destination is earlier in the program
20185 **       and ends on one of:
20186 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
20187 **       or if the P1 parameter is one instead of zero,
20188 **       then indent all opcodes between the earlier instruction
20189 **       and "Goto" by 2 spaces.
20190 */
explain_data_prepare(ShellState * p,sqlite3_stmt * pSql)20191 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
20192   int *abYield = 0;               /* True if op is an OP_Yield */
20193   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
20194   int iOp;                        /* Index of operation in p->aiIndent[] */
20195 
20196   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
20197                            "Return", 0 };
20198   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
20199                             "Rewind", 0 };
20200   const char *azGoto[] = { "Goto", 0 };
20201 
20202   /* The caller guarantees that the leftmost 4 columns of the statement
20203   ** passed to this function are equivalent to the leftmost 4 columns
20204   ** of EXPLAIN statement output. In practice the statement may be
20205   ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
20206   assert( sqlite3_column_count(pSql)>=4 );
20207   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
20208   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
20209   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
20210   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
20211 
20212   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
20213     int i;
20214     int iAddr = sqlite3_column_int(pSql, 0);
20215     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
20216     int p1 = sqlite3_column_int(pSql, 2);
20217     int p2 = sqlite3_column_int(pSql, 3);
20218 
20219     /* Assuming that p2 is an instruction address, set variable p2op to the
20220     ** index of that instruction in the aiIndent[] array. p2 and p2op may be
20221     ** different if the current instruction is part of a sub-program generated
20222     ** by an SQL trigger or foreign key.  */
20223     int p2op = (p2 + (iOp-iAddr));
20224 
20225     /* Grow the p->aiIndent array as required */
20226     if( iOp>=nAlloc ){
20227       nAlloc += 100;
20228       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
20229       shell_check_oom(p->aiIndent);
20230       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
20231       shell_check_oom(abYield);
20232     }
20233 
20234     abYield[iOp] = str_in_array(zOp, azYield);
20235     p->aiIndent[iOp] = 0;
20236     p->nIndent = iOp+1;
20237     if( str_in_array(zOp, azNext) && p2op>0 ){
20238       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
20239     }
20240     if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
20241       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
20242     }
20243   }
20244 
20245   p->iIndent = 0;
20246   sqlite3_free(abYield);
20247   sqlite3_reset(pSql);
20248 }
20249 
20250 /*
20251 ** Free the array allocated by explain_data_prepare().
20252 */
explain_data_delete(ShellState * p)20253 static void explain_data_delete(ShellState *p){
20254   sqlite3_free(p->aiIndent);
20255   p->aiIndent = 0;
20256   p->nIndent = 0;
20257   p->iIndent = 0;
20258 }
20259 
20260 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
20261 
20262 /*
20263 ** Display scan stats.
20264 */
display_scanstats(sqlite3 * db,ShellState * pArg)20265 static void display_scanstats(
20266   sqlite3 *db,                    /* Database to query */
20267   ShellState *pArg                /* Pointer to ShellState */
20268 ){
20269 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
20270   UNUSED_PARAMETER(db);
20271   UNUSED_PARAMETER(pArg);
20272 #else
20273   if( pArg->scanstatsOn==3 ){
20274     const char *zSql =
20275       "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
20276       "   round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
20277       "   FROM bytecode(?)";
20278 
20279     int rc = SQLITE_OK;
20280     sqlite3_stmt *pStmt = 0;
20281     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
20282     if( rc==SQLITE_OK ){
20283       sqlite3_stmt *pSave = pArg->pStmt;
20284       pArg->pStmt = pStmt;
20285       sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
20286 
20287       pArg->cnt = 0;
20288       pArg->cMode = MODE_ScanExp;
20289       explain_data_prepare(pArg, pStmt);
20290       exec_prepared_stmt(pArg, pStmt);
20291       explain_data_delete(pArg);
20292 
20293       sqlite3_finalize(pStmt);
20294       pArg->pStmt = pSave;
20295     }
20296   }else{
20297     display_explain_scanstats(db, pArg);
20298   }
20299 #endif
20300 }
20301 
20302 /*
20303 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
20304 */
20305 static unsigned int savedSelectTrace;
20306 static unsigned int savedWhereTrace;
disable_debug_trace_modes(void)20307 static void disable_debug_trace_modes(void){
20308   unsigned int zero = 0;
20309   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
20310   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
20311   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
20312   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
20313 }
restore_debug_trace_modes(void)20314 static void restore_debug_trace_modes(void){
20315   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
20316   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
20317 }
20318 
20319 /* Create the TEMP table used to store parameter bindings */
bind_table_init(ShellState * p)20320 static void bind_table_init(ShellState *p){
20321   int wrSchema = 0;
20322   int defensiveMode = 0;
20323   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
20324   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
20325   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
20326   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
20327   sqlite3_exec(p->db,
20328     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
20329     "  key TEXT PRIMARY KEY,\n"
20330     "  value\n"
20331     ") WITHOUT ROWID;",
20332     0, 0, 0);
20333   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
20334   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
20335 }
20336 
20337 /*
20338 ** Bind parameters on a prepared statement.
20339 **
20340 ** Parameter bindings are taken from a TEMP table of the form:
20341 **
20342 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
20343 **    WITHOUT ROWID;
20344 **
20345 ** No bindings occur if this table does not exist.  The name of the table
20346 ** begins with "sqlite_" so that it will not collide with ordinary application
20347 ** tables.  The table must be in the TEMP schema.
20348 */
bind_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)20349 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
20350   int nVar;
20351   int i;
20352   int rc;
20353   sqlite3_stmt *pQ = 0;
20354 
20355   nVar = sqlite3_bind_parameter_count(pStmt);
20356   if( nVar==0 ) return;  /* Nothing to do */
20357   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
20358                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
20359     rc = SQLITE_NOTFOUND;
20360     pQ = 0;
20361   }else{
20362     rc = sqlite3_prepare_v2(pArg->db,
20363             "SELECT value FROM temp.sqlite_parameters"
20364             " WHERE key=?1", -1, &pQ, 0);
20365   }
20366   for(i=1; i<=nVar; i++){
20367     char zNum[30];
20368     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
20369     if( zVar==0 ){
20370       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
20371       zVar = zNum;
20372     }
20373     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
20374     if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
20375       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
20376 #ifdef NAN
20377     }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
20378       sqlite3_bind_double(pStmt, i, NAN);
20379 #endif
20380 #ifdef INFINITY
20381     }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
20382       sqlite3_bind_double(pStmt, i, INFINITY);
20383 #endif
20384     }else{
20385       sqlite3_bind_null(pStmt, i);
20386     }
20387     sqlite3_reset(pQ);
20388   }
20389   sqlite3_finalize(pQ);
20390 }
20391 
20392 /*
20393 ** UTF8 box-drawing characters.  Imagine box lines like this:
20394 **
20395 **           1
20396 **           |
20397 **       4 --+-- 2
20398 **           |
20399 **           3
20400 **
20401 ** Each box characters has between 2 and 4 of the lines leading from
20402 ** the center.  The characters are here identified by the numbers of
20403 ** their corresponding lines.
20404 */
20405 #define BOX_24   "\342\224\200"  /* U+2500 --- */
20406 #define BOX_13   "\342\224\202"  /* U+2502  |  */
20407 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
20408 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
20409 #define BOX_12   "\342\224\224"  /* U+2514  '- */
20410 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
20411 #define BOX_123  "\342\224\234"  /* U+251c  |- */
20412 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
20413 #define BOX_234  "\342\224\254"  /* U+252c -,- */
20414 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
20415 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
20416 
20417 /* Draw horizontal line N characters long using unicode box
20418 ** characters
20419 */
print_box_line(int N)20420 static void print_box_line(int N){
20421   const char zDash[] =
20422       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
20423       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
20424   const int nDash = sizeof(zDash) - 1;
20425   N *= 3;
20426   while( N>nDash ){
20427     oputz(zDash);
20428     N -= nDash;
20429   }
20430   oputf("%.*s", N, zDash);
20431 }
20432 
20433 /*
20434 ** Draw a horizontal separator for a MODE_Box table.
20435 */
print_box_row_separator(ShellState * p,int nArg,const char * zSep1,const char * zSep2,const char * zSep3)20436 static void print_box_row_separator(
20437   ShellState *p,
20438   int nArg,
20439   const char *zSep1,
20440   const char *zSep2,
20441   const char *zSep3
20442 ){
20443   int i;
20444   if( nArg>0 ){
20445     oputz(zSep1);
20446     print_box_line(p->actualWidth[0]+2);
20447     for(i=1; i<nArg; i++){
20448       oputz(zSep2);
20449       print_box_line(p->actualWidth[i]+2);
20450     }
20451     oputz(zSep3);
20452   }
20453   oputz("\n");
20454 }
20455 
20456 /*
20457 ** z[] is a line of text that is to be displayed the .mode box or table or
20458 ** similar tabular formats.  z[] might contain control characters such
20459 ** as \n, \t, \f, or \r.
20460 **
20461 ** Compute characters to display on the first line of z[].  Stop at the
20462 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
20463 ** from malloc()) of that first line, which caller should free sometime.
20464 ** Write anything to display on the next line into *pzTail.  If this is
20465 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
20466 */
translateForDisplayAndDup(const unsigned char * z,const unsigned char ** pzTail,int mxWidth,u8 bWordWrap)20467 static char *translateForDisplayAndDup(
20468   const unsigned char *z,            /* Input text to be transformed */
20469   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
20470   int mxWidth,                       /* Max width.  0 means no limit */
20471   u8 bWordWrap                       /* If true, avoid breaking mid-word */
20472 ){
20473   int i;                 /* Input bytes consumed */
20474   int j;                 /* Output bytes generated */
20475   int k;                 /* Input bytes to be displayed */
20476   int n;                 /* Output column number */
20477   unsigned char *zOut;   /* Output text */
20478 
20479   if( z==0 ){
20480     *pzTail = 0;
20481     return 0;
20482   }
20483   if( mxWidth<0 ) mxWidth = -mxWidth;
20484   if( mxWidth==0 ) mxWidth = 1000000;
20485   i = j = n = 0;
20486   while( n<mxWidth ){
20487     if( z[i]>=' ' ){
20488       n++;
20489       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
20490       continue;
20491     }
20492     if( z[i]=='\t' ){
20493       do{
20494         n++;
20495         j++;
20496       }while( (n&7)!=0 && n<mxWidth );
20497       i++;
20498       continue;
20499     }
20500     break;
20501   }
20502   if( n>=mxWidth && bWordWrap  ){
20503     /* Perhaps try to back up to a better place to break the line */
20504     for(k=i; k>i/2; k--){
20505       if( isspace(z[k-1]) ) break;
20506     }
20507     if( k<=i/2 ){
20508       for(k=i; k>i/2; k--){
20509         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
20510       }
20511     }
20512     if( k<=i/2 ){
20513       k = i;
20514     }else{
20515       i = k;
20516       while( z[i]==' ' ) i++;
20517     }
20518   }else{
20519     k = i;
20520   }
20521   if( n>=mxWidth && z[i]>=' ' ){
20522    *pzTail = &z[i];
20523   }else if( z[i]=='\r' && z[i+1]=='\n' ){
20524     *pzTail = z[i+2] ? &z[i+2] : 0;
20525   }else if( z[i]==0 || z[i+1]==0 ){
20526     *pzTail = 0;
20527   }else{
20528     *pzTail = &z[i+1];
20529   }
20530   zOut = malloc( j+1 );
20531   shell_check_oom(zOut);
20532   i = j = n = 0;
20533   while( i<k ){
20534     if( z[i]>=' ' ){
20535       n++;
20536       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
20537       continue;
20538     }
20539     if( z[i]=='\t' ){
20540       do{
20541         n++;
20542         zOut[j++] = ' ';
20543       }while( (n&7)!=0 && n<mxWidth );
20544       i++;
20545       continue;
20546     }
20547     break;
20548   }
20549   zOut[j] = 0;
20550   return (char*)zOut;
20551 }
20552 
20553 /* Extract the value of the i-th current column for pStmt as an SQL literal
20554 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
20555 ** the caller.
20556 */
quoted_column(sqlite3_stmt * pStmt,int i)20557 static char *quoted_column(sqlite3_stmt *pStmt, int i){
20558   switch( sqlite3_column_type(pStmt, i) ){
20559     case SQLITE_NULL: {
20560       return sqlite3_mprintf("NULL");
20561     }
20562     case SQLITE_INTEGER:
20563     case SQLITE_FLOAT: {
20564       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
20565     }
20566     case SQLITE_TEXT: {
20567       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
20568     }
20569     case SQLITE_BLOB: {
20570       int j;
20571       sqlite3_str *pStr = sqlite3_str_new(0);
20572       const unsigned char *a = sqlite3_column_blob(pStmt,i);
20573       int n = sqlite3_column_bytes(pStmt,i);
20574       sqlite3_str_append(pStr, "x'", 2);
20575       for(j=0; j<n; j++){
20576         sqlite3_str_appendf(pStr, "%02x", a[j]);
20577       }
20578       sqlite3_str_append(pStr, "'", 1);
20579       return sqlite3_str_finish(pStr);
20580     }
20581   }
20582   return 0; /* Not reached */
20583 }
20584 
20585 /*
20586 ** Run a prepared statement and output the result in one of the
20587 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
20588 ** or MODE_Box.
20589 **
20590 ** This is different from ordinary exec_prepared_stmt() in that
20591 ** it has to run the entire query and gather the results into memory
20592 ** first, in order to determine column widths, before providing
20593 ** any output.
20594 */
exec_prepared_stmt_columnar(ShellState * p,sqlite3_stmt * pStmt)20595 static void exec_prepared_stmt_columnar(
20596   ShellState *p,                        /* Pointer to ShellState */
20597   sqlite3_stmt *pStmt                   /* Statement to run */
20598 ){
20599   sqlite3_int64 nRow = 0;
20600   int nColumn = 0;
20601   char **azData = 0;
20602   sqlite3_int64 nAlloc = 0;
20603   char *abRowDiv = 0;
20604   const unsigned char *uz;
20605   const char *z;
20606   char **azQuoted = 0;
20607   int rc;
20608   sqlite3_int64 i, nData;
20609   int j, nTotal, w, n;
20610   const char *colSep = 0;
20611   const char *rowSep = 0;
20612   const unsigned char **azNextLine = 0;
20613   int bNextLine = 0;
20614   int bMultiLineRowExists = 0;
20615   int bw = p->cmOpts.bWordWrap;
20616   const char *zEmpty = "";
20617   const char *zShowNull = p->nullValue;
20618 
20619   rc = sqlite3_step(pStmt);
20620   if( rc!=SQLITE_ROW ) return;
20621   nColumn = sqlite3_column_count(pStmt);
20622   nAlloc = nColumn*4;
20623   if( nAlloc<=0 ) nAlloc = 1;
20624   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
20625   shell_check_oom(azData);
20626   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
20627   shell_check_oom(azNextLine);
20628   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
20629   if( p->cmOpts.bQuote ){
20630     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
20631     shell_check_oom(azQuoted);
20632     memset(azQuoted, 0, nColumn*sizeof(char*) );
20633   }
20634   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
20635   shell_check_oom(abRowDiv);
20636   if( nColumn>p->nWidth ){
20637     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
20638     shell_check_oom(p->colWidth);
20639     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
20640     p->nWidth = nColumn;
20641     p->actualWidth = &p->colWidth[nColumn];
20642   }
20643   memset(p->actualWidth, 0, nColumn*sizeof(int));
20644   for(i=0; i<nColumn; i++){
20645     w = p->colWidth[i];
20646     if( w<0 ) w = -w;
20647     p->actualWidth[i] = w;
20648   }
20649   for(i=0; i<nColumn; i++){
20650     const unsigned char *zNotUsed;
20651     int wx = p->colWidth[i];
20652     if( wx==0 ){
20653       wx = p->cmOpts.iWrap;
20654     }
20655     if( wx<0 ) wx = -wx;
20656     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
20657     if( uz==0 ) uz = (u8*)"";
20658     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
20659   }
20660   do{
20661     int useNextLine = bNextLine;
20662     bNextLine = 0;
20663     if( (nRow+2)*nColumn >= nAlloc ){
20664       nAlloc *= 2;
20665       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
20666       shell_check_oom(azData);
20667       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
20668       shell_check_oom(abRowDiv);
20669     }
20670     abRowDiv[nRow] = 1;
20671     nRow++;
20672     for(i=0; i<nColumn; i++){
20673       int wx = p->colWidth[i];
20674       if( wx==0 ){
20675         wx = p->cmOpts.iWrap;
20676       }
20677       if( wx<0 ) wx = -wx;
20678       if( useNextLine ){
20679         uz = azNextLine[i];
20680         if( uz==0 ) uz = (u8*)zEmpty;
20681       }else if( p->cmOpts.bQuote ){
20682         sqlite3_free(azQuoted[i]);
20683         azQuoted[i] = quoted_column(pStmt,i);
20684         uz = (const unsigned char*)azQuoted[i];
20685       }else{
20686         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
20687         if( uz==0 ) uz = (u8*)zShowNull;
20688       }
20689       azData[nRow*nColumn + i]
20690         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
20691       if( azNextLine[i] ){
20692         bNextLine = 1;
20693         abRowDiv[nRow-1] = 0;
20694         bMultiLineRowExists = 1;
20695       }
20696     }
20697   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
20698   nTotal = nColumn*(nRow+1);
20699   for(i=0; i<nTotal; i++){
20700     z = azData[i];
20701     if( z==0 ) z = (char*)zEmpty;
20702     n = strlenChar(z);
20703     j = i%nColumn;
20704     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
20705   }
20706   if( seenInterrupt ) goto columnar_end;
20707   if( nColumn==0 ) goto columnar_end;
20708   switch( p->cMode ){
20709     case MODE_Column: {
20710       colSep = "  ";
20711       rowSep = "\n";
20712       if( p->showHeader ){
20713         for(i=0; i<nColumn; i++){
20714           w = p->actualWidth[i];
20715           if( p->colWidth[i]<0 ) w = -w;
20716           utf8_width_print(w, azData[i]);
20717           fputs(i==nColumn-1?"\n":"  ", p->out);
20718         }
20719         for(i=0; i<nColumn; i++){
20720           print_dashes(p->actualWidth[i]);
20721           fputs(i==nColumn-1?"\n":"  ", p->out);
20722         }
20723       }
20724       break;
20725     }
20726     case MODE_Table: {
20727       colSep = " | ";
20728       rowSep = " |\n";
20729       print_row_separator(p, nColumn, "+");
20730       fputs("| ", p->out);
20731       for(i=0; i<nColumn; i++){
20732         w = p->actualWidth[i];
20733         n = strlenChar(azData[i]);
20734         oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
20735         oputz(i==nColumn-1?" |\n":" | ");
20736       }
20737       print_row_separator(p, nColumn, "+");
20738       break;
20739     }
20740     case MODE_Markdown: {
20741       colSep = " | ";
20742       rowSep = " |\n";
20743       fputs("| ", p->out);
20744       for(i=0; i<nColumn; i++){
20745         w = p->actualWidth[i];
20746         n = strlenChar(azData[i]);
20747         oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
20748         oputz(i==nColumn-1?" |\n":" | ");
20749       }
20750       print_row_separator(p, nColumn, "|");
20751       break;
20752     }
20753     case MODE_Box: {
20754       colSep = " " BOX_13 " ";
20755       rowSep = " " BOX_13 "\n";
20756       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
20757       oputz(BOX_13 " ");
20758       for(i=0; i<nColumn; i++){
20759         w = p->actualWidth[i];
20760         n = strlenChar(azData[i]);
20761         oputf("%*s%s%*s%s",
20762               (w-n)/2, "", azData[i], (w-n+1)/2, "",
20763               i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
20764       }
20765       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20766       break;
20767     }
20768   }
20769   for(i=nColumn, j=0; i<nTotal; i++, j++){
20770     if( j==0 && p->cMode!=MODE_Column ){
20771       oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
20772     }
20773     z = azData[i];
20774     if( z==0 ) z = p->nullValue;
20775     w = p->actualWidth[j];
20776     if( p->colWidth[j]<0 ) w = -w;
20777     utf8_width_print(w, z);
20778     if( j==nColumn-1 ){
20779       oputz(rowSep);
20780       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
20781         if( p->cMode==MODE_Table ){
20782           print_row_separator(p, nColumn, "+");
20783         }else if( p->cMode==MODE_Box ){
20784           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20785         }else if( p->cMode==MODE_Column ){
20786           oputz("\n");
20787         }
20788       }
20789       j = -1;
20790       if( seenInterrupt ) goto columnar_end;
20791     }else{
20792       oputz(colSep);
20793     }
20794   }
20795   if( p->cMode==MODE_Table ){
20796     print_row_separator(p, nColumn, "+");
20797   }else if( p->cMode==MODE_Box ){
20798     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
20799   }
20800 columnar_end:
20801   if( seenInterrupt ){
20802     oputz("Interrupt\n");
20803   }
20804   nData = (nRow+1)*nColumn;
20805   for(i=0; i<nData; i++){
20806     z = azData[i];
20807     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
20808   }
20809   sqlite3_free(azData);
20810   sqlite3_free((void*)azNextLine);
20811   sqlite3_free(abRowDiv);
20812   if( azQuoted ){
20813     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
20814     sqlite3_free(azQuoted);
20815   }
20816 }
20817 
20818 /*
20819 ** Run a prepared statement
20820 */
exec_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)20821 static void exec_prepared_stmt(
20822   ShellState *pArg,                                /* Pointer to ShellState */
20823   sqlite3_stmt *pStmt                              /* Statement to run */
20824 ){
20825   int rc;
20826   sqlite3_uint64 nRow = 0;
20827 
20828   if( pArg->cMode==MODE_Column
20829    || pArg->cMode==MODE_Table
20830    || pArg->cMode==MODE_Box
20831    || pArg->cMode==MODE_Markdown
20832   ){
20833     exec_prepared_stmt_columnar(pArg, pStmt);
20834     return;
20835   }
20836 
20837   /* perform the first step.  this will tell us if we
20838   ** have a result set or not and how wide it is.
20839   */
20840   rc = sqlite3_step(pStmt);
20841   /* if we have a result set... */
20842   if( SQLITE_ROW == rc ){
20843     /* allocate space for col name ptr, value ptr, and type */
20844     int nCol = sqlite3_column_count(pStmt);
20845     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
20846     if( !pData ){
20847       shell_out_of_memory();
20848     }else{
20849       char **azCols = (char **)pData;      /* Names of result columns */
20850       char **azVals = &azCols[nCol];       /* Results */
20851       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
20852       int i, x;
20853       assert(sizeof(int) <= sizeof(char *));
20854       /* save off ptrs to column names */
20855       for(i=0; i<nCol; i++){
20856         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
20857       }
20858       do{
20859         nRow++;
20860         /* extract the data and data types */
20861         for(i=0; i<nCol; i++){
20862           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
20863           if( x==SQLITE_BLOB
20864            && pArg
20865            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
20866           ){
20867             azVals[i] = "";
20868           }else{
20869             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
20870           }
20871           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
20872             rc = SQLITE_NOMEM;
20873             break; /* from for */
20874           }
20875         } /* end for */
20876 
20877         /* if data and types extracted successfully... */
20878         if( SQLITE_ROW == rc ){
20879           /* call the supplied callback with the result row data */
20880           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
20881             rc = SQLITE_ABORT;
20882           }else{
20883             rc = sqlite3_step(pStmt);
20884           }
20885         }
20886       } while( SQLITE_ROW == rc );
20887       sqlite3_free(pData);
20888       if( pArg->cMode==MODE_Json ){
20889         fputs("]\n", pArg->out);
20890       }else if( pArg->cMode==MODE_Count ){
20891         char zBuf[200];
20892         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
20893                          nRow, nRow!=1 ? "s" : "");
20894         printf("%s", zBuf);
20895       }
20896     }
20897   }
20898 }
20899 
20900 #ifndef SQLITE_OMIT_VIRTUALTABLE
20901 /*
20902 ** This function is called to process SQL if the previous shell command
20903 ** was ".expert". It passes the SQL in the second argument directly to
20904 ** the sqlite3expert object.
20905 **
20906 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20907 ** code. In this case, (*pzErr) may be set to point to a buffer containing
20908 ** an English language error message. It is the responsibility of the
20909 ** caller to eventually free this buffer using sqlite3_free().
20910 */
expertHandleSQL(ShellState * pState,const char * zSql,char ** pzErr)20911 static int expertHandleSQL(
20912   ShellState *pState,
20913   const char *zSql,
20914   char **pzErr
20915 ){
20916   assert( pState->expert.pExpert );
20917   assert( pzErr==0 || *pzErr==0 );
20918   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
20919 }
20920 
20921 /*
20922 ** This function is called either to silently clean up the object
20923 ** created by the ".expert" command (if bCancel==1), or to generate a
20924 ** report from it and then clean it up (if bCancel==0).
20925 **
20926 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20927 ** code. In this case, (*pzErr) may be set to point to a buffer containing
20928 ** an English language error message. It is the responsibility of the
20929 ** caller to eventually free this buffer using sqlite3_free().
20930 */
expertFinish(ShellState * pState,int bCancel,char ** pzErr)20931 static int expertFinish(
20932   ShellState *pState,
20933   int bCancel,
20934   char **pzErr
20935 ){
20936   int rc = SQLITE_OK;
20937   sqlite3expert *p = pState->expert.pExpert;
20938   assert( p );
20939   assert( bCancel || pzErr==0 || *pzErr==0 );
20940   if( bCancel==0 ){
20941     int bVerbose = pState->expert.bVerbose;
20942 
20943     rc = sqlite3_expert_analyze(p, pzErr);
20944     if( rc==SQLITE_OK ){
20945       int nQuery = sqlite3_expert_count(p);
20946       int i;
20947 
20948       if( bVerbose ){
20949         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
20950         oputz("-- Candidates -----------------------------\n");
20951         oputf("%s\n", zCand);
20952       }
20953       for(i=0; i<nQuery; i++){
20954         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
20955         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
20956         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
20957         if( zIdx==0 ) zIdx = "(no new indexes)\n";
20958         if( bVerbose ){
20959           oputf("-- Query %d --------------------------------\n",i+1);
20960           oputf("%s\n\n", zSql);
20961         }
20962         oputf("%s\n", zIdx);
20963         oputf("%s\n", zEQP);
20964       }
20965     }
20966   }
20967   sqlite3_expert_destroy(p);
20968   pState->expert.pExpert = 0;
20969   return rc;
20970 }
20971 
20972 /*
20973 ** Implementation of ".expert" dot command.
20974 */
expertDotCommand(ShellState * pState,char ** azArg,int nArg)20975 static int expertDotCommand(
20976   ShellState *pState,             /* Current shell tool state */
20977   char **azArg,                   /* Array of arguments passed to dot command */
20978   int nArg                        /* Number of entries in azArg[] */
20979 ){
20980   int rc = SQLITE_OK;
20981   char *zErr = 0;
20982   int i;
20983   int iSample = 0;
20984 
20985   assert( pState->expert.pExpert==0 );
20986   memset(&pState->expert, 0, sizeof(ExpertInfo));
20987 
20988   for(i=1; rc==SQLITE_OK && i<nArg; i++){
20989     char *z = azArg[i];
20990     int n;
20991     if( z[0]=='-' && z[1]=='-' ) z++;
20992     n = strlen30(z);
20993     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
20994       pState->expert.bVerbose = 1;
20995     }
20996     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
20997       if( i==(nArg-1) ){
20998         eputf("option requires an argument: %s\n", z);
20999         rc = SQLITE_ERROR;
21000       }else{
21001         iSample = (int)integerValue(azArg[++i]);
21002         if( iSample<0 || iSample>100 ){
21003           eputf("value out of range: %s\n", azArg[i]);
21004           rc = SQLITE_ERROR;
21005         }
21006       }
21007     }
21008     else{
21009       eputf("unknown option: %s\n", z);
21010       rc = SQLITE_ERROR;
21011     }
21012   }
21013 
21014   if( rc==SQLITE_OK ){
21015     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
21016     if( pState->expert.pExpert==0 ){
21017       eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
21018       rc = SQLITE_ERROR;
21019     }else{
21020       sqlite3_expert_config(
21021           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
21022       );
21023     }
21024   }
21025   sqlite3_free(zErr);
21026 
21027   return rc;
21028 }
21029 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
21030 
21031 /*
21032 ** Execute a statement or set of statements.  Print
21033 ** any result rows/columns depending on the current mode
21034 ** set via the supplied callback.
21035 **
21036 ** This is very similar to SQLite's built-in sqlite3_exec()
21037 ** function except it takes a slightly different callback
21038 ** and callback data argument.
21039 */
shell_exec(ShellState * pArg,const char * zSql,char ** pzErrMsg)21040 static int shell_exec(
21041   ShellState *pArg,                         /* Pointer to ShellState */
21042   const char *zSql,                         /* SQL to be evaluated */
21043   char **pzErrMsg                           /* Error msg written here */
21044 ){
21045   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
21046   int rc = SQLITE_OK;             /* Return Code */
21047   int rc2;
21048   const char *zLeftover;          /* Tail of unprocessed SQL */
21049   sqlite3 *db = pArg->db;
21050 
21051   if( pzErrMsg ){
21052     *pzErrMsg = NULL;
21053   }
21054 
21055 #ifndef SQLITE_OMIT_VIRTUALTABLE
21056   if( pArg->expert.pExpert ){
21057     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
21058     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
21059   }
21060 #endif
21061 
21062   while( zSql[0] && (SQLITE_OK == rc) ){
21063     static const char *zStmtSql;
21064     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
21065     if( SQLITE_OK != rc ){
21066       if( pzErrMsg ){
21067         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
21068       }
21069     }else{
21070       if( !pStmt ){
21071         /* this happens for a comment or white-space */
21072         zSql = zLeftover;
21073         while( IsSpace(zSql[0]) ) zSql++;
21074         continue;
21075       }
21076       zStmtSql = sqlite3_sql(pStmt);
21077       if( zStmtSql==0 ) zStmtSql = "";
21078       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
21079 
21080       /* save off the prepared statement handle and reset row count */
21081       if( pArg ){
21082         pArg->pStmt = pStmt;
21083         pArg->cnt = 0;
21084       }
21085 
21086       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
21087       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
21088         sqlite3_stmt *pExplain;
21089         int triggerEQP = 0;
21090         disable_debug_trace_modes();
21091         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
21092         if( pArg->autoEQP>=AUTOEQP_trigger ){
21093           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
21094         }
21095         pExplain = pStmt;
21096         sqlite3_reset(pExplain);
21097         rc = sqlite3_stmt_explain(pExplain, 2);
21098         if( rc==SQLITE_OK ){
21099           while( sqlite3_step(pExplain)==SQLITE_ROW ){
21100             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
21101             int iEqpId = sqlite3_column_int(pExplain, 0);
21102             int iParentId = sqlite3_column_int(pExplain, 1);
21103             if( zEQPLine==0 ) zEQPLine = "";
21104             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
21105             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
21106           }
21107           eqp_render(pArg, 0);
21108         }
21109         if( pArg->autoEQP>=AUTOEQP_full ){
21110           /* Also do an EXPLAIN for ".eqp full" mode */
21111           sqlite3_reset(pExplain);
21112           rc = sqlite3_stmt_explain(pExplain, 1);
21113           if( rc==SQLITE_OK ){
21114             pArg->cMode = MODE_Explain;
21115             assert( sqlite3_stmt_isexplain(pExplain)==1 );
21116             explain_data_prepare(pArg, pExplain);
21117             exec_prepared_stmt(pArg, pExplain);
21118             explain_data_delete(pArg);
21119           }
21120         }
21121         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
21122           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
21123         }
21124         sqlite3_reset(pStmt);
21125         sqlite3_stmt_explain(pStmt, 0);
21126         restore_debug_trace_modes();
21127       }
21128 
21129       if( pArg ){
21130         int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
21131         pArg->cMode = pArg->mode;
21132         if( pArg->autoExplain ){
21133           if( bIsExplain ){
21134             pArg->cMode = MODE_Explain;
21135           }
21136           if( sqlite3_stmt_isexplain(pStmt)==2 ){
21137             pArg->cMode = MODE_EQP;
21138           }
21139         }
21140 
21141         /* If the shell is currently in ".explain" mode, gather the extra
21142         ** data required to add indents to the output.*/
21143         if( pArg->cMode==MODE_Explain && bIsExplain ){
21144           explain_data_prepare(pArg, pStmt);
21145         }
21146       }
21147 
21148       bind_prepared_stmt(pArg, pStmt);
21149       exec_prepared_stmt(pArg, pStmt);
21150       explain_data_delete(pArg);
21151       eqp_render(pArg, 0);
21152 
21153       /* print usage stats if stats on */
21154       if( pArg && pArg->statsOn ){
21155         display_stats(db, pArg, 0);
21156       }
21157 
21158       /* print loop-counters if required */
21159       if( pArg && pArg->scanstatsOn ){
21160         display_scanstats(db, pArg);
21161       }
21162 
21163       /* Finalize the statement just executed. If this fails, save a
21164       ** copy of the error message. Otherwise, set zSql to point to the
21165       ** next statement to execute. */
21166       rc2 = sqlite3_finalize(pStmt);
21167       if( rc!=SQLITE_NOMEM ) rc = rc2;
21168       if( rc==SQLITE_OK ){
21169         zSql = zLeftover;
21170         while( IsSpace(zSql[0]) ) zSql++;
21171       }else if( pzErrMsg ){
21172         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
21173       }
21174 
21175       /* clear saved stmt handle */
21176       if( pArg ){
21177         pArg->pStmt = NULL;
21178       }
21179     }
21180   } /* end while */
21181 
21182   return rc;
21183 }
21184 
21185 /*
21186 ** Release memory previously allocated by tableColumnList().
21187 */
freeColumnList(char ** azCol)21188 static void freeColumnList(char **azCol){
21189   int i;
21190   for(i=1; azCol[i]; i++){
21191     sqlite3_free(azCol[i]);
21192   }
21193   /* azCol[0] is a static string */
21194   sqlite3_free(azCol);
21195 }
21196 
21197 /*
21198 ** Return a list of pointers to strings which are the names of all
21199 ** columns in table zTab.   The memory to hold the names is dynamically
21200 ** allocated and must be released by the caller using a subsequent call
21201 ** to freeColumnList().
21202 **
21203 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
21204 ** value that needs to be preserved, then azCol[0] is filled in with the
21205 ** name of the rowid column.
21206 **
21207 ** The first regular column in the table is azCol[1].  The list is terminated
21208 ** by an entry with azCol[i]==0.
21209 */
tableColumnList(ShellState * p,const char * zTab)21210 static char **tableColumnList(ShellState *p, const char *zTab){
21211   char **azCol = 0;
21212   sqlite3_stmt *pStmt;
21213   char *zSql;
21214   int nCol = 0;
21215   int nAlloc = 0;
21216   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
21217   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
21218   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
21219   int rc;
21220 
21221   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
21222   shell_check_oom(zSql);
21223   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
21224   sqlite3_free(zSql);
21225   if( rc ) return 0;
21226   while( sqlite3_step(pStmt)==SQLITE_ROW ){
21227     if( nCol>=nAlloc-2 ){
21228       nAlloc = nAlloc*2 + nCol + 10;
21229       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
21230       shell_check_oom(azCol);
21231     }
21232     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
21233     shell_check_oom(azCol[nCol]);
21234     if( sqlite3_column_int(pStmt, 5) ){
21235       nPK++;
21236       if( nPK==1
21237        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
21238                           "INTEGER")==0
21239       ){
21240         isIPK = 1;
21241       }else{
21242         isIPK = 0;
21243       }
21244     }
21245   }
21246   sqlite3_finalize(pStmt);
21247   if( azCol==0 ) return 0;
21248   azCol[0] = 0;
21249   azCol[nCol+1] = 0;
21250 
21251   /* The decision of whether or not a rowid really needs to be preserved
21252   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
21253   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
21254   ** rowids on tables where the rowid is inaccessible because there are other
21255   ** columns in the table named "rowid", "_rowid_", and "oid".
21256   */
21257   if( preserveRowid && isIPK ){
21258     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
21259     ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
21260     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
21261     ** ROWID aliases.  To distinguish these cases, check to see if
21262     ** there is a "pk" entry in "PRAGMA index_list".  There will be
21263     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
21264     */
21265     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
21266                            " WHERE origin='pk'", zTab);
21267     shell_check_oom(zSql);
21268     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
21269     sqlite3_free(zSql);
21270     if( rc ){
21271       freeColumnList(azCol);
21272       return 0;
21273     }
21274     rc = sqlite3_step(pStmt);
21275     sqlite3_finalize(pStmt);
21276     preserveRowid = rc==SQLITE_ROW;
21277   }
21278   if( preserveRowid ){
21279     /* Only preserve the rowid if we can find a name to use for the
21280     ** rowid */
21281     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
21282     int i, j;
21283     for(j=0; j<3; j++){
21284       for(i=1; i<=nCol; i++){
21285         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
21286       }
21287       if( i>nCol ){
21288         /* At this point, we know that azRowid[j] is not the name of any
21289         ** ordinary column in the table.  Verify that azRowid[j] is a valid
21290         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
21291         ** tables will fail this last check */
21292         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
21293         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
21294         break;
21295       }
21296     }
21297   }
21298   return azCol;
21299 }
21300 
21301 /*
21302 ** Toggle the reverse_unordered_selects setting.
21303 */
toggleSelectOrder(sqlite3 * db)21304 static void toggleSelectOrder(sqlite3 *db){
21305   sqlite3_stmt *pStmt = 0;
21306   int iSetting = 0;
21307   char zStmt[100];
21308   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
21309   if( sqlite3_step(pStmt)==SQLITE_ROW ){
21310     iSetting = sqlite3_column_int(pStmt, 0);
21311   }
21312   sqlite3_finalize(pStmt);
21313   sqlite3_snprintf(sizeof(zStmt), zStmt,
21314        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
21315   sqlite3_exec(db, zStmt, 0, 0, 0);
21316 }
21317 
21318 /*
21319 ** This is a different callback routine used for dumping the database.
21320 ** Each row received by this callback consists of a table name,
21321 ** the table type ("index" or "table") and SQL to create the table.
21322 ** This routine should print text sufficient to recreate the table.
21323 */
dump_callback(void * pArg,int nArg,char ** azArg,char ** azNotUsed)21324 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
21325   int rc;
21326   const char *zTable;
21327   const char *zType;
21328   const char *zSql;
21329   ShellState *p = (ShellState *)pArg;
21330   int dataOnly;
21331   int noSys;
21332 
21333   UNUSED_PARAMETER(azNotUsed);
21334   if( nArg!=3 || azArg==0 ) return 0;
21335   zTable = azArg[0];
21336   zType = azArg[1];
21337   zSql = azArg[2];
21338   if( zTable==0 ) return 0;
21339   if( zType==0 ) return 0;
21340   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
21341   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
21342 
21343   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
21344     if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
21345   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
21346     if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
21347   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
21348     return 0;
21349   }else if( dataOnly ){
21350     /* no-op */
21351   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
21352     char *zIns;
21353     if( !p->writableSchema ){
21354       oputz("PRAGMA writable_schema=ON;\n");
21355       p->writableSchema = 1;
21356     }
21357     zIns = sqlite3_mprintf(
21358        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
21359        "VALUES('table','%q','%q',0,'%q');",
21360        zTable, zTable, zSql);
21361     shell_check_oom(zIns);
21362     oputf("%s\n", zIns);
21363     sqlite3_free(zIns);
21364     return 0;
21365   }else{
21366     printSchemaLine(zSql, ";\n");
21367   }
21368 
21369   if( cli_strcmp(zType, "table")==0 ){
21370     ShellText sSelect;
21371     ShellText sTable;
21372     char **azCol;
21373     int i;
21374     char *savedDestTable;
21375     int savedMode;
21376 
21377     azCol = tableColumnList(p, zTable);
21378     if( azCol==0 ){
21379       p->nErr++;
21380       return 0;
21381     }
21382 
21383     /* Always quote the table name, even if it appears to be pure ascii,
21384     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
21385     initText(&sTable);
21386     appendText(&sTable, zTable, quoteChar(zTable));
21387     /* If preserving the rowid, add a column list after the table name.
21388     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
21389     ** instead of the usual "INSERT INTO tab VALUES(...)".
21390     */
21391     if( azCol[0] ){
21392       appendText(&sTable, "(", 0);
21393       appendText(&sTable, azCol[0], 0);
21394       for(i=1; azCol[i]; i++){
21395         appendText(&sTable, ",", 0);
21396         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
21397       }
21398       appendText(&sTable, ")", 0);
21399     }
21400 
21401     /* Build an appropriate SELECT statement */
21402     initText(&sSelect);
21403     appendText(&sSelect, "SELECT ", 0);
21404     if( azCol[0] ){
21405       appendText(&sSelect, azCol[0], 0);
21406       appendText(&sSelect, ",", 0);
21407     }
21408     for(i=1; azCol[i]; i++){
21409       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
21410       if( azCol[i+1] ){
21411         appendText(&sSelect, ",", 0);
21412       }
21413     }
21414     freeColumnList(azCol);
21415     appendText(&sSelect, " FROM ", 0);
21416     appendText(&sSelect, zTable, quoteChar(zTable));
21417 
21418     savedDestTable = p->zDestTable;
21419     savedMode = p->mode;
21420     p->zDestTable = sTable.z;
21421     p->mode = p->cMode = MODE_Insert;
21422     rc = shell_exec(p, sSelect.z, 0);
21423     if( (rc&0xff)==SQLITE_CORRUPT ){
21424       oputz("/****** CORRUPTION ERROR *******/\n");
21425       toggleSelectOrder(p->db);
21426       shell_exec(p, sSelect.z, 0);
21427       toggleSelectOrder(p->db);
21428     }
21429     p->zDestTable = savedDestTable;
21430     p->mode = savedMode;
21431     freeText(&sTable);
21432     freeText(&sSelect);
21433     if( rc ) p->nErr++;
21434   }
21435   return 0;
21436 }
21437 
21438 /*
21439 ** Run zQuery.  Use dump_callback() as the callback routine so that
21440 ** the contents of the query are output as SQL statements.
21441 **
21442 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
21443 ** "ORDER BY rowid DESC" to the end.
21444 */
run_schema_dump_query(ShellState * p,const char * zQuery)21445 static int run_schema_dump_query(
21446   ShellState *p,
21447   const char *zQuery
21448 ){
21449   int rc;
21450   char *zErr = 0;
21451   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
21452   if( rc==SQLITE_CORRUPT ){
21453     char *zQ2;
21454     int len = strlen30(zQuery);
21455     oputz("/****** CORRUPTION ERROR *******/\n");
21456     if( zErr ){
21457       oputf("/****** %s ******/\n", zErr);
21458       sqlite3_free(zErr);
21459       zErr = 0;
21460     }
21461     zQ2 = malloc( len+100 );
21462     if( zQ2==0 ) return rc;
21463     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
21464     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
21465     if( rc ){
21466       oputf("/****** ERROR: %s ******/\n", zErr);
21467     }else{
21468       rc = SQLITE_CORRUPT;
21469     }
21470     sqlite3_free(zErr);
21471     free(zQ2);
21472   }
21473   return rc;
21474 }
21475 
21476 /*
21477 ** Text of help messages.
21478 **
21479 ** The help text for each individual command begins with a line that starts
21480 ** with ".".  Subsequent lines are supplemental information.
21481 **
21482 ** There must be two or more spaces between the end of the command and the
21483 ** start of the description of what that command does.
21484 */
21485 static const char *(azHelp[]) = {
21486 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
21487   && !defined(SQLITE_SHELL_FIDDLE)
21488   ".archive ...             Manage SQL archives",
21489   "   Each command must have exactly one of the following options:",
21490   "     -c, --create               Create a new archive",
21491   "     -u, --update               Add or update files with changed mtime",
21492   "     -i, --insert               Like -u but always add even if unchanged",
21493   "     -r, --remove               Remove files from archive",
21494   "     -t, --list                 List contents of archive",
21495   "     -x, --extract              Extract files from archive",
21496   "   Optional arguments:",
21497   "     -v, --verbose              Print each filename as it is processed",
21498   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
21499   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
21500   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
21501   "     -g, --glob                 Use glob matching for names in archive",
21502   "     -n, --dryrun               Show the SQL that would have occurred",
21503   "   Examples:",
21504   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
21505   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
21506   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
21507   "   See also:",
21508   "      http://sqlite.org/cli.html#sqlite_archive_support",
21509 #endif
21510 #ifndef SQLITE_OMIT_AUTHORIZATION
21511   ".auth ON|OFF             Show authorizer callbacks",
21512 #endif
21513 #ifndef SQLITE_SHELL_FIDDLE
21514   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
21515   "   Options:",
21516   "       --append            Use the appendvfs",
21517   "       --async             Write to FILE without journal and fsync()",
21518 #endif
21519   ".bail on|off             Stop after hitting an error.  Default OFF",
21520 #ifndef SQLITE_SHELL_FIDDLE
21521   ".cd DIRECTORY            Change the working directory to DIRECTORY",
21522 #endif
21523   ".changes on|off          Show number of rows changed by SQL",
21524 #ifndef SQLITE_SHELL_FIDDLE
21525   ".check GLOB              Fail if output since .testcase does not match",
21526   ".clone NEWDB             Clone data into NEWDB from the existing database",
21527 #endif
21528   ".connection [close] [#]  Open or close an auxiliary database connection",
21529 #if defined(_WIN32) || defined(WIN32)
21530   ".crnl on|off             Translate \\n to \\r\\n.  Default ON",
21531 #endif
21532   ".databases               List names and files of attached databases",
21533   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
21534 #if SQLITE_SHELL_HAVE_RECOVER
21535   ".dbinfo ?DB?             Show status information about the database",
21536 #endif
21537   ".dump ?OBJECTS?          Render database content as SQL",
21538   "   Options:",
21539   "     --data-only            Output only INSERT statements",
21540   "     --newlines             Allow unescaped newline characters in output",
21541   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
21542   "     --preserve-rowids      Include ROWID values in the output",
21543   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
21544   "   Additional LIKE patterns can be given in subsequent arguments",
21545   ".echo on|off             Turn command echo on or off",
21546   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
21547   "   Other Modes:",
21548 #ifdef SQLITE_DEBUG
21549   "      test                  Show raw EXPLAIN QUERY PLAN output",
21550   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
21551 #endif
21552   "      trigger               Like \"full\" but also show trigger bytecode",
21553 #ifndef SQLITE_SHELL_FIDDLE
21554   ".excel                   Display the output of next command in spreadsheet",
21555   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
21556 #endif
21557 #ifndef SQLITE_SHELL_FIDDLE
21558   ".exit ?CODE?             Exit this program with return-code CODE",
21559 #endif
21560   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
21561   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
21562   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
21563   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
21564   "   --help                  Show CMD details",
21565   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
21566   ".headers on|off          Turn display of headers on or off",
21567   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
21568 #ifndef SQLITE_SHELL_FIDDLE
21569   ".import FILE TABLE       Import data from FILE into TABLE",
21570   "   Options:",
21571   "     --ascii               Use \\037 and \\036 as column and row separators",
21572   "     --csv                 Use , and \\n as column and row separators",
21573   "     --skip N              Skip the first N rows of input",
21574   "     --schema S            Target table to be S.TABLE",
21575   "     -v                    \"Verbose\" - increase auxiliary output",
21576   "   Notes:",
21577   "     *  If TABLE does not exist, it is created.  The first row of input",
21578   "        determines the column names.",
21579   "     *  If neither --csv or --ascii are used, the input mode is derived",
21580   "        from the \".mode\" output mode",
21581   "     *  If FILE begins with \"|\" then it is a command that generates the",
21582   "        input text.",
21583 #endif
21584 #ifndef SQLITE_OMIT_TEST_CONTROL
21585   ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
21586 #endif
21587   ".indexes ?TABLE?         Show names of indexes",
21588   "                           If TABLE is specified, only show indexes for",
21589   "                           tables matching TABLE using the LIKE operator.",
21590 #ifdef SQLITE_ENABLE_IOTRACE
21591   ",iotrace FILE            Enable I/O diagnostic logging to FILE",
21592 #endif
21593   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
21594   ".lint OPTIONS            Report potential schema issues.",
21595   "     Options:",
21596   "        fkey-indexes     Find missing foreign key indexes",
21597 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
21598   ".load FILE ?ENTRY?       Load an extension library",
21599 #endif
21600 #if !defined(SQLITE_SHELL_FIDDLE)
21601   ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
21602 #else
21603   ".log on|off              Turn logging on or off.",
21604 #endif
21605   ".mode MODE ?OPTIONS?     Set output mode",
21606   "   MODE is one of:",
21607   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
21608   "     box         Tables using unicode box-drawing characters",
21609   "     csv         Comma-separated values",
21610   "     column      Output in columns.  (See .width)",
21611   "     html        HTML <table> code",
21612   "     insert      SQL insert statements for TABLE",
21613   "     json        Results in a JSON array",
21614   "     line        One value per line",
21615   "     list        Values delimited by \"|\"",
21616   "     markdown    Markdown table format",
21617   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
21618   "     quote       Escape answers as for SQL",
21619   "     table       ASCII-art table",
21620   "     tabs        Tab-separated values",
21621   "     tcl         TCL list elements",
21622   "   OPTIONS: (for columnar modes or insert mode):",
21623   "     --wrap N       Wrap output lines to no longer than N characters",
21624   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
21625   "     --ww           Shorthand for \"--wordwrap 1\"",
21626   "     --quote        Quote output text as SQL literals",
21627   "     --noquote      Do not quote output text",
21628   "     TABLE          The name of SQL table used for \"insert\" mode",
21629 #ifndef SQLITE_SHELL_FIDDLE
21630   ".nonce STRING            Suspend safe mode for one command if nonce matches",
21631 #endif
21632   ".nullvalue STRING        Use STRING in place of NULL values",
21633 #ifndef SQLITE_SHELL_FIDDLE
21634   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
21635   "     If FILE begins with '|' then open as a pipe",
21636   "       --bom  Put a UTF8 byte-order mark at the beginning",
21637   "       -e     Send output to the system text editor",
21638   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
21639   /* Note that .open is (partially) available in WASM builds but is
21640   ** currently only intended to be used by the fiddle tool, not
21641   ** end users, so is "undocumented." */
21642   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
21643   "     Options:",
21644   "        --append        Use appendvfs to append database to the end of FILE",
21645 #endif
21646 #ifndef SQLITE_OMIT_DESERIALIZE
21647   "        --deserialize   Load into memory using sqlite3_deserialize()",
21648   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
21649   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
21650 #endif
21651   "        --new           Initialize FILE to an empty database",
21652   "        --nofollow      Do not follow symbolic links",
21653   "        --readonly      Open FILE readonly",
21654   "        --zip           FILE is a ZIP archive",
21655 #ifndef SQLITE_SHELL_FIDDLE
21656   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
21657   "   If FILE begins with '|' then open it as a pipe.",
21658   "   Options:",
21659   "     --bom                 Prefix output with a UTF8 byte-order mark",
21660   "     -e                    Send output to the system text editor",
21661   "     -x                    Send output as CSV to a spreadsheet",
21662 #endif
21663   ".parameter CMD ...       Manage SQL parameter bindings",
21664   "   clear                   Erase all bindings",
21665   "   init                    Initialize the TEMP table that holds bindings",
21666   "   list                    List the current parameter bindings",
21667   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
21668   "                           PARAMETER should start with one of: $ : @ ?",
21669   "   unset PARAMETER         Remove PARAMETER from the binding table",
21670   ".print STRING...         Print literal STRING",
21671 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
21672   ".progress N              Invoke progress handler after every N opcodes",
21673   "   --limit N                 Interrupt after N progress callbacks",
21674   "   --once                    Do no more than one progress interrupt",
21675   "   --quiet|-q                No output except at interrupts",
21676   "   --reset                   Reset the count for each input and interrupt",
21677 #endif
21678   ".prompt MAIN CONTINUE    Replace the standard prompts",
21679 #ifndef SQLITE_SHELL_FIDDLE
21680   ".quit                    Stop interpreting input stream, exit if primary.",
21681   ".read FILE               Read input from FILE or command output",
21682   "    If FILE begins with \"|\", it is a command that generates the input.",
21683 #endif
21684 #if SQLITE_SHELL_HAVE_RECOVER
21685   ".recover                 Recover as much data as possible from corrupt db.",
21686   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
21687   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
21688   "   --no-rowids              Do not attempt to recover rowid values",
21689   "                            that are not also INTEGER PRIMARY KEYs",
21690 #endif
21691 #ifndef SQLITE_SHELL_FIDDLE
21692   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
21693   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
21694 #endif
21695   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
21696   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
21697   "   Options:",
21698   "      --indent             Try to pretty-print the schema",
21699   "      --nosys              Omit objects whose names start with \"sqlite_\"",
21700   ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
21701   "    Options:",
21702   "       --init               Create a new SELFTEST table",
21703   "       -v                   Verbose output",
21704   ".separator COL ?ROW?     Change the column and row separators",
21705 #if defined(SQLITE_ENABLE_SESSION)
21706   ".session ?NAME? CMD ...  Create or control sessions",
21707   "   Subcommands:",
21708   "     attach TABLE             Attach TABLE",
21709   "     changeset FILE           Write a changeset into FILE",
21710   "     close                    Close one session",
21711   "     enable ?BOOLEAN?         Set or query the enable bit",
21712   "     filter GLOB...           Reject tables matching GLOBs",
21713   "     indirect ?BOOLEAN?       Mark or query the indirect status",
21714   "     isempty                  Query whether the session is empty",
21715   "     list                     List currently open session names",
21716   "     open DB NAME             Open a new session on DB",
21717   "     patchset FILE            Write a patchset into FILE",
21718   "   If ?NAME? is omitted, the first defined session is used.",
21719 #endif
21720   ".sha3sum ...             Compute a SHA3 hash of database content",
21721   "    Options:",
21722   "      --schema              Also hash the sqlite_schema table",
21723   "      --sha3-224            Use the sha3-224 algorithm",
21724   "      --sha3-256            Use the sha3-256 algorithm (default)",
21725   "      --sha3-384            Use the sha3-384 algorithm",
21726   "      --sha3-512            Use the sha3-512 algorithm",
21727   "    Any other argument is a LIKE pattern for tables to hash",
21728 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
21729   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
21730 #endif
21731   ".show                    Show the current values for various settings",
21732   ".stats ?ARG?             Show stats or turn stats on or off",
21733   "   off                      Turn off automatic stat display",
21734   "   on                       Turn on automatic stat display",
21735   "   stmt                     Show statement stats",
21736   "   vmstep                   Show the virtual machine step count only",
21737 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
21738   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
21739 #endif
21740   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
21741 #ifndef SQLITE_SHELL_FIDDLE
21742   ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
21743 #endif
21744   ",testctrl CMD ...        Run various sqlite3_test_control() operations",
21745   "                           Run \".testctrl\" with no arguments for details",
21746   ".timeout MS              Try opening locked tables for MS milliseconds",
21747   ".timer on|off            Turn SQL timer on or off",
21748 #ifndef SQLITE_OMIT_TRACE
21749   ".trace ?OPTIONS?         Output each SQL statement as it is run",
21750   "    FILE                    Send output to FILE",
21751   "    stdout                  Send output to stdout",
21752   "    stderr                  Send output to stderr",
21753   "    off                     Disable tracing",
21754   "    --expanded              Expand query parameters",
21755 #ifdef SQLITE_ENABLE_NORMALIZE
21756   "    --normalized            Normal the SQL statements",
21757 #endif
21758   "    --plain                 Show SQL as it is input",
21759   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
21760   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
21761   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
21762   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
21763 #endif /* SQLITE_OMIT_TRACE */
21764 #ifdef SQLITE_DEBUG
21765   ".unmodule NAME ...       Unregister virtual table modules",
21766   "    --allexcept             Unregister everything except those named",
21767 #endif
21768   ".version                 Show source, library and compiler versions",
21769   ".vfsinfo ?AUX?           Information about the top-level VFS",
21770   ".vfslist                 List all available VFSes",
21771   ".vfsname ?AUX?           Print the name of the VFS stack",
21772   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
21773   "     Negative values right-justify",
21774 };
21775 
21776 /*
21777 ** Output help text.
21778 **
21779 ** zPattern describes the set of commands for which help text is provided.
21780 ** If zPattern is NULL, then show all commands, but only give a one-line
21781 ** description of each.
21782 **
21783 ** Return the number of matches.
21784 */
showHelp(FILE * out,const char * zPattern)21785 static int showHelp(FILE *out, const char *zPattern){
21786   int i = 0;
21787   int j = 0;
21788   int n = 0;
21789   char *zPat;
21790   if( zPattern==0
21791    || zPattern[0]=='0'
21792    || cli_strcmp(zPattern,"-a")==0
21793    || cli_strcmp(zPattern,"-all")==0
21794    || cli_strcmp(zPattern,"--all")==0
21795   ){
21796     enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
21797     enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
21798     /* Show all or most commands
21799     ** *zPattern==0   => summary of documented commands only
21800     ** *zPattern=='0' => whole help for undocumented commands
21801     ** Otherwise      => whole help for documented commands
21802     */
21803     enum HelpWanted hw = HW_SummaryOnly;
21804     enum HelpHave hh = HH_More;
21805     if( zPattern!=0 ){
21806       hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
21807     }
21808     for(i=0; i<ArraySize(azHelp); i++){
21809       switch( azHelp[i][0] ){
21810       case ',':
21811         hh = HH_Summary|HH_Undoc;
21812         break;
21813       case '.':
21814         hh = HH_Summary;
21815         break;
21816       default:
21817         hh &= ~HH_Summary;
21818         break;
21819       }
21820       if( ((hw^hh)&HH_Undoc)==0 ){
21821         if( (hh&HH_Summary)!=0 ){
21822           sputf(out, ".%s\n", azHelp[i]+1);
21823           ++n;
21824         }else if( (hw&HW_SummaryOnly)==0 ){
21825           sputf(out, "%s\n", azHelp[i]);
21826         }
21827       }
21828     }
21829   }else{
21830     /* Seek documented commands for which zPattern is an exact prefix */
21831     zPat = sqlite3_mprintf(".%s*", zPattern);
21832     shell_check_oom(zPat);
21833     for(i=0; i<ArraySize(azHelp); i++){
21834       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
21835         sputf(out, "%s\n", azHelp[i]);
21836         j = i+1;
21837         n++;
21838       }
21839     }
21840     sqlite3_free(zPat);
21841     if( n ){
21842       if( n==1 ){
21843         /* when zPattern is a prefix of exactly one command, then include
21844         ** the details of that command, which should begin at offset j */
21845         while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
21846           sputf(out, "%s\n", azHelp[j]);
21847           j++;
21848         }
21849       }
21850       return n;
21851     }
21852     /* Look for documented commands that contain zPattern anywhere.
21853     ** Show complete text of all documented commands that match. */
21854     zPat = sqlite3_mprintf("%%%s%%", zPattern);
21855     shell_check_oom(zPat);
21856     for(i=0; i<ArraySize(azHelp); i++){
21857       if( azHelp[i][0]==',' ){
21858         while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
21859         continue;
21860       }
21861       if( azHelp[i][0]=='.' ) j = i;
21862       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
21863         sputf(out, "%s\n", azHelp[j]);
21864         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
21865           j++;
21866           sputf(out, "%s\n", azHelp[j]);
21867         }
21868         i = j;
21869         n++;
21870       }
21871     }
21872     sqlite3_free(zPat);
21873   }
21874   return n;
21875 }
21876 
21877 /* Forward reference */
21878 static int process_input(ShellState *p);
21879 
21880 /*
21881 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
21882 ** and return a pointer to the buffer. The caller is responsible for freeing
21883 ** the memory.
21884 **
21885 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
21886 ** read.
21887 **
21888 ** For convenience, a nul-terminator byte is always appended to the data read
21889 ** from the file before the buffer is returned. This byte is not included in
21890 ** the final value of (*pnByte), if applicable.
21891 **
21892 ** NULL is returned if any error is encountered. The final value of *pnByte
21893 ** is undefined in this case.
21894 */
readFile(const char * zName,int * pnByte)21895 static char *readFile(const char *zName, int *pnByte){
21896   FILE *in = fopen(zName, "rb");
21897   long nIn;
21898   size_t nRead;
21899   char *pBuf;
21900   int rc;
21901   if( in==0 ) return 0;
21902   rc = fseek(in, 0, SEEK_END);
21903   if( rc!=0 ){
21904     eputf("Error: '%s' not seekable\n", zName);
21905     fclose(in);
21906     return 0;
21907   }
21908   nIn = ftell(in);
21909   rewind(in);
21910   pBuf = sqlite3_malloc64( nIn+1 );
21911   if( pBuf==0 ){
21912     eputz("Error: out of memory\n");
21913     fclose(in);
21914     return 0;
21915   }
21916   nRead = fread(pBuf, nIn, 1, in);
21917   fclose(in);
21918   if( nRead!=1 ){
21919     sqlite3_free(pBuf);
21920     eputf("Error: cannot read '%s'\n", zName);
21921     return 0;
21922   }
21923   pBuf[nIn] = 0;
21924   if( pnByte ) *pnByte = nIn;
21925   return pBuf;
21926 }
21927 
21928 #if defined(SQLITE_ENABLE_SESSION)
21929 /*
21930 ** Close a single OpenSession object and release all of its associated
21931 ** resources.
21932 */
session_close(OpenSession * pSession)21933 static void session_close(OpenSession *pSession){
21934   int i;
21935   sqlite3session_delete(pSession->p);
21936   sqlite3_free(pSession->zName);
21937   for(i=0; i<pSession->nFilter; i++){
21938     sqlite3_free(pSession->azFilter[i]);
21939   }
21940   sqlite3_free(pSession->azFilter);
21941   memset(pSession, 0, sizeof(OpenSession));
21942 }
21943 #endif
21944 
21945 /*
21946 ** Close all OpenSession objects and release all associated resources.
21947 */
21948 #if defined(SQLITE_ENABLE_SESSION)
session_close_all(ShellState * p,int i)21949 static void session_close_all(ShellState *p, int i){
21950   int j;
21951   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
21952   for(j=0; j<pAuxDb->nSession; j++){
21953     session_close(&pAuxDb->aSession[j]);
21954   }
21955   pAuxDb->nSession = 0;
21956 }
21957 #else
21958 # define session_close_all(X,Y)
21959 #endif
21960 
21961 /*
21962 ** Implementation of the xFilter function for an open session.  Omit
21963 ** any tables named by ".session filter" but let all other table through.
21964 */
21965 #if defined(SQLITE_ENABLE_SESSION)
session_filter(void * pCtx,const char * zTab)21966 static int session_filter(void *pCtx, const char *zTab){
21967   OpenSession *pSession = (OpenSession*)pCtx;
21968   int i;
21969   for(i=0; i<pSession->nFilter; i++){
21970     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
21971   }
21972   return 1;
21973 }
21974 #endif
21975 
21976 /*
21977 ** Try to deduce the type of file for zName based on its content.  Return
21978 ** one of the SHELL_OPEN_* constants.
21979 **
21980 ** If the file does not exist or is empty but its name looks like a ZIP
21981 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
21982 ** Otherwise, assume an ordinary database regardless of the filename if
21983 ** the type cannot be determined from content.
21984 */
deduceDatabaseType(const char * zName,int dfltZip)21985 int deduceDatabaseType(const char *zName, int dfltZip){
21986   FILE *f = fopen(zName, "rb");
21987   size_t n;
21988   int rc = SHELL_OPEN_UNSPEC;
21989   char zBuf[100];
21990   if( f==0 ){
21991     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
21992        return SHELL_OPEN_ZIPFILE;
21993     }else{
21994        return SHELL_OPEN_NORMAL;
21995     }
21996   }
21997   n = fread(zBuf, 16, 1, f);
21998   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
21999     fclose(f);
22000     return SHELL_OPEN_NORMAL;
22001   }
22002   fseek(f, -25, SEEK_END);
22003   n = fread(zBuf, 25, 1, f);
22004   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
22005     rc = SHELL_OPEN_APPENDVFS;
22006   }else{
22007     fseek(f, -22, SEEK_END);
22008     n = fread(zBuf, 22, 1, f);
22009     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
22010        && zBuf[3]==0x06 ){
22011       rc = SHELL_OPEN_ZIPFILE;
22012     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
22013       rc = SHELL_OPEN_ZIPFILE;
22014     }
22015   }
22016   fclose(f);
22017   return rc;
22018 }
22019 
22020 #ifndef SQLITE_OMIT_DESERIALIZE
22021 /*
22022 ** Reconstruct an in-memory database using the output from the "dbtotxt"
22023 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
22024 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
22025 */
readHexDb(ShellState * p,int * pnData)22026 static unsigned char *readHexDb(ShellState *p, int *pnData){
22027   unsigned char *a = 0;
22028   int nLine;
22029   int n = 0;
22030   int pgsz = 0;
22031   int iOffset = 0;
22032   int j, k;
22033   int rc;
22034   FILE *in;
22035   const char *zDbFilename = p->pAuxDb->zDbFilename;
22036   unsigned int x[16];
22037   char zLine[1000];
22038   if( zDbFilename ){
22039     in = fopen(zDbFilename, "r");
22040     if( in==0 ){
22041       eputf("cannot open \"%s\" for reading\n", zDbFilename);
22042       return 0;
22043     }
22044     nLine = 0;
22045   }else{
22046     in = p->in;
22047     nLine = p->lineno;
22048     if( in==0 ) in = stdin;
22049   }
22050   *pnData = 0;
22051   nLine++;
22052   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
22053   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
22054   if( rc!=2 ) goto readHexDb_error;
22055   if( n<0 ) goto readHexDb_error;
22056   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
22057   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
22058   a = sqlite3_malloc( n ? n : 1 );
22059   shell_check_oom(a);
22060   memset(a, 0, n);
22061   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
22062     eputz("invalid pagesize\n");
22063     goto readHexDb_error;
22064   }
22065   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
22066     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
22067     if( rc==2 ){
22068       iOffset = k;
22069       continue;
22070     }
22071     if( cli_strncmp(zLine, "| end ", 6)==0 ){
22072       break;
22073     }
22074     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
22075                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
22076                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
22077     if( rc==17 ){
22078       k = iOffset+j;
22079       if( k+16<=n && k>=0 ){
22080         int ii;
22081         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
22082       }
22083     }
22084   }
22085   *pnData = n;
22086   if( in!=p->in ){
22087     fclose(in);
22088   }else{
22089     p->lineno = nLine;
22090   }
22091   return a;
22092 
22093 readHexDb_error:
22094   if( in!=p->in ){
22095     fclose(in);
22096   }else{
22097     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
22098       nLine++;
22099       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
22100     }
22101     p->lineno = nLine;
22102   }
22103   sqlite3_free(a);
22104   eputf("Error on line %d of --hexdb input\n", nLine);
22105   return 0;
22106 }
22107 #endif /* SQLITE_OMIT_DESERIALIZE */
22108 
22109 /*
22110 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
22111 */
shellUSleepFunc(sqlite3_context * context,int argcUnused,sqlite3_value ** argv)22112 static void shellUSleepFunc(
22113   sqlite3_context *context,
22114   int argcUnused,
22115   sqlite3_value **argv
22116 ){
22117   int sleep = sqlite3_value_int(argv[0]);
22118   (void)argcUnused;
22119   sqlite3_sleep(sleep/1000);
22120   sqlite3_result_int(context, sleep);
22121 }
22122 
22123 /* Flags for open_db().
22124 **
22125 ** The default behavior of open_db() is to exit(1) if the database fails to
22126 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
22127 ** but still returns without calling exit.
22128 **
22129 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
22130 ** ZIP archive if the file does not exist or is empty and its name matches
22131 ** the *.zip pattern.
22132 */
22133 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
22134 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
22135 
22136 /*
22137 ** Make sure the database is open.  If it is not, then open it.  If
22138 ** the database fails to open, print an error message and exit.
22139 */
open_db(ShellState * p,int openFlags)22140 static void open_db(ShellState *p, int openFlags){
22141   if( p->db==0 ){
22142     const char *zDbFilename = p->pAuxDb->zDbFilename;
22143     if( p->openMode==SHELL_OPEN_UNSPEC ){
22144       if( zDbFilename==0 || zDbFilename[0]==0 ){
22145         p->openMode = SHELL_OPEN_NORMAL;
22146       }else{
22147         p->openMode = (u8)deduceDatabaseType(zDbFilename,
22148                              (openFlags & OPEN_DB_ZIPFILE)!=0);
22149       }
22150     }
22151     switch( p->openMode ){
22152       case SHELL_OPEN_APPENDVFS: {
22153         sqlite3_open_v2(zDbFilename, &p->db,
22154            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
22155         break;
22156       }
22157       case SHELL_OPEN_HEXDB:
22158       case SHELL_OPEN_DESERIALIZE: {
22159         sqlite3_open(0, &p->db);
22160         break;
22161       }
22162       case SHELL_OPEN_ZIPFILE: {
22163         sqlite3_open(":memory:", &p->db);
22164         break;
22165       }
22166       case SHELL_OPEN_READONLY: {
22167         sqlite3_open_v2(zDbFilename, &p->db,
22168             SQLITE_OPEN_READONLY|p->openFlags, 0);
22169         break;
22170       }
22171       case SHELL_OPEN_UNSPEC:
22172       case SHELL_OPEN_NORMAL: {
22173         sqlite3_open_v2(zDbFilename, &p->db,
22174            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
22175         break;
22176       }
22177     }
22178     globalDb = p->db;
22179     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22180       eputf("Error: unable to open database \"%s\": %s\n",
22181             zDbFilename, sqlite3_errmsg(p->db));
22182       if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
22183         exit(1);
22184       }
22185       sqlite3_close(p->db);
22186       sqlite3_open(":memory:", &p->db);
22187       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22188         eputz("Also: unable to open substitute in-memory database.\n");
22189         exit(1);
22190       }else{
22191         eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
22192               zDbFilename);
22193       }
22194     }
22195     sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
22196 
22197     /* Reflect the use or absence of --unsafe-testing invocation. */
22198     {
22199       int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
22200       sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
22201       sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
22202     }
22203 
22204 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22205     sqlite3_enable_load_extension(p->db, 1);
22206 #endif
22207     sqlite3_shathree_init(p->db, 0, 0);
22208     sqlite3_uint_init(p->db, 0, 0);
22209     sqlite3_decimal_init(p->db, 0, 0);
22210     sqlite3_base64_init(p->db, 0, 0);
22211     sqlite3_base85_init(p->db, 0, 0);
22212     sqlite3_regexp_init(p->db, 0, 0);
22213     sqlite3_ieee_init(p->db, 0, 0);
22214     sqlite3_series_init(p->db, 0, 0);
22215 #ifndef SQLITE_SHELL_FIDDLE
22216     sqlite3_fileio_init(p->db, 0, 0);
22217     sqlite3_completion_init(p->db, 0, 0);
22218 #endif
22219 #ifdef SQLITE_HAVE_ZLIB
22220     if( !p->bSafeModePersist ){
22221       sqlite3_zipfile_init(p->db, 0, 0);
22222       sqlite3_sqlar_init(p->db, 0, 0);
22223     }
22224 #endif
22225 #ifdef SQLITE_SHELL_EXTFUNCS
22226     /* Create a preprocessing mechanism for extensions to make
22227      * their own provisions for being built into the shell.
22228      * This is a short-span macro. See further below for usage.
22229      */
22230 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
22231 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
22232     /* Let custom-included extensions get their ..._init() called.
22233      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
22234      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
22235      * initialization routine to be called.
22236      */
22237     {
22238       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
22239     /* Let custom-included extensions expose their functionality.
22240      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
22241      * the SQL functions, virtual tables, collating sequences or
22242      * VFS's implemented by the extension to be registered.
22243      */
22244       if( irc==SQLITE_OK
22245           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
22246         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
22247       }
22248 #undef SHELL_SUB_MACRO
22249 #undef SHELL_SUBMACRO
22250     }
22251 #endif
22252 
22253     sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
22254                             shellStrtod, 0, 0);
22255     sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
22256                             shellDtostr, 0, 0);
22257     sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
22258                             shellDtostr, 0, 0);
22259     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
22260                             shellAddSchemaName, 0, 0);
22261     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
22262                             shellModuleSchema, 0, 0);
22263     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
22264                             shellPutsFunc, 0, 0);
22265     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
22266                             shellUSleepFunc, 0, 0);
22267 #ifndef SQLITE_NOHAVE_SYSTEM
22268     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
22269                             editFunc, 0, 0);
22270     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
22271                             editFunc, 0, 0);
22272 #endif
22273 
22274 // Begin Android Add
22275 #ifndef NO_ANDROID_FUNCS
22276     int err = register_localized_collators(p->db, "en_US", 0);
22277     if (err != SQLITE_OK) {
22278       fprintf(stderr, "register_localized_collators() failed\n");
22279       exit(1);
22280     }
22281     err = register_android_functions(p->db, 0);
22282     if (err != SQLITE_OK) {
22283       fprintf(stderr, "register_android_functions() failed\n");
22284       exit(1);
22285     }
22286 #endif
22287 // End Android Add
22288 
22289     if( p->openMode==SHELL_OPEN_ZIPFILE ){
22290       char *zSql = sqlite3_mprintf(
22291          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
22292       shell_check_oom(zSql);
22293       sqlite3_exec(p->db, zSql, 0, 0, 0);
22294       sqlite3_free(zSql);
22295     }
22296 #ifndef SQLITE_OMIT_DESERIALIZE
22297     else
22298     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
22299       int rc;
22300       int nData = 0;
22301       unsigned char *aData;
22302       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
22303         aData = (unsigned char*)readFile(zDbFilename, &nData);
22304       }else{
22305         aData = readHexDb(p, &nData);
22306       }
22307       if( aData==0 ){
22308         return;
22309       }
22310       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
22311                    SQLITE_DESERIALIZE_RESIZEABLE |
22312                    SQLITE_DESERIALIZE_FREEONCLOSE);
22313       if( rc ){
22314         eputf("Error: sqlite3_deserialize() returns %d\n", rc);
22315       }
22316       if( p->szMax>0 ){
22317         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
22318       }
22319     }
22320 #endif
22321   }
22322   if( p->db!=0 ){
22323     if( p->bSafeModePersist ){
22324       sqlite3_set_authorizer(p->db, safeModeAuth, p);
22325     }
22326     sqlite3_db_config(
22327         p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
22328     );
22329   }
22330 }
22331 
22332 /*
22333 ** Attempt to close the database connection.  Report errors.
22334 */
close_db(sqlite3 * db)22335 void close_db(sqlite3 *db){
22336   int rc = sqlite3_close(db);
22337   if( rc ){
22338     eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
22339   }
22340 }
22341 
22342 #if HAVE_READLINE || HAVE_EDITLINE
22343 /*
22344 ** Readline completion callbacks
22345 */
readline_completion_generator(const char * text,int state)22346 static char *readline_completion_generator(const char *text, int state){
22347   static sqlite3_stmt *pStmt = 0;
22348   char *zRet;
22349   if( state==0 ){
22350     char *zSql;
22351     sqlite3_finalize(pStmt);
22352     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
22353                            "  FROM completion(%Q) ORDER BY 1", text);
22354     shell_check_oom(zSql);
22355     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
22356     sqlite3_free(zSql);
22357   }
22358   if( sqlite3_step(pStmt)==SQLITE_ROW ){
22359     const char *z = (const char*)sqlite3_column_text(pStmt,0);
22360     zRet = z ? strdup(z) : 0;
22361   }else{
22362     sqlite3_finalize(pStmt);
22363     pStmt = 0;
22364     zRet = 0;
22365   }
22366   return zRet;
22367 }
readline_completion(const char * zText,int iStart,int iEnd)22368 static char **readline_completion(const char *zText, int iStart, int iEnd){
22369   (void)iStart;
22370   (void)iEnd;
22371   rl_attempted_completion_over = 1;
22372   return rl_completion_matches(zText, readline_completion_generator);
22373 }
22374 
22375 #elif HAVE_LINENOISE
22376 /*
22377 ** Linenoise completion callback
22378 */
linenoise_completion(const char * zLine,linenoiseCompletions * lc)22379 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
22380   i64 nLine = strlen(zLine);
22381   i64 i, iStart;
22382   sqlite3_stmt *pStmt = 0;
22383   char *zSql;
22384   char zBuf[1000];
22385 
22386   if( nLine>(i64)sizeof(zBuf)-30 ) return;
22387   if( zLine[0]=='.' || zLine[0]=='#') return;
22388   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
22389   if( i==nLine-1 ) return;
22390   iStart = i+1;
22391   memcpy(zBuf, zLine, iStart);
22392   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
22393                          "  FROM completion(%Q,%Q) ORDER BY 1",
22394                          &zLine[iStart], zLine);
22395   shell_check_oom(zSql);
22396   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
22397   sqlite3_free(zSql);
22398   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
22399   while( sqlite3_step(pStmt)==SQLITE_ROW ){
22400     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
22401     int nCompletion = sqlite3_column_bytes(pStmt, 0);
22402     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
22403       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
22404       linenoiseAddCompletion(lc, zBuf);
22405     }
22406   }
22407   sqlite3_finalize(pStmt);
22408 }
22409 #endif
22410 
22411 /*
22412 ** Do C-language style dequoting.
22413 **
22414 **    \a    -> alarm
22415 **    \b    -> backspace
22416 **    \t    -> tab
22417 **    \n    -> newline
22418 **    \v    -> vertical tab
22419 **    \f    -> form feed
22420 **    \r    -> carriage return
22421 **    \s    -> space
22422 **    \"    -> "
22423 **    \'    -> '
22424 **    \\    -> backslash
22425 **    \NNN  -> ascii character NNN in octal
22426 **    \xHH  -> ascii character HH in hexadecimal
22427 */
resolve_backslashes(char * z)22428 static void resolve_backslashes(char *z){
22429   int i, j;
22430   char c;
22431   while( *z && *z!='\\' ) z++;
22432   for(i=j=0; (c = z[i])!=0; i++, j++){
22433     if( c=='\\' && z[i+1]!=0 ){
22434       c = z[++i];
22435       if( c=='a' ){
22436         c = '\a';
22437       }else if( c=='b' ){
22438         c = '\b';
22439       }else if( c=='t' ){
22440         c = '\t';
22441       }else if( c=='n' ){
22442         c = '\n';
22443       }else if( c=='v' ){
22444         c = '\v';
22445       }else if( c=='f' ){
22446         c = '\f';
22447       }else if( c=='r' ){
22448         c = '\r';
22449       }else if( c=='"' ){
22450         c = '"';
22451       }else if( c=='\'' ){
22452         c = '\'';
22453       }else if( c=='\\' ){
22454         c = '\\';
22455       }else if( c=='x' ){
22456         int nhd = 0, hdv;
22457         u8 hv = 0;
22458         while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
22459           hv = (u8)((hv<<4)|hdv);
22460           ++nhd;
22461         }
22462         i += nhd;
22463         c = (u8)hv;
22464       }else if( c>='0' && c<='7' ){
22465         c -= '0';
22466         if( z[i+1]>='0' && z[i+1]<='7' ){
22467           i++;
22468           c = (c<<3) + z[i] - '0';
22469           if( z[i+1]>='0' && z[i+1]<='7' ){
22470             i++;
22471             c = (c<<3) + z[i] - '0';
22472           }
22473         }
22474       }
22475     }
22476     z[j] = c;
22477   }
22478   if( j<i ) z[j] = 0;
22479 }
22480 
22481 /*
22482 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
22483 ** for TRUE and FALSE.  Return the integer value if appropriate.
22484 */
booleanValue(const char * zArg)22485 static int booleanValue(const char *zArg){
22486   int i;
22487   if( zArg[0]=='0' && zArg[1]=='x' ){
22488     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
22489   }else{
22490     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
22491   }
22492   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
22493   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
22494     return 1;
22495   }
22496   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
22497     return 0;
22498   }
22499   eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
22500   return 0;
22501 }
22502 
22503 /*
22504 ** Set or clear a shell flag according to a boolean value.
22505 */
setOrClearFlag(ShellState * p,unsigned mFlag,const char * zArg)22506 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
22507   if( booleanValue(zArg) ){
22508     ShellSetFlag(p, mFlag);
22509   }else{
22510     ShellClearFlag(p, mFlag);
22511   }
22512 }
22513 
22514 /*
22515 ** Close an output file, assuming it is not stderr or stdout
22516 */
output_file_close(FILE * f)22517 static void output_file_close(FILE *f){
22518   if( f && f!=stdout && f!=stderr ) fclose(f);
22519 }
22520 
22521 /*
22522 ** Try to open an output file.   The names "stdout" and "stderr" are
22523 ** recognized and do the right thing.  NULL is returned if the output
22524 ** filename is "off".
22525 */
output_file_open(const char * zFile,int bTextMode)22526 static FILE *output_file_open(const char *zFile, int bTextMode){
22527   FILE *f;
22528   if( cli_strcmp(zFile,"stdout")==0 ){
22529     f = stdout;
22530   }else if( cli_strcmp(zFile, "stderr")==0 ){
22531     f = stderr;
22532   }else if( cli_strcmp(zFile, "off")==0 ){
22533     f = 0;
22534   }else{
22535     f = fopen(zFile, bTextMode ? "w" : "wb");
22536     if( f==0 ){
22537       eputf("Error: cannot open \"%s\"\n", zFile);
22538     }
22539   }
22540   return f;
22541 }
22542 
22543 #ifndef SQLITE_OMIT_TRACE
22544 /*
22545 ** A routine for handling output from sqlite3_trace().
22546 */
sql_trace_callback(unsigned mType,void * pArg,void * pP,void * pX)22547 static int sql_trace_callback(
22548   unsigned mType,         /* The trace type */
22549   void *pArg,             /* The ShellState pointer */
22550   void *pP,               /* Usually a pointer to sqlite_stmt */
22551   void *pX                /* Auxiliary output */
22552 ){
22553   ShellState *p = (ShellState*)pArg;
22554   sqlite3_stmt *pStmt;
22555   const char *zSql;
22556   i64 nSql;
22557   if( p->traceOut==0 ) return 0;
22558   if( mType==SQLITE_TRACE_CLOSE ){
22559     sputz(p->traceOut, "-- closing database connection\n");
22560     return 0;
22561   }
22562   if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
22563     zSql = (const char*)pX;
22564   }else{
22565     pStmt = (sqlite3_stmt*)pP;
22566     switch( p->eTraceType ){
22567       case SHELL_TRACE_EXPANDED: {
22568         zSql = sqlite3_expanded_sql(pStmt);
22569         break;
22570       }
22571 #ifdef SQLITE_ENABLE_NORMALIZE
22572       case SHELL_TRACE_NORMALIZED: {
22573         zSql = sqlite3_normalized_sql(pStmt);
22574         break;
22575       }
22576 #endif
22577       default: {
22578         zSql = sqlite3_sql(pStmt);
22579         break;
22580       }
22581     }
22582   }
22583   if( zSql==0 ) return 0;
22584   nSql = strlen(zSql);
22585   if( nSql>1000000000 ) nSql = 1000000000;
22586   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
22587   switch( mType ){
22588     case SQLITE_TRACE_ROW:
22589     case SQLITE_TRACE_STMT: {
22590       sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
22591       break;
22592     }
22593     case SQLITE_TRACE_PROFILE: {
22594       sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
22595       sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
22596       break;
22597     }
22598   }
22599   return 0;
22600 }
22601 #endif
22602 
22603 /*
22604 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
22605 ** a useful spot to set a debugger breakpoint.
22606 **
22607 ** This routine does not do anything practical.  The code are there simply
22608 ** to prevent the compiler from optimizing this routine out.
22609 */
test_breakpoint(void)22610 static void test_breakpoint(void){
22611   static unsigned int nCall = 0;
22612   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
22613 }
22614 
22615 /*
22616 ** An object used to read a CSV and other files for import.
22617 */
22618 typedef struct ImportCtx ImportCtx;
22619 struct ImportCtx {
22620   const char *zFile;  /* Name of the input file */
22621   FILE *in;           /* Read the CSV text from this input stream */
22622   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
22623   char *z;            /* Accumulated text for a field */
22624   int n;              /* Number of bytes in z */
22625   int nAlloc;         /* Space allocated for z[] */
22626   int nLine;          /* Current line number */
22627   int nRow;           /* Number of rows imported */
22628   int nErr;           /* Number of errors encountered */
22629   int bNotFirst;      /* True if one or more bytes already read */
22630   int cTerm;          /* Character that terminated the most recent field */
22631   int cColSep;        /* The column separator character.  (Usually ",") */
22632   int cRowSep;        /* The row separator character.  (Usually "\n") */
22633 };
22634 
22635 /* Clean up resourced used by an ImportCtx */
import_cleanup(ImportCtx * p)22636 static void import_cleanup(ImportCtx *p){
22637   if( p->in!=0 && p->xCloser!=0 ){
22638     p->xCloser(p->in);
22639     p->in = 0;
22640   }
22641   sqlite3_free(p->z);
22642   p->z = 0;
22643 }
22644 
22645 /* Append a single byte to z[] */
import_append_char(ImportCtx * p,int c)22646 static void import_append_char(ImportCtx *p, int c){
22647   if( p->n+1>=p->nAlloc ){
22648     p->nAlloc += p->nAlloc + 100;
22649     p->z = sqlite3_realloc64(p->z, p->nAlloc);
22650     shell_check_oom(p->z);
22651   }
22652   p->z[p->n++] = (char)c;
22653 }
22654 
22655 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
22656 ** with the option of having a separator other than ",".
22657 **
22658 **   +  Input comes from p->in.
22659 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
22660 **      from sqlite3_malloc64().
22661 **   +  Use p->cSep as the column separator.  The default is ",".
22662 **   +  Use p->rSep as the row separator.  The default is "\n".
22663 **   +  Keep track of the line number in p->nLine.
22664 **   +  Store the character that terminates the field in p->cTerm.  Store
22665 **      EOF on end-of-file.
22666 **   +  Report syntax errors on stderr
22667 */
csv_read_one_field(ImportCtx * p)22668 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
22669   int c;
22670   int cSep = (u8)p->cColSep;
22671   int rSep = (u8)p->cRowSep;
22672   p->n = 0;
22673   c = fgetc(p->in);
22674   if( c==EOF || seenInterrupt ){
22675     p->cTerm = EOF;
22676     return 0;
22677   }
22678   if( c=='"' ){
22679     int pc, ppc;
22680     int startLine = p->nLine;
22681     int cQuote = c;
22682     pc = ppc = 0;
22683     while( 1 ){
22684       c = fgetc(p->in);
22685       if( c==rSep ) p->nLine++;
22686       if( c==cQuote ){
22687         if( pc==cQuote ){
22688           pc = 0;
22689           continue;
22690         }
22691       }
22692       if( (c==cSep && pc==cQuote)
22693        || (c==rSep && pc==cQuote)
22694        || (c==rSep && pc=='\r' && ppc==cQuote)
22695        || (c==EOF && pc==cQuote)
22696       ){
22697         do{ p->n--; }while( p->z[p->n]!=cQuote );
22698         p->cTerm = c;
22699         break;
22700       }
22701       if( pc==cQuote && c!='\r' ){
22702         eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
22703       }
22704       if( c==EOF ){
22705         eputf("%s:%d: unterminated %c-quoted field\n",
22706               p->zFile, startLine, cQuote);
22707         p->cTerm = c;
22708         break;
22709       }
22710       import_append_char(p, c);
22711       ppc = pc;
22712       pc = c;
22713     }
22714   }else{
22715     /* If this is the first field being parsed and it begins with the
22716     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
22717     if( (c&0xff)==0xef && p->bNotFirst==0 ){
22718       import_append_char(p, c);
22719       c = fgetc(p->in);
22720       if( (c&0xff)==0xbb ){
22721         import_append_char(p, c);
22722         c = fgetc(p->in);
22723         if( (c&0xff)==0xbf ){
22724           p->bNotFirst = 1;
22725           p->n = 0;
22726           return csv_read_one_field(p);
22727         }
22728       }
22729     }
22730     while( c!=EOF && c!=cSep && c!=rSep ){
22731       import_append_char(p, c);
22732       c = fgetc(p->in);
22733     }
22734     if( c==rSep ){
22735       p->nLine++;
22736       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
22737     }
22738     p->cTerm = c;
22739   }
22740   if( p->z ) p->z[p->n] = 0;
22741   p->bNotFirst = 1;
22742   return p->z;
22743 }
22744 
22745 /* Read a single field of ASCII delimited text.
22746 **
22747 **   +  Input comes from p->in.
22748 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
22749 **      from sqlite3_malloc64().
22750 **   +  Use p->cSep as the column separator.  The default is "\x1F".
22751 **   +  Use p->rSep as the row separator.  The default is "\x1E".
22752 **   +  Keep track of the row number in p->nLine.
22753 **   +  Store the character that terminates the field in p->cTerm.  Store
22754 **      EOF on end-of-file.
22755 **   +  Report syntax errors on stderr
22756 */
ascii_read_one_field(ImportCtx * p)22757 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
22758   int c;
22759   int cSep = (u8)p->cColSep;
22760   int rSep = (u8)p->cRowSep;
22761   p->n = 0;
22762   c = fgetc(p->in);
22763   if( c==EOF || seenInterrupt ){
22764     p->cTerm = EOF;
22765     return 0;
22766   }
22767   while( c!=EOF && c!=cSep && c!=rSep ){
22768     import_append_char(p, c);
22769     c = fgetc(p->in);
22770   }
22771   if( c==rSep ){
22772     p->nLine++;
22773   }
22774   p->cTerm = c;
22775   if( p->z ) p->z[p->n] = 0;
22776   return p->z;
22777 }
22778 
22779 /*
22780 ** Try to transfer data for table zTable.  If an error is seen while
22781 ** moving forward, try to go backwards.  The backwards movement won't
22782 ** work for WITHOUT ROWID tables.
22783 */
tryToCloneData(ShellState * p,sqlite3 * newDb,const char * zTable)22784 static void tryToCloneData(
22785   ShellState *p,
22786   sqlite3 *newDb,
22787   const char *zTable
22788 ){
22789   sqlite3_stmt *pQuery = 0;
22790   sqlite3_stmt *pInsert = 0;
22791   char *zQuery = 0;
22792   char *zInsert = 0;
22793   int rc;
22794   int i, j, n;
22795   int nTable = strlen30(zTable);
22796   int k = 0;
22797   int cnt = 0;
22798   const int spinRate = 10000;
22799 
22800   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
22801   shell_check_oom(zQuery);
22802   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22803   if( rc ){
22804     eputf("Error %d: %s on [%s]\n",
22805           sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
22806     goto end_data_xfer;
22807   }
22808   n = sqlite3_column_count(pQuery);
22809   zInsert = sqlite3_malloc64(200 + nTable + n*3);
22810   shell_check_oom(zInsert);
22811   sqlite3_snprintf(200+nTable,zInsert,
22812                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
22813   i = strlen30(zInsert);
22814   for(j=1; j<n; j++){
22815     memcpy(zInsert+i, ",?", 2);
22816     i += 2;
22817   }
22818   memcpy(zInsert+i, ");", 3);
22819   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
22820   if( rc ){
22821     eputf("Error %d: %s on [%s]\n",
22822           sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
22823     goto end_data_xfer;
22824   }
22825   for(k=0; k<2; k++){
22826     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22827       for(i=0; i<n; i++){
22828         switch( sqlite3_column_type(pQuery, i) ){
22829           case SQLITE_NULL: {
22830             sqlite3_bind_null(pInsert, i+1);
22831             break;
22832           }
22833           case SQLITE_INTEGER: {
22834             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
22835             break;
22836           }
22837           case SQLITE_FLOAT: {
22838             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
22839             break;
22840           }
22841           case SQLITE_TEXT: {
22842             sqlite3_bind_text(pInsert, i+1,
22843                              (const char*)sqlite3_column_text(pQuery,i),
22844                              -1, SQLITE_STATIC);
22845             break;
22846           }
22847           case SQLITE_BLOB: {
22848             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
22849                                             sqlite3_column_bytes(pQuery,i),
22850                                             SQLITE_STATIC);
22851             break;
22852           }
22853         }
22854       } /* End for */
22855       rc = sqlite3_step(pInsert);
22856       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
22857         eputf("Error %d: %s\n",
22858               sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
22859       }
22860       sqlite3_reset(pInsert);
22861       cnt++;
22862       if( (cnt%spinRate)==0 ){
22863         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
22864         fflush(stdout);
22865       }
22866     } /* End while */
22867     if( rc==SQLITE_DONE ) break;
22868     sqlite3_finalize(pQuery);
22869     sqlite3_free(zQuery);
22870     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
22871                              zTable);
22872     shell_check_oom(zQuery);
22873     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22874     if( rc ){
22875       eputf("Warning: cannot step \"%s\" backwards", zTable);
22876       break;
22877     }
22878   } /* End for(k=0...) */
22879 
22880 end_data_xfer:
22881   sqlite3_finalize(pQuery);
22882   sqlite3_finalize(pInsert);
22883   sqlite3_free(zQuery);
22884   sqlite3_free(zInsert);
22885 }
22886 
22887 
22888 /*
22889 ** Try to transfer all rows of the schema that match zWhere.  For
22890 ** each row, invoke xForEach() on the object defined by that row.
22891 ** If an error is encountered while moving forward through the
22892 ** sqlite_schema table, try again moving backwards.
22893 */
tryToCloneSchema(ShellState * p,sqlite3 * newDb,const char * zWhere,void (* xForEach)(ShellState *,sqlite3 *,const char *))22894 static void tryToCloneSchema(
22895   ShellState *p,
22896   sqlite3 *newDb,
22897   const char *zWhere,
22898   void (*xForEach)(ShellState*,sqlite3*,const char*)
22899 ){
22900   sqlite3_stmt *pQuery = 0;
22901   char *zQuery = 0;
22902   int rc;
22903   const unsigned char *zName;
22904   const unsigned char *zSql;
22905   char *zErrMsg = 0;
22906 
22907   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22908                            " WHERE %s ORDER BY rowid ASC", zWhere);
22909   shell_check_oom(zQuery);
22910   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22911   if( rc ){
22912     eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
22913           sqlite3_errmsg(p->db), zQuery);
22914     goto end_schema_xfer;
22915   }
22916   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22917     zName = sqlite3_column_text(pQuery, 0);
22918     zSql = sqlite3_column_text(pQuery, 1);
22919     if( zName==0 || zSql==0 ) continue;
22920     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
22921       sputf(stdout, "%s... ", zName); fflush(stdout);
22922       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22923       if( zErrMsg ){
22924         eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22925         sqlite3_free(zErrMsg);
22926         zErrMsg = 0;
22927       }
22928     }
22929     if( xForEach ){
22930       xForEach(p, newDb, (const char*)zName);
22931     }
22932     sputz(stdout, "done\n");
22933   }
22934   if( rc!=SQLITE_DONE ){
22935     sqlite3_finalize(pQuery);
22936     sqlite3_free(zQuery);
22937     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22938                              " WHERE %s ORDER BY rowid DESC", zWhere);
22939     shell_check_oom(zQuery);
22940     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22941     if( rc ){
22942       eputf("Error: (%d) %s on [%s]\n",
22943             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
22944       goto end_schema_xfer;
22945     }
22946     while( sqlite3_step(pQuery)==SQLITE_ROW ){
22947       zName = sqlite3_column_text(pQuery, 0);
22948       zSql = sqlite3_column_text(pQuery, 1);
22949       if( zName==0 || zSql==0 ) continue;
22950       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
22951       sputf(stdout, "%s... ", zName); fflush(stdout);
22952       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22953       if( zErrMsg ){
22954         eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22955         sqlite3_free(zErrMsg);
22956         zErrMsg = 0;
22957       }
22958       if( xForEach ){
22959         xForEach(p, newDb, (const char*)zName);
22960       }
22961       sputz(stdout, "done\n");
22962     }
22963   }
22964 end_schema_xfer:
22965   sqlite3_finalize(pQuery);
22966   sqlite3_free(zQuery);
22967 }
22968 
22969 /*
22970 ** Open a new database file named "zNewDb".  Try to recover as much information
22971 ** as possible out of the main database (which might be corrupt) and write it
22972 ** into zNewDb.
22973 */
tryToClone(ShellState * p,const char * zNewDb)22974 static void tryToClone(ShellState *p, const char *zNewDb){
22975   int rc;
22976   sqlite3 *newDb = 0;
22977   if( access(zNewDb,0)==0 ){
22978     eputf("File \"%s\" already exists.\n", zNewDb);
22979     return;
22980   }
22981   rc = sqlite3_open(zNewDb, &newDb);
22982   if( rc ){
22983     eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
22984   }else{
22985     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
22986     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
22987     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
22988     tryToCloneSchema(p, newDb, "type!='table'", 0);
22989     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
22990     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
22991   }
22992   close_db(newDb);
22993 }
22994 
22995 #ifndef SQLITE_SHELL_FIDDLE
22996 /*
22997 ** Change the output stream (file or pipe or console) to something else.
22998 */
output_redir(ShellState * p,FILE * pfNew)22999 static void output_redir(ShellState *p, FILE *pfNew){
23000   if( p->out != stdout ) eputz("Output already redirected.\n");
23001   else{
23002     p->out = pfNew;
23003     setOutputStream(pfNew);
23004   }
23005 }
23006 
23007 /*
23008 ** Change the output file back to stdout.
23009 **
23010 ** If the p->doXdgOpen flag is set, that means the output was being
23011 ** redirected to a temporary file named by p->zTempFile.  In that case,
23012 ** launch start/open/xdg-open on that temporary file.
23013 */
output_reset(ShellState * p)23014 static void output_reset(ShellState *p){
23015   if( p->outfile[0]=='|' ){
23016 #ifndef SQLITE_OMIT_POPEN
23017     pclose(p->out);
23018 #endif
23019   }else{
23020     output_file_close(p->out);
23021 #ifndef SQLITE_NOHAVE_SYSTEM
23022     if( p->doXdgOpen ){
23023       const char *zXdgOpenCmd =
23024 #if defined(_WIN32)
23025       "start";
23026 #elif defined(__APPLE__)
23027       "open";
23028 #else
23029       "xdg-open";
23030 #endif
23031       char *zCmd;
23032       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
23033       if( system(zCmd) ){
23034         eputf("Failed: [%s]\n", zCmd);
23035       }else{
23036         /* Give the start/open/xdg-open command some time to get
23037         ** going before we continue, and potential delete the
23038         ** p->zTempFile data file out from under it */
23039         sqlite3_sleep(2000);
23040       }
23041       sqlite3_free(zCmd);
23042       outputModePop(p);
23043       p->doXdgOpen = 0;
23044     }
23045 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
23046   }
23047   p->outfile[0] = 0;
23048   p->out = stdout;
23049   setOutputStream(stdout);
23050 }
23051 #else
23052 # define output_redir(SS,pfO)
23053 # define output_reset(SS)
23054 #endif
23055 
23056 /*
23057 ** Run an SQL command and return the single integer result.
23058 */
db_int(sqlite3 * db,const char * zSql)23059 static int db_int(sqlite3 *db, const char *zSql){
23060   sqlite3_stmt *pStmt;
23061   int res = 0;
23062   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
23063   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
23064     res = sqlite3_column_int(pStmt,0);
23065   }
23066   sqlite3_finalize(pStmt);
23067   return res;
23068 }
23069 
23070 #if SQLITE_SHELL_HAVE_RECOVER
23071 /*
23072 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
23073 */
get2byteInt(unsigned char * a)23074 static unsigned int get2byteInt(unsigned char *a){
23075   return (a[0]<<8) + a[1];
23076 }
get4byteInt(unsigned char * a)23077 static unsigned int get4byteInt(unsigned char *a){
23078   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
23079 }
23080 
23081 /*
23082 ** Implementation of the ".dbinfo" command.
23083 **
23084 ** Return 1 on error, 2 to exit, and 0 otherwise.
23085 */
shell_dbinfo_command(ShellState * p,int nArg,char ** azArg)23086 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
23087   static const struct { const char *zName; int ofst; } aField[] = {
23088      { "file change counter:",  24  },
23089      { "database page count:",  28  },
23090      { "freelist page count:",  36  },
23091      { "schema cookie:",        40  },
23092      { "schema format:",        44  },
23093      { "default cache size:",   48  },
23094      { "autovacuum top root:",  52  },
23095      { "incremental vacuum:",   64  },
23096      { "text encoding:",        56  },
23097      { "user version:",         60  },
23098      { "application id:",       68  },
23099      { "software version:",     96  },
23100   };
23101   static const struct { const char *zName; const char *zSql; } aQuery[] = {
23102      { "number of tables:",
23103        "SELECT count(*) FROM %s WHERE type='table'" },
23104      { "number of indexes:",
23105        "SELECT count(*) FROM %s WHERE type='index'" },
23106      { "number of triggers:",
23107        "SELECT count(*) FROM %s WHERE type='trigger'" },
23108      { "number of views:",
23109        "SELECT count(*) FROM %s WHERE type='view'" },
23110      { "schema size:",
23111        "SELECT total(length(sql)) FROM %s" },
23112   };
23113   int i, rc;
23114   unsigned iDataVersion;
23115   char *zSchemaTab;
23116   char *zDb = nArg>=2 ? azArg[1] : "main";
23117   sqlite3_stmt *pStmt = 0;
23118   unsigned char aHdr[100];
23119   open_db(p, 0);
23120   if( p->db==0 ) return 1;
23121   rc = sqlite3_prepare_v2(p->db,
23122              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
23123              -1, &pStmt, 0);
23124   if( rc ){
23125     eputf("error: %s\n", sqlite3_errmsg(p->db));
23126     sqlite3_finalize(pStmt);
23127     return 1;
23128   }
23129   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
23130   if( sqlite3_step(pStmt)==SQLITE_ROW
23131    && sqlite3_column_bytes(pStmt,0)>100
23132   ){
23133     const u8 *pb = sqlite3_column_blob(pStmt,0);
23134     shell_check_oom(pb);
23135     memcpy(aHdr, pb, 100);
23136     sqlite3_finalize(pStmt);
23137   }else{
23138     eputz("unable to read database header\n");
23139     sqlite3_finalize(pStmt);
23140     return 1;
23141   }
23142   i = get2byteInt(aHdr+16);
23143   if( i==1 ) i = 65536;
23144   oputf("%-20s %d\n", "database page size:", i);
23145   oputf("%-20s %d\n", "write format:", aHdr[18]);
23146   oputf("%-20s %d\n", "read format:", aHdr[19]);
23147   oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
23148   for(i=0; i<ArraySize(aField); i++){
23149     int ofst = aField[i].ofst;
23150     unsigned int val = get4byteInt(aHdr + ofst);
23151     oputf("%-20s %u", aField[i].zName, val);
23152     switch( ofst ){
23153       case 56: {
23154         if( val==1 ) oputz(" (utf8)");
23155         if( val==2 ) oputz(" (utf16le)");
23156         if( val==3 ) oputz(" (utf16be)");
23157       }
23158     }
23159     oputz("\n");
23160   }
23161   if( zDb==0 ){
23162     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
23163   }else if( cli_strcmp(zDb,"temp")==0 ){
23164     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
23165   }else{
23166     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
23167   }
23168   for(i=0; i<ArraySize(aQuery); i++){
23169     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
23170     int val = db_int(p->db, zSql);
23171     sqlite3_free(zSql);
23172     oputf("%-20s %d\n", aQuery[i].zName, val);
23173   }
23174   sqlite3_free(zSchemaTab);
23175   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
23176   oputf("%-20s %u\n", "data version", iDataVersion);
23177   return 0;
23178 }
23179 #endif /* SQLITE_SHELL_HAVE_RECOVER */
23180 
23181 /*
23182 ** Print the current sqlite3_errmsg() value to stderr and return 1.
23183 */
shellDatabaseError(sqlite3 * db)23184 static int shellDatabaseError(sqlite3 *db){
23185   const char *zErr = sqlite3_errmsg(db);
23186   eputf("Error: %s\n", zErr);
23187   return 1;
23188 }
23189 
23190 /*
23191 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
23192 ** if they match and FALSE (0) if they do not match.
23193 **
23194 ** Globbing rules:
23195 **
23196 **      '*'       Matches any sequence of zero or more characters.
23197 **
23198 **      '?'       Matches exactly one character.
23199 **
23200 **     [...]      Matches one character from the enclosed list of
23201 **                characters.
23202 **
23203 **     [^...]     Matches one character not in the enclosed list.
23204 **
23205 **      '#'       Matches any sequence of one or more digits with an
23206 **                optional + or - sign in front
23207 **
23208 **      ' '       Any span of whitespace matches any other span of
23209 **                whitespace.
23210 **
23211 ** Extra whitespace at the end of z[] is ignored.
23212 */
testcase_glob(const char * zGlob,const char * z)23213 static int testcase_glob(const char *zGlob, const char *z){
23214   int c, c2;
23215   int invert;
23216   int seen;
23217 
23218   while( (c = (*(zGlob++)))!=0 ){
23219     if( IsSpace(c) ){
23220       if( !IsSpace(*z) ) return 0;
23221       while( IsSpace(*zGlob) ) zGlob++;
23222       while( IsSpace(*z) ) z++;
23223     }else if( c=='*' ){
23224       while( (c=(*(zGlob++))) == '*' || c=='?' ){
23225         if( c=='?' && (*(z++))==0 ) return 0;
23226       }
23227       if( c==0 ){
23228         return 1;
23229       }else if( c=='[' ){
23230         while( *z && testcase_glob(zGlob-1,z)==0 ){
23231           z++;
23232         }
23233         return (*z)!=0;
23234       }
23235       while( (c2 = (*(z++)))!=0 ){
23236         while( c2!=c ){
23237           c2 = *(z++);
23238           if( c2==0 ) return 0;
23239         }
23240         if( testcase_glob(zGlob,z) ) return 1;
23241       }
23242       return 0;
23243     }else if( c=='?' ){
23244       if( (*(z++))==0 ) return 0;
23245     }else if( c=='[' ){
23246       int prior_c = 0;
23247       seen = 0;
23248       invert = 0;
23249       c = *(z++);
23250       if( c==0 ) return 0;
23251       c2 = *(zGlob++);
23252       if( c2=='^' ){
23253         invert = 1;
23254         c2 = *(zGlob++);
23255       }
23256       if( c2==']' ){
23257         if( c==']' ) seen = 1;
23258         c2 = *(zGlob++);
23259       }
23260       while( c2 && c2!=']' ){
23261         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
23262           c2 = *(zGlob++);
23263           if( c>=prior_c && c<=c2 ) seen = 1;
23264           prior_c = 0;
23265         }else{
23266           if( c==c2 ){
23267             seen = 1;
23268           }
23269           prior_c = c2;
23270         }
23271         c2 = *(zGlob++);
23272       }
23273       if( c2==0 || (seen ^ invert)==0 ) return 0;
23274     }else if( c=='#' ){
23275       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
23276       if( !IsDigit(z[0]) ) return 0;
23277       z++;
23278       while( IsDigit(z[0]) ){ z++; }
23279     }else{
23280       if( c!=(*(z++)) ) return 0;
23281     }
23282   }
23283   while( IsSpace(*z) ){ z++; }
23284   return *z==0;
23285 }
23286 
23287 
23288 /*
23289 ** Compare the string as a command-line option with either one or two
23290 ** initial "-" characters.
23291 */
optionMatch(const char * zStr,const char * zOpt)23292 static int optionMatch(const char *zStr, const char *zOpt){
23293   if( zStr[0]!='-' ) return 0;
23294   zStr++;
23295   if( zStr[0]=='-' ) zStr++;
23296   return cli_strcmp(zStr, zOpt)==0;
23297 }
23298 
23299 /*
23300 ** Delete a file.
23301 */
shellDeleteFile(const char * zFilename)23302 int shellDeleteFile(const char *zFilename){
23303   int rc;
23304 #ifdef _WIN32
23305   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
23306   rc = _wunlink(z);
23307   sqlite3_free(z);
23308 #else
23309   rc = unlink(zFilename);
23310 #endif
23311   return rc;
23312 }
23313 
23314 /*
23315 ** Try to delete the temporary file (if there is one) and free the
23316 ** memory used to hold the name of the temp file.
23317 */
clearTempFile(ShellState * p)23318 static void clearTempFile(ShellState *p){
23319   if( p->zTempFile==0 ) return;
23320   if( p->doXdgOpen ) return;
23321   if( shellDeleteFile(p->zTempFile) ) return;
23322   sqlite3_free(p->zTempFile);
23323   p->zTempFile = 0;
23324 }
23325 
23326 /*
23327 ** Create a new temp file name with the given suffix.
23328 */
newTempFile(ShellState * p,const char * zSuffix)23329 static void newTempFile(ShellState *p, const char *zSuffix){
23330   clearTempFile(p);
23331   sqlite3_free(p->zTempFile);
23332   p->zTempFile = 0;
23333   if( p->db ){
23334     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
23335   }
23336   if( p->zTempFile==0 ){
23337     /* If p->db is an in-memory database then the TEMPFILENAME file-control
23338     ** will not work and we will need to fallback to guessing */
23339     char *zTemp;
23340     sqlite3_uint64 r;
23341     sqlite3_randomness(sizeof(r), &r);
23342     zTemp = getenv("TEMP");
23343     if( zTemp==0 ) zTemp = getenv("TMP");
23344     if( zTemp==0 ){
23345 #ifdef _WIN32
23346       zTemp = "\\tmp";
23347 #else
23348       zTemp = "/tmp";
23349 #endif
23350     }
23351     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
23352   }else{
23353     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
23354   }
23355   shell_check_oom(p->zTempFile);
23356 }
23357 
23358 
23359 /*
23360 ** The implementation of SQL scalar function fkey_collate_clause(), used
23361 ** by the ".lint fkey-indexes" command. This scalar function is always
23362 ** called with four arguments - the parent table name, the parent column name,
23363 ** the child table name and the child column name.
23364 **
23365 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
23366 **
23367 ** If either of the named tables or columns do not exist, this function
23368 ** returns an empty string. An empty string is also returned if both tables
23369 ** and columns exist but have the same default collation sequence. Or,
23370 ** if both exist but the default collation sequences are different, this
23371 ** function returns the string " COLLATE <parent-collation>", where
23372 ** <parent-collation> is the default collation sequence of the parent column.
23373 */
shellFkeyCollateClause(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)23374 static void shellFkeyCollateClause(
23375   sqlite3_context *pCtx,
23376   int nVal,
23377   sqlite3_value **apVal
23378 ){
23379   sqlite3 *db = sqlite3_context_db_handle(pCtx);
23380   const char *zParent;
23381   const char *zParentCol;
23382   const char *zParentSeq;
23383   const char *zChild;
23384   const char *zChildCol;
23385   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
23386   int rc;
23387 
23388   assert( nVal==4 );
23389   zParent = (const char*)sqlite3_value_text(apVal[0]);
23390   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
23391   zChild = (const char*)sqlite3_value_text(apVal[2]);
23392   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
23393 
23394   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
23395   rc = sqlite3_table_column_metadata(
23396       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
23397   );
23398   if( rc==SQLITE_OK ){
23399     rc = sqlite3_table_column_metadata(
23400         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
23401     );
23402   }
23403 
23404   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
23405     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
23406     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
23407     sqlite3_free(z);
23408   }
23409 }
23410 
23411 
23412 /*
23413 ** The implementation of dot-command ".lint fkey-indexes".
23414 */
lintFkeyIndexes(ShellState * pState,char ** azArg,int nArg)23415 static int lintFkeyIndexes(
23416   ShellState *pState,             /* Current shell tool state */
23417   char **azArg,                   /* Array of arguments passed to dot command */
23418   int nArg                        /* Number of entries in azArg[] */
23419 ){
23420   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
23421   int bVerbose = 0;               /* If -verbose is present */
23422   int bGroupByParent = 0;         /* If -groupbyparent is present */
23423   int i;                          /* To iterate through azArg[] */
23424   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
23425   int rc;                         /* Return code */
23426   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
23427 
23428   /*
23429   ** This SELECT statement returns one row for each foreign key constraint
23430   ** in the schema of the main database. The column values are:
23431   **
23432   ** 0. The text of an SQL statement similar to:
23433   **
23434   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
23435   **
23436   **    This SELECT is similar to the one that the foreign keys implementation
23437   **    needs to run internally on child tables. If there is an index that can
23438   **    be used to optimize this query, then it can also be used by the FK
23439   **    implementation to optimize DELETE or UPDATE statements on the parent
23440   **    table.
23441   **
23442   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
23443   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
23444   **    contains an index that can be used to optimize the query.
23445   **
23446   ** 2. Human readable text that describes the child table and columns. e.g.
23447   **
23448   **       "child_table(child_key1, child_key2)"
23449   **
23450   ** 3. Human readable text that describes the parent table and columns. e.g.
23451   **
23452   **       "parent_table(parent_key1, parent_key2)"
23453   **
23454   ** 4. A full CREATE INDEX statement for an index that could be used to
23455   **    optimize DELETE or UPDATE statements on the parent table. e.g.
23456   **
23457   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
23458   **
23459   ** 5. The name of the parent table.
23460   **
23461   ** These six values are used by the C logic below to generate the report.
23462   */
23463   const char *zSql =
23464   "SELECT "
23465     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
23466     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
23467     "  || fkey_collate_clause("
23468     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
23469     ", "
23470     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
23471     "  || group_concat('*=?', ' AND ') || ')'"
23472     ", "
23473     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
23474     ", "
23475     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
23476     ", "
23477     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
23478     "  || ' ON ' || quote(s.name) || '('"
23479     "  || group_concat(quote(f.[from]) ||"
23480     "        fkey_collate_clause("
23481     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
23482     "  || ');'"
23483     ", "
23484     "     f.[table] "
23485     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
23486     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
23487     "GROUP BY s.name, f.id "
23488     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
23489   ;
23490   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
23491 
23492   for(i=2; i<nArg; i++){
23493     int n = strlen30(azArg[i]);
23494     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
23495       bVerbose = 1;
23496     }
23497     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
23498       bGroupByParent = 1;
23499       zIndent = "    ";
23500     }
23501     else{
23502       eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
23503       return SQLITE_ERROR;
23504     }
23505   }
23506 
23507   /* Register the fkey_collate_clause() SQL function */
23508   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
23509       0, shellFkeyCollateClause, 0, 0
23510   );
23511 
23512 
23513   if( rc==SQLITE_OK ){
23514     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
23515   }
23516   if( rc==SQLITE_OK ){
23517     sqlite3_bind_int(pSql, 1, bGroupByParent);
23518   }
23519 
23520   if( rc==SQLITE_OK ){
23521     int rc2;
23522     char *zPrev = 0;
23523     while( SQLITE_ROW==sqlite3_step(pSql) ){
23524       int res = -1;
23525       sqlite3_stmt *pExplain = 0;
23526       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
23527       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
23528       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
23529       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
23530       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
23531       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
23532 
23533       if( zEQP==0 ) continue;
23534       if( zGlob==0 ) continue;
23535       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
23536       if( rc!=SQLITE_OK ) break;
23537       if( SQLITE_ROW==sqlite3_step(pExplain) ){
23538         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
23539         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
23540                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
23541       }
23542       rc = sqlite3_finalize(pExplain);
23543       if( rc!=SQLITE_OK ) break;
23544 
23545       if( res<0 ){
23546         eputz("Error: internal error");
23547         break;
23548       }else{
23549         if( bGroupByParent
23550         && (bVerbose || res==0)
23551         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
23552         ){
23553           oputf("-- Parent table %s\n", zParent);
23554           sqlite3_free(zPrev);
23555           zPrev = sqlite3_mprintf("%s", zParent);
23556         }
23557 
23558         if( res==0 ){
23559           oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
23560         }else if( bVerbose ){
23561           oputf("%s/* no extra indexes required for %s -> %s */\n",
23562                 zIndent, zFrom, zTarget
23563           );
23564         }
23565       }
23566     }
23567     sqlite3_free(zPrev);
23568 
23569     if( rc!=SQLITE_OK ){
23570       eputf("%s\n", sqlite3_errmsg(db));
23571     }
23572 
23573     rc2 = sqlite3_finalize(pSql);
23574     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
23575       rc = rc2;
23576       eputf("%s\n", sqlite3_errmsg(db));
23577     }
23578   }else{
23579     eputf("%s\n", sqlite3_errmsg(db));
23580   }
23581 
23582   return rc;
23583 }
23584 
23585 /*
23586 ** Implementation of ".lint" dot command.
23587 */
lintDotCommand(ShellState * pState,char ** azArg,int nArg)23588 static int lintDotCommand(
23589   ShellState *pState,             /* Current shell tool state */
23590   char **azArg,                   /* Array of arguments passed to dot command */
23591   int nArg                        /* Number of entries in azArg[] */
23592 ){
23593   int n;
23594   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
23595   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
23596   return lintFkeyIndexes(pState, azArg, nArg);
23597 
23598  usage:
23599   eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
23600   eputz("Where sub-commands are:\n");
23601   eputz("    fkey-indexes\n");
23602   return SQLITE_ERROR;
23603 }
23604 
23605 #if !defined SQLITE_OMIT_VIRTUALTABLE
shellPrepare(sqlite3 * db,int * pRc,const char * zSql,sqlite3_stmt ** ppStmt)23606 static void shellPrepare(
23607   sqlite3 *db,
23608   int *pRc,
23609   const char *zSql,
23610   sqlite3_stmt **ppStmt
23611 ){
23612   *ppStmt = 0;
23613   if( *pRc==SQLITE_OK ){
23614     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
23615     if( rc!=SQLITE_OK ){
23616       eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
23617       *pRc = rc;
23618     }
23619   }
23620 }
23621 
23622 /*
23623 ** Create a prepared statement using printf-style arguments for the SQL.
23624 **
23625 ** This routine is could be marked "static".  But it is not always used,
23626 ** depending on compile-time options.  By omitting the "static", we avoid
23627 ** nuisance compiler warnings about "defined but not used".
23628 */
shellPreparePrintf(sqlite3 * db,int * pRc,sqlite3_stmt ** ppStmt,const char * zFmt,...)23629 void shellPreparePrintf(
23630   sqlite3 *db,
23631   int *pRc,
23632   sqlite3_stmt **ppStmt,
23633   const char *zFmt,
23634   ...
23635 ){
23636   *ppStmt = 0;
23637   if( *pRc==SQLITE_OK ){
23638     va_list ap;
23639     char *z;
23640     va_start(ap, zFmt);
23641     z = sqlite3_vmprintf(zFmt, ap);
23642     va_end(ap);
23643     if( z==0 ){
23644       *pRc = SQLITE_NOMEM;
23645     }else{
23646       shellPrepare(db, pRc, z, ppStmt);
23647       sqlite3_free(z);
23648     }
23649   }
23650 }
23651 
23652 /* Finalize the prepared statement created using shellPreparePrintf().
23653 **
23654 ** This routine is could be marked "static".  But it is not always used,
23655 ** depending on compile-time options.  By omitting the "static", we avoid
23656 ** nuisance compiler warnings about "defined but not used".
23657 */
shellFinalize(int * pRc,sqlite3_stmt * pStmt)23658 void shellFinalize(
23659   int *pRc,
23660   sqlite3_stmt *pStmt
23661 ){
23662   if( pStmt ){
23663     sqlite3 *db = sqlite3_db_handle(pStmt);
23664     int rc = sqlite3_finalize(pStmt);
23665     if( *pRc==SQLITE_OK ){
23666       if( rc!=SQLITE_OK ){
23667         eputf("SQL error: %s\n", sqlite3_errmsg(db));
23668       }
23669       *pRc = rc;
23670     }
23671   }
23672 }
23673 
23674 /* Reset the prepared statement created using shellPreparePrintf().
23675 **
23676 ** This routine is could be marked "static".  But it is not always used,
23677 ** depending on compile-time options.  By omitting the "static", we avoid
23678 ** nuisance compiler warnings about "defined but not used".
23679 */
shellReset(int * pRc,sqlite3_stmt * pStmt)23680 void shellReset(
23681   int *pRc,
23682   sqlite3_stmt *pStmt
23683 ){
23684   int rc = sqlite3_reset(pStmt);
23685   if( *pRc==SQLITE_OK ){
23686     if( rc!=SQLITE_OK ){
23687       sqlite3 *db = sqlite3_db_handle(pStmt);
23688       eputf("SQL error: %s\n", sqlite3_errmsg(db));
23689     }
23690     *pRc = rc;
23691   }
23692 }
23693 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
23694 
23695 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
23696 /******************************************************************************
23697 ** The ".archive" or ".ar" command.
23698 */
23699 /*
23700 ** Structure representing a single ".ar" command.
23701 */
23702 typedef struct ArCommand ArCommand;
23703 struct ArCommand {
23704   u8 eCmd;                        /* An AR_CMD_* value */
23705   u8 bVerbose;                    /* True if --verbose */
23706   u8 bZip;                        /* True if the archive is a ZIP */
23707   u8 bDryRun;                     /* True if --dry-run */
23708   u8 bAppend;                     /* True if --append */
23709   u8 bGlob;                       /* True if --glob */
23710   u8 fromCmdLine;                 /* Run from -A instead of .archive */
23711   int nArg;                       /* Number of command arguments */
23712   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
23713   const char *zFile;              /* --file argument, or NULL */
23714   const char *zDir;               /* --directory argument, or NULL */
23715   char **azArg;                   /* Array of command arguments */
23716   ShellState *p;                  /* Shell state */
23717   sqlite3 *db;                    /* Database containing the archive */
23718 };
23719 
23720 /*
23721 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
23722 */
arUsage(FILE * f)23723 static int arUsage(FILE *f){
23724   showHelp(f,"archive");
23725   return SQLITE_ERROR;
23726 }
23727 
23728 /*
23729 ** Print an error message for the .ar command to stderr and return
23730 ** SQLITE_ERROR.
23731 */
arErrorMsg(ArCommand * pAr,const char * zFmt,...)23732 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
23733   va_list ap;
23734   char *z;
23735   va_start(ap, zFmt);
23736   z = sqlite3_vmprintf(zFmt, ap);
23737   va_end(ap);
23738   eputf("Error: %s\n", z);
23739   if( pAr->fromCmdLine ){
23740     eputz("Use \"-A\" for more help\n");
23741   }else{
23742     eputz("Use \".archive --help\" for more help\n");
23743   }
23744   sqlite3_free(z);
23745   return SQLITE_ERROR;
23746 }
23747 
23748 /*
23749 ** Values for ArCommand.eCmd.
23750 */
23751 #define AR_CMD_CREATE       1
23752 #define AR_CMD_UPDATE       2
23753 #define AR_CMD_INSERT       3
23754 #define AR_CMD_EXTRACT      4
23755 #define AR_CMD_LIST         5
23756 #define AR_CMD_HELP         6
23757 #define AR_CMD_REMOVE       7
23758 
23759 /*
23760 ** Other (non-command) switches.
23761 */
23762 #define AR_SWITCH_VERBOSE     8
23763 #define AR_SWITCH_FILE        9
23764 #define AR_SWITCH_DIRECTORY  10
23765 #define AR_SWITCH_APPEND     11
23766 #define AR_SWITCH_DRYRUN     12
23767 #define AR_SWITCH_GLOB       13
23768 
arProcessSwitch(ArCommand * pAr,int eSwitch,const char * zArg)23769 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
23770   switch( eSwitch ){
23771     case AR_CMD_CREATE:
23772     case AR_CMD_EXTRACT:
23773     case AR_CMD_LIST:
23774     case AR_CMD_REMOVE:
23775     case AR_CMD_UPDATE:
23776     case AR_CMD_INSERT:
23777     case AR_CMD_HELP:
23778       if( pAr->eCmd ){
23779         return arErrorMsg(pAr, "multiple command options");
23780       }
23781       pAr->eCmd = eSwitch;
23782       break;
23783 
23784     case AR_SWITCH_DRYRUN:
23785       pAr->bDryRun = 1;
23786       break;
23787     case AR_SWITCH_GLOB:
23788       pAr->bGlob = 1;
23789       break;
23790     case AR_SWITCH_VERBOSE:
23791       pAr->bVerbose = 1;
23792       break;
23793     case AR_SWITCH_APPEND:
23794       pAr->bAppend = 1;
23795       deliberate_fall_through;
23796     case AR_SWITCH_FILE:
23797       pAr->zFile = zArg;
23798       break;
23799     case AR_SWITCH_DIRECTORY:
23800       pAr->zDir = zArg;
23801       break;
23802   }
23803 
23804   return SQLITE_OK;
23805 }
23806 
23807 /*
23808 ** Parse the command line for an ".ar" command. The results are written into
23809 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
23810 ** successfully, otherwise an error message is written to stderr and
23811 ** SQLITE_ERROR returned.
23812 */
arParseCommand(char ** azArg,int nArg,ArCommand * pAr)23813 static int arParseCommand(
23814   char **azArg,                   /* Array of arguments passed to dot command */
23815   int nArg,                       /* Number of entries in azArg[] */
23816   ArCommand *pAr                  /* Populate this object */
23817 ){
23818   struct ArSwitch {
23819     const char *zLong;
23820     char cShort;
23821     u8 eSwitch;
23822     u8 bArg;
23823   } aSwitch[] = {
23824     { "create",    'c', AR_CMD_CREATE,       0 },
23825     { "extract",   'x', AR_CMD_EXTRACT,      0 },
23826     { "insert",    'i', AR_CMD_INSERT,       0 },
23827     { "list",      't', AR_CMD_LIST,         0 },
23828     { "remove",    'r', AR_CMD_REMOVE,       0 },
23829     { "update",    'u', AR_CMD_UPDATE,       0 },
23830     { "help",      'h', AR_CMD_HELP,         0 },
23831     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
23832     { "file",      'f', AR_SWITCH_FILE,      1 },
23833     { "append",    'a', AR_SWITCH_APPEND,    1 },
23834     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
23835     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
23836     { "glob",      'g', AR_SWITCH_GLOB,      0 },
23837   };
23838   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
23839   struct ArSwitch *pEnd = &aSwitch[nSwitch];
23840 
23841   if( nArg<=1 ){
23842     eputz("Wrong number of arguments.  Usage:\n");
23843     return arUsage(stderr);
23844   }else{
23845     char *z = azArg[1];
23846     if( z[0]!='-' ){
23847       /* Traditional style [tar] invocation */
23848       int i;
23849       int iArg = 2;
23850       for(i=0; z[i]; i++){
23851         const char *zArg = 0;
23852         struct ArSwitch *pOpt;
23853         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23854           if( z[i]==pOpt->cShort ) break;
23855         }
23856         if( pOpt==pEnd ){
23857           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23858         }
23859         if( pOpt->bArg ){
23860           if( iArg>=nArg ){
23861             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
23862           }
23863           zArg = azArg[iArg++];
23864         }
23865         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23866       }
23867       pAr->nArg = nArg-iArg;
23868       if( pAr->nArg>0 ){
23869         pAr->azArg = &azArg[iArg];
23870       }
23871     }else{
23872       /* Non-traditional invocation */
23873       int iArg;
23874       for(iArg=1; iArg<nArg; iArg++){
23875         int n;
23876         z = azArg[iArg];
23877         if( z[0]!='-' ){
23878           /* All remaining command line words are command arguments. */
23879           pAr->azArg = &azArg[iArg];
23880           pAr->nArg = nArg-iArg;
23881           break;
23882         }
23883         n = strlen30(z);
23884 
23885         if( z[1]!='-' ){
23886           int i;
23887           /* One or more short options */
23888           for(i=1; i<n; i++){
23889             const char *zArg = 0;
23890             struct ArSwitch *pOpt;
23891             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23892               if( z[i]==pOpt->cShort ) break;
23893             }
23894             if( pOpt==pEnd ){
23895               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23896             }
23897             if( pOpt->bArg ){
23898               if( i<(n-1) ){
23899                 zArg = &z[i+1];
23900                 i = n;
23901               }else{
23902                 if( iArg>=(nArg-1) ){
23903                   return arErrorMsg(pAr, "option requires an argument: %c",
23904                                     z[i]);
23905                 }
23906                 zArg = azArg[++iArg];
23907               }
23908             }
23909             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23910           }
23911         }else if( z[2]=='\0' ){
23912           /* A -- option, indicating that all remaining command line words
23913           ** are command arguments.  */
23914           pAr->azArg = &azArg[iArg+1];
23915           pAr->nArg = nArg-iArg-1;
23916           break;
23917         }else{
23918           /* A long option */
23919           const char *zArg = 0;             /* Argument for option, if any */
23920           struct ArSwitch *pMatch = 0;      /* Matching option */
23921           struct ArSwitch *pOpt;            /* Iterator */
23922           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23923             const char *zLong = pOpt->zLong;
23924             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
23925               if( pMatch ){
23926                 return arErrorMsg(pAr, "ambiguous option: %s",z);
23927               }else{
23928                 pMatch = pOpt;
23929               }
23930             }
23931           }
23932 
23933           if( pMatch==0 ){
23934             return arErrorMsg(pAr, "unrecognized option: %s", z);
23935           }
23936           if( pMatch->bArg ){
23937             if( iArg>=(nArg-1) ){
23938               return arErrorMsg(pAr, "option requires an argument: %s", z);
23939             }
23940             zArg = azArg[++iArg];
23941           }
23942           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
23943         }
23944       }
23945     }
23946   }
23947   if( pAr->eCmd==0 ){
23948     eputz("Required argument missing.  Usage:\n");
23949     return arUsage(stderr);
23950   }
23951   return SQLITE_OK;
23952 }
23953 
23954 /*
23955 ** This function assumes that all arguments within the ArCommand.azArg[]
23956 ** array refer to archive members, as for the --extract, --list or --remove
23957 ** commands. It checks that each of them are "present". If any specified
23958 ** file is not present in the archive, an error is printed to stderr and an
23959 ** error code returned. Otherwise, if all specified arguments are present
23960 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
23961 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
23962 ** when pAr->bGlob is true.
23963 **
23964 ** This function strips any trailing '/' characters from each argument.
23965 ** This is consistent with the way the [tar] command seems to work on
23966 ** Linux.
23967 */
arCheckEntries(ArCommand * pAr)23968 static int arCheckEntries(ArCommand *pAr){
23969   int rc = SQLITE_OK;
23970   if( pAr->nArg ){
23971     int i, j;
23972     sqlite3_stmt *pTest = 0;
23973     const char *zSel = (pAr->bGlob)
23974       ? "SELECT name FROM %s WHERE glob($name,name)"
23975       : "SELECT name FROM %s WHERE name=$name";
23976 
23977     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
23978     j = sqlite3_bind_parameter_index(pTest, "$name");
23979     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
23980       char *z = pAr->azArg[i];
23981       int n = strlen30(z);
23982       int bOk = 0;
23983       while( n>0 && z[n-1]=='/' ) n--;
23984       z[n] = '\0';
23985       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
23986       if( SQLITE_ROW==sqlite3_step(pTest) ){
23987         bOk = 1;
23988       }
23989       shellReset(&rc, pTest);
23990       if( rc==SQLITE_OK && bOk==0 ){
23991         eputf("not found in archive: %s\n", z);
23992         rc = SQLITE_ERROR;
23993       }
23994     }
23995     shellFinalize(&rc, pTest);
23996   }
23997   return rc;
23998 }
23999 
24000 /*
24001 ** Format a WHERE clause that can be used against the "sqlar" table to
24002 ** identify all archive members that match the command arguments held
24003 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
24004 ** The caller is responsible for eventually calling sqlite3_free() on
24005 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
24006 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
24007 */
arWhereClause(int * pRc,ArCommand * pAr,char ** pzWhere)24008 static void arWhereClause(
24009   int *pRc,
24010   ArCommand *pAr,
24011   char **pzWhere                  /* OUT: New WHERE clause */
24012 ){
24013   char *zWhere = 0;
24014   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
24015   if( *pRc==SQLITE_OK ){
24016     if( pAr->nArg==0 ){
24017       zWhere = sqlite3_mprintf("1");
24018     }else{
24019       int i;
24020       const char *zSep = "";
24021       for(i=0; i<pAr->nArg; i++){
24022         const char *z = pAr->azArg[i];
24023         zWhere = sqlite3_mprintf(
24024           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
24025           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
24026         );
24027         if( zWhere==0 ){
24028           *pRc = SQLITE_NOMEM;
24029           break;
24030         }
24031         zSep = " OR ";
24032       }
24033     }
24034   }
24035   *pzWhere = zWhere;
24036 }
24037 
24038 /*
24039 ** Implementation of .ar "lisT" command.
24040 */
arListCommand(ArCommand * pAr)24041 static int arListCommand(ArCommand *pAr){
24042   const char *zSql = "SELECT %s FROM %s WHERE %s";
24043   const char *azCols[] = {
24044     "name",
24045     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
24046   };
24047 
24048   char *zWhere = 0;
24049   sqlite3_stmt *pSql = 0;
24050   int rc;
24051 
24052   rc = arCheckEntries(pAr);
24053   arWhereClause(&rc, pAr, &zWhere);
24054 
24055   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
24056                      pAr->zSrcTable, zWhere);
24057   if( pAr->bDryRun ){
24058     oputf("%s\n", sqlite3_sql(pSql));
24059   }else{
24060     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
24061       if( pAr->bVerbose ){
24062         oputf("%s % 10d  %s  %s\n",
24063               sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
24064               sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
24065       }else{
24066         oputf("%s\n", sqlite3_column_text(pSql, 0));
24067       }
24068     }
24069   }
24070   shellFinalize(&rc, pSql);
24071   sqlite3_free(zWhere);
24072   return rc;
24073 }
24074 
24075 /*
24076 ** Implementation of .ar "Remove" command.
24077 */
arRemoveCommand(ArCommand * pAr)24078 static int arRemoveCommand(ArCommand *pAr){
24079   int rc = 0;
24080   char *zSql = 0;
24081   char *zWhere = 0;
24082 
24083   if( pAr->nArg ){
24084     /* Verify that args actually exist within the archive before proceeding.
24085     ** And formulate a WHERE clause to match them.  */
24086     rc = arCheckEntries(pAr);
24087     arWhereClause(&rc, pAr, &zWhere);
24088   }
24089   if( rc==SQLITE_OK ){
24090     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
24091                            pAr->zSrcTable, zWhere);
24092     if( pAr->bDryRun ){
24093       oputf("%s\n", zSql);
24094     }else{
24095       char *zErr = 0;
24096       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
24097       if( rc==SQLITE_OK ){
24098         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
24099         if( rc!=SQLITE_OK ){
24100           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
24101         }else{
24102           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
24103         }
24104       }
24105       if( zErr ){
24106         sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
24107         sqlite3_free(zErr);
24108       }
24109     }
24110   }
24111   sqlite3_free(zWhere);
24112   sqlite3_free(zSql);
24113   return rc;
24114 }
24115 
24116 /*
24117 ** Implementation of .ar "eXtract" command.
24118 */
arExtractCommand(ArCommand * pAr)24119 static int arExtractCommand(ArCommand *pAr){
24120   const char *zSql1 =
24121     "SELECT "
24122     " ($dir || name),"
24123     " writefile(($dir || name), %s, mode, mtime) "
24124     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
24125     " AND name NOT GLOB '*..[/\\]*'";
24126 
24127   const char *azExtraArg[] = {
24128     "sqlar_uncompress(data, sz)",
24129     "data"
24130   };
24131 
24132   sqlite3_stmt *pSql = 0;
24133   int rc = SQLITE_OK;
24134   char *zDir = 0;
24135   char *zWhere = 0;
24136   int i, j;
24137 
24138   /* If arguments are specified, check that they actually exist within
24139   ** the archive before proceeding. And formulate a WHERE clause to
24140   ** match them.  */
24141   rc = arCheckEntries(pAr);
24142   arWhereClause(&rc, pAr, &zWhere);
24143 
24144   if( rc==SQLITE_OK ){
24145     if( pAr->zDir ){
24146       zDir = sqlite3_mprintf("%s/", pAr->zDir);
24147     }else{
24148       zDir = sqlite3_mprintf("");
24149     }
24150     if( zDir==0 ) rc = SQLITE_NOMEM;
24151   }
24152 
24153   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
24154       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
24155   );
24156 
24157   if( rc==SQLITE_OK ){
24158     j = sqlite3_bind_parameter_index(pSql, "$dir");
24159     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
24160 
24161     /* Run the SELECT statement twice. The first time, writefile() is called
24162     ** for all archive members that should be extracted. The second time,
24163     ** only for the directories. This is because the timestamps for
24164     ** extracted directories must be reset after they are populated (as
24165     ** populating them changes the timestamp).  */
24166     for(i=0; i<2; i++){
24167       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
24168       sqlite3_bind_int(pSql, j, i);
24169       if( pAr->bDryRun ){
24170         oputf("%s\n", sqlite3_sql(pSql));
24171       }else{
24172         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
24173           if( i==0 && pAr->bVerbose ){
24174             oputf("%s\n", sqlite3_column_text(pSql, 0));
24175           }
24176         }
24177       }
24178       shellReset(&rc, pSql);
24179     }
24180     shellFinalize(&rc, pSql);
24181   }
24182 
24183   sqlite3_free(zDir);
24184   sqlite3_free(zWhere);
24185   return rc;
24186 }
24187 
24188 /*
24189 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
24190 */
arExecSql(ArCommand * pAr,const char * zSql)24191 static int arExecSql(ArCommand *pAr, const char *zSql){
24192   int rc;
24193   if( pAr->bDryRun ){
24194     oputf("%s\n", zSql);
24195     rc = SQLITE_OK;
24196   }else{
24197     char *zErr = 0;
24198     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
24199     if( zErr ){
24200       sputf(stdout, "ERROR: %s\n", zErr);
24201       sqlite3_free(zErr);
24202     }
24203   }
24204   return rc;
24205 }
24206 
24207 
24208 /*
24209 ** Implementation of .ar "create", "insert", and "update" commands.
24210 **
24211 **     create    ->     Create a new SQL archive
24212 **     insert    ->     Insert or reinsert all files listed
24213 **     update    ->     Insert files that have changed or that were not
24214 **                      previously in the archive
24215 **
24216 ** Create the "sqlar" table in the database if it does not already exist.
24217 ** Then add each file in the azFile[] array to the archive. Directories
24218 ** are added recursively. If argument bVerbose is non-zero, a message is
24219 ** printed on stdout for each file archived.
24220 **
24221 ** The create command is the same as update, except that it drops
24222 ** any existing "sqlar" table before beginning.  The "insert" command
24223 ** always overwrites every file named on the command-line, where as
24224 ** "update" only overwrites if the size or mtime or mode has changed.
24225 */
arCreateOrUpdateCommand(ArCommand * pAr,int bUpdate,int bOnlyIfChanged)24226 static int arCreateOrUpdateCommand(
24227   ArCommand *pAr,                 /* Command arguments and options */
24228   int bUpdate,                    /* true for a --create. */
24229   int bOnlyIfChanged              /* Only update if file has changed */
24230 ){
24231   const char *zCreate =
24232       "CREATE TABLE IF NOT EXISTS sqlar(\n"
24233       "  name TEXT PRIMARY KEY,  -- name of the file\n"
24234       "  mode INT,               -- access permissions\n"
24235       "  mtime INT,              -- last modification time\n"
24236       "  sz INT,                 -- original file size\n"
24237       "  data BLOB               -- compressed content\n"
24238       ")";
24239   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
24240   const char *zInsertFmt[2] = {
24241      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
24242      "  SELECT\n"
24243      "    %s,\n"
24244      "    mode,\n"
24245      "    mtime,\n"
24246      "    CASE substr(lsmode(mode),1,1)\n"
24247      "      WHEN '-' THEN length(data)\n"
24248      "      WHEN 'd' THEN 0\n"
24249      "      ELSE -1 END,\n"
24250      "    sqlar_compress(data)\n"
24251      "  FROM fsdir(%Q,%Q) AS disk\n"
24252      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
24253      ,
24254      "REPLACE INTO %s(name,mode,mtime,data)\n"
24255      "  SELECT\n"
24256      "    %s,\n"
24257      "    mode,\n"
24258      "    mtime,\n"
24259      "    data\n"
24260      "  FROM fsdir(%Q,%Q) AS disk\n"
24261      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
24262   };
24263   int i;                          /* For iterating through azFile[] */
24264   int rc;                         /* Return code */
24265   const char *zTab = 0;           /* SQL table into which to insert */
24266   char *zSql;
24267   char zTemp[50];
24268   char *zExists = 0;
24269 
24270   arExecSql(pAr, "PRAGMA page_size=512");
24271   rc = arExecSql(pAr, "SAVEPOINT ar;");
24272   if( rc!=SQLITE_OK ) return rc;
24273   zTemp[0] = 0;
24274   if( pAr->bZip ){
24275     /* Initialize the zipfile virtual table, if necessary */
24276     if( pAr->zFile ){
24277       sqlite3_uint64 r;
24278       sqlite3_randomness(sizeof(r),&r);
24279       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
24280       zTab = zTemp;
24281       zSql = sqlite3_mprintf(
24282          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
24283          zTab, pAr->zFile
24284       );
24285       rc = arExecSql(pAr, zSql);
24286       sqlite3_free(zSql);
24287     }else{
24288       zTab = "zip";
24289     }
24290   }else{
24291     /* Initialize the table for an SQLAR */
24292     zTab = "sqlar";
24293     if( bUpdate==0 ){
24294       rc = arExecSql(pAr, zDrop);
24295       if( rc!=SQLITE_OK ) goto end_ar_transaction;
24296     }
24297     rc = arExecSql(pAr, zCreate);
24298   }
24299   if( bOnlyIfChanged ){
24300     zExists = sqlite3_mprintf(
24301       " AND NOT EXISTS("
24302           "SELECT 1 FROM %s AS mem"
24303           " WHERE mem.name=disk.name"
24304           " AND mem.mtime=disk.mtime"
24305           " AND mem.mode=disk.mode)", zTab);
24306   }else{
24307     zExists = sqlite3_mprintf("");
24308   }
24309   if( zExists==0 ) rc = SQLITE_NOMEM;
24310   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
24311     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
24312         pAr->bVerbose ? "shell_putsnl(name)" : "name",
24313         pAr->azArg[i], pAr->zDir, zExists);
24314     rc = arExecSql(pAr, zSql2);
24315     sqlite3_free(zSql2);
24316   }
24317 end_ar_transaction:
24318   if( rc!=SQLITE_OK ){
24319     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
24320   }else{
24321     rc = arExecSql(pAr, "RELEASE ar;");
24322     if( pAr->bZip && pAr->zFile ){
24323       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
24324       arExecSql(pAr, zSql);
24325       sqlite3_free(zSql);
24326     }
24327   }
24328   sqlite3_free(zExists);
24329   return rc;
24330 }
24331 
24332 /*
24333 ** Implementation of ".ar" dot command.
24334 */
arDotCommand(ShellState * pState,int fromCmdLine,char ** azArg,int nArg)24335 static int arDotCommand(
24336   ShellState *pState,          /* Current shell tool state */
24337   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
24338   char **azArg,                /* Array of arguments passed to dot command */
24339   int nArg                     /* Number of entries in azArg[] */
24340 ){
24341   ArCommand cmd;
24342   int rc;
24343   memset(&cmd, 0, sizeof(cmd));
24344   cmd.fromCmdLine = fromCmdLine;
24345   rc = arParseCommand(azArg, nArg, &cmd);
24346   if( rc==SQLITE_OK ){
24347     int eDbType = SHELL_OPEN_UNSPEC;
24348     cmd.p = pState;
24349     cmd.db = pState->db;
24350     if( cmd.zFile ){
24351       eDbType = deduceDatabaseType(cmd.zFile, 1);
24352     }else{
24353       eDbType = pState->openMode;
24354     }
24355     if( eDbType==SHELL_OPEN_ZIPFILE ){
24356       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
24357         if( cmd.zFile==0 ){
24358           cmd.zSrcTable = sqlite3_mprintf("zip");
24359         }else{
24360           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
24361         }
24362       }
24363       cmd.bZip = 1;
24364     }else if( cmd.zFile ){
24365       int flags;
24366       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
24367       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
24368            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
24369         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
24370       }else{
24371         flags = SQLITE_OPEN_READONLY;
24372       }
24373       cmd.db = 0;
24374       if( cmd.bDryRun ){
24375         oputf("-- open database '%s'%s\n", cmd.zFile,
24376               eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
24377       }
24378       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
24379              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
24380       if( rc!=SQLITE_OK ){
24381         eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
24382         goto end_ar_command;
24383       }
24384       sqlite3_fileio_init(cmd.db, 0, 0);
24385       sqlite3_sqlar_init(cmd.db, 0, 0);
24386       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
24387                               shellPutsFunc, 0, 0);
24388 
24389     }
24390     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
24391       if( cmd.eCmd!=AR_CMD_CREATE
24392        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
24393       ){
24394         eputz("database does not contain an 'sqlar' table\n");
24395         rc = SQLITE_ERROR;
24396         goto end_ar_command;
24397       }
24398       cmd.zSrcTable = sqlite3_mprintf("sqlar");
24399     }
24400 
24401     switch( cmd.eCmd ){
24402       case AR_CMD_CREATE:
24403         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
24404         break;
24405 
24406       case AR_CMD_EXTRACT:
24407         rc = arExtractCommand(&cmd);
24408         break;
24409 
24410       case AR_CMD_LIST:
24411         rc = arListCommand(&cmd);
24412         break;
24413 
24414       case AR_CMD_HELP:
24415         arUsage(pState->out);
24416         break;
24417 
24418       case AR_CMD_INSERT:
24419         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
24420         break;
24421 
24422       case AR_CMD_REMOVE:
24423         rc = arRemoveCommand(&cmd);
24424         break;
24425 
24426       default:
24427         assert( cmd.eCmd==AR_CMD_UPDATE );
24428         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
24429         break;
24430     }
24431   }
24432 end_ar_command:
24433   if( cmd.db!=pState->db ){
24434     close_db(cmd.db);
24435   }
24436   sqlite3_free(cmd.zSrcTable);
24437 
24438   return rc;
24439 }
24440 /* End of the ".archive" or ".ar" command logic
24441 *******************************************************************************/
24442 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
24443 
24444 #if SQLITE_SHELL_HAVE_RECOVER
24445 
24446 /*
24447 ** This function is used as a callback by the recover extension. Simply
24448 ** print the supplied SQL statement to stdout.
24449 */
recoverSqlCb(void * pCtx,const char * zSql)24450 static int recoverSqlCb(void *pCtx, const char *zSql){
24451   ShellState *pState = (ShellState*)pCtx;
24452   sputf(pState->out, "%s;\n", zSql);
24453   return SQLITE_OK;
24454 }
24455 
24456 /*
24457 ** This function is called to recover data from the database. A script
24458 ** to construct a new database containing all recovered data is output
24459 ** on stream pState->out.
24460 */
recoverDatabaseCmd(ShellState * pState,int nArg,char ** azArg)24461 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
24462   int rc = SQLITE_OK;
24463   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
24464   const char *zLAF = "lost_and_found";
24465   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
24466   int bRowids = 1;                /* 0 if --no-rowids */
24467   sqlite3_recover *p = 0;
24468   int i = 0;
24469 
24470   for(i=1; i<nArg; i++){
24471     char *z = azArg[i];
24472     int n;
24473     if( z[0]=='-' && z[1]=='-' ) z++;
24474     n = strlen30(z);
24475     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
24476       bFreelist = 0;
24477     }else
24478     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
24479       /* This option determines the name of the ATTACH-ed database used
24480       ** internally by the recovery extension.  The default is "" which
24481       ** means to use a temporary database that is automatically deleted
24482       ** when closed.  This option is undocumented and might disappear at
24483       ** any moment. */
24484       i++;
24485       zRecoveryDb = azArg[i];
24486     }else
24487     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
24488       i++;
24489       zLAF = azArg[i];
24490     }else
24491     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
24492       bRowids = 0;
24493     }
24494     else{
24495       eputf("unexpected option: %s\n", azArg[i]);
24496       showHelp(pState->out, azArg[0]);
24497       return 1;
24498     }
24499   }
24500 
24501   p = sqlite3_recover_init_sql(
24502       pState->db, "main", recoverSqlCb, (void*)pState
24503   );
24504 
24505   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
24506   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
24507   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
24508   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
24509 
24510   sqlite3_recover_run(p);
24511   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
24512     const char *zErr = sqlite3_recover_errmsg(p);
24513     int errCode = sqlite3_recover_errcode(p);
24514     eputf("sql error: %s (%d)\n", zErr, errCode);
24515   }
24516   rc = sqlite3_recover_finish(p);
24517   return rc;
24518 }
24519 #endif /* SQLITE_SHELL_HAVE_RECOVER */
24520 
24521 
24522 /*
24523  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
24524  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
24525  *   close db and set it to 0, and return the columns spec, to later
24526  *   be sqlite3_free()'ed by the caller.
24527  * The return is 0 when either:
24528  *   (a) The db was not initialized and zCol==0 (There are no columns.)
24529  *   (b) zCol!=0  (Column was added, db initialized as needed.)
24530  * The 3rd argument, pRenamed, references an out parameter. If the
24531  * pointer is non-zero, its referent will be set to a summary of renames
24532  * done if renaming was necessary, or set to 0 if none was done. The out
24533  * string (if any) must be sqlite3_free()'ed by the caller.
24534  */
24535 #ifdef SHELL_DEBUG
24536 #define rc_err_oom_die(rc) \
24537   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
24538   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
24539     eputf("E:%d\n",rc), assert(0)
24540 #else
rc_err_oom_die(int rc)24541 static void rc_err_oom_die(int rc){
24542   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
24543   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
24544 }
24545 #endif
24546 
24547 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
24548 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
24549 #else  /* Otherwise, memory is faster/better for the transient DB. */
24550 static const char *zCOL_DB = ":memory:";
24551 #endif
24552 
24553 /* Define character (as C string) to separate generated column ordinal
24554  * from protected part of incoming column names. This defaults to "_"
24555  * so that incoming column identifiers that did not need not be quoted
24556  * remain usable without being quoted. It must be one character.
24557  */
24558 #ifndef SHELL_AUTOCOLUMN_SEP
24559 # define AUTOCOLUMN_SEP "_"
24560 #else
24561 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
24562 #endif
24563 
zAutoColumn(const char * zColNew,sqlite3 ** pDb,char ** pzRenamed)24564 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
24565   /* Queries and D{D,M}L used here */
24566   static const char * const zTabMake = "\
24567 CREATE TABLE ColNames(\
24568  cpos INTEGER PRIMARY KEY,\
24569  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
24570 CREATE VIEW RepeatedNames AS \
24571 SELECT DISTINCT t.name FROM ColNames t \
24572 WHERE t.name COLLATE NOCASE IN (\
24573  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
24574 );\
24575 ";
24576   static const char * const zTabFill = "\
24577 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
24578  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
24579 ";
24580   static const char * const zHasDupes = "\
24581 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
24582  <count(name) FROM ColNames\
24583 ";
24584 #ifdef SHELL_COLUMN_RENAME_CLEAN
24585   static const char * const zDedoctor = "\
24586 UPDATE ColNames SET chop=iif(\
24587   (substring(name,nlen,1) BETWEEN '0' AND '9')\
24588   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
24589  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
24590  0\
24591 )\
24592 ";
24593 #endif
24594   static const char * const zSetReps = "\
24595 UPDATE ColNames AS t SET reps=\
24596 (SELECT count(*) FROM ColNames d \
24597  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
24598  COLLATE NOCASE\
24599 )\
24600 ";
24601 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
24602   static const char * const zColDigits = "\
24603 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
24604 ";
24605 #else
24606   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
24607   static const char * const zColDigits = "\
24608 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
24609  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
24610  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
24611 ";
24612 #endif
24613   static const char * const zRenameRank =
24614 #ifdef SHELL_COLUMN_RENAME_CLEAN
24615     "UPDATE ColNames AS t SET suff="
24616     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
24617 #else /* ...RENAME_MINIMAL_ONE_PASS */
24618 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
24619 "  SELECT 0 AS nlz"
24620 "  UNION"
24621 "  SELECT nlz+1 AS nlz FROM Lzn"
24622 "  WHERE EXISTS("
24623 "   SELECT 1"
24624 "   FROM ColNames t, ColNames o"
24625 "   WHERE"
24626 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
24627 "     printf('%s"AUTOCOLUMN_SEP"%s',"
24628 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
24629 "     t.name"
24630 "    )"
24631 "    ="
24632 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
24633 "     printf('%s"AUTOCOLUMN_SEP"%s',"
24634 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
24635 "     o.name"
24636 "    )"
24637 "    COLLATE NOCASE"
24638 "    AND o.cpos<>t.cpos"
24639 "   GROUP BY t.cpos"
24640 "  )"
24641 ") UPDATE Colnames AS t SET"
24642 " chop = 0," /* No chopping, never touch incoming names. */
24643 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
24644 "  printf('"AUTOCOLUMN_SEP"%s', substring("
24645 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
24646 "  ''"
24647 " )"
24648 #endif
24649     ;
24650   static const char * const zCollectVar = "\
24651 SELECT\
24652  '('||x'0a'\
24653  || group_concat(\
24654   cname||' TEXT',\
24655   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
24656  ||')' AS ColsSpec \
24657 FROM (\
24658  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
24659  FROM ColNames ORDER BY cpos\
24660 )";
24661   static const char * const zRenamesDone =
24662     "SELECT group_concat("
24663     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
24664     " ','||x'0a')"
24665     "FROM ColNames WHERE suff<>'' OR chop!=0"
24666     ;
24667   int rc;
24668   sqlite3_stmt *pStmt = 0;
24669   assert(pDb!=0);
24670   if( zColNew ){
24671     /* Add initial or additional column. Init db if necessary. */
24672     if( *pDb==0 ){
24673       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
24674 #ifdef SHELL_COLFIX_DB
24675       if(*zCOL_DB!=':')
24676         sqlite3_exec(*pDb,"drop table if exists ColNames;"
24677                      "drop view if exists RepeatedNames;",0,0,0);
24678 #endif
24679 #undef SHELL_COLFIX_DB
24680       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
24681       rc_err_oom_die(rc);
24682     }
24683     assert(*pDb!=0);
24684     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
24685     rc_err_oom_die(rc);
24686     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
24687     rc_err_oom_die(rc);
24688     rc = sqlite3_step(pStmt);
24689     rc_err_oom_die(rc);
24690     sqlite3_finalize(pStmt);
24691     return 0;
24692   }else if( *pDb==0 ){
24693     return 0;
24694   }else{
24695     /* Formulate the columns spec, close the DB, zero *pDb. */
24696     char *zColsSpec = 0;
24697     int hasDupes = db_int(*pDb, zHasDupes);
24698     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
24699     if( hasDupes ){
24700 #ifdef SHELL_COLUMN_RENAME_CLEAN
24701       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
24702       rc_err_oom_die(rc);
24703 #endif
24704       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
24705       rc_err_oom_die(rc);
24706       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
24707       rc_err_oom_die(rc);
24708       sqlite3_bind_int(pStmt, 1, nDigits);
24709       rc = sqlite3_step(pStmt);
24710       sqlite3_finalize(pStmt);
24711       if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
24712     }
24713     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
24714     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
24715     rc_err_oom_die(rc);
24716     rc = sqlite3_step(pStmt);
24717     if( rc==SQLITE_ROW ){
24718       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
24719     }else{
24720       zColsSpec = 0;
24721     }
24722     if( pzRenamed!=0 ){
24723       if( !hasDupes ) *pzRenamed = 0;
24724       else{
24725         sqlite3_finalize(pStmt);
24726         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
24727             && SQLITE_ROW==sqlite3_step(pStmt) ){
24728           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
24729         }else
24730           *pzRenamed = 0;
24731       }
24732     }
24733     sqlite3_finalize(pStmt);
24734     sqlite3_close(*pDb);
24735     *pDb = 0;
24736     return zColsSpec;
24737   }
24738 }
24739 
24740 /*
24741 ** If an input line begins with "." then invoke this routine to
24742 ** process that line.
24743 **
24744 ** Return 1 on error, 2 to exit, and 0 otherwise.
24745 */
do_meta_command(char * zLine,ShellState * p)24746 static int do_meta_command(char *zLine, ShellState *p){
24747   int h = 1;
24748   int nArg = 0;
24749   int n, c;
24750   int rc = 0;
24751   char *azArg[52];
24752 
24753 #ifndef SQLITE_OMIT_VIRTUALTABLE
24754   if( p->expert.pExpert ){
24755     expertFinish(p, 1, 0);
24756   }
24757 #endif
24758 
24759   /* Parse the input line into tokens.
24760   */
24761   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
24762     while( IsSpace(zLine[h]) ){ h++; }
24763     if( zLine[h]==0 ) break;
24764     if( zLine[h]=='\'' || zLine[h]=='"' ){
24765       int delim = zLine[h++];
24766       azArg[nArg++] = &zLine[h];
24767       while( zLine[h] && zLine[h]!=delim ){
24768         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
24769         h++;
24770       }
24771       if( zLine[h]==delim ){
24772         zLine[h++] = 0;
24773       }
24774       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
24775     }else{
24776       azArg[nArg++] = &zLine[h];
24777       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
24778       if( zLine[h] ) zLine[h++] = 0;
24779     }
24780   }
24781   azArg[nArg] = 0;
24782 
24783   /* Process the input line.
24784   */
24785   if( nArg==0 ) return 0; /* no tokens, no error */
24786   n = strlen30(azArg[0]);
24787   c = azArg[0][0];
24788   clearTempFile(p);
24789 
24790 #ifndef SQLITE_OMIT_AUTHORIZATION
24791   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
24792     if( nArg!=2 ){
24793       eputz("Usage: .auth ON|OFF\n");
24794       rc = 1;
24795       goto meta_command_exit;
24796     }
24797     open_db(p, 0);
24798     if( booleanValue(azArg[1]) ){
24799       sqlite3_set_authorizer(p->db, shellAuth, p);
24800     }else if( p->bSafeModePersist ){
24801       sqlite3_set_authorizer(p->db, safeModeAuth, p);
24802     }else{
24803       sqlite3_set_authorizer(p->db, 0, 0);
24804     }
24805   }else
24806 #endif
24807 
24808 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
24809   && !defined(SQLITE_SHELL_FIDDLE)
24810   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
24811     open_db(p, 0);
24812     failIfSafeMode(p, "cannot run .archive in safe mode");
24813     rc = arDotCommand(p, 0, azArg, nArg);
24814   }else
24815 #endif
24816 
24817 #ifndef SQLITE_SHELL_FIDDLE
24818   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
24819    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
24820   ){
24821     const char *zDestFile = 0;
24822     const char *zDb = 0;
24823     sqlite3 *pDest;
24824     sqlite3_backup *pBackup;
24825     int j;
24826     int bAsync = 0;
24827     const char *zVfs = 0;
24828     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
24829     for(j=1; j<nArg; j++){
24830       const char *z = azArg[j];
24831       if( z[0]=='-' ){
24832         if( z[1]=='-' ) z++;
24833         if( cli_strcmp(z, "-append")==0 ){
24834           zVfs = "apndvfs";
24835         }else
24836         if( cli_strcmp(z, "-async")==0 ){
24837           bAsync = 1;
24838         }else
24839         {
24840           eputf("unknown option: %s\n", azArg[j]);
24841           return 1;
24842         }
24843       }else if( zDestFile==0 ){
24844         zDestFile = azArg[j];
24845       }else if( zDb==0 ){
24846         zDb = zDestFile;
24847         zDestFile = azArg[j];
24848       }else{
24849         eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
24850         return 1;
24851       }
24852     }
24853     if( zDestFile==0 ){
24854       eputz("missing FILENAME argument on .backup\n");
24855       return 1;
24856     }
24857     if( zDb==0 ) zDb = "main";
24858     rc = sqlite3_open_v2(zDestFile, &pDest,
24859                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
24860     if( rc!=SQLITE_OK ){
24861       eputf("Error: cannot open \"%s\"\n", zDestFile);
24862       close_db(pDest);
24863       return 1;
24864     }
24865     if( bAsync ){
24866       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
24867                    0, 0, 0);
24868     }
24869     open_db(p, 0);
24870     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
24871     if( pBackup==0 ){
24872       eputf("Error: %s\n", sqlite3_errmsg(pDest));
24873       close_db(pDest);
24874       return 1;
24875     }
24876     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
24877     sqlite3_backup_finish(pBackup);
24878     if( rc==SQLITE_DONE ){
24879       rc = 0;
24880     }else{
24881       eputf("Error: %s\n", sqlite3_errmsg(pDest));
24882       rc = 1;
24883     }
24884     close_db(pDest);
24885   }else
24886 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24887 
24888   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
24889     if( nArg==2 ){
24890       bail_on_error = booleanValue(azArg[1]);
24891     }else{
24892       eputz("Usage: .bail on|off\n");
24893       rc = 1;
24894     }
24895   }else
24896 
24897   /* Undocumented.  Legacy only.  See "crnl" below */
24898   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
24899     if( nArg==2 ){
24900       if( booleanValue(azArg[1]) ){
24901         setBinaryMode(p->out, 1);
24902       }else{
24903         setTextMode(p->out, 1);
24904       }
24905     }else{
24906       eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
24907             "Usage: .binary on|off\n");
24908       rc = 1;
24909     }
24910   }else
24911 
24912   /* The undocumented ".breakpoint" command causes a call to the no-op
24913   ** routine named test_breakpoint().
24914   */
24915   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
24916     test_breakpoint();
24917   }else
24918 
24919 #ifndef SQLITE_SHELL_FIDDLE
24920   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
24921     failIfSafeMode(p, "cannot run .cd in safe mode");
24922     if( nArg==2 ){
24923 #if defined(_WIN32) || defined(WIN32)
24924       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
24925       rc = !SetCurrentDirectoryW(z);
24926       sqlite3_free(z);
24927 #else
24928       rc = chdir(azArg[1]);
24929 #endif
24930       if( rc ){
24931         eputf("Cannot change to directory \"%s\"\n", azArg[1]);
24932         rc = 1;
24933       }
24934     }else{
24935       eputz("Usage: .cd DIRECTORY\n");
24936       rc = 1;
24937     }
24938   }else
24939 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24940 
24941   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
24942     if( nArg==2 ){
24943       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
24944     }else{
24945       eputz("Usage: .changes on|off\n");
24946       rc = 1;
24947     }
24948   }else
24949 
24950 #ifndef SQLITE_SHELL_FIDDLE
24951   /* Cancel output redirection, if it is currently set (by .testcase)
24952   ** Then read the content of the testcase-out.txt file and compare against
24953   ** azArg[1].  If there are differences, report an error and exit.
24954   */
24955   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
24956     char *zRes = 0;
24957     output_reset(p);
24958     if( nArg!=2 ){
24959       eputz("Usage: .check GLOB-PATTERN\n");
24960       rc = 2;
24961     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
24962       rc = 2;
24963     }else if( testcase_glob(azArg[1],zRes)==0 ){
24964       eputf("testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
24965             p->zTestcase, azArg[1], zRes);
24966       rc = 1;
24967     }else{
24968       oputf("testcase-%s ok\n", p->zTestcase);
24969       p->nCheck++;
24970     }
24971     sqlite3_free(zRes);
24972   }else
24973 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24974 
24975 #ifndef SQLITE_SHELL_FIDDLE
24976   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
24977     failIfSafeMode(p, "cannot run .clone in safe mode");
24978     if( nArg==2 ){
24979       tryToClone(p, azArg[1]);
24980     }else{
24981       eputz("Usage: .clone FILENAME\n");
24982       rc = 1;
24983     }
24984   }else
24985 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24986 
24987   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
24988     if( nArg==1 ){
24989       /* List available connections */
24990       int i;
24991       for(i=0; i<ArraySize(p->aAuxDb); i++){
24992         const char *zFile = p->aAuxDb[i].zDbFilename;
24993         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
24994           zFile = "(not open)";
24995         }else if( zFile==0 ){
24996           zFile = "(memory)";
24997         }else if( zFile[0]==0 ){
24998           zFile = "(temporary-file)";
24999         }
25000         if( p->pAuxDb == &p->aAuxDb[i] ){
25001           sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
25002         }else if( p->aAuxDb[i].db!=0 ){
25003           sputf(stdout, "       %d: %s\n", i, zFile);
25004         }
25005       }
25006     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
25007       int i = azArg[1][0] - '0';
25008       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
25009         p->pAuxDb->db = p->db;
25010         p->pAuxDb = &p->aAuxDb[i];
25011         globalDb = p->db = p->pAuxDb->db;
25012         p->pAuxDb->db = 0;
25013       }
25014     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
25015            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
25016       int i = azArg[2][0] - '0';
25017       if( i<0 || i>=ArraySize(p->aAuxDb) ){
25018         /* No-op */
25019       }else if( p->pAuxDb == &p->aAuxDb[i] ){
25020         eputz("cannot close the active database connection\n");
25021         rc = 1;
25022       }else if( p->aAuxDb[i].db ){
25023         session_close_all(p, i);
25024         close_db(p->aAuxDb[i].db);
25025         p->aAuxDb[i].db = 0;
25026       }
25027     }else{
25028       eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
25029       rc = 1;
25030     }
25031   }else
25032 
25033   if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
25034     if( nArg==2 ){
25035       if( booleanValue(azArg[1]) ){
25036         setTextMode(p->out, 1);
25037       }else{
25038         setBinaryMode(p->out, 1);
25039       }
25040     }else{
25041 #if !defined(_WIN32) && !defined(WIN32)
25042       eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
25043 #endif
25044       eputz("Usage: .crnl on|off\n");
25045       rc = 1;
25046     }
25047   }else
25048 
25049   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
25050     char **azName = 0;
25051     int nName = 0;
25052     sqlite3_stmt *pStmt;
25053     int i;
25054     open_db(p, 0);
25055     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
25056     if( rc ){
25057       eputf("Error: %s\n", sqlite3_errmsg(p->db));
25058       rc = 1;
25059     }else{
25060       while( sqlite3_step(pStmt)==SQLITE_ROW ){
25061         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
25062         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
25063         if( zSchema==0 || zFile==0 ) continue;
25064         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
25065         shell_check_oom(azName);
25066         azName[nName*2] = strdup(zSchema);
25067         azName[nName*2+1] = strdup(zFile);
25068         nName++;
25069       }
25070     }
25071     sqlite3_finalize(pStmt);
25072     for(i=0; i<nName; i++){
25073       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
25074       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
25075       const char *z = azName[i*2+1];
25076       oputf("%s: %s %s%s\n",
25077             azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
25078             eTxn==SQLITE_TXN_NONE ? "" :
25079             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
25080       free(azName[i*2]);
25081       free(azName[i*2+1]);
25082     }
25083     sqlite3_free(azName);
25084   }else
25085 
25086   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
25087     static const struct DbConfigChoices {
25088       const char *zName;
25089       int op;
25090     } aDbConfig[] = {
25091         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
25092         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
25093         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
25094         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
25095         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
25096         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
25097         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
25098         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
25099         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
25100         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
25101         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
25102         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
25103         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
25104         { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
25105         { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
25106         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
25107         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
25108         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
25109     };
25110     int ii, v;
25111     open_db(p, 0);
25112     for(ii=0; ii<ArraySize(aDbConfig); ii++){
25113       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
25114       if( nArg>=3 ){
25115         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
25116       }
25117       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
25118       oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
25119       if( nArg>1 ) break;
25120     }
25121     if( nArg>1 && ii==ArraySize(aDbConfig) ){
25122       eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
25123       eputz("Enter \".dbconfig\" with no arguments for a list\n");
25124     }
25125   }else
25126 
25127 #if SQLITE_SHELL_HAVE_RECOVER
25128   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
25129     rc = shell_dbinfo_command(p, nArg, azArg);
25130   }else
25131 
25132   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
25133     open_db(p, 0);
25134     rc = recoverDatabaseCmd(p, nArg, azArg);
25135   }else
25136 #endif /* SQLITE_SHELL_HAVE_RECOVER */
25137 
25138   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
25139     char *zLike = 0;
25140     char *zSql;
25141     int i;
25142     int savedShowHeader = p->showHeader;
25143     int savedShellFlags = p->shellFlgs;
25144     ShellClearFlag(p,
25145        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
25146        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
25147     for(i=1; i<nArg; i++){
25148       if( azArg[i][0]=='-' ){
25149         const char *z = azArg[i]+1;
25150         if( z[0]=='-' ) z++;
25151         if( cli_strcmp(z,"preserve-rowids")==0 ){
25152 #ifdef SQLITE_OMIT_VIRTUALTABLE
25153           eputz("The --preserve-rowids option is not compatible"
25154                 " with SQLITE_OMIT_VIRTUALTABLE\n");
25155           rc = 1;
25156           sqlite3_free(zLike);
25157           goto meta_command_exit;
25158 #else
25159           ShellSetFlag(p, SHFLG_PreserveRowid);
25160 #endif
25161         }else
25162         if( cli_strcmp(z,"newlines")==0 ){
25163           ShellSetFlag(p, SHFLG_Newlines);
25164         }else
25165         if( cli_strcmp(z,"data-only")==0 ){
25166           ShellSetFlag(p, SHFLG_DumpDataOnly);
25167         }else
25168         if( cli_strcmp(z,"nosys")==0 ){
25169           ShellSetFlag(p, SHFLG_DumpNoSys);
25170         }else
25171         {
25172           eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
25173           rc = 1;
25174           sqlite3_free(zLike);
25175           goto meta_command_exit;
25176         }
25177       }else{
25178         /* azArg[i] contains a LIKE pattern. This ".dump" request should
25179         ** only dump data for tables for which either the table name matches
25180         ** the LIKE pattern, or the table appears to be a shadow table of
25181         ** a virtual table for which the name matches the LIKE pattern.
25182         */
25183         char *zExpr = sqlite3_mprintf(
25184             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
25185             "  SELECT 1 FROM sqlite_schema WHERE "
25186             "    name LIKE %Q ESCAPE '\\' AND"
25187             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
25188             "    substr(o.name, 1, length(name)+1) == (name||'_')"
25189             ")", azArg[i], azArg[i]
25190         );
25191 
25192         if( zLike ){
25193           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
25194         }else{
25195           zLike = zExpr;
25196         }
25197       }
25198     }
25199 
25200     open_db(p, 0);
25201 
25202     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25203       /* When playing back a "dump", the content might appear in an order
25204       ** which causes immediate foreign key constraints to be violated.
25205       ** So disable foreign-key constraint enforcement to prevent problems. */
25206       oputz("PRAGMA foreign_keys=OFF;\n");
25207       oputz("BEGIN TRANSACTION;\n");
25208     }
25209     p->writableSchema = 0;
25210     p->showHeader = 0;
25211     /* Set writable_schema=ON since doing so forces SQLite to initialize
25212     ** as much of the schema as it can even if the sqlite_schema table is
25213     ** corrupt. */
25214     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
25215     p->nErr = 0;
25216     if( zLike==0 ) zLike = sqlite3_mprintf("true");
25217     zSql = sqlite3_mprintf(
25218       "SELECT name, type, sql FROM sqlite_schema AS o "
25219       "WHERE (%s) AND type=='table'"
25220       "  AND sql NOT NULL"
25221       " ORDER BY tbl_name='sqlite_sequence', rowid",
25222       zLike
25223     );
25224     run_schema_dump_query(p,zSql);
25225     sqlite3_free(zSql);
25226     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25227       zSql = sqlite3_mprintf(
25228         "SELECT sql FROM sqlite_schema AS o "
25229         "WHERE (%s) AND sql NOT NULL"
25230         "  AND type IN ('index','trigger','view')",
25231         zLike
25232       );
25233       run_table_dump_query(p, zSql);
25234       sqlite3_free(zSql);
25235     }
25236     sqlite3_free(zLike);
25237     if( p->writableSchema ){
25238       oputz("PRAGMA writable_schema=OFF;\n");
25239       p->writableSchema = 0;
25240     }
25241     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
25242     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
25243     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25244       oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
25245     }
25246     p->showHeader = savedShowHeader;
25247     p->shellFlgs = savedShellFlags;
25248   }else
25249 
25250   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
25251     if( nArg==2 ){
25252       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
25253     }else{
25254       eputz("Usage: .echo on|off\n");
25255       rc = 1;
25256     }
25257   }else
25258 
25259   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
25260     if( nArg==2 ){
25261       p->autoEQPtest = 0;
25262       if( p->autoEQPtrace ){
25263         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
25264         p->autoEQPtrace = 0;
25265       }
25266       if( cli_strcmp(azArg[1],"full")==0 ){
25267         p->autoEQP = AUTOEQP_full;
25268       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
25269         p->autoEQP = AUTOEQP_trigger;
25270 #ifdef SQLITE_DEBUG
25271       }else if( cli_strcmp(azArg[1],"test")==0 ){
25272         p->autoEQP = AUTOEQP_on;
25273         p->autoEQPtest = 1;
25274       }else if( cli_strcmp(azArg[1],"trace")==0 ){
25275         p->autoEQP = AUTOEQP_full;
25276         p->autoEQPtrace = 1;
25277         open_db(p, 0);
25278         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
25279         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
25280 #endif
25281       }else{
25282         p->autoEQP = (u8)booleanValue(azArg[1]);
25283       }
25284     }else{
25285       eputz("Usage: .eqp off|on|trace|trigger|full\n");
25286       rc = 1;
25287     }
25288   }else
25289 
25290 #ifndef SQLITE_SHELL_FIDDLE
25291   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
25292     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
25293     rc = 2;
25294   }else
25295 #endif
25296 
25297   /* The ".explain" command is automatic now.  It is largely pointless.  It
25298   ** retained purely for backwards compatibility */
25299   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
25300     int val = 1;
25301     if( nArg>=2 ){
25302       if( cli_strcmp(azArg[1],"auto")==0 ){
25303         val = 99;
25304       }else{
25305         val =  booleanValue(azArg[1]);
25306       }
25307     }
25308     if( val==1 && p->mode!=MODE_Explain ){
25309       p->normalMode = p->mode;
25310       p->mode = MODE_Explain;
25311       p->autoExplain = 0;
25312     }else if( val==0 ){
25313       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
25314       p->autoExplain = 0;
25315     }else if( val==99 ){
25316       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
25317       p->autoExplain = 1;
25318     }
25319   }else
25320 
25321 #ifndef SQLITE_OMIT_VIRTUALTABLE
25322   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
25323     if( p->bSafeMode ){
25324       eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
25325             azArg[0]);
25326       rc = 1;
25327     }else{
25328       open_db(p, 0);
25329       expertDotCommand(p, azArg, nArg);
25330     }
25331   }else
25332 #endif
25333 
25334   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
25335     static const struct {
25336        const char *zCtrlName;   /* Name of a test-control option */
25337        int ctrlCode;            /* Integer code for that option */
25338        const char *zUsage;      /* Usage notes */
25339     } aCtrl[] = {
25340       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
25341       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
25342       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
25343       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
25344       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
25345    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
25346       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
25347       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
25348       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
25349       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
25350    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
25351     };
25352     int filectrl = -1;
25353     int iCtrl = -1;
25354     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
25355     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
25356     int n2, i;
25357     const char *zCmd = 0;
25358     const char *zSchema = 0;
25359 
25360     open_db(p, 0);
25361     zCmd = nArg>=2 ? azArg[1] : "help";
25362 
25363     if( zCmd[0]=='-'
25364      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
25365      && nArg>=4
25366     ){
25367       zSchema = azArg[2];
25368       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
25369       nArg -= 2;
25370       zCmd = azArg[1];
25371     }
25372 
25373     /* The argument can optionally begin with "-" or "--" */
25374     if( zCmd[0]=='-' && zCmd[1] ){
25375       zCmd++;
25376       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
25377     }
25378 
25379     /* --help lists all file-controls */
25380     if( cli_strcmp(zCmd,"help")==0 ){
25381       oputz("Available file-controls:\n");
25382       for(i=0; i<ArraySize(aCtrl); i++){
25383         oputf("  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
25384       }
25385       rc = 1;
25386       goto meta_command_exit;
25387     }
25388 
25389     /* convert filectrl text option to value. allow any unique prefix
25390     ** of the option name, or a numerical value. */
25391     n2 = strlen30(zCmd);
25392     for(i=0; i<ArraySize(aCtrl); i++){
25393       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
25394         if( filectrl<0 ){
25395           filectrl = aCtrl[i].ctrlCode;
25396           iCtrl = i;
25397         }else{
25398           eputf("Error: ambiguous file-control: \"%s\"\n"
25399                 "Use \".filectrl --help\" for help\n", zCmd);
25400           rc = 1;
25401           goto meta_command_exit;
25402         }
25403       }
25404     }
25405     if( filectrl<0 ){
25406       eputf("Error: unknown file-control: %s\n"
25407             "Use \".filectrl --help\" for help\n", zCmd);
25408     }else{
25409       switch(filectrl){
25410         case SQLITE_FCNTL_SIZE_LIMIT: {
25411           if( nArg!=2 && nArg!=3 ) break;
25412           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
25413           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
25414           isOk = 1;
25415           break;
25416         }
25417         case SQLITE_FCNTL_LOCK_TIMEOUT:
25418         case SQLITE_FCNTL_CHUNK_SIZE: {
25419           int x;
25420           if( nArg!=3 ) break;
25421           x = (int)integerValue(azArg[2]);
25422           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25423           isOk = 2;
25424           break;
25425         }
25426         case SQLITE_FCNTL_PERSIST_WAL:
25427         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
25428           int x;
25429           if( nArg!=2 && nArg!=3 ) break;
25430           x = nArg==3 ? booleanValue(azArg[2]) : -1;
25431           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25432           iRes = x;
25433           isOk = 1;
25434           break;
25435         }
25436         case SQLITE_FCNTL_DATA_VERSION:
25437         case SQLITE_FCNTL_HAS_MOVED: {
25438           int x;
25439           if( nArg!=2 ) break;
25440           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25441           iRes = x;
25442           isOk = 1;
25443           break;
25444         }
25445         case SQLITE_FCNTL_TEMPFILENAME: {
25446           char *z = 0;
25447           if( nArg!=2 ) break;
25448           sqlite3_file_control(p->db, zSchema, filectrl, &z);
25449           if( z ){
25450             oputf("%s\n", z);
25451             sqlite3_free(z);
25452           }
25453           isOk = 2;
25454           break;
25455         }
25456         case SQLITE_FCNTL_RESERVE_BYTES: {
25457           int x;
25458           if( nArg>=3 ){
25459             x = atoi(azArg[2]);
25460             sqlite3_file_control(p->db, zSchema, filectrl, &x);
25461           }
25462           x = -1;
25463           sqlite3_file_control(p->db, zSchema, filectrl, &x);
25464           oputf("%d\n", x);
25465           isOk = 2;
25466           break;
25467         }
25468       }
25469     }
25470     if( isOk==0 && iCtrl>=0 ){
25471       oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
25472       rc = 1;
25473     }else if( isOk==1 ){
25474       char zBuf[100];
25475       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
25476       oputf("%s\n", zBuf);
25477     }
25478   }else
25479 
25480   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
25481     ShellState data;
25482     int doStats = 0;
25483     memcpy(&data, p, sizeof(data));
25484     data.showHeader = 0;
25485     data.cMode = data.mode = MODE_Semi;
25486     if( nArg==2 && optionMatch(azArg[1], "indent") ){
25487       data.cMode = data.mode = MODE_Pretty;
25488       nArg = 1;
25489     }
25490     if( nArg!=1 ){
25491       eputz("Usage: .fullschema ?--indent?\n");
25492       rc = 1;
25493       goto meta_command_exit;
25494     }
25495     open_db(p, 0);
25496     rc = sqlite3_exec(p->db,
25497        "SELECT sql FROM"
25498        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
25499        "     FROM sqlite_schema UNION ALL"
25500        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
25501        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
25502        "ORDER BY x",
25503        callback, &data, 0
25504     );
25505     if( rc==SQLITE_OK ){
25506       sqlite3_stmt *pStmt;
25507       rc = sqlite3_prepare_v2(p->db,
25508                "SELECT rowid FROM sqlite_schema"
25509                " WHERE name GLOB 'sqlite_stat[134]'",
25510                -1, &pStmt, 0);
25511       if( rc==SQLITE_OK ){
25512         doStats = sqlite3_step(pStmt)==SQLITE_ROW;
25513         sqlite3_finalize(pStmt);
25514       }
25515     }
25516     if( doStats==0 ){
25517       oputz("/* No STAT tables available */\n");
25518     }else{
25519       oputz("ANALYZE sqlite_schema;\n");
25520       data.cMode = data.mode = MODE_Insert;
25521       data.zDestTable = "sqlite_stat1";
25522       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
25523       data.zDestTable = "sqlite_stat4";
25524       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
25525       oputz("ANALYZE sqlite_schema;\n");
25526     }
25527   }else
25528 
25529   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
25530     if( nArg==2 ){
25531       p->showHeader = booleanValue(azArg[1]);
25532       p->shellFlgs |= SHFLG_HeaderSet;
25533     }else{
25534       eputz("Usage: .headers on|off\n");
25535       rc = 1;
25536     }
25537   }else
25538 
25539   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
25540     if( nArg>=2 ){
25541       n = showHelp(p->out, azArg[1]);
25542       if( n==0 ){
25543         oputf("Nothing matches '%s'\n", azArg[1]);
25544       }
25545     }else{
25546       showHelp(p->out, 0);
25547     }
25548   }else
25549 
25550 #ifndef SQLITE_SHELL_FIDDLE
25551   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
25552     char *zTable = 0;           /* Insert data into this table */
25553     char *zSchema = 0;          /* within this schema (may default to "main") */
25554     char *zFile = 0;            /* Name of file to extra content from */
25555     sqlite3_stmt *pStmt = NULL; /* A statement */
25556     int nCol;                   /* Number of columns in the table */
25557     int nByte;                  /* Number of bytes in an SQL string */
25558     int i, j;                   /* Loop counters */
25559     int needCommit;             /* True to COMMIT or ROLLBACK at end */
25560     int nSep;                   /* Number of bytes in p->colSeparator[] */
25561     char *zSql;                 /* An SQL statement */
25562     char *zFullTabName;         /* Table name with schema if applicable */
25563     ImportCtx sCtx;             /* Reader context */
25564     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
25565     int eVerbose = 0;           /* Larger for more console output */
25566     int nSkip = 0;              /* Initial lines to skip */
25567     int useOutputMode = 1;      /* Use output mode to determine separators */
25568     char *zCreate = 0;          /* CREATE TABLE statement text */
25569 
25570     failIfSafeMode(p, "cannot run .import in safe mode");
25571     memset(&sCtx, 0, sizeof(sCtx));
25572     if( p->mode==MODE_Ascii ){
25573       xRead = ascii_read_one_field;
25574     }else{
25575       xRead = csv_read_one_field;
25576     }
25577     rc = 1;
25578     for(i=1; i<nArg; i++){
25579       char *z = azArg[i];
25580       if( z[0]=='-' && z[1]=='-' ) z++;
25581       if( z[0]!='-' ){
25582         if( zFile==0 ){
25583           zFile = z;
25584         }else if( zTable==0 ){
25585           zTable = z;
25586         }else{
25587           oputf("ERROR: extra argument: \"%s\".  Usage:\n", z);
25588           showHelp(p->out, "import");
25589           goto meta_command_exit;
25590         }
25591       }else if( cli_strcmp(z,"-v")==0 ){
25592         eVerbose++;
25593       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
25594         zSchema = azArg[++i];
25595       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
25596         nSkip = integerValue(azArg[++i]);
25597       }else if( cli_strcmp(z,"-ascii")==0 ){
25598         sCtx.cColSep = SEP_Unit[0];
25599         sCtx.cRowSep = SEP_Record[0];
25600         xRead = ascii_read_one_field;
25601         useOutputMode = 0;
25602       }else if( cli_strcmp(z,"-csv")==0 ){
25603         sCtx.cColSep = ',';
25604         sCtx.cRowSep = '\n';
25605         xRead = csv_read_one_field;
25606         useOutputMode = 0;
25607       }else{
25608         oputf("ERROR: unknown option: \"%s\".  Usage:\n", z);
25609         showHelp(p->out, "import");
25610         goto meta_command_exit;
25611       }
25612     }
25613     if( zTable==0 ){
25614       oputf("ERROR: missing %s argument. Usage:\n",
25615             zFile==0 ? "FILE" : "TABLE");
25616       showHelp(p->out, "import");
25617       goto meta_command_exit;
25618     }
25619     seenInterrupt = 0;
25620     open_db(p, 0);
25621     if( useOutputMode ){
25622       /* If neither the --csv or --ascii options are specified, then set
25623       ** the column and row separator characters from the output mode. */
25624       nSep = strlen30(p->colSeparator);
25625       if( nSep==0 ){
25626         eputz("Error: non-null column separator required for import\n");
25627         goto meta_command_exit;
25628       }
25629       if( nSep>1 ){
25630         eputz("Error: multi-character column separators not allowed"
25631               " for import\n");
25632         goto meta_command_exit;
25633       }
25634       nSep = strlen30(p->rowSeparator);
25635       if( nSep==0 ){
25636         eputz("Error: non-null row separator required for import\n");
25637         goto meta_command_exit;
25638       }
25639       if( nSep==2 && p->mode==MODE_Csv
25640        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
25641       ){
25642         /* When importing CSV (only), if the row separator is set to the
25643         ** default output row separator, change it to the default input
25644         ** row separator.  This avoids having to maintain different input
25645         ** and output row separators. */
25646         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25647         nSep = strlen30(p->rowSeparator);
25648       }
25649       if( nSep>1 ){
25650         eputz("Error: multi-character row separators not allowed"
25651               " for import\n");
25652         goto meta_command_exit;
25653       }
25654       sCtx.cColSep = (u8)p->colSeparator[0];
25655       sCtx.cRowSep = (u8)p->rowSeparator[0];
25656     }
25657     sCtx.zFile = zFile;
25658     sCtx.nLine = 1;
25659     if( sCtx.zFile[0]=='|' ){
25660 #ifdef SQLITE_OMIT_POPEN
25661       eputz("Error: pipes are not supported in this OS\n");
25662       goto meta_command_exit;
25663 #else
25664       sCtx.in = popen(sCtx.zFile+1, "r");
25665       sCtx.zFile = "<pipe>";
25666       sCtx.xCloser = pclose;
25667 #endif
25668     }else{
25669       sCtx.in = fopen(sCtx.zFile, "rb");
25670       sCtx.xCloser = fclose;
25671     }
25672     if( sCtx.in==0 ){
25673       eputf("Error: cannot open \"%s\"\n", zFile);
25674       goto meta_command_exit;
25675     }
25676     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
25677       char zSep[2];
25678       zSep[1] = 0;
25679       zSep[0] = sCtx.cColSep;
25680       oputz("Column separator ");
25681       output_c_string(zSep);
25682       oputz(", row separator ");
25683       zSep[0] = sCtx.cRowSep;
25684       output_c_string(zSep);
25685       oputz("\n");
25686     }
25687     sCtx.z = sqlite3_malloc64(120);
25688     if( sCtx.z==0 ){
25689       import_cleanup(&sCtx);
25690       shell_out_of_memory();
25691     }
25692     /* Below, resources must be freed before exit. */
25693     while( (nSkip--)>0 ){
25694       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
25695     }
25696     if( zSchema!=0 ){
25697       zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
25698     }else{
25699       zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
25700     }
25701     zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
25702     if( zSql==0 || zFullTabName==0 ){
25703       import_cleanup(&sCtx);
25704       shell_out_of_memory();
25705     }
25706     nByte = strlen30(zSql);
25707     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25708     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
25709     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
25710       sqlite3 *dbCols = 0;
25711       char *zRenames = 0;
25712       char *zColDefs;
25713       zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
25714       while( xRead(&sCtx) ){
25715         zAutoColumn(sCtx.z, &dbCols, 0);
25716         if( sCtx.cTerm!=sCtx.cColSep ) break;
25717       }
25718       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
25719       if( zRenames!=0 ){
25720         sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
25721               "Columns renamed during .import %s due to duplicates:\n"
25722               "%s\n", sCtx.zFile, zRenames);
25723         sqlite3_free(zRenames);
25724       }
25725       assert(dbCols==0);
25726       if( zColDefs==0 ){
25727         eputf("%s: empty file\n", sCtx.zFile);
25728       import_fail:
25729         sqlite3_free(zCreate);
25730         sqlite3_free(zSql);
25731         sqlite3_free(zFullTabName);
25732         import_cleanup(&sCtx);
25733         rc = 1;
25734         goto meta_command_exit;
25735       }
25736       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
25737       if( eVerbose>=1 ){
25738         oputf("%s\n", zCreate);
25739       }
25740       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
25741       if( rc ){
25742         eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
25743         goto import_fail;
25744       }
25745       sqlite3_free(zCreate);
25746       zCreate = 0;
25747       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25748     }
25749     if( rc ){
25750       if (pStmt) sqlite3_finalize(pStmt);
25751       eputf("Error: %s\n", sqlite3_errmsg(p->db));
25752       goto import_fail;
25753     }
25754     sqlite3_free(zSql);
25755     nCol = sqlite3_column_count(pStmt);
25756     sqlite3_finalize(pStmt);
25757     pStmt = 0;
25758     if( nCol==0 ) return 0; /* no columns, no error */
25759     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
25760     if( zSql==0 ){
25761       import_cleanup(&sCtx);
25762       shell_out_of_memory();
25763     }
25764     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
25765     j = strlen30(zSql);
25766     for(i=1; i<nCol; i++){
25767       zSql[j++] = ',';
25768       zSql[j++] = '?';
25769     }
25770     zSql[j++] = ')';
25771     zSql[j] = 0;
25772     if( eVerbose>=2 ){
25773       oputf("Insert using: %s\n", zSql);
25774     }
25775     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25776     if( rc ){
25777       eputf("Error: %s\n", sqlite3_errmsg(p->db));
25778       if (pStmt) sqlite3_finalize(pStmt);
25779       goto import_fail;
25780     }
25781     sqlite3_free(zSql);
25782     sqlite3_free(zFullTabName);
25783     needCommit = sqlite3_get_autocommit(p->db);
25784     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
25785     do{
25786       int startLine = sCtx.nLine;
25787       for(i=0; i<nCol; i++){
25788         char *z = xRead(&sCtx);
25789         /*
25790         ** Did we reach end-of-file before finding any columns?
25791         ** If so, stop instead of NULL filling the remaining columns.
25792         */
25793         if( z==0 && i==0 ) break;
25794         /*
25795         ** Did we reach end-of-file OR end-of-line before finding any
25796         ** columns in ASCII mode?  If so, stop instead of NULL filling
25797         ** the remaining columns.
25798         */
25799         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
25800         /*
25801         ** For CSV mode, per RFC 4180, accept EOF in lieu of final
25802         ** record terminator but only for last field of multi-field row.
25803         ** (If there are too few fields, it's not valid CSV anyway.)
25804         */
25805         if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
25806           z = "";
25807         }
25808         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
25809         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
25810           eputf("%s:%d: expected %d columns but found %d"
25811                 " - filling the rest with NULL\n",
25812                 sCtx.zFile, startLine, nCol, i+1);
25813           i += 2;
25814           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
25815         }
25816       }
25817       if( sCtx.cTerm==sCtx.cColSep ){
25818         do{
25819           xRead(&sCtx);
25820           i++;
25821         }while( sCtx.cTerm==sCtx.cColSep );
25822         eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
25823               sCtx.zFile, startLine, nCol, i);
25824       }
25825       if( i>=nCol ){
25826         sqlite3_step(pStmt);
25827         rc = sqlite3_reset(pStmt);
25828         if( rc!=SQLITE_OK ){
25829           eputf("%s:%d: INSERT failed: %s\n",
25830                 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
25831           sCtx.nErr++;
25832         }else{
25833           sCtx.nRow++;
25834         }
25835       }
25836     }while( sCtx.cTerm!=EOF );
25837 
25838     import_cleanup(&sCtx);
25839     sqlite3_finalize(pStmt);
25840     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
25841     if( eVerbose>0 ){
25842       oputf("Added %d rows with %d errors using %d lines of input\n",
25843             sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
25844     }
25845   }else
25846 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25847 
25848 #ifndef SQLITE_UNTESTABLE
25849   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
25850     char *zSql;
25851     char *zCollist = 0;
25852     sqlite3_stmt *pStmt;
25853     int tnum = 0;
25854     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
25855     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
25856     int i;
25857     if( !ShellHasFlag(p,SHFLG_TestingMode) ){
25858       eputf(".%s unavailable without --unsafe-testing\n",
25859             "imposter");
25860       rc = 1;
25861       goto meta_command_exit;
25862     }
25863     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
25864       eputz("Usage: .imposter INDEX IMPOSTER\n"
25865             "       .imposter off\n");
25866       /* Also allowed, but not documented:
25867       **
25868       **    .imposter TABLE IMPOSTER
25869       **
25870       ** where TABLE is a WITHOUT ROWID table.  In that case, the
25871       ** imposter is another WITHOUT ROWID table with the columns in
25872       ** storage order. */
25873       rc = 1;
25874       goto meta_command_exit;
25875     }
25876     open_db(p, 0);
25877     if( nArg==2 ){
25878       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
25879       goto meta_command_exit;
25880     }
25881     zSql = sqlite3_mprintf(
25882       "SELECT rootpage, 0 FROM sqlite_schema"
25883       " WHERE name='%q' AND type='index'"
25884       "UNION ALL "
25885       "SELECT rootpage, 1 FROM sqlite_schema"
25886       " WHERE name='%q' AND type='table'"
25887       "   AND sql LIKE '%%without%%rowid%%'",
25888       azArg[1], azArg[1]
25889     );
25890     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25891     sqlite3_free(zSql);
25892     if( sqlite3_step(pStmt)==SQLITE_ROW ){
25893       tnum = sqlite3_column_int(pStmt, 0);
25894       isWO = sqlite3_column_int(pStmt, 1);
25895     }
25896     sqlite3_finalize(pStmt);
25897     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
25898     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25899     sqlite3_free(zSql);
25900     i = 0;
25901     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
25902       char zLabel[20];
25903       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
25904       i++;
25905       if( zCol==0 ){
25906         if( sqlite3_column_int(pStmt,1)==-1 ){
25907           zCol = "_ROWID_";
25908         }else{
25909           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
25910           zCol = zLabel;
25911         }
25912       }
25913       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
25914         lenPK = (int)strlen(zCollist);
25915       }
25916       if( zCollist==0 ){
25917         zCollist = sqlite3_mprintf("\"%w\"", zCol);
25918       }else{
25919         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
25920       }
25921     }
25922     sqlite3_finalize(pStmt);
25923     if( i==0 || tnum==0 ){
25924       eputf("no such index: \"%s\"\n", azArg[1]);
25925       rc = 1;
25926       sqlite3_free(zCollist);
25927       goto meta_command_exit;
25928     }
25929     if( lenPK==0 ) lenPK = 100000;
25930     zSql = sqlite3_mprintf(
25931           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
25932           azArg[2], zCollist, lenPK, zCollist);
25933     sqlite3_free(zCollist);
25934     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
25935     if( rc==SQLITE_OK ){
25936       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
25937       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
25938       if( rc ){
25939         eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
25940       }else{
25941         sputf(stdout, "%s;\n", zSql);
25942         sputf(stdout, "WARNING: writing to an imposter table will corrupt"
25943               " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
25944       }
25945     }else{
25946       eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
25947       rc = 1;
25948     }
25949     sqlite3_free(zSql);
25950   }else
25951 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
25952 
25953 #ifdef SQLITE_ENABLE_IOTRACE
25954   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
25955     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
25956     if( iotrace && iotrace!=stdout ) fclose(iotrace);
25957     iotrace = 0;
25958     if( nArg<2 ){
25959       sqlite3IoTrace = 0;
25960     }else if( cli_strcmp(azArg[1], "-")==0 ){
25961       sqlite3IoTrace = iotracePrintf;
25962       iotrace = stdout;
25963     }else{
25964       iotrace = fopen(azArg[1], "w");
25965       if( iotrace==0 ){
25966         eputf("Error: cannot open \"%s\"\n", azArg[1]);
25967         sqlite3IoTrace = 0;
25968         rc = 1;
25969       }else{
25970         sqlite3IoTrace = iotracePrintf;
25971       }
25972     }
25973   }else
25974 #endif
25975 
25976   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
25977     static const struct {
25978        const char *zLimitName;   /* Name of a limit */
25979        int limitCode;            /* Integer code for that limit */
25980     } aLimit[] = {
25981       { "length",                SQLITE_LIMIT_LENGTH                    },
25982       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
25983       { "column",                SQLITE_LIMIT_COLUMN                    },
25984       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
25985       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
25986       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
25987       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
25988       { "attached",              SQLITE_LIMIT_ATTACHED                  },
25989       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
25990       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
25991       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
25992       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
25993     };
25994     int i, n2;
25995     open_db(p, 0);
25996     if( nArg==1 ){
25997       for(i=0; i<ArraySize(aLimit); i++){
25998         sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
25999               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
26000       }
26001     }else if( nArg>3 ){
26002       eputz("Usage: .limit NAME ?NEW-VALUE?\n");
26003       rc = 1;
26004       goto meta_command_exit;
26005     }else{
26006       int iLimit = -1;
26007       n2 = strlen30(azArg[1]);
26008       for(i=0; i<ArraySize(aLimit); i++){
26009         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
26010           if( iLimit<0 ){
26011             iLimit = i;
26012           }else{
26013             eputf("ambiguous limit: \"%s\"\n", azArg[1]);
26014             rc = 1;
26015             goto meta_command_exit;
26016           }
26017         }
26018       }
26019       if( iLimit<0 ){
26020         eputf("unknown limit: \"%s\"\n"
26021               "enter \".limits\" with no arguments for a list.\n",
26022               azArg[1]);
26023         rc = 1;
26024         goto meta_command_exit;
26025       }
26026       if( nArg==3 ){
26027         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
26028                       (int)integerValue(azArg[2]));
26029       }
26030       sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
26031             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
26032     }
26033   }else
26034 
26035   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
26036     open_db(p, 0);
26037     lintDotCommand(p, azArg, nArg);
26038   }else
26039 
26040 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
26041   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
26042     const char *zFile, *zProc;
26043     char *zErrMsg = 0;
26044     failIfSafeMode(p, "cannot run .load in safe mode");
26045     if( nArg<2 || azArg[1][0]==0 ){
26046       /* Must have a non-empty FILE. (Will not load self.) */
26047       eputz("Usage: .load FILE ?ENTRYPOINT?\n");
26048       rc = 1;
26049       goto meta_command_exit;
26050     }
26051     zFile = azArg[1];
26052     zProc = nArg>=3 ? azArg[2] : 0;
26053     open_db(p, 0);
26054     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
26055     if( rc!=SQLITE_OK ){
26056       eputf("Error: %s\n", zErrMsg);
26057       sqlite3_free(zErrMsg);
26058       rc = 1;
26059     }
26060   }else
26061 #endif
26062 
26063   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
26064     if( nArg!=2 ){
26065       eputz("Usage: .log FILENAME\n");
26066       rc = 1;
26067     }else{
26068       const char *zFile = azArg[1];
26069       if( p->bSafeMode
26070        && cli_strcmp(zFile,"on")!=0
26071        && cli_strcmp(zFile,"off")!=0
26072       ){
26073         sputz(stdout, "cannot set .log to anything other"
26074               " than \"on\" or \"off\"\n");
26075         zFile = "off";
26076       }
26077       output_file_close(p->pLog);
26078       if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
26079       p->pLog = output_file_open(zFile, 0);
26080     }
26081   }else
26082 
26083   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
26084     const char *zMode = 0;
26085     const char *zTabname = 0;
26086     int i, n2;
26087     ColModeOpts cmOpts = ColModeOpts_default;
26088     for(i=1; i<nArg; i++){
26089       const char *z = azArg[i];
26090       if( optionMatch(z,"wrap") && i+1<nArg ){
26091         cmOpts.iWrap = integerValue(azArg[++i]);
26092       }else if( optionMatch(z,"ww") ){
26093         cmOpts.bWordWrap = 1;
26094       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
26095         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
26096       }else if( optionMatch(z,"quote") ){
26097         cmOpts.bQuote = 1;
26098       }else if( optionMatch(z,"noquote") ){
26099         cmOpts.bQuote = 0;
26100       }else if( zMode==0 ){
26101         zMode = z;
26102         /* Apply defaults for qbox pseudo-mode.  If that
26103          * overwrites already-set values, user was informed of this.
26104          */
26105         if( cli_strcmp(z, "qbox")==0 ){
26106           ColModeOpts cmo = ColModeOpts_default_qbox;
26107           zMode = "box";
26108           cmOpts = cmo;
26109         }
26110       }else if( zTabname==0 ){
26111         zTabname = z;
26112       }else if( z[0]=='-' ){
26113         eputf("unknown option: %s\n", z);
26114         eputz("options:\n"
26115               "  --noquote\n"
26116               "  --quote\n"
26117               "  --wordwrap on/off\n"
26118               "  --wrap N\n"
26119               "  --ww\n");
26120         rc = 1;
26121         goto meta_command_exit;
26122       }else{
26123         eputf("extra argument: \"%s\"\n", z);
26124         rc = 1;
26125         goto meta_command_exit;
26126       }
26127     }
26128     if( zMode==0 ){
26129       if( p->mode==MODE_Column
26130        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
26131       ){
26132         oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
26133               modeDescr[p->mode], p->cmOpts.iWrap,
26134               p->cmOpts.bWordWrap ? "on" : "off",
26135               p->cmOpts.bQuote ? "" : "no");
26136       }else{
26137         oputf("current output mode: %s\n", modeDescr[p->mode]);
26138       }
26139       zMode = modeDescr[p->mode];
26140     }
26141     n2 = strlen30(zMode);
26142     if( cli_strncmp(zMode,"lines",n2)==0 ){
26143       p->mode = MODE_Line;
26144       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26145     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
26146       p->mode = MODE_Column;
26147       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
26148         p->showHeader = 1;
26149       }
26150       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26151       p->cmOpts = cmOpts;
26152     }else if( cli_strncmp(zMode,"list",n2)==0 ){
26153       p->mode = MODE_List;
26154       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
26155       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26156     }else if( cli_strncmp(zMode,"html",n2)==0 ){
26157       p->mode = MODE_Html;
26158     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
26159       p->mode = MODE_Tcl;
26160       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
26161       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26162     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
26163       p->mode = MODE_Csv;
26164       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26165       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
26166     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
26167       p->mode = MODE_List;
26168       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
26169     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
26170       p->mode = MODE_Insert;
26171       set_table_name(p, zTabname ? zTabname : "table");
26172     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
26173       p->mode = MODE_Quote;
26174       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26175       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26176     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
26177       p->mode = MODE_Ascii;
26178       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
26179       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
26180     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
26181       p->mode = MODE_Markdown;
26182       p->cmOpts = cmOpts;
26183     }else if( cli_strncmp(zMode,"table",n2)==0 ){
26184       p->mode = MODE_Table;
26185       p->cmOpts = cmOpts;
26186     }else if( cli_strncmp(zMode,"box",n2)==0 ){
26187       p->mode = MODE_Box;
26188       p->cmOpts = cmOpts;
26189     }else if( cli_strncmp(zMode,"count",n2)==0 ){
26190       p->mode = MODE_Count;
26191     }else if( cli_strncmp(zMode,"off",n2)==0 ){
26192       p->mode = MODE_Off;
26193     }else if( cli_strncmp(zMode,"json",n2)==0 ){
26194       p->mode = MODE_Json;
26195     }else{
26196       eputz("Error: mode should be one of: "
26197             "ascii box column csv html insert json line list markdown "
26198             "qbox quote table tabs tcl\n");
26199       rc = 1;
26200     }
26201     p->cMode = p->mode;
26202   }else
26203 
26204 #ifndef SQLITE_SHELL_FIDDLE
26205   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
26206     if( nArg!=2 ){
26207       eputz("Usage: .nonce NONCE\n");
26208       rc = 1;
26209     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
26210       eputf("line %d: incorrect nonce: \"%s\"\n",
26211             p->lineno, azArg[1]);
26212       exit(1);
26213     }else{
26214       p->bSafeMode = 0;
26215       return 0;  /* Return immediately to bypass the safe mode reset
26216                  ** at the end of this procedure */
26217     }
26218   }else
26219 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26220 
26221   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
26222     if( nArg==2 ){
26223       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
26224                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
26225     }else{
26226       eputz("Usage: .nullvalue STRING\n");
26227       rc = 1;
26228     }
26229   }else
26230 
26231   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
26232     const char *zFN = 0;     /* Pointer to constant filename */
26233     char *zNewFilename = 0;  /* Name of the database file to open */
26234     int iName = 1;           /* Index in azArg[] of the filename */
26235     int newFlag = 0;         /* True to delete file before opening */
26236     int openMode = SHELL_OPEN_UNSPEC;
26237 
26238     /* Check for command-line arguments */
26239     for(iName=1; iName<nArg; iName++){
26240       const char *z = azArg[iName];
26241 #ifndef SQLITE_SHELL_FIDDLE
26242       if( optionMatch(z,"new") ){
26243         newFlag = 1;
26244 #ifdef SQLITE_HAVE_ZLIB
26245       }else if( optionMatch(z, "zip") ){
26246         openMode = SHELL_OPEN_ZIPFILE;
26247 #endif
26248       }else if( optionMatch(z, "append") ){
26249         openMode = SHELL_OPEN_APPENDVFS;
26250       }else if( optionMatch(z, "readonly") ){
26251         openMode = SHELL_OPEN_READONLY;
26252       }else if( optionMatch(z, "nofollow") ){
26253         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
26254 #ifndef SQLITE_OMIT_DESERIALIZE
26255       }else if( optionMatch(z, "deserialize") ){
26256         openMode = SHELL_OPEN_DESERIALIZE;
26257       }else if( optionMatch(z, "hexdb") ){
26258         openMode = SHELL_OPEN_HEXDB;
26259       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
26260         p->szMax = integerValue(azArg[++iName]);
26261 #endif /* SQLITE_OMIT_DESERIALIZE */
26262       }else
26263 #endif /* !SQLITE_SHELL_FIDDLE */
26264       if( z[0]=='-' ){
26265         eputf("unknown option: %s\n", z);
26266         rc = 1;
26267         goto meta_command_exit;
26268       }else if( zFN ){
26269         eputf("extra argument: \"%s\"\n", z);
26270         rc = 1;
26271         goto meta_command_exit;
26272       }else{
26273         zFN = z;
26274       }
26275     }
26276 
26277     /* Close the existing database */
26278     session_close_all(p, -1);
26279     close_db(p->db);
26280     p->db = 0;
26281     p->pAuxDb->zDbFilename = 0;
26282     sqlite3_free(p->pAuxDb->zFreeOnClose);
26283     p->pAuxDb->zFreeOnClose = 0;
26284     p->openMode = openMode;
26285     p->openFlags = 0;
26286     p->szMax = 0;
26287 
26288     /* If a filename is specified, try to open it first */
26289     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
26290       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
26291 #ifndef SQLITE_SHELL_FIDDLE
26292       if( p->bSafeMode
26293        && p->openMode!=SHELL_OPEN_HEXDB
26294        && zFN
26295        && cli_strcmp(zFN,":memory:")!=0
26296       ){
26297         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
26298       }
26299 #else
26300       /* WASM mode has its own sandboxed pseudo-filesystem. */
26301 #endif
26302       if( zFN ){
26303         zNewFilename = sqlite3_mprintf("%s", zFN);
26304         shell_check_oom(zNewFilename);
26305       }else{
26306         zNewFilename = 0;
26307       }
26308       p->pAuxDb->zDbFilename = zNewFilename;
26309       open_db(p, OPEN_DB_KEEPALIVE);
26310       if( p->db==0 ){
26311         eputf("Error: cannot open '%s'\n", zNewFilename);
26312         sqlite3_free(zNewFilename);
26313       }else{
26314         p->pAuxDb->zFreeOnClose = zNewFilename;
26315       }
26316     }
26317     if( p->db==0 ){
26318       /* As a fall-back open a TEMP database */
26319       p->pAuxDb->zDbFilename = 0;
26320       open_db(p, 0);
26321     }
26322   }else
26323 
26324 #ifndef SQLITE_SHELL_FIDDLE
26325   if( (c=='o'
26326         && (cli_strncmp(azArg[0], "output", n)==0
26327             || cli_strncmp(azArg[0], "once", n)==0))
26328    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
26329   ){
26330     char *zFile = 0;
26331     int bTxtMode = 0;
26332     int i;
26333     int eMode = 0;
26334     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
26335     static const char *zBomUtf8 = "\xef\xbb\xbf";
26336     const char *zBom = 0;
26337 
26338     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
26339     if( c=='e' ){
26340       eMode = 'x';
26341       bOnce = 2;
26342     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
26343       bOnce = 1;
26344     }
26345     for(i=1; i<nArg; i++){
26346       char *z = azArg[i];
26347       if( z[0]=='-' ){
26348         if( z[1]=='-' ) z++;
26349         if( cli_strcmp(z,"-bom")==0 ){
26350           zBom = zBomUtf8;
26351         }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
26352           eMode = 'x';  /* spreadsheet */
26353         }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
26354           eMode = 'e';  /* text editor */
26355         }else{
26356           oputf("ERROR: unknown option: \"%s\".  Usage:\n", azArg[i]);
26357           showHelp(p->out, azArg[0]);
26358           rc = 1;
26359           goto meta_command_exit;
26360         }
26361       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
26362         zFile = sqlite3_mprintf("%s", z);
26363         if( zFile && zFile[0]=='|' ){
26364           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
26365           break;
26366         }
26367       }else{
26368         oputf("ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
26369         showHelp(p->out, azArg[0]);
26370         rc = 1;
26371         sqlite3_free(zFile);
26372         goto meta_command_exit;
26373       }
26374     }
26375     if( zFile==0 ){
26376       zFile = sqlite3_mprintf("stdout");
26377     }
26378     if( bOnce ){
26379       p->outCount = 2;
26380     }else{
26381       p->outCount = 0;
26382     }
26383     output_reset(p);
26384 #ifndef SQLITE_NOHAVE_SYSTEM
26385     if( eMode=='e' || eMode=='x' ){
26386       p->doXdgOpen = 1;
26387       outputModePush(p);
26388       if( eMode=='x' ){
26389         /* spreadsheet mode.  Output as CSV. */
26390         newTempFile(p, "csv");
26391         ShellClearFlag(p, SHFLG_Echo);
26392         p->mode = MODE_Csv;
26393         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26394         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
26395       }else{
26396         /* text editor mode */
26397         newTempFile(p, "txt");
26398         bTxtMode = 1;
26399       }
26400       sqlite3_free(zFile);
26401       zFile = sqlite3_mprintf("%s", p->zTempFile);
26402     }
26403 #endif /* SQLITE_NOHAVE_SYSTEM */
26404     shell_check_oom(zFile);
26405     if( zFile[0]=='|' ){
26406 #ifdef SQLITE_OMIT_POPEN
26407       eputz("Error: pipes are not supported in this OS\n");
26408       rc = 1;
26409       output_redir(p, stdout);
26410 #else
26411       FILE *pfPipe = popen(zFile + 1, "w");
26412       if( pfPipe==0 ){
26413         eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
26414         rc = 1;
26415       }else{
26416         output_redir(p, pfPipe);
26417         if( zBom ) oputz(zBom);
26418         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
26419       }
26420 #endif
26421     }else{
26422       FILE *pfFile = output_file_open(zFile, bTxtMode);
26423       if( pfFile==0 ){
26424         if( cli_strcmp(zFile,"off")!=0 ){
26425           eputf("Error: cannot write to \"%s\"\n", zFile);
26426         }
26427         rc = 1;
26428       } else {
26429         output_redir(p, pfFile);
26430         if( zBom ) oputz(zBom);
26431         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
26432       }
26433     }
26434     sqlite3_free(zFile);
26435   }else
26436 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26437 
26438   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
26439     open_db(p,0);
26440     if( nArg<=1 ) goto parameter_syntax_error;
26441 
26442     /* .parameter clear
26443     ** Clear all bind parameters by dropping the TEMP table that holds them.
26444     */
26445     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
26446       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
26447                    0, 0, 0);
26448     }else
26449 
26450     /* .parameter list
26451     ** List all bind parameters.
26452     */
26453     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
26454       sqlite3_stmt *pStmt = 0;
26455       int rx;
26456       int len = 0;
26457       rx = sqlite3_prepare_v2(p->db,
26458              "SELECT max(length(key)) "
26459              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
26460       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26461         len = sqlite3_column_int(pStmt, 0);
26462         if( len>40 ) len = 40;
26463       }
26464       sqlite3_finalize(pStmt);
26465       pStmt = 0;
26466       if( len ){
26467         rx = sqlite3_prepare_v2(p->db,
26468              "SELECT key, quote(value) "
26469              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
26470         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26471           oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
26472                 sqlite3_column_text(pStmt,1));
26473         }
26474         sqlite3_finalize(pStmt);
26475       }
26476     }else
26477 
26478     /* .parameter init
26479     ** Make sure the TEMP table used to hold bind parameters exists.
26480     ** Create it if necessary.
26481     */
26482     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
26483       bind_table_init(p);
26484     }else
26485 
26486     /* .parameter set NAME VALUE
26487     ** Set or reset a bind parameter.  NAME should be the full parameter
26488     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
26489     ** VALUE can be in either SQL literal notation, or if not it will be
26490     ** understood to be a text string.
26491     */
26492     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
26493       int rx;
26494       char *zSql;
26495       sqlite3_stmt *pStmt;
26496       const char *zKey = azArg[2];
26497       const char *zValue = azArg[3];
26498       bind_table_init(p);
26499       zSql = sqlite3_mprintf(
26500                   "REPLACE INTO temp.sqlite_parameters(key,value)"
26501                   "VALUES(%Q,%s);", zKey, zValue);
26502       shell_check_oom(zSql);
26503       pStmt = 0;
26504       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
26505       sqlite3_free(zSql);
26506       if( rx!=SQLITE_OK ){
26507         sqlite3_finalize(pStmt);
26508         pStmt = 0;
26509         zSql = sqlite3_mprintf(
26510                    "REPLACE INTO temp.sqlite_parameters(key,value)"
26511                    "VALUES(%Q,%Q);", zKey, zValue);
26512         shell_check_oom(zSql);
26513         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
26514         sqlite3_free(zSql);
26515         if( rx!=SQLITE_OK ){
26516           oputf("Error: %s\n", sqlite3_errmsg(p->db));
26517           sqlite3_finalize(pStmt);
26518           pStmt = 0;
26519           rc = 1;
26520         }
26521       }
26522       sqlite3_step(pStmt);
26523       sqlite3_finalize(pStmt);
26524     }else
26525 
26526     /* .parameter unset NAME
26527     ** Remove the NAME binding from the parameter binding table, if it
26528     ** exists.
26529     */
26530     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
26531       char *zSql = sqlite3_mprintf(
26532           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
26533       shell_check_oom(zSql);
26534       sqlite3_exec(p->db, zSql, 0, 0, 0);
26535       sqlite3_free(zSql);
26536     }else
26537     /* If no command name matches, show a syntax error */
26538     parameter_syntax_error:
26539     showHelp(p->out, "parameter");
26540   }else
26541 
26542   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
26543     int i;
26544     for(i=1; i<nArg; i++){
26545       if( i>1 ) oputz(" ");
26546       oputz(azArg[i]);
26547     }
26548     oputz("\n");
26549   }else
26550 
26551 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
26552   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
26553     int i;
26554     int nn = 0;
26555     p->flgProgress = 0;
26556     p->mxProgress = 0;
26557     p->nProgress = 0;
26558     for(i=1; i<nArg; i++){
26559       const char *z = azArg[i];
26560       if( z[0]=='-' ){
26561         z++;
26562         if( z[0]=='-' ) z++;
26563         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
26564           p->flgProgress |= SHELL_PROGRESS_QUIET;
26565           continue;
26566         }
26567         if( cli_strcmp(z,"reset")==0 ){
26568           p->flgProgress |= SHELL_PROGRESS_RESET;
26569           continue;
26570         }
26571         if( cli_strcmp(z,"once")==0 ){
26572           p->flgProgress |= SHELL_PROGRESS_ONCE;
26573           continue;
26574         }
26575         if( cli_strcmp(z,"limit")==0 ){
26576           if( i+1>=nArg ){
26577             eputz("Error: missing argument on --limit\n");
26578             rc = 1;
26579             goto meta_command_exit;
26580           }else{
26581             p->mxProgress = (int)integerValue(azArg[++i]);
26582           }
26583           continue;
26584         }
26585         eputf("Error: unknown option: \"%s\"\n", azArg[i]);
26586         rc = 1;
26587         goto meta_command_exit;
26588       }else{
26589         nn = (int)integerValue(z);
26590       }
26591     }
26592     open_db(p, 0);
26593     sqlite3_progress_handler(p->db, nn, progress_handler, p);
26594   }else
26595 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
26596 
26597   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
26598     if( nArg >= 2) {
26599       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
26600     }
26601     if( nArg >= 3) {
26602       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
26603     }
26604   }else
26605 
26606 #ifndef SQLITE_SHELL_FIDDLE
26607   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
26608     rc = 2;
26609   }else
26610 #endif
26611 
26612 #ifndef SQLITE_SHELL_FIDDLE
26613   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
26614     FILE *inSaved = p->in;
26615     int savedLineno = p->lineno;
26616     failIfSafeMode(p, "cannot run .read in safe mode");
26617     if( nArg!=2 ){
26618       eputz("Usage: .read FILE\n");
26619       rc = 1;
26620       goto meta_command_exit;
26621     }
26622     if( azArg[1][0]=='|' ){
26623 #ifdef SQLITE_OMIT_POPEN
26624       eputz("Error: pipes are not supported in this OS\n");
26625       rc = 1;
26626       p->out = stdout;
26627 #else
26628       p->in = popen(azArg[1]+1, "r");
26629       if( p->in==0 ){
26630         eputf("Error: cannot open \"%s\"\n", azArg[1]);
26631         rc = 1;
26632       }else{
26633         rc = process_input(p);
26634         pclose(p->in);
26635       }
26636 #endif
26637     }else if( (p->in = openChrSource(azArg[1]))==0 ){
26638       eputf("Error: cannot open \"%s\"\n", azArg[1]);
26639       rc = 1;
26640     }else{
26641       rc = process_input(p);
26642       fclose(p->in);
26643     }
26644     p->in = inSaved;
26645     p->lineno = savedLineno;
26646   }else
26647 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26648 
26649 #ifndef SQLITE_SHELL_FIDDLE
26650   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
26651     const char *zSrcFile;
26652     const char *zDb;
26653     sqlite3 *pSrc;
26654     sqlite3_backup *pBackup;
26655     int nTimeout = 0;
26656 
26657     failIfSafeMode(p, "cannot run .restore in safe mode");
26658     if( nArg==2 ){
26659       zSrcFile = azArg[1];
26660       zDb = "main";
26661     }else if( nArg==3 ){
26662       zSrcFile = azArg[2];
26663       zDb = azArg[1];
26664     }else{
26665       eputz("Usage: .restore ?DB? FILE\n");
26666       rc = 1;
26667       goto meta_command_exit;
26668     }
26669     rc = sqlite3_open(zSrcFile, &pSrc);
26670     if( rc!=SQLITE_OK ){
26671       eputf("Error: cannot open \"%s\"\n", zSrcFile);
26672       close_db(pSrc);
26673       return 1;
26674     }
26675     open_db(p, 0);
26676     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
26677     if( pBackup==0 ){
26678       eputf("Error: %s\n", sqlite3_errmsg(p->db));
26679       close_db(pSrc);
26680       return 1;
26681     }
26682     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
26683           || rc==SQLITE_BUSY  ){
26684       if( rc==SQLITE_BUSY ){
26685         if( nTimeout++ >= 3 ) break;
26686         sqlite3_sleep(100);
26687       }
26688     }
26689     sqlite3_backup_finish(pBackup);
26690     if( rc==SQLITE_DONE ){
26691       rc = 0;
26692     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
26693       eputz("Error: source database is busy\n");
26694       rc = 1;
26695     }else{
26696       eputf("Error: %s\n", sqlite3_errmsg(p->db));
26697       rc = 1;
26698     }
26699     close_db(pSrc);
26700   }else
26701 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26702 
26703   if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
26704     if( nArg==2 ){
26705       if( cli_strcmp(azArg[1], "vm")==0 ){
26706         p->scanstatsOn = 3;
26707       }else
26708       if( cli_strcmp(azArg[1], "est")==0 ){
26709         p->scanstatsOn = 2;
26710       }else{
26711         p->scanstatsOn = (u8)booleanValue(azArg[1]);
26712       }
26713       open_db(p, 0);
26714       sqlite3_db_config(
26715           p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
26716       );
26717 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
26718       eputz("Warning: .scanstats not available in this build.\n");
26719 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
26720       if( p->scanstatsOn==3 ){
26721         eputz("Warning: \".scanstats vm\" not available in this build.\n");
26722       }
26723 #endif
26724     }else{
26725       eputz("Usage: .scanstats on|off|est\n");
26726       rc = 1;
26727     }
26728   }else
26729 
26730   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
26731     ShellText sSelect;
26732     ShellState data;
26733     char *zErrMsg = 0;
26734     const char *zDiv = "(";
26735     const char *zName = 0;
26736     int iSchema = 0;
26737     int bDebug = 0;
26738     int bNoSystemTabs = 0;
26739     int ii;
26740 
26741     open_db(p, 0);
26742     memcpy(&data, p, sizeof(data));
26743     data.showHeader = 0;
26744     data.cMode = data.mode = MODE_Semi;
26745     initText(&sSelect);
26746     for(ii=1; ii<nArg; ii++){
26747       if( optionMatch(azArg[ii],"indent") ){
26748         data.cMode = data.mode = MODE_Pretty;
26749       }else if( optionMatch(azArg[ii],"debug") ){
26750         bDebug = 1;
26751       }else if( optionMatch(azArg[ii],"nosys") ){
26752         bNoSystemTabs = 1;
26753       }else if( azArg[ii][0]=='-' ){
26754         eputf("Unknown option: \"%s\"\n", azArg[ii]);
26755         rc = 1;
26756         goto meta_command_exit;
26757       }else if( zName==0 ){
26758         zName = azArg[ii];
26759       }else{
26760         eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
26761         rc = 1;
26762         goto meta_command_exit;
26763       }
26764     }
26765     if( zName!=0 ){
26766       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
26767                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
26768                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
26769                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
26770       if( isSchema ){
26771         char *new_argv[2], *new_colv[2];
26772         new_argv[0] = sqlite3_mprintf(
26773                       "CREATE TABLE %s (\n"
26774                       "  type text,\n"
26775                       "  name text,\n"
26776                       "  tbl_name text,\n"
26777                       "  rootpage integer,\n"
26778                       "  sql text\n"
26779                       ")", zName);
26780         shell_check_oom(new_argv[0]);
26781         new_argv[1] = 0;
26782         new_colv[0] = "sql";
26783         new_colv[1] = 0;
26784         callback(&data, 1, new_argv, new_colv);
26785         sqlite3_free(new_argv[0]);
26786       }
26787     }
26788     if( zDiv ){
26789       sqlite3_stmt *pStmt = 0;
26790       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
26791                               -1, &pStmt, 0);
26792       if( rc ){
26793         eputf("Error: %s\n", sqlite3_errmsg(p->db));
26794         sqlite3_finalize(pStmt);
26795         rc = 1;
26796         goto meta_command_exit;
26797       }
26798       appendText(&sSelect, "SELECT sql FROM", 0);
26799       iSchema = 0;
26800       while( sqlite3_step(pStmt)==SQLITE_ROW ){
26801         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
26802         char zScNum[30];
26803         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
26804         appendText(&sSelect, zDiv, 0);
26805         zDiv = " UNION ALL ";
26806         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
26807         if( sqlite3_stricmp(zDb, "main")!=0 ){
26808           appendText(&sSelect, zDb, '\'');
26809         }else{
26810           appendText(&sSelect, "NULL", 0);
26811         }
26812         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
26813         appendText(&sSelect, zScNum, 0);
26814         appendText(&sSelect, " AS snum, ", 0);
26815         appendText(&sSelect, zDb, '\'');
26816         appendText(&sSelect, " AS sname FROM ", 0);
26817         appendText(&sSelect, zDb, quoteChar(zDb));
26818         appendText(&sSelect, ".sqlite_schema", 0);
26819       }
26820       sqlite3_finalize(pStmt);
26821 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
26822       if( zName ){
26823         appendText(&sSelect,
26824            " UNION ALL SELECT shell_module_schema(name),"
26825            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
26826         0);
26827       }
26828 #endif
26829       appendText(&sSelect, ") WHERE ", 0);
26830       if( zName ){
26831         char *zQarg = sqlite3_mprintf("%Q", zName);
26832         int bGlob;
26833         shell_check_oom(zQarg);
26834         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
26835                 strchr(zName, '[') != 0;
26836         if( strchr(zName, '.') ){
26837           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
26838         }else{
26839           appendText(&sSelect, "lower(tbl_name)", 0);
26840         }
26841         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
26842         appendText(&sSelect, zQarg, 0);
26843         if( !bGlob ){
26844           appendText(&sSelect, " ESCAPE '\\' ", 0);
26845         }
26846         appendText(&sSelect, " AND ", 0);
26847         sqlite3_free(zQarg);
26848       }
26849       if( bNoSystemTabs ){
26850         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
26851       }
26852       appendText(&sSelect, "sql IS NOT NULL"
26853                            " ORDER BY snum, rowid", 0);
26854       if( bDebug ){
26855         oputf("SQL: %s;\n", sSelect.z);
26856       }else{
26857         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
26858       }
26859       freeText(&sSelect);
26860     }
26861     if( zErrMsg ){
26862       eputf("Error: %s\n", zErrMsg);
26863       sqlite3_free(zErrMsg);
26864       rc = 1;
26865     }else if( rc != SQLITE_OK ){
26866       eputz("Error: querying schema information\n");
26867       rc = 1;
26868     }else{
26869       rc = 0;
26870     }
26871   }else
26872 
26873   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
26874    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
26875   ){
26876     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
26877     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
26878   }else
26879 
26880 #if defined(SQLITE_ENABLE_SESSION)
26881   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
26882     struct AuxDb *pAuxDb = p->pAuxDb;
26883     OpenSession *pSession = &pAuxDb->aSession[0];
26884     char **azCmd = &azArg[1];
26885     int iSes = 0;
26886     int nCmd = nArg - 1;
26887     int i;
26888     if( nArg<=1 ) goto session_syntax_error;
26889     open_db(p, 0);
26890     if( nArg>=3 ){
26891       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
26892         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
26893       }
26894       if( iSes<pAuxDb->nSession ){
26895         pSession = &pAuxDb->aSession[iSes];
26896         azCmd++;
26897         nCmd--;
26898       }else{
26899         pSession = &pAuxDb->aSession[0];
26900         iSes = 0;
26901       }
26902     }
26903 
26904     /* .session attach TABLE
26905     ** Invoke the sqlite3session_attach() interface to attach a particular
26906     ** table so that it is never filtered.
26907     */
26908     if( cli_strcmp(azCmd[0],"attach")==0 ){
26909       if( nCmd!=2 ) goto session_syntax_error;
26910       if( pSession->p==0 ){
26911         session_not_open:
26912         eputz("ERROR: No sessions are open\n");
26913       }else{
26914         rc = sqlite3session_attach(pSession->p, azCmd[1]);
26915         if( rc ){
26916           eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
26917           rc = 0;
26918         }
26919       }
26920     }else
26921 
26922     /* .session changeset FILE
26923     ** .session patchset FILE
26924     ** Write a changeset or patchset into a file.  The file is overwritten.
26925     */
26926     if( cli_strcmp(azCmd[0],"changeset")==0
26927      || cli_strcmp(azCmd[0],"patchset")==0
26928     ){
26929       FILE *out = 0;
26930       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
26931       if( nCmd!=2 ) goto session_syntax_error;
26932       if( pSession->p==0 ) goto session_not_open;
26933       out = fopen(azCmd[1], "wb");
26934       if( out==0 ){
26935         eputf("ERROR: cannot open \"%s\" for writing\n",
26936               azCmd[1]);
26937       }else{
26938         int szChng;
26939         void *pChng;
26940         if( azCmd[0][0]=='c' ){
26941           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
26942         }else{
26943           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
26944         }
26945         if( rc ){
26946           sputf(stdout, "Error: error code %d\n", rc);
26947           rc = 0;
26948         }
26949         if( pChng
26950           && fwrite(pChng, szChng, 1, out)!=1 ){
26951           eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
26952         }
26953         sqlite3_free(pChng);
26954         fclose(out);
26955       }
26956     }else
26957 
26958     /* .session close
26959     ** Close the identified session
26960     */
26961     if( cli_strcmp(azCmd[0], "close")==0 ){
26962       if( nCmd!=1 ) goto session_syntax_error;
26963       if( pAuxDb->nSession ){
26964         session_close(pSession);
26965         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
26966       }
26967     }else
26968 
26969     /* .session enable ?BOOLEAN?
26970     ** Query or set the enable flag
26971     */
26972     if( cli_strcmp(azCmd[0], "enable")==0 ){
26973       int ii;
26974       if( nCmd>2 ) goto session_syntax_error;
26975       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
26976       if( pAuxDb->nSession ){
26977         ii = sqlite3session_enable(pSession->p, ii);
26978         oputf("session %s enable flag = %d\n", pSession->zName, ii);
26979       }
26980     }else
26981 
26982     /* .session filter GLOB ....
26983     ** Set a list of GLOB patterns of table names to be excluded.
26984     */
26985     if( cli_strcmp(azCmd[0], "filter")==0 ){
26986       int ii, nByte;
26987       if( nCmd<2 ) goto session_syntax_error;
26988       if( pAuxDb->nSession ){
26989         for(ii=0; ii<pSession->nFilter; ii++){
26990           sqlite3_free(pSession->azFilter[ii]);
26991         }
26992         sqlite3_free(pSession->azFilter);
26993         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
26994         pSession->azFilter = sqlite3_malloc( nByte );
26995         shell_check_oom( pSession->azFilter );
26996         for(ii=1; ii<nCmd; ii++){
26997           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
26998           shell_check_oom(x);
26999         }
27000         pSession->nFilter = ii-1;
27001       }
27002     }else
27003 
27004     /* .session indirect ?BOOLEAN?
27005     ** Query or set the indirect flag
27006     */
27007     if( cli_strcmp(azCmd[0], "indirect")==0 ){
27008       int ii;
27009       if( nCmd>2 ) goto session_syntax_error;
27010       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
27011       if( pAuxDb->nSession ){
27012         ii = sqlite3session_indirect(pSession->p, ii);
27013         oputf("session %s indirect flag = %d\n", pSession->zName, ii);
27014       }
27015     }else
27016 
27017     /* .session isempty
27018     ** Determine if the session is empty
27019     */
27020     if( cli_strcmp(azCmd[0], "isempty")==0 ){
27021       int ii;
27022       if( nCmd!=1 ) goto session_syntax_error;
27023       if( pAuxDb->nSession ){
27024         ii = sqlite3session_isempty(pSession->p);
27025         oputf("session %s isempty flag = %d\n", pSession->zName, ii);
27026       }
27027     }else
27028 
27029     /* .session list
27030     ** List all currently open sessions
27031     */
27032     if( cli_strcmp(azCmd[0],"list")==0 ){
27033       for(i=0; i<pAuxDb->nSession; i++){
27034         oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
27035       }
27036     }else
27037 
27038     /* .session open DB NAME
27039     ** Open a new session called NAME on the attached database DB.
27040     ** DB is normally "main".
27041     */
27042     if( cli_strcmp(azCmd[0],"open")==0 ){
27043       char *zName;
27044       if( nCmd!=3 ) goto session_syntax_error;
27045       zName = azCmd[2];
27046       if( zName[0]==0 ) goto session_syntax_error;
27047       for(i=0; i<pAuxDb->nSession; i++){
27048         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
27049           eputf("Session \"%s\" already exists\n", zName);
27050           goto meta_command_exit;
27051         }
27052       }
27053       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
27054         eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
27055         goto meta_command_exit;
27056       }
27057       pSession = &pAuxDb->aSession[pAuxDb->nSession];
27058       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
27059       if( rc ){
27060         eputf("Cannot open session: error code=%d\n", rc);
27061         rc = 0;
27062         goto meta_command_exit;
27063       }
27064       pSession->nFilter = 0;
27065       sqlite3session_table_filter(pSession->p, session_filter, pSession);
27066       pAuxDb->nSession++;
27067       pSession->zName = sqlite3_mprintf("%s", zName);
27068       shell_check_oom(pSession->zName);
27069     }else
27070     /* If no command name matches, show a syntax error */
27071     session_syntax_error:
27072     showHelp(p->out, "session");
27073   }else
27074 #endif
27075 
27076 #ifdef SQLITE_DEBUG
27077   /* Undocumented commands for internal testing.  Subject to change
27078   ** without notice. */
27079   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
27080     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
27081       int i, v;
27082       for(i=1; i<nArg; i++){
27083         v = booleanValue(azArg[i]);
27084         oputf("%s: %d 0x%x\n", azArg[i], v, v);
27085       }
27086     }
27087     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
27088       int i; sqlite3_int64 v;
27089       for(i=1; i<nArg; i++){
27090         char zBuf[200];
27091         v = integerValue(azArg[i]);
27092         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
27093         oputz(zBuf);
27094       }
27095     }
27096   }else
27097 #endif
27098 
27099   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
27100     int bIsInit = 0;         /* True to initialize the SELFTEST table */
27101     int bVerbose = 0;        /* Verbose output */
27102     int bSelftestExists;     /* True if SELFTEST already exists */
27103     int i, k;                /* Loop counters */
27104     int nTest = 0;           /* Number of tests runs */
27105     int nErr = 0;            /* Number of errors seen */
27106     ShellText str;           /* Answer for a query */
27107     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
27108 
27109     open_db(p,0);
27110     for(i=1; i<nArg; i++){
27111       const char *z = azArg[i];
27112       if( z[0]=='-' && z[1]=='-' ) z++;
27113       if( cli_strcmp(z,"-init")==0 ){
27114         bIsInit = 1;
27115       }else
27116       if( cli_strcmp(z,"-v")==0 ){
27117         bVerbose++;
27118       }else
27119       {
27120         eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
27121         eputz("Should be one of: --init -v\n");
27122         rc = 1;
27123         goto meta_command_exit;
27124       }
27125     }
27126     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
27127            != SQLITE_OK ){
27128       bSelftestExists = 0;
27129     }else{
27130       bSelftestExists = 1;
27131     }
27132     if( bIsInit ){
27133       createSelftestTable(p);
27134       bSelftestExists = 1;
27135     }
27136     initText(&str);
27137     appendText(&str, "x", 0);
27138     for(k=bSelftestExists; k>=0; k--){
27139       if( k==1 ){
27140         rc = sqlite3_prepare_v2(p->db,
27141             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
27142             -1, &pStmt, 0);
27143       }else{
27144         rc = sqlite3_prepare_v2(p->db,
27145           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
27146           "      (1,'run','PRAGMA integrity_check','ok')",
27147           -1, &pStmt, 0);
27148       }
27149       if( rc ){
27150         eputz("Error querying the selftest table\n");
27151         rc = 1;
27152         sqlite3_finalize(pStmt);
27153         goto meta_command_exit;
27154       }
27155       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
27156         int tno = sqlite3_column_int(pStmt, 0);
27157         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
27158         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
27159         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
27160 
27161         if( zOp==0 ) continue;
27162         if( zSql==0 ) continue;
27163         if( zAns==0 ) continue;
27164         k = 0;
27165         if( bVerbose>0 ){
27166           sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
27167         }
27168         if( cli_strcmp(zOp,"memo")==0 ){
27169           oputf("%s\n", zSql);
27170         }else
27171         if( cli_strcmp(zOp,"run")==0 ){
27172           char *zErrMsg = 0;
27173           str.n = 0;
27174           str.z[0] = 0;
27175           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
27176           nTest++;
27177           if( bVerbose ){
27178             oputf("Result: %s\n", str.z);
27179           }
27180           if( rc || zErrMsg ){
27181             nErr++;
27182             rc = 1;
27183             oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
27184             sqlite3_free(zErrMsg);
27185           }else if( cli_strcmp(zAns,str.z)!=0 ){
27186             nErr++;
27187             rc = 1;
27188             oputf("%d: Expected: [%s]\n", tno, zAns);
27189             oputf("%d:      Got: [%s]\n", tno, str.z);
27190           }
27191         }
27192         else{
27193           eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
27194           rc = 1;
27195           break;
27196         }
27197       } /* End loop over rows of content from SELFTEST */
27198       sqlite3_finalize(pStmt);
27199     } /* End loop over k */
27200     freeText(&str);
27201     oputf("%d errors out of %d tests\n", nErr, nTest);
27202   }else
27203 
27204   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
27205     if( nArg<2 || nArg>3 ){
27206       eputz("Usage: .separator COL ?ROW?\n");
27207       rc = 1;
27208     }
27209     if( nArg>=2 ){
27210       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
27211                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
27212     }
27213     if( nArg>=3 ){
27214       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
27215                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
27216     }
27217   }else
27218 
27219   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
27220     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
27221     int i;                   /* Loop counter */
27222     int bSchema = 0;         /* Also hash the schema */
27223     int bSeparate = 0;       /* Hash each table separately */
27224     int iSize = 224;         /* Hash algorithm to use */
27225     int bDebug = 0;          /* Only show the query that would have run */
27226     sqlite3_stmt *pStmt;     /* For querying tables names */
27227     char *zSql;              /* SQL to be run */
27228     char *zSep;              /* Separator */
27229     ShellText sSql;          /* Complete SQL for the query to run the hash */
27230     ShellText sQuery;        /* Set of queries used to read all content */
27231     open_db(p, 0);
27232     for(i=1; i<nArg; i++){
27233       const char *z = azArg[i];
27234       if( z[0]=='-' ){
27235         z++;
27236         if( z[0]=='-' ) z++;
27237         if( cli_strcmp(z,"schema")==0 ){
27238           bSchema = 1;
27239         }else
27240         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
27241          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
27242         ){
27243           iSize = atoi(&z[5]);
27244         }else
27245         if( cli_strcmp(z,"debug")==0 ){
27246           bDebug = 1;
27247         }else
27248         {
27249           eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
27250           showHelp(p->out, azArg[0]);
27251           rc = 1;
27252           goto meta_command_exit;
27253         }
27254       }else if( zLike ){
27255         eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
27256         rc = 1;
27257         goto meta_command_exit;
27258       }else{
27259         zLike = z;
27260         bSeparate = 1;
27261         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
27262       }
27263     }
27264     if( bSchema ){
27265       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
27266              " WHERE type='table' AND coalesce(rootpage,0)>1"
27267              " UNION ALL SELECT 'sqlite_schema'"
27268              " ORDER BY 1 collate nocase";
27269     }else{
27270       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
27271              " WHERE type='table' AND coalesce(rootpage,0)>1"
27272              " AND name NOT LIKE 'sqlite_%'"
27273              " ORDER BY 1 collate nocase";
27274     }
27275     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27276     initText(&sQuery);
27277     initText(&sSql);
27278     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
27279     zSep = "VALUES(";
27280     while( SQLITE_ROW==sqlite3_step(pStmt) ){
27281       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
27282       if( zTab==0 ) continue;
27283       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
27284       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
27285         appendText(&sQuery,"SELECT * FROM ", 0);
27286         appendText(&sQuery,zTab,'"');
27287         appendText(&sQuery," NOT INDEXED;", 0);
27288       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
27289         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
27290                            " ORDER BY name;", 0);
27291       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
27292         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
27293                            " ORDER BY name;", 0);
27294       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
27295         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
27296                            " ORDER BY tbl,idx;", 0);
27297       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
27298         appendText(&sQuery, "SELECT * FROM ", 0);
27299         appendText(&sQuery, zTab, 0);
27300         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
27301       }
27302       appendText(&sSql, zSep, 0);
27303       appendText(&sSql, sQuery.z, '\'');
27304       sQuery.n = 0;
27305       appendText(&sSql, ",", 0);
27306       appendText(&sSql, zTab, '\'');
27307       zSep = "),(";
27308     }
27309     sqlite3_finalize(pStmt);
27310     if( bSeparate ){
27311       zSql = sqlite3_mprintf(
27312           "%s))"
27313           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
27314           "   FROM [sha3sum$query]",
27315           sSql.z, iSize);
27316     }else{
27317       zSql = sqlite3_mprintf(
27318           "%s))"
27319           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
27320           "   FROM [sha3sum$query]",
27321           sSql.z, iSize);
27322     }
27323     shell_check_oom(zSql);
27324     freeText(&sQuery);
27325     freeText(&sSql);
27326     if( bDebug ){
27327       oputf("%s\n", zSql);
27328     }else{
27329       shell_exec(p, zSql, 0);
27330     }
27331 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27332     {
27333       int lrc;
27334       char *zRevText = /* Query for reversible to-blob-to-text check */
27335         "SELECT lower(name) as tname FROM sqlite_schema\n"
27336         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
27337         "AND name NOT LIKE 'sqlite_%%'%s\n"
27338         "ORDER BY 1 collate nocase";
27339       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
27340       zRevText = sqlite3_mprintf(
27341           /* lower-case query is first run, producing upper-case query. */
27342           "with tabcols as materialized(\n"
27343           "select tname, cname\n"
27344           "from ("
27345           " select printf('\"%%w\"',ss.tname) as tname,"
27346           " printf('\"%%w\"',ti.name) as cname\n"
27347           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
27348           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
27349           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
27350           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
27351           "FROM '||tname||' WHERE '\n"
27352           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
27353           "|| ' AND typeof('||cname||')=''text'' ',\n"
27354           "' OR ') as query, tname from tabcols group by tname)"
27355           , zRevText);
27356       shell_check_oom(zRevText);
27357       if( bDebug ) oputf("%s\n", zRevText);
27358       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
27359       if( lrc!=SQLITE_OK ){
27360         /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
27361         ** user does cruel and unnatural things like ".limit expr_depth 0". */
27362         rc = 1;
27363       }else{
27364         if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
27365         lrc = SQLITE_ROW==sqlite3_step(pStmt);
27366         if( lrc ){
27367           const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
27368           sqlite3_stmt *pCheckStmt;
27369           lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
27370           if( bDebug ) oputf("%s\n", zGenQuery);
27371           if( lrc!=SQLITE_OK ){
27372             rc = 1;
27373           }else{
27374             if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
27375               double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
27376               if( countIrreversible>0 ){
27377                 int sz = (int)(countIrreversible + 0.5);
27378                 eputf("Digest includes %d invalidly encoded text field%s.\n",
27379                       sz, (sz>1)? "s": "");
27380               }
27381             }
27382             sqlite3_finalize(pCheckStmt);
27383           }
27384           sqlite3_finalize(pStmt);
27385         }
27386       }
27387       if( rc ) eputz(".sha3sum failed.\n");
27388       sqlite3_free(zRevText);
27389     }
27390 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
27391     sqlite3_free(zSql);
27392   }else
27393 
27394 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
27395   if( c=='s'
27396    && (cli_strncmp(azArg[0], "shell", n)==0
27397        || cli_strncmp(azArg[0],"system",n)==0)
27398   ){
27399     char *zCmd;
27400     int i, x;
27401     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
27402     if( nArg<2 ){
27403       eputz("Usage: .system COMMAND\n");
27404       rc = 1;
27405       goto meta_command_exit;
27406     }
27407     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
27408     for(i=2; i<nArg && zCmd!=0; i++){
27409       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
27410                              zCmd, azArg[i]);
27411     }
27412     consoleRestore();
27413     x = zCmd!=0 ? system(zCmd) : 1;
27414     consoleRenewSetup();
27415     sqlite3_free(zCmd);
27416     if( x ) eputf("System command returns %d\n", x);
27417   }else
27418 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
27419 
27420   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
27421     static const char *azBool[] = { "off", "on", "trigger", "full"};
27422     const char *zOut;
27423     int i;
27424     if( nArg!=1 ){
27425       eputz("Usage: .show\n");
27426       rc = 1;
27427       goto meta_command_exit;
27428     }
27429     oputf("%12.12s: %s\n","echo",
27430           azBool[ShellHasFlag(p, SHFLG_Echo)]);
27431     oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
27432     oputf("%12.12s: %s\n","explain",
27433           p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
27434     oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
27435     if( p->mode==MODE_Column
27436      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
27437     ){
27438       oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
27439             modeDescr[p->mode], p->cmOpts.iWrap,
27440             p->cmOpts.bWordWrap ? "on" : "off",
27441             p->cmOpts.bQuote ? "" : "no");
27442     }else{
27443       oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
27444     }
27445     oputf("%12.12s: ", "nullvalue");
27446     output_c_string(p->nullValue);
27447     oputz("\n");
27448     oputf("%12.12s: %s\n","output",
27449           strlen30(p->outfile) ? p->outfile : "stdout");
27450     oputf("%12.12s: ", "colseparator");
27451      output_c_string(p->colSeparator);
27452      oputz("\n");
27453     oputf("%12.12s: ", "rowseparator");
27454      output_c_string(p->rowSeparator);
27455      oputz("\n");
27456     switch( p->statsOn ){
27457       case 0:  zOut = "off";     break;
27458       default: zOut = "on";      break;
27459       case 2:  zOut = "stmt";    break;
27460       case 3:  zOut = "vmstep";  break;
27461     }
27462     oputf("%12.12s: %s\n","stats", zOut);
27463     oputf("%12.12s: ", "width");
27464     for (i=0;i<p->nWidth;i++) {
27465       oputf("%d ", p->colWidth[i]);
27466     }
27467     oputz("\n");
27468     oputf("%12.12s: %s\n", "filename",
27469           p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
27470   }else
27471 
27472   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
27473     if( nArg==2 ){
27474       if( cli_strcmp(azArg[1],"stmt")==0 ){
27475         p->statsOn = 2;
27476       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
27477         p->statsOn = 3;
27478       }else{
27479         p->statsOn = (u8)booleanValue(azArg[1]);
27480       }
27481     }else if( nArg==1 ){
27482       display_stats(p->db, p, 0);
27483     }else{
27484       eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
27485       rc = 1;
27486     }
27487   }else
27488 
27489   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
27490    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
27491                  || cli_strncmp(azArg[0], "indexes", n)==0) )
27492   ){
27493     sqlite3_stmt *pStmt;
27494     char **azResult;
27495     int nRow, nAlloc;
27496     int ii;
27497     ShellText s;
27498     initText(&s);
27499     open_db(p, 0);
27500     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
27501     if( rc ){
27502       sqlite3_finalize(pStmt);
27503       return shellDatabaseError(p->db);
27504     }
27505 
27506     if( nArg>2 && c=='i' ){
27507       /* It is an historical accident that the .indexes command shows an error
27508       ** when called with the wrong number of arguments whereas the .tables
27509       ** command does not. */
27510       eputz("Usage: .indexes ?LIKE-PATTERN?\n");
27511       rc = 1;
27512       sqlite3_finalize(pStmt);
27513       goto meta_command_exit;
27514     }
27515     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
27516       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
27517       if( zDbName==0 ) continue;
27518       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
27519       if( sqlite3_stricmp(zDbName, "main")==0 ){
27520         appendText(&s, "SELECT name FROM ", 0);
27521       }else{
27522         appendText(&s, "SELECT ", 0);
27523         appendText(&s, zDbName, '\'');
27524         appendText(&s, "||'.'||name FROM ", 0);
27525       }
27526       appendText(&s, zDbName, '"');
27527       appendText(&s, ".sqlite_schema ", 0);
27528       if( c=='t' ){
27529         appendText(&s," WHERE type IN ('table','view')"
27530                       "   AND name NOT LIKE 'sqlite_%'"
27531                       "   AND name LIKE ?1", 0);
27532       }else{
27533         appendText(&s," WHERE type='index'"
27534                       "   AND tbl_name LIKE ?1", 0);
27535       }
27536     }
27537     rc = sqlite3_finalize(pStmt);
27538     if( rc==SQLITE_OK ){
27539       appendText(&s, " ORDER BY 1", 0);
27540       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
27541     }
27542     freeText(&s);
27543     if( rc ) return shellDatabaseError(p->db);
27544 
27545     /* Run the SQL statement prepared by the above block. Store the results
27546     ** as an array of nul-terminated strings in azResult[].  */
27547     nRow = nAlloc = 0;
27548     azResult = 0;
27549     if( nArg>1 ){
27550       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
27551     }else{
27552       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
27553     }
27554     while( sqlite3_step(pStmt)==SQLITE_ROW ){
27555       if( nRow>=nAlloc ){
27556         char **azNew;
27557         int n2 = nAlloc*2 + 10;
27558         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
27559         shell_check_oom(azNew);
27560         nAlloc = n2;
27561         azResult = azNew;
27562       }
27563       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
27564       shell_check_oom(azResult[nRow]);
27565       nRow++;
27566     }
27567     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
27568       rc = shellDatabaseError(p->db);
27569     }
27570 
27571     /* Pretty-print the contents of array azResult[] to the output */
27572     if( rc==0 && nRow>0 ){
27573       int len, maxlen = 0;
27574       int i, j;
27575       int nPrintCol, nPrintRow;
27576       for(i=0; i<nRow; i++){
27577         len = strlen30(azResult[i]);
27578         if( len>maxlen ) maxlen = len;
27579       }
27580       nPrintCol = 80/(maxlen+2);
27581       if( nPrintCol<1 ) nPrintCol = 1;
27582       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
27583       for(i=0; i<nPrintRow; i++){
27584         for(j=i; j<nRow; j+=nPrintRow){
27585           char *zSp = j<nPrintRow ? "" : "  ";
27586           oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
27587         }
27588         oputz("\n");
27589       }
27590     }
27591 
27592     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
27593     sqlite3_free(azResult);
27594   }else
27595 
27596 #ifndef SQLITE_SHELL_FIDDLE
27597   /* Begin redirecting output to the file "testcase-out.txt" */
27598   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
27599     output_reset(p);
27600     p->out = output_file_open("testcase-out.txt", 0);
27601     if( p->out==0 ){
27602       eputz("Error: cannot open 'testcase-out.txt'\n");
27603     }
27604     if( nArg>=2 ){
27605       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
27606     }else{
27607       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
27608     }
27609   }else
27610 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
27611 
27612 #ifndef SQLITE_UNTESTABLE
27613   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
27614     static const struct {
27615        const char *zCtrlName;   /* Name of a test-control option */
27616        int ctrlCode;            /* Integer code for that option */
27617        int unSafe;              /* Not valid unless --unsafe-testing */
27618        const char *zUsage;      /* Usage notes */
27619     } aCtrl[] = {
27620     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
27621     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
27622   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
27623   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
27624     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
27625     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
27626   /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
27627     {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
27628     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
27629     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
27630     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
27631     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
27632     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
27633 #ifdef YYCOVERAGE
27634     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
27635 #endif
27636     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
27637     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
27638     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
27639     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
27640     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
27641     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
27642     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
27643     {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
27644     };
27645     int testctrl = -1;
27646     int iCtrl = -1;
27647     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
27648     int isOk = 0;
27649     int i, n2;
27650     const char *zCmd = 0;
27651 
27652     open_db(p, 0);
27653     zCmd = nArg>=2 ? azArg[1] : "help";
27654 
27655     /* The argument can optionally begin with "-" or "--" */
27656     if( zCmd[0]=='-' && zCmd[1] ){
27657       zCmd++;
27658       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
27659     }
27660 
27661     /* --help lists all test-controls */
27662     if( cli_strcmp(zCmd,"help")==0 ){
27663       oputz("Available test-controls:\n");
27664       for(i=0; i<ArraySize(aCtrl); i++){
27665         if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
27666         oputf("  .testctrl %s %s\n",
27667               aCtrl[i].zCtrlName, aCtrl[i].zUsage);
27668       }
27669       rc = 1;
27670       goto meta_command_exit;
27671     }
27672 
27673     /* convert testctrl text option to value. allow any unique prefix
27674     ** of the option name, or a numerical value. */
27675     n2 = strlen30(zCmd);
27676     for(i=0; i<ArraySize(aCtrl); i++){
27677       if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
27678       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
27679         if( testctrl<0 ){
27680           testctrl = aCtrl[i].ctrlCode;
27681           iCtrl = i;
27682         }else{
27683           eputf("Error: ambiguous test-control: \"%s\"\n"
27684                 "Use \".testctrl --help\" for help\n", zCmd);
27685           rc = 1;
27686           goto meta_command_exit;
27687         }
27688       }
27689     }
27690     if( testctrl<0 ){
27691       eputf("Error: unknown test-control: %s\n"
27692             "Use \".testctrl --help\" for help\n", zCmd);
27693     }else{
27694       switch(testctrl){
27695 
27696         /* sqlite3_test_control(int, db, int) */
27697         case SQLITE_TESTCTRL_OPTIMIZATIONS:
27698         case SQLITE_TESTCTRL_FK_NO_ACTION:
27699           if( nArg==3 ){
27700             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
27701             rc2 = sqlite3_test_control(testctrl, p->db, opt);
27702             isOk = 3;
27703           }
27704           break;
27705 
27706         /* sqlite3_test_control(int) */
27707         case SQLITE_TESTCTRL_PRNG_SAVE:
27708         case SQLITE_TESTCTRL_PRNG_RESTORE:
27709         case SQLITE_TESTCTRL_BYTEORDER:
27710           if( nArg==2 ){
27711             rc2 = sqlite3_test_control(testctrl);
27712             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
27713           }
27714           break;
27715 
27716         /* sqlite3_test_control(int, uint) */
27717         case SQLITE_TESTCTRL_PENDING_BYTE:
27718           if( nArg==3 ){
27719             unsigned int opt = (unsigned int)integerValue(azArg[2]);
27720             rc2 = sqlite3_test_control(testctrl, opt);
27721             isOk = 3;
27722           }
27723           break;
27724 
27725         /* sqlite3_test_control(int, int, sqlite3*) */
27726         case SQLITE_TESTCTRL_PRNG_SEED:
27727           if( nArg==3 || nArg==4 ){
27728             int ii = (int)integerValue(azArg[2]);
27729             sqlite3 *db;
27730             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
27731               sqlite3_randomness(sizeof(ii),&ii);
27732               sputf(stdout, "-- random seed: %d\n", ii);
27733             }
27734             if( nArg==3 ){
27735               db = 0;
27736             }else{
27737               db = p->db;
27738               /* Make sure the schema has been loaded */
27739               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
27740             }
27741             rc2 = sqlite3_test_control(testctrl, ii, db);
27742             isOk = 3;
27743           }
27744           break;
27745 
27746         /* sqlite3_test_control(int, int) */
27747         case SQLITE_TESTCTRL_ASSERT:
27748         case SQLITE_TESTCTRL_ALWAYS:
27749           if( nArg==3 ){
27750             int opt = booleanValue(azArg[2]);
27751             rc2 = sqlite3_test_control(testctrl, opt);
27752             isOk = 1;
27753           }
27754           break;
27755 
27756         /* sqlite3_test_control(int, int) */
27757         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
27758         case SQLITE_TESTCTRL_NEVER_CORRUPT:
27759           if( nArg==3 ){
27760             int opt = booleanValue(azArg[2]);
27761             rc2 = sqlite3_test_control(testctrl, opt);
27762             isOk = 3;
27763           }
27764           break;
27765 
27766         /* sqlite3_test_control(int, int) */
27767         case SQLITE_TESTCTRL_USELONGDOUBLE: {
27768           int opt = -1;
27769           if( nArg==3 ){
27770             if( cli_strcmp(azArg[2],"default")==0 ){
27771               opt = 2;
27772             }else{
27773               opt = booleanValue(azArg[2]);
27774             }
27775           }
27776           rc2 = sqlite3_test_control(testctrl, opt);
27777           isOk = 1;
27778           break;
27779         }
27780 
27781         /* sqlite3_test_control(sqlite3*) */
27782         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
27783           rc2 = sqlite3_test_control(testctrl, p->db);
27784           isOk = 3;
27785           break;
27786 
27787         case SQLITE_TESTCTRL_IMPOSTER:
27788           if( nArg==5 ){
27789             rc2 = sqlite3_test_control(testctrl, p->db,
27790                           azArg[2],
27791                           integerValue(azArg[3]),
27792                           integerValue(azArg[4]));
27793             isOk = 3;
27794           }
27795           break;
27796 
27797         case SQLITE_TESTCTRL_SEEK_COUNT: {
27798           u64 x = 0;
27799           rc2 = sqlite3_test_control(testctrl, p->db, &x);
27800           oputf("%llu\n", x);
27801           isOk = 3;
27802           break;
27803         }
27804 
27805 #ifdef YYCOVERAGE
27806         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
27807           if( nArg==2 ){
27808             sqlite3_test_control(testctrl, p->out);
27809             isOk = 3;
27810           }
27811           break;
27812         }
27813 #endif
27814 #ifdef SQLITE_DEBUG
27815         case SQLITE_TESTCTRL_TUNE: {
27816           if( nArg==4 ){
27817             int id = (int)integerValue(azArg[2]);
27818             int val = (int)integerValue(azArg[3]);
27819             sqlite3_test_control(testctrl, id, &val);
27820             isOk = 3;
27821           }else if( nArg==3 ){
27822             int id = (int)integerValue(azArg[2]);
27823             sqlite3_test_control(testctrl, -id, &rc2);
27824             isOk = 1;
27825           }else if( nArg==2 ){
27826             int id = 1;
27827             while(1){
27828               int val = 0;
27829               rc2 = sqlite3_test_control(testctrl, -id, &val);
27830               if( rc2!=SQLITE_OK ) break;
27831               if( id>1 ) oputz("  ");
27832               oputf("%d: %d", id, val);
27833               id++;
27834             }
27835             if( id>1 ) oputz("\n");
27836             isOk = 3;
27837           }
27838           break;
27839         }
27840 #endif
27841         case SQLITE_TESTCTRL_SORTER_MMAP:
27842           if( nArg==3 ){
27843             int opt = (unsigned int)integerValue(azArg[2]);
27844             rc2 = sqlite3_test_control(testctrl, p->db, opt);
27845             isOk = 3;
27846           }
27847           break;
27848       }
27849     }
27850     if( isOk==0 && iCtrl>=0 ){
27851       oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
27852       rc = 1;
27853     }else if( isOk==1 ){
27854       oputf("%d\n", rc2);
27855     }else if( isOk==2 ){
27856       oputf("0x%08x\n", rc2);
27857     }
27858   }else
27859 #endif /* !defined(SQLITE_UNTESTABLE) */
27860 
27861   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
27862     open_db(p, 0);
27863     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
27864   }else
27865 
27866   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
27867     if( nArg==2 ){
27868       enableTimer = booleanValue(azArg[1]);
27869       if( enableTimer && !HAS_TIMER ){
27870         eputz("Error: timer not available on this system.\n");
27871         enableTimer = 0;
27872       }
27873     }else{
27874       eputz("Usage: .timer on|off\n");
27875       rc = 1;
27876     }
27877   }else
27878 
27879 #ifndef SQLITE_OMIT_TRACE
27880   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
27881     int mType = 0;
27882     int jj;
27883     open_db(p, 0);
27884     for(jj=1; jj<nArg; jj++){
27885       const char *z = azArg[jj];
27886       if( z[0]=='-' ){
27887         if( optionMatch(z, "expanded") ){
27888           p->eTraceType = SHELL_TRACE_EXPANDED;
27889         }
27890 #ifdef SQLITE_ENABLE_NORMALIZE
27891         else if( optionMatch(z, "normalized") ){
27892           p->eTraceType = SHELL_TRACE_NORMALIZED;
27893         }
27894 #endif
27895         else if( optionMatch(z, "plain") ){
27896           p->eTraceType = SHELL_TRACE_PLAIN;
27897         }
27898         else if( optionMatch(z, "profile") ){
27899           mType |= SQLITE_TRACE_PROFILE;
27900         }
27901         else if( optionMatch(z, "row") ){
27902           mType |= SQLITE_TRACE_ROW;
27903         }
27904         else if( optionMatch(z, "stmt") ){
27905           mType |= SQLITE_TRACE_STMT;
27906         }
27907         else if( optionMatch(z, "close") ){
27908           mType |= SQLITE_TRACE_CLOSE;
27909         }
27910         else {
27911           eputf("Unknown option \"%s\" on \".trace\"\n", z);
27912           rc = 1;
27913           goto meta_command_exit;
27914         }
27915       }else{
27916         output_file_close(p->traceOut);
27917         p->traceOut = output_file_open(z, 0);
27918       }
27919     }
27920     if( p->traceOut==0 ){
27921       sqlite3_trace_v2(p->db, 0, 0, 0);
27922     }else{
27923       if( mType==0 ) mType = SQLITE_TRACE_STMT;
27924       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
27925     }
27926   }else
27927 #endif /* !defined(SQLITE_OMIT_TRACE) */
27928 
27929 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27930   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
27931     int ii;
27932     int lenOpt;
27933     char *zOpt;
27934     if( nArg<2 ){
27935       eputz("Usage: .unmodule [--allexcept] NAME ...\n");
27936       rc = 1;
27937       goto meta_command_exit;
27938     }
27939     open_db(p, 0);
27940     zOpt = azArg[1];
27941     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
27942     lenOpt = (int)strlen(zOpt);
27943     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
27944       assert( azArg[nArg]==0 );
27945       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
27946     }else{
27947       for(ii=1; ii<nArg; ii++){
27948         sqlite3_create_module(p->db, azArg[ii], 0, 0);
27949       }
27950     }
27951   }else
27952 #endif
27953 
27954 #if SQLITE_USER_AUTHENTICATION
27955   if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
27956     if( nArg<2 ){
27957       eputz("Usage: .user SUBCOMMAND ...\n");
27958       rc = 1;
27959       goto meta_command_exit;
27960     }
27961     open_db(p, 0);
27962     if( cli_strcmp(azArg[1],"login")==0 ){
27963       if( nArg!=4 ){
27964         eputz("Usage: .user login USER PASSWORD\n");
27965         rc = 1;
27966         goto meta_command_exit;
27967       }
27968       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
27969                                      strlen30(azArg[3]));
27970       if( rc ){
27971         eputf("Authentication failed for user %s\n", azArg[2]);
27972         rc = 1;
27973       }
27974     }else if( cli_strcmp(azArg[1],"add")==0 ){
27975       if( nArg!=5 ){
27976         eputz("Usage: .user add USER PASSWORD ISADMIN\n");
27977         rc = 1;
27978         goto meta_command_exit;
27979       }
27980       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
27981                             booleanValue(azArg[4]));
27982       if( rc ){
27983         eputf("User-Add failed: %d\n", rc);
27984         rc = 1;
27985       }
27986     }else if( cli_strcmp(azArg[1],"edit")==0 ){
27987       if( nArg!=5 ){
27988         eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
27989         rc = 1;
27990         goto meta_command_exit;
27991       }
27992       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
27993                               booleanValue(azArg[4]));
27994       if( rc ){
27995         eputf("User-Edit failed: %d\n", rc);
27996         rc = 1;
27997       }
27998     }else if( cli_strcmp(azArg[1],"delete")==0 ){
27999       if( nArg!=3 ){
28000         eputz("Usage: .user delete USER\n");
28001         rc = 1;
28002         goto meta_command_exit;
28003       }
28004       rc = sqlite3_user_delete(p->db, azArg[2]);
28005       if( rc ){
28006         eputf("User-Delete failed: %d\n", rc);
28007         rc = 1;
28008       }
28009     }else{
28010       eputz("Usage: .user login|add|edit|delete ...\n");
28011       rc = 1;
28012       goto meta_command_exit;
28013     }
28014   }else
28015 #endif /* SQLITE_USER_AUTHENTICATION */
28016 
28017   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
28018     char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
28019     oputf("SQLite %s %s\n" /*extra-version-info*/,
28020           sqlite3_libversion(), sqlite3_sourceid());
28021 #if SQLITE_HAVE_ZLIB
28022     oputf("zlib version %s\n", zlibVersion());
28023 #endif
28024 #define CTIMEOPT_VAL_(opt) #opt
28025 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
28026 #if defined(__clang__) && defined(__clang_major__)
28027     oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
28028           CTIMEOPT_VAL(__clang_minor__) "."
28029           CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
28030 #elif defined(_MSC_VER)
28031     oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
28032 #elif defined(__GNUC__) && defined(__VERSION__)
28033     oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
28034 #endif
28035   }else
28036 
28037   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
28038     const char *zDbName = nArg==2 ? azArg[1] : "main";
28039     sqlite3_vfs *pVfs = 0;
28040     if( p->db ){
28041       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
28042       if( pVfs ){
28043         oputf("vfs.zName      = \"%s\"\n", pVfs->zName);
28044         oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
28045         oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
28046         oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
28047       }
28048     }
28049   }else
28050 
28051   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
28052     sqlite3_vfs *pVfs;
28053     sqlite3_vfs *pCurrent = 0;
28054     if( p->db ){
28055       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
28056     }
28057     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
28058       oputf("vfs.zName      = \"%s\"%s\n", pVfs->zName,
28059             pVfs==pCurrent ? "  <--- CURRENT" : "");
28060       oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
28061       oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
28062       oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
28063       if( pVfs->pNext ){
28064         oputz("-----------------------------------\n");
28065       }
28066     }
28067   }else
28068 
28069   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
28070     const char *zDbName = nArg==2 ? azArg[1] : "main";
28071     char *zVfsName = 0;
28072     if( p->db ){
28073       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
28074       if( zVfsName ){
28075         oputf("%s\n", zVfsName);
28076         sqlite3_free(zVfsName);
28077       }
28078     }
28079   }else
28080 
28081   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
28082     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
28083     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
28084   }else
28085 
28086   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
28087     int j;
28088     assert( nArg<=ArraySize(azArg) );
28089     p->nWidth = nArg-1;
28090     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
28091     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
28092     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
28093     for(j=1; j<nArg; j++){
28094       p->colWidth[j-1] = (int)integerValue(azArg[j]);
28095     }
28096   }else
28097 
28098   {
28099     eputf("Error: unknown command or invalid arguments: "
28100           " \"%s\". Enter \".help\" for help\n", azArg[0]);
28101     rc = 1;
28102   }
28103 
28104 meta_command_exit:
28105   if( p->outCount ){
28106     p->outCount--;
28107     if( p->outCount==0 ) output_reset(p);
28108   }
28109   p->bSafeMode = p->bSafeModePersist;
28110   return rc;
28111 }
28112 
28113 /* Line scan result and intermediate states (supporting scan resumption)
28114 */
28115 #ifndef CHAR_BIT
28116 # define CHAR_BIT 8
28117 #endif
28118 typedef enum {
28119   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
28120   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
28121   QSS_Start = 0
28122 } QuickScanState;
28123 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
28124 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
28125 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
28126 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
28127 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
28128 
28129 /*
28130 ** Scan line for classification to guide shell's handling.
28131 ** The scan is resumable for subsequent lines when prior
28132 ** return values are passed as the 2nd argument.
28133 */
quickscan(char * zLine,QuickScanState qss,SCAN_TRACKER_REFTYPE pst)28134 static QuickScanState quickscan(char *zLine, QuickScanState qss,
28135                                 SCAN_TRACKER_REFTYPE pst){
28136   char cin;
28137   char cWait = (char)qss; /* intentional narrowing loss */
28138   if( cWait==0 ){
28139   PlainScan:
28140     assert( cWait==0 );
28141     while( (cin = *zLine++)!=0 ){
28142       if( IsSpace(cin) )
28143         continue;
28144       switch (cin){
28145       case '-':
28146         if( *zLine!='-' )
28147           break;
28148         while((cin = *++zLine)!=0 )
28149           if( cin=='\n')
28150             goto PlainScan;
28151         return qss;
28152       case ';':
28153         qss |= QSS_EndingSemi;
28154         continue;
28155       case '/':
28156         if( *zLine=='*' ){
28157           ++zLine;
28158           cWait = '*';
28159           CONTINUE_PROMPT_AWAITS(pst, "/*");
28160           qss = QSS_SETV(qss, cWait);
28161           goto TermScan;
28162         }
28163         break;
28164       case '[':
28165         cin = ']';
28166         deliberate_fall_through;
28167       case '`': case '\'': case '"':
28168         cWait = cin;
28169         qss = QSS_HasDark | cWait;
28170         CONTINUE_PROMPT_AWAITC(pst, cin);
28171         goto TermScan;
28172       case '(':
28173         CONTINUE_PAREN_INCR(pst, 1);
28174         break;
28175       case ')':
28176         CONTINUE_PAREN_INCR(pst, -1);
28177         break;
28178       default:
28179         break;
28180       }
28181       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
28182     }
28183   }else{
28184   TermScan:
28185     while( (cin = *zLine++)!=0 ){
28186       if( cin==cWait ){
28187         switch( cWait ){
28188         case '*':
28189           if( *zLine != '/' )
28190             continue;
28191           ++zLine;
28192           cWait = 0;
28193           CONTINUE_PROMPT_AWAITC(pst, 0);
28194           qss = QSS_SETV(qss, 0);
28195           goto PlainScan;
28196         case '`': case '\'': case '"':
28197           if(*zLine==cWait){
28198             /* Swallow doubled end-delimiter.*/
28199             ++zLine;
28200             continue;
28201           }
28202           deliberate_fall_through;
28203         case ']':
28204           cWait = 0;
28205           CONTINUE_PROMPT_AWAITC(pst, 0);
28206           qss = QSS_SETV(qss, 0);
28207           goto PlainScan;
28208         default: assert(0);
28209         }
28210       }
28211     }
28212   }
28213   return qss;
28214 }
28215 
28216 /*
28217 ** Return TRUE if the line typed in is an SQL command terminator other
28218 ** than a semi-colon.  The SQL Server style "go" command is understood
28219 ** as is the Oracle "/".
28220 */
line_is_command_terminator(char * zLine)28221 static int line_is_command_terminator(char *zLine){
28222   while( IsSpace(zLine[0]) ){ zLine++; };
28223   if( zLine[0]=='/' )
28224     zLine += 1; /* Oracle */
28225   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
28226     zLine += 2; /* SQL Server */
28227   else
28228     return 0;
28229   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
28230 }
28231 
28232 /*
28233 ** The CLI needs a working sqlite3_complete() to work properly.  So error
28234 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
28235 */
28236 #ifdef SQLITE_OMIT_COMPLETE
28237 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
28238 #endif
28239 
28240 /*
28241 ** Return true if zSql is a complete SQL statement.  Return false if it
28242 ** ends in the middle of a string literal or C-style comment.
28243 */
line_is_complete(char * zSql,int nSql)28244 static int line_is_complete(char *zSql, int nSql){
28245   int rc;
28246   if( zSql==0 ) return 1;
28247   zSql[nSql] = ';';
28248   zSql[nSql+1] = 0;
28249   rc = sqlite3_complete(zSql);
28250   zSql[nSql] = 0;
28251   return rc;
28252 }
28253 
28254 /*
28255 ** Run a single line of SQL.  Return the number of errors.
28256 */
runOneSqlLine(ShellState * p,char * zSql,FILE * in,int startline)28257 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
28258   int rc;
28259   char *zErrMsg = 0;
28260 
28261   open_db(p, 0);
28262   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
28263   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
28264   BEGIN_TIMER;
28265   rc = shell_exec(p, zSql, &zErrMsg);
28266   END_TIMER;
28267   if( rc || zErrMsg ){
28268     char zPrefix[100];
28269     const char *zErrorTail;
28270     const char *zErrorType;
28271     if( zErrMsg==0 ){
28272       zErrorType = "Error";
28273       zErrorTail = sqlite3_errmsg(p->db);
28274     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
28275       zErrorType = "Parse error";
28276       zErrorTail = &zErrMsg[12];
28277     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
28278       zErrorType = "Runtime error";
28279       zErrorTail = &zErrMsg[10];
28280     }else{
28281       zErrorType = "Error";
28282       zErrorTail = zErrMsg;
28283     }
28284     if( in!=0 || !stdin_is_interactive ){
28285       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
28286                        "%s near line %d:", zErrorType, startline);
28287     }else{
28288       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
28289     }
28290     eputf("%s %s\n", zPrefix, zErrorTail);
28291     sqlite3_free(zErrMsg);
28292     zErrMsg = 0;
28293     return 1;
28294   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
28295     char zLineBuf[2000];
28296     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
28297             "changes: %lld   total_changes: %lld",
28298             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
28299     oputf("%s\n", zLineBuf);
28300   }
28301   return 0;
28302 }
28303 
echo_group_input(ShellState * p,const char * zDo)28304 static void echo_group_input(ShellState *p, const char *zDo){
28305   if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
28306 }
28307 
28308 #ifdef SQLITE_SHELL_FIDDLE
28309 /*
28310 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
28311 ** impl because we need the global shellState and cannot access it from that
28312 ** function without moving lots of code around (creating a larger/messier diff).
28313 */
one_input_line(FILE * in,char * zPrior,int isContinuation)28314 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
28315   /* Parse the next line from shellState.wasm.zInput. */
28316   const char *zBegin = shellState.wasm.zPos;
28317   const char *z = zBegin;
28318   char *zLine = 0;
28319   i64 nZ = 0;
28320 
28321   UNUSED_PARAMETER(in);
28322   UNUSED_PARAMETER(isContinuation);
28323   if(!z || !*z){
28324     return 0;
28325   }
28326   while(*z && isspace(*z)) ++z;
28327   zBegin = z;
28328   for(; *z && '\n'!=*z; ++nZ, ++z){}
28329   if(nZ>0 && '\r'==zBegin[nZ-1]){
28330     --nZ;
28331   }
28332   shellState.wasm.zPos = z;
28333   zLine = realloc(zPrior, nZ+1);
28334   shell_check_oom(zLine);
28335   memcpy(zLine, zBegin, nZ);
28336   zLine[nZ] = 0;
28337   return zLine;
28338 }
28339 #endif /* SQLITE_SHELL_FIDDLE */
28340 
28341 /*
28342 ** Read input from *in and process it.  If *in==0 then input
28343 ** is interactive - the user is typing it it.  Otherwise, input
28344 ** is coming from a file or device.  A prompt is issued and history
28345 ** is saved only if input is interactive.  An interrupt signal will
28346 ** cause this routine to exit immediately, unless input is interactive.
28347 **
28348 ** Return the number of errors.
28349 */
process_input(ShellState * p)28350 static int process_input(ShellState *p){
28351   char *zLine = 0;          /* A single input line */
28352   char *zSql = 0;           /* Accumulated SQL text */
28353   i64 nLine;                /* Length of current line */
28354   i64 nSql = 0;             /* Bytes of zSql[] used */
28355   i64 nAlloc = 0;           /* Allocated zSql[] space */
28356   int rc;                   /* Error code */
28357   int errCnt = 0;           /* Number of errors seen */
28358   i64 startline = 0;        /* Line number for start of current input */
28359   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
28360 
28361   if( p->inputNesting==MAX_INPUT_NESTING ){
28362     /* This will be more informative in a later version. */
28363     eputf("Input nesting limit (%d) reached at line %d."
28364           " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
28365     return 1;
28366   }
28367   ++p->inputNesting;
28368   p->lineno = 0;
28369   CONTINUE_PROMPT_RESET;
28370   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
28371     fflush(p->out);
28372     zLine = one_input_line(p->in, zLine, nSql>0);
28373     if( zLine==0 ){
28374       /* End of input */
28375       if( p->in==0 && stdin_is_interactive ) oputz("\n");
28376       break;
28377     }
28378     if( seenInterrupt ){
28379       if( p->in!=0 ) break;
28380       seenInterrupt = 0;
28381     }
28382     p->lineno++;
28383     if( QSS_INPLAIN(qss)
28384         && line_is_command_terminator(zLine)
28385         && line_is_complete(zSql, nSql) ){
28386       memcpy(zLine,";",2);
28387     }
28388     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
28389     if( QSS_PLAINWHITE(qss) && nSql==0 ){
28390       /* Just swallow single-line whitespace */
28391       echo_group_input(p, zLine);
28392       qss = QSS_Start;
28393       continue;
28394     }
28395     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
28396       CONTINUE_PROMPT_RESET;
28397       echo_group_input(p, zLine);
28398       if( zLine[0]=='.' ){
28399         rc = do_meta_command(zLine, p);
28400         if( rc==2 ){ /* exit requested */
28401           break;
28402         }else if( rc ){
28403           errCnt++;
28404         }
28405       }
28406       qss = QSS_Start;
28407       continue;
28408     }
28409     /* No single-line dispositions remain; accumulate line(s). */
28410     nLine = strlen(zLine);
28411     if( nSql+nLine+2>=nAlloc ){
28412       /* Grow buffer by half-again increments when big. */
28413       nAlloc = nSql+(nSql>>1)+nLine+100;
28414       zSql = realloc(zSql, nAlloc);
28415       shell_check_oom(zSql);
28416     }
28417     if( nSql==0 ){
28418       i64 i;
28419       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
28420       assert( nAlloc>0 && zSql!=0 );
28421       memcpy(zSql, zLine+i, nLine+1-i);
28422       startline = p->lineno;
28423       nSql = nLine-i;
28424     }else{
28425       zSql[nSql++] = '\n';
28426       memcpy(zSql+nSql, zLine, nLine+1);
28427       nSql += nLine;
28428     }
28429     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
28430       echo_group_input(p, zSql);
28431       errCnt += runOneSqlLine(p, zSql, p->in, startline);
28432       CONTINUE_PROMPT_RESET;
28433       nSql = 0;
28434       if( p->outCount ){
28435         output_reset(p);
28436         p->outCount = 0;
28437       }else{
28438         clearTempFile(p);
28439       }
28440       p->bSafeMode = p->bSafeModePersist;
28441       qss = QSS_Start;
28442     }else if( nSql && QSS_PLAINWHITE(qss) ){
28443       echo_group_input(p, zSql);
28444       nSql = 0;
28445       qss = QSS_Start;
28446     }
28447   }
28448   if( nSql ){
28449     /* This may be incomplete. Let the SQL parser deal with that. */
28450     echo_group_input(p, zSql);
28451     errCnt += runOneSqlLine(p, zSql, p->in, startline);
28452     CONTINUE_PROMPT_RESET;
28453   }
28454   free(zSql);
28455   free(zLine);
28456   --p->inputNesting;
28457   return errCnt>0;
28458 }
28459 
28460 /*
28461 ** Return a pathname which is the user's home directory.  A
28462 ** 0 return indicates an error of some kind.
28463 */
find_home_dir(int clearFlag)28464 static char *find_home_dir(int clearFlag){
28465   static char *home_dir = NULL;
28466   if( clearFlag ){
28467     free(home_dir);
28468     home_dir = 0;
28469     return 0;
28470   }
28471   if( home_dir ) return home_dir;
28472 
28473 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
28474      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
28475   {
28476     struct passwd *pwent;
28477     uid_t uid = getuid();
28478     if( (pwent=getpwuid(uid)) != NULL) {
28479       home_dir = pwent->pw_dir;
28480     }
28481   }
28482 #endif
28483 
28484 #if defined(_WIN32_WCE)
28485   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
28486    */
28487   home_dir = "/";
28488 #else
28489 
28490 #if defined(_WIN32) || defined(WIN32)
28491   if (!home_dir) {
28492     home_dir = getenv("USERPROFILE");
28493   }
28494 #endif
28495 
28496   if (!home_dir) {
28497     home_dir = getenv("HOME");
28498   }
28499 
28500 #if defined(_WIN32) || defined(WIN32)
28501   if (!home_dir) {
28502     char *zDrive, *zPath;
28503     int n;
28504     zDrive = getenv("HOMEDRIVE");
28505     zPath = getenv("HOMEPATH");
28506     if( zDrive && zPath ){
28507       n = strlen30(zDrive) + strlen30(zPath) + 1;
28508       home_dir = malloc( n );
28509       if( home_dir==0 ) return 0;
28510       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
28511       return home_dir;
28512     }
28513     home_dir = "c:\\";
28514   }
28515 #endif
28516 
28517 #endif /* !_WIN32_WCE */
28518 
28519   if( home_dir ){
28520     i64 n = strlen(home_dir) + 1;
28521     char *z = malloc( n );
28522     if( z ) memcpy(z, home_dir, n);
28523     home_dir = z;
28524   }
28525 
28526   return home_dir;
28527 }
28528 
28529 /*
28530 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
28531 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
28532 ** the path to it, else return 0. The result is cached for
28533 ** subsequent calls.
28534 */
find_xdg_config(void)28535 static const char *find_xdg_config(void){
28536 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
28537      || defined(__RTP__) || defined(_WRS_KERNEL)
28538   return 0;
28539 #else
28540   static int alreadyTried = 0;
28541   static char *zConfig = 0;
28542   const char *zXdgHome;
28543 
28544   if( alreadyTried!=0 ){
28545     return zConfig;
28546   }
28547   alreadyTried = 1;
28548   zXdgHome = getenv("XDG_CONFIG_HOME");
28549   if( zXdgHome==0 ){
28550     return 0;
28551   }
28552   zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
28553   shell_check_oom(zConfig);
28554   if( access(zConfig,0)!=0 ){
28555     sqlite3_free(zConfig);
28556     zConfig = 0;
28557   }
28558   return zConfig;
28559 #endif
28560 }
28561 
28562 /*
28563 ** Read input from the file given by sqliterc_override.  Or if that
28564 ** parameter is NULL, take input from the first of find_xdg_config()
28565 ** or ~/.sqliterc which is found.
28566 **
28567 ** Returns the number of errors.
28568 */
process_sqliterc(ShellState * p,const char * sqliterc_override)28569 static void process_sqliterc(
28570   ShellState *p,                  /* Configuration data */
28571   const char *sqliterc_override   /* Name of config file. NULL to use default */
28572 ){
28573   char *home_dir = NULL;
28574   const char *sqliterc = sqliterc_override;
28575   char *zBuf = 0;
28576   FILE *inSaved = p->in;
28577   int savedLineno = p->lineno;
28578 
28579   if( sqliterc == NULL ){
28580     sqliterc = find_xdg_config();
28581   }
28582   if( sqliterc == NULL ){
28583     home_dir = find_home_dir(0);
28584     if( home_dir==0 ){
28585       eputz("-- warning: cannot find home directory;"
28586             " cannot read ~/.sqliterc\n");
28587       return;
28588     }
28589     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
28590     shell_check_oom(zBuf);
28591     sqliterc = zBuf;
28592   }
28593   p->in = fopen(sqliterc,"rb");
28594   if( p->in ){
28595     if( stdin_is_interactive ){
28596       eputf("-- Loading resources from %s\n", sqliterc);
28597     }
28598     if( process_input(p) && bail_on_error ) exit(1);
28599     fclose(p->in);
28600   }else if( sqliterc_override!=0 ){
28601     eputf("cannot open: \"%s\"\n", sqliterc);
28602     if( bail_on_error ) exit(1);
28603   }
28604   p->in = inSaved;
28605   p->lineno = savedLineno;
28606   sqlite3_free(zBuf);
28607 }
28608 
28609 /*
28610 ** Show available command line options
28611 */
28612 static const char zOptions[] =
28613   "   --                   treat no subsequent arguments as options\n"
28614 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
28615   "   -A ARGS...           run \".archive ARGS\" and exit\n"
28616 #endif
28617   "   -append              append the database to the end of the file\n"
28618   "   -ascii               set output mode to 'ascii'\n"
28619   "   -bail                stop after hitting an error\n"
28620   "   -batch               force batch I/O\n"
28621   "   -box                 set output mode to 'box'\n"
28622   "   -column              set output mode to 'column'\n"
28623   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
28624   "   -csv                 set output mode to 'csv'\n"
28625 #if !defined(SQLITE_OMIT_DESERIALIZE)
28626   "   -deserialize         open the database using sqlite3_deserialize()\n"
28627 #endif
28628   "   -echo                print inputs before execution\n"
28629   "   -init FILENAME       read/process named file\n"
28630   "   -[no]header          turn headers on or off\n"
28631 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
28632   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
28633 #endif
28634   "   -help                show this message\n"
28635   "   -html                set output mode to HTML\n"
28636   "   -interactive         force interactive I/O\n"
28637   "   -json                set output mode to 'json'\n"
28638   "   -line                set output mode to 'line'\n"
28639   "   -list                set output mode to 'list'\n"
28640   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
28641   "   -markdown            set output mode to 'markdown'\n"
28642 #if !defined(SQLITE_OMIT_DESERIALIZE)
28643   "   -maxsize N           maximum size for a --deserialize database\n"
28644 #endif
28645   "   -memtrace            trace all memory allocations and deallocations\n"
28646   "   -mmap N              default mmap size set to N\n"
28647 #ifdef SQLITE_ENABLE_MULTIPLEX
28648   "   -multiplex           enable the multiplexor VFS\n"
28649 #endif
28650   "   -newline SEP         set output row separator. Default: '\\n'\n"
28651   "   -nofollow            refuse to open symbolic links to database files\n"
28652   "   -nonce STRING        set the safe-mode escape nonce\n"
28653   "   -no-rowid-in-view    Disable rowid-in-view using sqlite3_config()\n"
28654   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
28655   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
28656   "   -pcachetrace         trace all page cache operations\n"
28657   "   -quote               set output mode to 'quote'\n"
28658   "   -readonly            open the database read-only\n"
28659   "   -safe                enable safe-mode\n"
28660   "   -separator SEP       set output column separator. Default: '|'\n"
28661 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
28662   "   -sorterref SIZE      sorter references threshold size\n"
28663 #endif
28664   "   -stats               print memory stats before each finalize\n"
28665   "   -table               set output mode to 'table'\n"
28666   "   -tabs                set output mode to 'tabs'\n"
28667   "   -unsafe-testing      allow unsafe commands and modes for testing\n"
28668   "   -version             show SQLite version\n"
28669   "   -vfs NAME            use NAME as the default VFS\n"
28670 #ifdef SQLITE_ENABLE_VFSTRACE
28671   "   -vfstrace            enable tracing of all VFS calls\n"
28672 #endif
28673 #ifdef SQLITE_HAVE_ZLIB
28674   "   -zip                 open the file as a ZIP Archive\n"
28675 #endif
28676 ;
usage(int showDetail)28677 static void usage(int showDetail){
28678   eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
28679        "FILENAME is the name of an SQLite database. A new database is created\n"
28680        "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
28681   if( showDetail ){
28682     eputf("OPTIONS include:\n%s", zOptions);
28683   }else{
28684     eputz("Use the -help option for additional information\n");
28685   }
28686   exit(1);
28687 }
28688 
28689 /*
28690 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
28691 ** error message if it is initialized.
28692 */
verify_uninitialized(void)28693 static void verify_uninitialized(void){
28694   if( sqlite3_config(-1)==SQLITE_MISUSE ){
28695     sputz(stdout, "WARNING: attempt to configure SQLite after"
28696           " initialization.\n");
28697   }
28698 }
28699 
28700 /*
28701 ** Initialize the state information in data
28702 */
main_init(ShellState * data)28703 static void main_init(ShellState *data) {
28704   memset(data, 0, sizeof(*data));
28705   data->normalMode = data->cMode = data->mode = MODE_List;
28706   data->autoExplain = 1;
28707   data->pAuxDb = &data->aAuxDb[0];
28708   memcpy(data->colSeparator,SEP_Column, 2);
28709   memcpy(data->rowSeparator,SEP_Row, 2);
28710   data->showHeader = 0;
28711   data->shellFlgs = SHFLG_Lookaside;
28712   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
28713 #if !defined(SQLITE_SHELL_FIDDLE)
28714   verify_uninitialized();
28715 #endif
28716   sqlite3_config(SQLITE_CONFIG_URI, 1);
28717   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
28718   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
28719   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
28720 }
28721 
28722 /*
28723 ** Output text to the console in a font that attracts extra attention.
28724 */
28725 #if defined(_WIN32) || defined(WIN32)
printBold(const char * zText)28726 static void printBold(const char *zText){
28727 #if !SQLITE_OS_WINRT
28728   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
28729   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
28730   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
28731   SetConsoleTextAttribute(out,
28732          FOREGROUND_RED|FOREGROUND_INTENSITY
28733   );
28734 #endif
28735   oputz(zText);
28736 #if !SQLITE_OS_WINRT
28737   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
28738 #endif
28739 }
28740 #else
printBold(const char * zText)28741 static void printBold(const char *zText){
28742   oputf("\033[1m%s\033[0m", zText);
28743 }
28744 #endif
28745 
28746 /*
28747 ** Get the argument to an --option.  Throw an error and die if no argument
28748 ** is available.
28749 */
cmdline_option_value(int argc,char ** argv,int i)28750 static char *cmdline_option_value(int argc, char **argv, int i){
28751   if( i==argc ){
28752     eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
28753     exit(1);
28754   }
28755   return argv[i];
28756 }
28757 
sayAbnormalExit(void)28758 static void sayAbnormalExit(void){
28759   if( seenInterrupt ) eputz("Program interrupted.\n");
28760 }
28761 
28762 #ifndef SQLITE_SHELL_IS_UTF8
28763 #  if (defined(_WIN32) || defined(WIN32)) \
28764    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
28765 #    define SQLITE_SHELL_IS_UTF8          (0)
28766 #  else
28767 #    define SQLITE_SHELL_IS_UTF8          (1)
28768 #  endif
28769 #endif
28770 
28771 #ifdef SQLITE_SHELL_FIDDLE
28772 #  define main fiddle_main
28773 #endif
28774 
28775 #if SQLITE_SHELL_IS_UTF8
main(int argc,char ** argv)28776 int SQLITE_CDECL main(int argc, char **argv){
28777 #else
28778 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
28779   char **argv;
28780 #endif
28781 #ifdef SQLITE_DEBUG
28782   sqlite3_int64 mem_main_enter = 0;
28783 #endif
28784   char *zErrMsg = 0;
28785 #ifdef SQLITE_SHELL_FIDDLE
28786 #  define data shellState
28787 #else
28788   ShellState data;
28789   StreamsAreConsole consStreams = SAC_NoConsole;
28790 #endif
28791   const char *zInitFile = 0;
28792   int i;
28793   int rc = 0;
28794   int warnInmemoryDb = 0;
28795   int readStdin = 1;
28796   int nCmd = 0;
28797   int nOptsEnd = argc;
28798   char **azCmd = 0;
28799   const char *zVfs = 0;           /* Value of -vfs command-line option */
28800 #if !SQLITE_SHELL_IS_UTF8
28801   char **argvToFree = 0;
28802   int argcToFree = 0;
28803 #endif
28804   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
28805 
28806 #ifdef SQLITE_SHELL_FIDDLE
28807   stdin_is_interactive = 0;
28808   stdout_is_console = 1;
28809   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
28810 #else
28811   consStreams = consoleClassifySetup(stdin, stdout, stderr);
28812   stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
28813   stdout_is_console = (consStreams & SAC_OutConsole)!=0;
28814   atexit(consoleRestore);
28815 #endif
28816   atexit(sayAbnormalExit);
28817 #ifdef SQLITE_DEBUG
28818   mem_main_enter = sqlite3_memory_used();
28819 #endif
28820 #if !defined(_WIN32_WCE)
28821   if( getenv("SQLITE_DEBUG_BREAK") ){
28822     if( isatty(0) && isatty(2) ){
28823       eputf("attach debugger to process %d and press any key to continue.\n",
28824             GETPID());
28825       fgetc(stdin);
28826     }else{
28827 #if defined(_WIN32) || defined(WIN32)
28828 #if SQLITE_OS_WINRT
28829       __debugbreak();
28830 #else
28831       DebugBreak();
28832 #endif
28833 #elif defined(SIGTRAP)
28834       raise(SIGTRAP);
28835 #endif
28836     }
28837   }
28838 #endif
28839   /* Register a valid signal handler early, before much else is done. */
28840 #ifdef SIGINT
28841   signal(SIGINT, interrupt_handler);
28842 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
28843   if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
28844     eputz("No ^C handler.\n");
28845   }
28846 #endif
28847 
28848 #if USE_SYSTEM_SQLITE+0!=1
28849   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
28850     eputf("SQLite header and source version mismatch\n%s\n%s\n",
28851           sqlite3_sourceid(), SQLITE_SOURCE_ID);
28852     exit(1);
28853   }
28854 #endif
28855   main_init(&data);
28856 
28857   /* On Windows, we must translate command-line arguments into UTF-8.
28858   ** The SQLite memory allocator subsystem has to be enabled in order to
28859   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
28860   ** subsequent sqlite3_config() calls will work.  So copy all results into
28861   ** memory that does not come from the SQLite memory allocator.
28862   */
28863 #if !SQLITE_SHELL_IS_UTF8
28864   sqlite3_initialize();
28865   argvToFree = malloc(sizeof(argv[0])*argc*2);
28866   shell_check_oom(argvToFree);
28867   argcToFree = argc;
28868   argv = argvToFree + argc;
28869   for(i=0; i<argc; i++){
28870     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
28871     i64 n;
28872     shell_check_oom(z);
28873     n = strlen(z);
28874     argv[i] = malloc( n+1 );
28875     shell_check_oom(argv[i]);
28876     memcpy(argv[i], z, n+1);
28877     argvToFree[i] = argv[i];
28878     sqlite3_free(z);
28879   }
28880   sqlite3_shutdown();
28881 #endif
28882 
28883   assert( argc>=1 && argv && argv[0] );
28884   Argv0 = argv[0];
28885 
28886 #ifdef SQLITE_SHELL_DBNAME_PROC
28887   {
28888     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
28889     ** of a C-function that will provide the name of the database file.  Use
28890     ** this compile-time option to embed this shell program in larger
28891     ** applications. */
28892     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
28893     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
28894     warnInmemoryDb = 0;
28895   }
28896 #endif
28897 
28898   /* Do an initial pass through the command-line argument to locate
28899   ** the name of the database file, the name of the initialization file,
28900   ** the size of the alternative malloc heap, options affecting commands
28901   ** or SQL run from the command line, and the first command to execute.
28902   */
28903 #ifndef SQLITE_SHELL_FIDDLE
28904   verify_uninitialized();
28905 #endif
28906   for(i=1; i<argc; i++){
28907     char *z;
28908     z = argv[i];
28909     if( z[0]!='-' || i>nOptsEnd ){
28910       if( data.aAuxDb->zDbFilename==0 ){
28911         data.aAuxDb->zDbFilename = z;
28912       }else{
28913         /* Excess arguments are interpreted as SQL (or dot-commands) and
28914         ** mean that nothing is read from stdin */
28915         readStdin = 0;
28916         nCmd++;
28917         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
28918         shell_check_oom(azCmd);
28919         azCmd[nCmd-1] = z;
28920       }
28921       continue;
28922     }
28923     if( z[1]=='-' ) z++;
28924     if( cli_strcmp(z, "-")==0 ){
28925       nOptsEnd = i;
28926       continue;
28927     }else if( cli_strcmp(z,"-separator")==0
28928      || cli_strcmp(z,"-nullvalue")==0
28929      || cli_strcmp(z,"-newline")==0
28930      || cli_strcmp(z,"-cmd")==0
28931     ){
28932       (void)cmdline_option_value(argc, argv, ++i);
28933     }else if( cli_strcmp(z,"-init")==0 ){
28934       zInitFile = cmdline_option_value(argc, argv, ++i);
28935     }else if( cli_strcmp(z,"-interactive")==0 ){
28936       /* Need to check for interactive override here to so that it can
28937       ** affect console setup (for Windows only) and testing thereof.
28938       */
28939       stdin_is_interactive = 1;
28940     }else if( cli_strcmp(z,"-batch")==0 ){
28941       /* Need to check for batch mode here to so we can avoid printing
28942       ** informational messages (like from process_sqliterc) before
28943       ** we do the actual processing of arguments later in a second pass.
28944       */
28945       stdin_is_interactive = 0;
28946     }else if( cli_strcmp(z,"-utf8")==0 ){
28947     }else if( cli_strcmp(z,"-no-utf8")==0 ){
28948     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
28949       int val = 0;
28950       sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
28951       assert( val==0 );
28952     }else if( cli_strcmp(z,"-heap")==0 ){
28953 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
28954       const char *zSize;
28955       sqlite3_int64 szHeap;
28956 
28957       zSize = cmdline_option_value(argc, argv, ++i);
28958       szHeap = integerValue(zSize);
28959       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
28960       verify_uninitialized();
28961       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
28962 #else
28963       (void)cmdline_option_value(argc, argv, ++i);
28964 #endif
28965     }else if( cli_strcmp(z,"-pagecache")==0 ){
28966       sqlite3_int64 n, sz;
28967       sz = integerValue(cmdline_option_value(argc,argv,++i));
28968       if( sz>70000 ) sz = 70000;
28969       if( sz<0 ) sz = 0;
28970       n = integerValue(cmdline_option_value(argc,argv,++i));
28971       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
28972         n = 0xffffffffffffLL/sz;
28973       }
28974       verify_uninitialized();
28975       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
28976                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
28977       data.shellFlgs |= SHFLG_Pagecache;
28978     }else if( cli_strcmp(z,"-lookaside")==0 ){
28979       int n, sz;
28980       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
28981       if( sz<0 ) sz = 0;
28982       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
28983       if( n<0 ) n = 0;
28984       verify_uninitialized();
28985       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
28986       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
28987     }else if( cli_strcmp(z,"-threadsafe")==0 ){
28988       int n;
28989       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
28990       verify_uninitialized();
28991       switch( n ){
28992          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
28993          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
28994          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
28995       }
28996 #ifdef SQLITE_ENABLE_VFSTRACE
28997     }else if( cli_strcmp(z,"-vfstrace")==0 ){
28998       extern int vfstrace_register(
28999          const char *zTraceName,
29000          const char *zOldVfsName,
29001          int (*xOut)(const char*,void*),
29002          void *pOutArg,
29003          int makeDefault
29004       );
29005       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
29006 #endif
29007 #ifdef SQLITE_ENABLE_MULTIPLEX
29008     }else if( cli_strcmp(z,"-multiplex")==0 ){
29009       extern int sqlite3_multiplex_initialize(const char*,int);
29010       sqlite3_multiplex_initialize(0, 1);
29011 #endif
29012     }else if( cli_strcmp(z,"-mmap")==0 ){
29013       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
29014       verify_uninitialized();
29015       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
29016 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
29017     }else if( cli_strcmp(z,"-sorterref")==0 ){
29018       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
29019       verify_uninitialized();
29020       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
29021 #endif
29022     }else if( cli_strcmp(z,"-vfs")==0 ){
29023       zVfs = cmdline_option_value(argc, argv, ++i);
29024 #ifdef SQLITE_HAVE_ZLIB
29025     }else if( cli_strcmp(z,"-zip")==0 ){
29026       data.openMode = SHELL_OPEN_ZIPFILE;
29027 #endif
29028     }else if( cli_strcmp(z,"-append")==0 ){
29029       data.openMode = SHELL_OPEN_APPENDVFS;
29030 #ifndef SQLITE_OMIT_DESERIALIZE
29031     }else if( cli_strcmp(z,"-deserialize")==0 ){
29032       data.openMode = SHELL_OPEN_DESERIALIZE;
29033     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29034       data.szMax = integerValue(argv[++i]);
29035 #endif
29036     }else if( cli_strcmp(z,"-readonly")==0 ){
29037       data.openMode = SHELL_OPEN_READONLY;
29038     }else if( cli_strcmp(z,"-nofollow")==0 ){
29039       data.openFlags = SQLITE_OPEN_NOFOLLOW;
29040 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
29041     }else if( cli_strncmp(z, "-A",2)==0 ){
29042       /* All remaining command-line arguments are passed to the ".archive"
29043       ** command, so ignore them */
29044       break;
29045 #endif
29046     }else if( cli_strcmp(z, "-memtrace")==0 ){
29047       sqlite3MemTraceActivate(stderr);
29048     }else if( cli_strcmp(z, "-pcachetrace")==0 ){
29049       sqlite3PcacheTraceActivate(stderr);
29050     }else if( cli_strcmp(z,"-bail")==0 ){
29051       bail_on_error = 1;
29052     }else if( cli_strcmp(z,"-nonce")==0 ){
29053       free(data.zNonce);
29054       data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
29055     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29056       ShellSetFlag(&data,SHFLG_TestingMode);
29057     }else if( cli_strcmp(z,"-safe")==0 ){
29058       /* no-op - catch this on the second pass */
29059     }
29060   }
29061 #ifndef SQLITE_SHELL_FIDDLE
29062   verify_uninitialized();
29063 #endif
29064 
29065 
29066 #ifdef SQLITE_SHELL_INIT_PROC
29067   {
29068     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
29069     ** of a C-function that will perform initialization actions on SQLite that
29070     ** occur just before or after sqlite3_initialize(). Use this compile-time
29071     ** option to embed this shell program in larger applications. */
29072     extern void SQLITE_SHELL_INIT_PROC(void);
29073     SQLITE_SHELL_INIT_PROC();
29074   }
29075 #else
29076   /* All the sqlite3_config() calls have now been made. So it is safe
29077   ** to call sqlite3_initialize() and process any command line -vfs option. */
29078   sqlite3_initialize();
29079 #endif
29080 
29081   if( zVfs ){
29082     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
29083     if( pVfs ){
29084       sqlite3_vfs_register(pVfs, 1);
29085     }else{
29086       eputf("no such VFS: \"%s\"\n", zVfs);
29087       exit(1);
29088     }
29089   }
29090 
29091   if( data.pAuxDb->zDbFilename==0 ){
29092 #ifndef SQLITE_OMIT_MEMORYDB
29093     data.pAuxDb->zDbFilename = ":memory:";
29094     warnInmemoryDb = argc==1;
29095 #else
29096     eputf("%s: Error: no database filename specified\n", Argv0);
29097     return 1;
29098 #endif
29099   }
29100   data.out = stdout;
29101 #ifndef SQLITE_SHELL_FIDDLE
29102   sqlite3_appendvfs_init(0,0,0);
29103 #endif
29104 
29105   /* Go ahead and open the database file if it already exists.  If the
29106   ** file does not exist, delay opening it.  This prevents empty database
29107   ** files from being created if a user mistypes the database name argument
29108   ** to the sqlite command-line tool.
29109   */
29110   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
29111     open_db(&data, 0);
29112   }
29113 
29114   /* Process the initialization file if there is one.  If no -init option
29115   ** is given on the command line, look for a file named ~/.sqliterc and
29116   ** try to process it.
29117   */
29118   process_sqliterc(&data,zInitFile);
29119 
29120   /* Make a second pass through the command-line argument and set
29121   ** options.  This second pass is delayed until after the initialization
29122   ** file is processed so that the command-line arguments will override
29123   ** settings in the initialization file.
29124   */
29125   for(i=1; i<argc; i++){
29126     char *z = argv[i];
29127     if( z[0]!='-' || i>=nOptsEnd ) continue;
29128     if( z[1]=='-' ){ z++; }
29129     if( cli_strcmp(z,"-init")==0 ){
29130       i++;
29131     }else if( cli_strcmp(z,"-html")==0 ){
29132       data.mode = MODE_Html;
29133     }else if( cli_strcmp(z,"-list")==0 ){
29134       data.mode = MODE_List;
29135     }else if( cli_strcmp(z,"-quote")==0 ){
29136       data.mode = MODE_Quote;
29137       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
29138       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
29139     }else if( cli_strcmp(z,"-line")==0 ){
29140       data.mode = MODE_Line;
29141     }else if( cli_strcmp(z,"-column")==0 ){
29142       data.mode = MODE_Column;
29143     }else if( cli_strcmp(z,"-json")==0 ){
29144       data.mode = MODE_Json;
29145     }else if( cli_strcmp(z,"-markdown")==0 ){
29146       data.mode = MODE_Markdown;
29147     }else if( cli_strcmp(z,"-table")==0 ){
29148       data.mode = MODE_Table;
29149     }else if( cli_strcmp(z,"-box")==0 ){
29150       data.mode = MODE_Box;
29151     }else if( cli_strcmp(z,"-csv")==0 ){
29152       data.mode = MODE_Csv;
29153       memcpy(data.colSeparator,",",2);
29154 #ifdef SQLITE_HAVE_ZLIB
29155     }else if( cli_strcmp(z,"-zip")==0 ){
29156       data.openMode = SHELL_OPEN_ZIPFILE;
29157 #endif
29158     }else if( cli_strcmp(z,"-append")==0 ){
29159       data.openMode = SHELL_OPEN_APPENDVFS;
29160 #ifndef SQLITE_OMIT_DESERIALIZE
29161     }else if( cli_strcmp(z,"-deserialize")==0 ){
29162       data.openMode = SHELL_OPEN_DESERIALIZE;
29163     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29164       data.szMax = integerValue(argv[++i]);
29165 #endif
29166     }else if( cli_strcmp(z,"-readonly")==0 ){
29167       data.openMode = SHELL_OPEN_READONLY;
29168     }else if( cli_strcmp(z,"-nofollow")==0 ){
29169       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
29170     }else if( cli_strcmp(z,"-ascii")==0 ){
29171       data.mode = MODE_Ascii;
29172       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
29173       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
29174     }else if( cli_strcmp(z,"-tabs")==0 ){
29175       data.mode = MODE_List;
29176       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
29177       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
29178     }else if( cli_strcmp(z,"-separator")==0 ){
29179       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
29180                        "%s",cmdline_option_value(argc,argv,++i));
29181     }else if( cli_strcmp(z,"-newline")==0 ){
29182       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
29183                        "%s",cmdline_option_value(argc,argv,++i));
29184     }else if( cli_strcmp(z,"-nullvalue")==0 ){
29185       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
29186                        "%s",cmdline_option_value(argc,argv,++i));
29187     }else if( cli_strcmp(z,"-header")==0 ){
29188       data.showHeader = 1;
29189       ShellSetFlag(&data, SHFLG_HeaderSet);
29190      }else if( cli_strcmp(z,"-noheader")==0 ){
29191       data.showHeader = 0;
29192       ShellSetFlag(&data, SHFLG_HeaderSet);
29193     }else if( cli_strcmp(z,"-echo")==0 ){
29194       ShellSetFlag(&data, SHFLG_Echo);
29195     }else if( cli_strcmp(z,"-eqp")==0 ){
29196       data.autoEQP = AUTOEQP_on;
29197     }else if( cli_strcmp(z,"-eqpfull")==0 ){
29198       data.autoEQP = AUTOEQP_full;
29199     }else if( cli_strcmp(z,"-stats")==0 ){
29200       data.statsOn = 1;
29201     }else if( cli_strcmp(z,"-scanstats")==0 ){
29202       data.scanstatsOn = 1;
29203     }else if( cli_strcmp(z,"-backslash")==0 ){
29204       /* Undocumented command-line option: -backslash
29205       ** Causes C-style backslash escapes to be evaluated in SQL statements
29206       ** prior to sending the SQL into SQLite.  Useful for injecting
29207       ** crazy bytes in the middle of SQL statements for testing and debugging.
29208       */
29209       ShellSetFlag(&data, SHFLG_Backslash);
29210     }else if( cli_strcmp(z,"-bail")==0 ){
29211       /* No-op.  The bail_on_error flag should already be set. */
29212     }else if( cli_strcmp(z,"-version")==0 ){
29213       oputf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
29214             8*(int)sizeof(char*));
29215       return 0;
29216     }else if( cli_strcmp(z,"-interactive")==0 ){
29217       /* already handled */
29218     }else if( cli_strcmp(z,"-batch")==0 ){
29219       /* already handled */
29220     }else if( cli_strcmp(z,"-utf8")==0 ){
29221       /* already handled */
29222     }else if( cli_strcmp(z,"-no-utf8")==0 ){
29223       /* already handled */
29224     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
29225       /* already handled */
29226     }else if( cli_strcmp(z,"-heap")==0 ){
29227       i++;
29228     }else if( cli_strcmp(z,"-pagecache")==0 ){
29229       i+=2;
29230     }else if( cli_strcmp(z,"-lookaside")==0 ){
29231       i+=2;
29232     }else if( cli_strcmp(z,"-threadsafe")==0 ){
29233       i+=2;
29234     }else if( cli_strcmp(z,"-nonce")==0 ){
29235       i += 2;
29236     }else if( cli_strcmp(z,"-mmap")==0 ){
29237       i++;
29238     }else if( cli_strcmp(z,"-memtrace")==0 ){
29239       i++;
29240     }else if( cli_strcmp(z,"-pcachetrace")==0 ){
29241       i++;
29242 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
29243     }else if( cli_strcmp(z,"-sorterref")==0 ){
29244       i++;
29245 #endif
29246     }else if( cli_strcmp(z,"-vfs")==0 ){
29247       i++;
29248 #ifdef SQLITE_ENABLE_VFSTRACE
29249     }else if( cli_strcmp(z,"-vfstrace")==0 ){
29250       i++;
29251 #endif
29252 #ifdef SQLITE_ENABLE_MULTIPLEX
29253     }else if( cli_strcmp(z,"-multiplex")==0 ){
29254       i++;
29255 #endif
29256     }else if( cli_strcmp(z,"-help")==0 ){
29257       usage(1);
29258     }else if( cli_strcmp(z,"-cmd")==0 ){
29259       /* Run commands that follow -cmd first and separately from commands
29260       ** that simply appear on the command-line.  This seems goofy.  It would
29261       ** be better if all commands ran in the order that they appear.  But
29262       ** we retain the goofy behavior for historical compatibility. */
29263       if( i==argc-1 ) break;
29264       z = cmdline_option_value(argc,argv,++i);
29265       if( z[0]=='.' ){
29266         rc = do_meta_command(z, &data);
29267         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
29268       }else{
29269         open_db(&data, 0);
29270         rc = shell_exec(&data, z, &zErrMsg);
29271         if( zErrMsg!=0 ){
29272           eputf("Error: %s\n", zErrMsg);
29273           if( bail_on_error ) return rc!=0 ? rc : 1;
29274         }else if( rc!=0 ){
29275           eputf("Error: unable to process SQL \"%s\"\n", z);
29276           if( bail_on_error ) return rc;
29277         }
29278       }
29279 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
29280     }else if( cli_strncmp(z, "-A", 2)==0 ){
29281       if( nCmd>0 ){
29282         eputf("Error: cannot mix regular SQL or dot-commands"
29283               " with \"%s\"\n", z);
29284         return 1;
29285       }
29286       open_db(&data, OPEN_DB_ZIPFILE);
29287       if( z[2] ){
29288         argv[i] = &z[2];
29289         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
29290       }else{
29291         arDotCommand(&data, 1, argv+i, argc-i);
29292       }
29293       readStdin = 0;
29294       break;
29295 #endif
29296     }else if( cli_strcmp(z,"-safe")==0 ){
29297       data.bSafeMode = data.bSafeModePersist = 1;
29298     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29299       /* Acted upon in first pass. */
29300     }else{
29301       eputf("%s: Error: unknown option: %s\n", Argv0, z);
29302       eputz("Use -help for a list of options.\n");
29303       return 1;
29304     }
29305     data.cMode = data.mode;
29306   }
29307 
29308   if( !readStdin ){
29309     /* Run all arguments that do not begin with '-' as if they were separate
29310     ** command-line inputs, except for the argToSkip argument which contains
29311     ** the database filename.
29312     */
29313     for(i=0; i<nCmd; i++){
29314       if( azCmd[i][0]=='.' ){
29315         rc = do_meta_command(azCmd[i], &data);
29316         if( rc ){
29317           free(azCmd);
29318           return rc==2 ? 0 : rc;
29319         }
29320       }else{
29321         open_db(&data, 0);
29322         echo_group_input(&data, azCmd[i]);
29323         rc = shell_exec(&data, azCmd[i], &zErrMsg);
29324         if( zErrMsg || rc ){
29325           if( zErrMsg!=0 ){
29326             eputf("Error: %s\n", zErrMsg);
29327           }else{
29328             eputf("Error: unable to process SQL: %s\n", azCmd[i]);
29329           }
29330           sqlite3_free(zErrMsg);
29331           free(azCmd);
29332           return rc!=0 ? rc : 1;
29333         }
29334       }
29335     }
29336   }else{
29337     /* Run commands received from standard input
29338     */
29339     if( stdin_is_interactive ){
29340       char *zHome;
29341       char *zHistory;
29342       int nHistory;
29343 #if CIO_WIN_WC_XLATE
29344 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
29345 #else
29346 # define SHELL_CIO_CHAR_SET ""
29347 #endif
29348       oputf("SQLite version %s %.19s%s\n" /*extra-version-info*/
29349             "Enter \".help\" for usage hints.\n",
29350             sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
29351       if( warnInmemoryDb ){
29352         oputz("Connected to a ");
29353         printBold("transient in-memory database");
29354         oputz(".\nUse \".open FILENAME\" to reopen on a"
29355               " persistent database.\n");
29356       }
29357       zHistory = getenv("SQLITE_HISTORY");
29358       if( zHistory ){
29359         zHistory = strdup(zHistory);
29360       }else if( (zHome = find_home_dir(0))!=0 ){
29361         nHistory = strlen30(zHome) + 20;
29362         if( (zHistory = malloc(nHistory))!=0 ){
29363           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
29364         }
29365       }
29366       if( zHistory ){ shell_read_history(zHistory); }
29367 #if HAVE_READLINE || HAVE_EDITLINE
29368       rl_attempted_completion_function = readline_completion;
29369 #elif HAVE_LINENOISE
29370       linenoiseSetCompletionCallback(linenoise_completion);
29371 #endif
29372       data.in = 0;
29373       rc = process_input(&data);
29374       if( zHistory ){
29375         shell_stifle_history(2000);
29376         shell_write_history(zHistory);
29377         free(zHistory);
29378       }
29379     }else{
29380       data.in = stdin;
29381       rc = process_input(&data);
29382     }
29383   }
29384 #ifndef SQLITE_SHELL_FIDDLE
29385   /* In WASM mode we have to leave the db state in place so that
29386   ** client code can "push" SQL into it after this call returns. */
29387   free(azCmd);
29388   set_table_name(&data, 0);
29389   if( data.db ){
29390     session_close_all(&data, -1);
29391     close_db(data.db);
29392   }
29393   for(i=0; i<ArraySize(data.aAuxDb); i++){
29394     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
29395     if( data.aAuxDb[i].db ){
29396       session_close_all(&data, i);
29397       close_db(data.aAuxDb[i].db);
29398     }
29399   }
29400   find_home_dir(1);
29401   output_reset(&data);
29402   data.doXdgOpen = 0;
29403   clearTempFile(&data);
29404 #if !SQLITE_SHELL_IS_UTF8
29405   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
29406   free(argvToFree);
29407 #endif
29408   free(data.colWidth);
29409   free(data.zNonce);
29410   /* Clear the global data structure so that valgrind will detect memory
29411   ** leaks */
29412   memset(&data, 0, sizeof(data));
29413 #ifdef SQLITE_DEBUG
29414   if( sqlite3_memory_used()>mem_main_enter ){
29415     eputf("Memory leaked: %u bytes\n",
29416           (unsigned int)(sqlite3_memory_used()-mem_main_enter));
29417   }
29418 #endif
29419 #endif /* !SQLITE_SHELL_FIDDLE */
29420   return rc;
29421 }
29422 
29423 
29424 #ifdef SQLITE_SHELL_FIDDLE
29425 /* Only for emcc experimentation purposes. */
29426 int fiddle_experiment(int a,int b){
29427   return a + b;
29428 }
29429 
29430 /*
29431 ** Returns a pointer to the current DB handle.
29432 */
29433 sqlite3 * fiddle_db_handle(){
29434   return globalDb;
29435 }
29436 
29437 /*
29438 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
29439 ** "main" is assumed. Returns 0 if no db with the given name is
29440 ** open.
29441 */
29442 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
29443   sqlite3_vfs * pVfs = 0;
29444   if(globalDb){
29445     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
29446                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
29447   }
29448   return pVfs;
29449 }
29450 
29451 /* Only for emcc experimentation purposes. */
29452 sqlite3 * fiddle_db_arg(sqlite3 *arg){
29453     printf("fiddle_db_arg(%p)\n", (const void*)arg);
29454     return arg;
29455 }
29456 
29457 /*
29458 ** Intended to be called via a SharedWorker() while a separate
29459 ** SharedWorker() (which manages the wasm module) is performing work
29460 ** which should be interrupted. Unfortunately, SharedWorker is not
29461 ** portable enough to make real use of.
29462 */
29463 void fiddle_interrupt(void){
29464   if( globalDb ) sqlite3_interrupt(globalDb);
29465 }
29466 
29467 /*
29468 ** Returns the filename of the given db name, assuming "main" if
29469 ** zDbName is NULL. Returns NULL if globalDb is not opened.
29470 */
29471 const char * fiddle_db_filename(const char * zDbName){
29472     return globalDb
29473       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
29474       : NULL;
29475 }
29476 
29477 /*
29478 ** Completely wipes out the contents of the currently-opened database
29479 ** but leaves its storage intact for reuse.
29480 */
29481 void fiddle_reset_db(void){
29482   if( globalDb ){
29483     int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
29484     if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
29485     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
29486   }
29487 }
29488 
29489 /*
29490 ** Uses the current database's VFS xRead to stream the db file's
29491 ** contents out to the given callback. The callback gets a single
29492 ** chunk of size n (its 2nd argument) on each call and must return 0
29493 ** on success, non-0 on error. This function returns 0 on success,
29494 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
29495 ** code from the callback. Note that this is not thread-friendly: it
29496 ** expects that it will be the only thread reading the db file and
29497 ** takes no measures to ensure that is the case.
29498 */
29499 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
29500   sqlite3_int64 nSize = 0;
29501   sqlite3_int64 nPos = 0;
29502   sqlite3_file * pFile = 0;
29503   unsigned char buf[1024 * 8];
29504   int nBuf = (int)sizeof(buf);
29505   int rc = shellState.db
29506     ? sqlite3_file_control(shellState.db, "main",
29507                            SQLITE_FCNTL_FILE_POINTER, &pFile)
29508     : SQLITE_NOTFOUND;
29509   if( rc ) return rc;
29510   rc = pFile->pMethods->xFileSize(pFile, &nSize);
29511   if( rc ) return rc;
29512   if(nSize % nBuf){
29513     /* DB size is not an even multiple of the buffer size. Reduce
29514     ** buffer size so that we do not unduly inflate the db size when
29515     ** exporting. */
29516     if(0 == nSize % 4096) nBuf = 4096;
29517     else if(0 == nSize % 2048) nBuf = 2048;
29518     else if(0 == nSize % 1024) nBuf = 1024;
29519     else nBuf = 512;
29520   }
29521   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
29522     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
29523     if(SQLITE_IOERR_SHORT_READ == rc){
29524       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
29525     }
29526     if( 0==rc ) rc = xCallback(buf, nBuf);
29527   }
29528   return rc;
29529 }
29530 
29531 /*
29532 ** Trivial exportable function for emscripten. It processes zSql as if
29533 ** it were input to the sqlite3 shell and redirects all output to the
29534 ** wasm binding. fiddle_main() must have been called before this
29535 ** is called, or results are undefined.
29536 */
29537 void fiddle_exec(const char * zSql){
29538   if(zSql && *zSql){
29539     if('.'==*zSql) puts(zSql);
29540     shellState.wasm.zInput = zSql;
29541     shellState.wasm.zPos = zSql;
29542     process_input(&shellState);
29543     shellState.wasm.zInput = shellState.wasm.zPos = 0;
29544   }
29545 }
29546 #endif /* SQLITE_SHELL_FIDDLE */
29547