xref: /freebsd/contrib/sqlite3/shell.c (revision de9468837c92cab304c658480bd32dbe4e022d01)
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37 typedef unsigned int u32;
38 typedef unsigned short int u16;
39 
40 /*
41 ** Optionally #include a user-defined header, whereby compilation options
42 ** may be set prior to where they take effect, but after platform setup.
43 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
44 ** file. Note that this macro has a like effect on sqlite3.c compilation.
45 */
46 # define SHELL_STRINGIFY_(f) #f
47 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
48 #ifdef SQLITE_CUSTOM_INCLUDE
49 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
50 #endif
51 
52 /*
53 ** Determine if we are dealing with WinRT, which provides only a subset of
54 ** the full Win32 API.
55 */
56 #if !defined(SQLITE_OS_WINRT)
57 # define SQLITE_OS_WINRT 0
58 #endif
59 
60 /*
61 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
62 ** somewhat for use as a WASM module in a web browser. This flag
63 ** should only be used when building the "fiddle" web application, as
64 ** the browser-mode build has much different user input requirements
65 ** and this build mode rewires the user input subsystem to account for
66 ** that.
67 */
68 
69 /*
70 ** Warning pragmas copied from msvc.h in the core.
71 */
72 #if defined(_MSC_VER)
73 #pragma warning(disable : 4054)
74 #pragma warning(disable : 4055)
75 #pragma warning(disable : 4100)
76 #pragma warning(disable : 4127)
77 #pragma warning(disable : 4130)
78 #pragma warning(disable : 4152)
79 #pragma warning(disable : 4189)
80 #pragma warning(disable : 4206)
81 #pragma warning(disable : 4210)
82 #pragma warning(disable : 4232)
83 #pragma warning(disable : 4244)
84 #pragma warning(disable : 4305)
85 #pragma warning(disable : 4306)
86 #pragma warning(disable : 4702)
87 #pragma warning(disable : 4706)
88 #endif /* defined(_MSC_VER) */
89 
90 /*
91 ** No support for loadable extensions in VxWorks.
92 */
93 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
94 # define SQLITE_OMIT_LOAD_EXTENSION 1
95 #endif
96 
97 /*
98 ** Enable large-file support for fopen() and friends on unix.
99 */
100 #ifndef SQLITE_DISABLE_LFS
101 # define _LARGE_FILE       1
102 # ifndef _FILE_OFFSET_BITS
103 #   define _FILE_OFFSET_BITS 64
104 # endif
105 # define _LARGEFILE_SOURCE 1
106 #endif
107 
108 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
109 /*
110 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
111 ** to expose strdup().
112 */
113 # define _POSIX_SOURCE
114 #endif
115 
116 #include <stdlib.h>
117 #include <string.h>
118 #include <stdio.h>
119 #include <assert.h>
120 #include <math.h>
121 #include "sqlite3.h"
122 typedef sqlite3_int64 i64;
123 typedef sqlite3_uint64 u64;
124 typedef unsigned char u8;
125 #if SQLITE_USER_AUTHENTICATION
126 # include "sqlite3userauth.h"
127 #endif
128 #include <ctype.h>
129 #include <stdarg.h>
130 
131 #if !defined(_WIN32) && !defined(WIN32)
132 # include <signal.h>
133 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
134 #  include <pwd.h>
135 # endif
136 #endif
137 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
138 # include <unistd.h>
139 # include <dirent.h>
140 # define GETPID getpid
141 # if defined(__MINGW32__)
142 #  define DIRENT dirent
143 #  ifndef S_ISLNK
144 #   define S_ISLNK(mode) (0)
145 #  endif
146 # endif
147 #else
148 # define GETPID (int)GetCurrentProcessId
149 #endif
150 #include <sys/types.h>
151 #include <sys/stat.h>
152 
153 #if HAVE_READLINE
154 # include <readline/readline.h>
155 # include <readline/history.h>
156 #endif
157 
158 #if HAVE_EDITLINE
159 # include <editline/readline.h>
160 #endif
161 
162 #if HAVE_EDITLINE || HAVE_READLINE
163 
164 # define shell_add_history(X) add_history(X)
165 # define shell_read_history(X) read_history(X)
166 # define shell_write_history(X) write_history(X)
167 # define shell_stifle_history(X) stifle_history(X)
168 # define shell_readline(X) readline(X)
169 
170 #elif HAVE_LINENOISE
171 
172 # include "linenoise.h"
173 # define shell_add_history(X) linenoiseHistoryAdd(X)
174 # define shell_read_history(X) linenoiseHistoryLoad(X)
175 # define shell_write_history(X) linenoiseHistorySave(X)
176 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
177 # define shell_readline(X) linenoise(X)
178 
179 #else
180 
181 # define shell_read_history(X)
182 # define shell_write_history(X)
183 # define shell_stifle_history(X)
184 
185 # define SHELL_USE_LOCAL_GETLINE 1
186 #endif
187 
188 #ifndef deliberate_fall_through
189 /* Quiet some compilers about some of our intentional code. */
190 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
191 #  define deliberate_fall_through __attribute__((fallthrough));
192 # else
193 #  define deliberate_fall_through
194 # endif
195 #endif
196 
197 #if defined(_WIN32) || defined(WIN32)
198 # if SQLITE_OS_WINRT
199 #  define SQLITE_OMIT_POPEN 1
200 # else
201 #  include <io.h>
202 #  include <fcntl.h>
203 #  define isatty(h) _isatty(h)
204 #  ifndef access
205 #   define access(f,m) _access((f),(m))
206 #  endif
207 #  ifndef unlink
208 #   define unlink _unlink
209 #  endif
210 #  ifndef strdup
211 #   define strdup _strdup
212 #  endif
213 #  undef popen
214 #  define popen _popen
215 #  undef pclose
216 #  define pclose _pclose
217 # endif
218 #else
219  /* Make sure isatty() has a prototype. */
220  extern int isatty(int);
221 
222 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
223   /* popen and pclose are not C89 functions and so are
224   ** sometimes omitted from the <stdio.h> header */
225    extern FILE *popen(const char*,const char*);
226    extern int pclose(FILE*);
227 # else
228 #  define SQLITE_OMIT_POPEN 1
229 # endif
230 #endif
231 
232 #if defined(_WIN32_WCE)
233 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
234  * thus we always assume that we have a console. That can be
235  * overridden with the -batch command line option.
236  */
237 #define isatty(x) 1
238 #endif
239 
240 /* ctype macros that work with signed characters */
241 #define IsSpace(X)  isspace((unsigned char)X)
242 #define IsDigit(X)  isdigit((unsigned char)X)
243 #define ToLower(X)  (char)tolower((unsigned char)X)
244 
245 #if defined(_WIN32) || defined(WIN32)
246 #if SQLITE_OS_WINRT
247 #include <intrin.h>
248 #endif
249 #undef WIN32_LEAN_AND_MEAN
250 #define WIN32_LEAN_AND_MEAN
251 #include <windows.h>
252 
253 /* string conversion routines only needed on Win32 */
254 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
255 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
256 #endif
257 
258 /* Use console I/O package as a direct INCLUDE. */
259 #define SQLITE_INTERNAL_LINKAGE static
260 
261 #ifdef SQLITE_SHELL_FIDDLE
262 /* Deselect most features from the console I/O package for Fiddle. */
263 # define SQLITE_CIO_NO_REDIRECT
264 # define SQLITE_CIO_NO_CLASSIFY
265 # define SQLITE_CIO_NO_TRANSLATE
266 # define SQLITE_CIO_NO_SETMODE
267 #endif
268 /************************* Begin ../ext/consio/console_io.h ******************/
269 /*
270 ** 2023 November 1
271 **
272 ** The author disclaims copyright to this source code.  In place of
273 ** a legal notice, here is a blessing:
274 **
275 **    May you do good and not evil.
276 **    May you find forgiveness for yourself and forgive others.
277 **    May you share freely, never taking more than you give.
278 **
279 ********************************************************************************
280 ** This file exposes various interfaces used for console and other I/O
281 ** by the SQLite project command-line tools. These interfaces are used
282 ** at either source conglomeration time, compilation time, or run time.
283 ** This source provides for either inclusion into conglomerated,
284 ** "single-source" forms or separate compilation then linking.
285 **
286 ** Platform dependencies are "hidden" here by various stratagems so
287 ** that, provided certain conditions are met, the programs using this
288 ** source or object code compiled from it need no explicit conditional
289 ** compilation in their source for their console and stream I/O.
290 **
291 ** The symbols and functionality exposed here are not a public API.
292 ** This code may change in tandem with other project code as needed.
293 **
294 ** When this .h file and its companion .c are directly incorporated into
295 ** a source conglomeration (such as shell.c), the preprocessor symbol
296 ** CIO_WIN_WC_XLATE is defined as 0 or 1, reflecting whether console I/O
297 ** translation for Windows is effected for the build.
298 */
299 #define HAVE_CONSOLE_IO_H 1
300 #ifndef SQLITE_INTERNAL_LINKAGE
301 # define SQLITE_INTERNAL_LINKAGE extern /* external to translation unit */
302 # include <stdio.h>
303 #else
304 # define SHELL_NO_SYSINC /* Better yet, modify mkshellc.tcl for this. */
305 #endif
306 
307 #ifndef SQLITE3_H
308 /* # include "sqlite3.h" */
309 #endif
310 
311 #ifndef SQLITE_CIO_NO_CLASSIFY
312 
313 /* Define enum for use with following function. */
314 typedef enum StreamsAreConsole {
315   SAC_NoConsole = 0,
316   SAC_InConsole = 1, SAC_OutConsole = 2, SAC_ErrConsole = 4,
317   SAC_AnyConsole = 0x7
318 } StreamsAreConsole;
319 
320 /*
321 ** Classify the three standard I/O streams according to whether
322 ** they are connected to a console attached to the process.
323 **
324 ** Returns the bit-wise OR of SAC_{In,Out,Err}Console values,
325 ** or SAC_NoConsole if none of the streams reaches a console.
326 **
327 ** This function should be called before any I/O is done with
328 ** the given streams. As a side-effect, the given inputs are
329 ** recorded so that later I/O operations on them may be done
330 ** differently than the C library FILE* I/O would be done,
331 ** iff the stream is used for the I/O functions that follow,
332 ** and to support the ones that use an implicit stream.
333 **
334 ** On some platforms, stream or console mode alteration (aka
335 ** "Setup") may be made which is undone by consoleRestore().
336 */
337 SQLITE_INTERNAL_LINKAGE StreamsAreConsole
338 consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr );
339 /* A usual call for convenience: */
340 #define SQLITE_STD_CONSOLE_INIT() consoleClassifySetup(stdin,stdout,stderr)
341 
342 /*
343 ** After an initial call to consoleClassifySetup(...), renew
344 ** the same setup it effected. (A call not after is an error.)
345 ** This will restore state altered by consoleRestore();
346 **
347 ** Applications which run an inferior (child) process which
348 ** inherits the same I/O streams may call this function after
349 ** such a process exits to guard against console mode changes.
350 */
351 SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void);
352 
353 /*
354 ** Undo any side-effects left by consoleClassifySetup(...).
355 **
356 ** This should be called after consoleClassifySetup() and
357 ** before the process terminates normally. It is suitable
358 ** for use with the atexit() C library procedure. After
359 ** this call, no console I/O should be done until one of
360 ** console{Classify or Renew}Setup(...) is called again.
361 **
362 ** Applications which run an inferior (child) process that
363 ** inherits the same I/O streams might call this procedure
364 ** before so that said process will have a console setup
365 ** however users have configured it or come to expect.
366 */
367 SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void );
368 
369 #else /* defined(SQLITE_CIO_NO_CLASSIFY) */
370 # define consoleClassifySetup(i,o,e)
371 # define consoleRenewSetup()
372 # define consoleRestore()
373 #endif /* defined(SQLITE_CIO_NO_CLASSIFY) */
374 
375 #ifndef SQLITE_CIO_NO_REDIRECT
376 /*
377 ** Set stream to be used for the functions below which write
378 ** to "the designated X stream", where X is Output or Error.
379 ** Returns the previous value.
380 **
381 ** Alternatively, pass the special value, invalidFileStream,
382 ** to get the designated stream value without setting it.
383 **
384 ** Before the designated streams are set, they default to
385 ** those passed to consoleClassifySetup(...), and before
386 ** that is called they default to stdout and stderr.
387 **
388 ** It is error to close a stream so designated, then, without
389 ** designating another, use the corresponding {o,e}Emit(...).
390 */
391 SQLITE_INTERNAL_LINKAGE FILE *invalidFileStream;
392 SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf);
393 # ifdef CONSIO_SET_ERROR_STREAM
394 SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf);
395 # endif
396 #else
397 # define setOutputStream(pf)
398 # define setErrorStream(pf)
399 #endif /* !defined(SQLITE_CIO_NO_REDIRECT) */
400 
401 #ifndef SQLITE_CIO_NO_TRANSLATE
402 /*
403 ** Emit output like fprintf(). If the output is going to the
404 ** console and translation from UTF-8 is necessary, perform
405 ** the needed translation. Otherwise, write formatted output
406 ** to the provided stream almost as-is, possibly with newline
407 ** translation as specified by set{Binary,Text}Mode().
408 */
409 SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...);
410 /* Like fPrintfUtf8 except stream is always the designated output. */
411 SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...);
412 /* Like fPrintfUtf8 except stream is always the designated error. */
413 SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...);
414 
415 /*
416 ** Emit output like fputs(). If the output is going to the
417 ** console and translation from UTF-8 is necessary, perform
418 ** the needed translation. Otherwise, write given text to the
419 ** provided stream almost as-is, possibly with newline
420 ** translation as specified by set{Binary,Text}Mode().
421 */
422 SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO);
423 /* Like fPutsUtf8 except stream is always the designated output. */
424 SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z);
425 /* Like fPutsUtf8 except stream is always the designated error. */
426 SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z);
427 
428 /*
429 ** Emit output like fPutsUtf8(), except that the length of the
430 ** accepted char or character sequence is limited by nAccept.
431 **
432 ** Returns the number of accepted char values.
433 */
434 #ifdef CONSIO_SPUTB
435 SQLITE_INTERNAL_LINKAGE int
436 fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
437 /* Like fPutbUtf8 except stream is always the designated output. */
438 #endif
439 SQLITE_INTERNAL_LINKAGE int
440 oPutbUtf8(const char *cBuf, int nAccept);
441 /* Like fPutbUtf8 except stream is always the designated error. */
442 #ifdef CONSIO_EPUTB
443 SQLITE_INTERNAL_LINKAGE int
444 ePutbUtf8(const char *cBuf, int nAccept);
445 #endif
446 
447 /*
448 ** Collect input like fgets(...) with special provisions for input
449 ** from the console on platforms that require same. Defers to the
450 ** C library fgets() when input is not from the console. Newline
451 ** translation may be done as set by set{Binary,Text}Mode(). As a
452 ** convenience, pfIn==NULL is treated as stdin.
453 */
454 SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn);
455 /* Like fGetsUtf8 except stream is always the designated input. */
456 /* SQLITE_INTERNAL_LINKAGE char* iGetsUtf8(char *cBuf, int ncMax); */
457 
458 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
459 
460 #ifndef SQLITE_CIO_NO_SETMODE
461 /*
462 ** Set given stream for binary mode, where newline translation is
463 ** not done, or for text mode where, for some platforms, newlines
464 ** are translated to the platform's conventional char sequence.
465 ** If bFlush true, flush the stream.
466 **
467 ** An additional side-effect is that if the stream is one passed
468 ** to consoleClassifySetup() as an output, it is flushed first.
469 **
470 ** Note that binary/text mode has no effect on console I/O
471 ** translation. On all platforms, newline to the console starts
472 ** a new line and CR,LF chars from the console become a newline.
473 */
474 SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *, short bFlush);
475 SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *, short bFlush);
476 #endif
477 
478 #ifdef SQLITE_CIO_PROMPTED_IN
479 typedef struct Prompts {
480   int numPrompts;
481   const char **azPrompts;
482 } Prompts;
483 
484 /*
485 ** Macros for use of a line editor.
486 **
487 ** The following macros define operations involving use of a
488 ** line-editing library or simple console interaction.
489 ** A "T" argument is a text (char *) buffer or filename.
490 ** A "N" argument is an integer.
491 **
492 ** SHELL_ADD_HISTORY(T) // Record text as line(s) of history.
493 ** SHELL_READ_HISTORY(T) // Read history from file named by T.
494 ** SHELL_WRITE_HISTORY(T) // Write history to file named by T.
495 ** SHELL_STIFLE_HISTORY(N) // Limit history to N entries.
496 **
497 ** A console program which does interactive console input is
498 ** expected to call:
499 ** SHELL_READ_HISTORY(T) before collecting such input;
500 ** SHELL_ADD_HISTORY(T) as record-worthy input is taken;
501 ** SHELL_STIFLE_HISTORY(N) after console input ceases; then
502 ** SHELL_WRITE_HISTORY(T) before the program exits.
503 */
504 
505 /*
506 ** Retrieve a single line of input text from an input stream.
507 **
508 ** If pfIn is the input stream passed to consoleClassifySetup(),
509 ** and azPrompt is not NULL, then a prompt is issued before the
510 ** line is collected, as selected by the isContinuation flag.
511 ** Array azPrompt[{0,1}] holds the {main,continuation} prompt.
512 **
513 ** If zBufPrior is not NULL then it is a buffer from a prior
514 ** call to this routine that can be reused, or will be freed.
515 **
516 ** The result is stored in space obtained from malloc() and
517 ** must either be freed by the caller or else passed back to
518 ** this function as zBufPrior for reuse.
519 **
520 ** This function may call upon services of a line-editing
521 ** library to interactively collect line edited input.
522 */
523 SQLITE_INTERNAL_LINKAGE char *
524 shellGetLine(FILE *pfIn, char *zBufPrior, int nLen,
525              short isContinuation, Prompts azPrompt);
526 #endif /* defined(SQLITE_CIO_PROMPTED_IN) */
527 /*
528 ** TBD: Define an interface for application(s) to generate
529 ** completion candidates for use by the line-editor.
530 **
531 ** This may be premature; the CLI is the only application
532 ** that does this. Yet, getting line-editing melded into
533 ** console I/O is desirable because a line-editing library
534 ** may have to establish console operating mode, possibly
535 ** in a way that interferes with the above functionality.
536 */
537 
538 #if !(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))
539 /* Skip over as much z[] input char sequence as is valid UTF-8,
540 ** limited per nAccept char's or whole characters and containing
541 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
542 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
543 ** Limit: nAccept>=0 => char count, nAccept<0 => character
544  */
545 SQLITE_INTERNAL_LINKAGE const char*
546 zSkipValidUtf8(const char *z, int nAccept, long ccm);
547 
548 #endif
549 
550 /************************* End ../ext/consio/console_io.h ********************/
551 /************************* Begin ../ext/consio/console_io.c ******************/
552 /*
553 ** 2023 November 4
554 **
555 ** The author disclaims copyright to this source code.  In place of
556 ** a legal notice, here is a blessing:
557 **
558 **    May you do good and not evil.
559 **    May you find forgiveness for yourself and forgive others.
560 **    May you share freely, never taking more than you give.
561 **
562 ********************************************************************************
563 ** This file implements various interfaces used for console and stream I/O
564 ** by the SQLite project command-line tools, as explained in console_io.h .
565 ** Functions prefixed by "SQLITE_INTERNAL_LINKAGE" behave as described there.
566 */
567 
568 #ifndef SQLITE_CDECL
569 # define SQLITE_CDECL
570 #endif
571 
572 #ifndef SHELL_NO_SYSINC
573 # include <stdarg.h>
574 # include <string.h>
575 # include <stdlib.h>
576 # include <limits.h>
577 # include <assert.h>
578 /* # include "sqlite3.h" */
579 #endif
580 #ifndef HAVE_CONSOLE_IO_H
581 # include "console_io.h"
582 #endif
583 #if defined(_MSC_VER)
584 # pragma warning(disable : 4204)
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
handleOfFile(FILE * pf)608 static HANDLE handleOfFile(FILE *pf){
609   int fileDesc = _fileno(pf);
610   union { intptr_t osfh; HANDLE fh; } fid = {
611     (fileDesc>=0)? _get_osfhandle(fileDesc) : (intptr_t)INVALID_HANDLE_VALUE
612   };
613   return fid.fh;
614 }
615 #endif
616 
617 #ifndef SQLITE_CIO_NO_TRANSLATE
618 typedef struct PerStreamTags {
619 # if CIO_WIN_WC_XLATE
620   HANDLE hx;
621   DWORD consMode;
622   char acIncomplete[4];
623 # else
624   short reachesConsole;
625 # endif
626   FILE *pf;
627 } PerStreamTags;
628 
629 /* Define NULL-like value for things which can validly be 0. */
630 # define SHELL_INVALID_FILE_PTR ((FILE *)~0)
631 # if CIO_WIN_WC_XLATE
632 #  define SHELL_INVALID_CONS_MODE 0xFFFF0000
633 # endif
634 
635 # if CIO_WIN_WC_XLATE
636 #  define PST_INITIALIZER { INVALID_HANDLE_VALUE, SHELL_INVALID_CONS_MODE, \
637       {0,0,0,0}, SHELL_INVALID_FILE_PTR }
638 # else
639 #  define PST_INITIALIZER { 0, SHELL_INVALID_FILE_PTR }
640 # endif
641 
642 /* Quickly say whether a known output is going to the console. */
643 # if CIO_WIN_WC_XLATE
pstReachesConsole(PerStreamTags * ppst)644 static short pstReachesConsole(PerStreamTags *ppst){
645   return (ppst->hx != INVALID_HANDLE_VALUE);
646 }
647 # else
648 #  define pstReachesConsole(ppst) 0
649 # endif
650 
651 # if CIO_WIN_WC_XLATE
restoreConsoleArb(PerStreamTags * ppst)652 static void restoreConsoleArb(PerStreamTags *ppst){
653   if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode);
654 }
655 # else
656 #  define restoreConsoleArb(ppst)
657 # endif
658 
659 /* Say whether FILE* appears to be a console, collect associated info. */
streamOfConsole(FILE * pf,PerStreamTags * ppst)660 static short streamOfConsole(FILE *pf, /* out */ PerStreamTags *ppst){
661 # if CIO_WIN_WC_XLATE
662   short rv = 0;
663   DWORD dwCM = SHELL_INVALID_CONS_MODE;
664   HANDLE fh = handleOfFile(pf);
665   ppst->pf = pf;
666   if( INVALID_HANDLE_VALUE != fh ){
667     rv = (GetFileType(fh) == FILE_TYPE_CHAR && GetConsoleMode(fh,&dwCM));
668   }
669   ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE;
670   ppst->consMode = dwCM;
671   return rv;
672 # else
673   ppst->pf = pf;
674   ppst->reachesConsole = ( (short)isatty(fileno(pf)) );
675   return ppst->reachesConsole;
676 # endif
677 }
678 
679 # ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
680 #  define ENABLE_VIRTUAL_TERMINAL_PROCESSING  (0x4)
681 # endif
682 
683 # if CIO_WIN_WC_XLATE
684 /* Define console modes for use with the Windows Console API. */
685 #  define SHELL_CONI_MODE \
686   (ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE | ENABLE_LINE_INPUT | 0x80 \
687   | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS | ENABLE_PROCESSED_INPUT)
688 #  define SHELL_CONO_MODE (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT \
689   | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
690 # endif
691 
692 typedef struct ConsoleInfo {
693   PerStreamTags pstSetup[3];
694   PerStreamTags pstDesignated[3];
695   StreamsAreConsole sacSetup;
696 } ConsoleInfo;
697 
isValidStreamInfo(PerStreamTags * ppst)698 static short isValidStreamInfo(PerStreamTags *ppst){
699   return (ppst->pf != SHELL_INVALID_FILE_PTR);
700 }
701 
702 static ConsoleInfo consoleInfo = {
703   { /* pstSetup */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
704   { /* pstDesignated[] */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
705   SAC_NoConsole /* sacSetup */
706 };
707 
708 SQLITE_INTERNAL_LINKAGE FILE* invalidFileStream = (FILE *)~0;
709 
710 # if CIO_WIN_WC_XLATE
maybeSetupAsConsole(PerStreamTags * ppst,short odir)711 static void maybeSetupAsConsole(PerStreamTags *ppst, short odir){
712   if( pstReachesConsole(ppst) ){
713     DWORD cm = odir? SHELL_CONO_MODE : SHELL_CONI_MODE;
714     SetConsoleMode(ppst->hx, cm);
715   }
716 }
717 # else
718 #  define maybeSetupAsConsole(ppst,odir)
719 # endif
720 
consoleRenewSetup(void)721 SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void){
722 # if CIO_WIN_WC_XLATE
723   int ix = 0;
724   while( ix < 6 ){
725     PerStreamTags *ppst = (ix<3)?
726       &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3];
727     maybeSetupAsConsole(ppst, (ix % 3)>0);
728     ++ix;
729   }
730 # endif
731 }
732 
733 SQLITE_INTERNAL_LINKAGE StreamsAreConsole
consoleClassifySetup(FILE * pfIn,FILE * pfOut,FILE * pfErr)734 consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr ){
735   StreamsAreConsole rv = SAC_NoConsole;
736   FILE* apf[3] = { pfIn, pfOut, pfErr };
737   int ix;
738   for( ix = 2; ix >= 0; --ix ){
739     PerStreamTags *ppst = &consoleInfo.pstSetup[ix];
740     if( streamOfConsole(apf[ix], ppst) ){
741       rv |= (SAC_InConsole<<ix);
742     }
743     consoleInfo.pstDesignated[ix] = *ppst;
744     if( ix > 0 ) fflush(apf[ix]);
745   }
746   consoleInfo.sacSetup = rv;
747   consoleRenewSetup();
748   return rv;
749 }
750 
consoleRestore(void)751 SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void ){
752 # if CIO_WIN_WC_XLATE
753   static ConsoleInfo *pci = &consoleInfo;
754   if( pci->sacSetup ){
755     int ix;
756     for( ix=0; ix<3; ++ix ){
757       if( pci->sacSetup & (SAC_InConsole<<ix) ){
758         PerStreamTags *ppst = &pci->pstSetup[ix];
759         SetConsoleMode(ppst->hx, ppst->consMode);
760       }
761     }
762   }
763 # endif
764 }
765 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
766 
767 #ifdef SQLITE_CIO_INPUT_REDIR
768 /* Say whether given FILE* is among those known, via either
769 ** consoleClassifySetup() or set{Output,Error}Stream, as
770 ** readable, and return an associated PerStreamTags pointer
771 ** if so. Otherwise, return 0.
772 */
isKnownReadable(FILE * pf)773 static PerStreamTags * isKnownReadable(FILE *pf){
774   static PerStreamTags *apst[] = {
775     &consoleInfo.pstDesignated[0], &consoleInfo.pstSetup[0], 0
776   };
777   int ix = 0;
778   do {
779     if( apst[ix]->pf == pf ) break;
780   } while( apst[++ix] != 0 );
781   return apst[ix];
782 }
783 #endif
784 
785 #ifndef SQLITE_CIO_NO_TRANSLATE
786 /* Say whether given FILE* is among those known, via either
787 ** consoleClassifySetup() or set{Output,Error}Stream, as
788 ** writable, and return an associated PerStreamTags pointer
789 ** if so. Otherwise, return 0.
790 */
isKnownWritable(FILE * pf)791 static PerStreamTags * isKnownWritable(FILE *pf){
792   static PerStreamTags *apst[] = {
793     &consoleInfo.pstDesignated[1], &consoleInfo.pstDesignated[2],
794     &consoleInfo.pstSetup[1], &consoleInfo.pstSetup[2], 0
795   };
796   int ix = 0;
797   do {
798     if( apst[ix]->pf == pf ) break;
799   } while( apst[++ix] != 0 );
800   return apst[ix];
801 }
802 
designateEmitStream(FILE * pf,unsigned chix)803 static FILE *designateEmitStream(FILE *pf, unsigned chix){
804   FILE *rv = consoleInfo.pstDesignated[chix].pf;
805   if( pf == invalidFileStream ) return rv;
806   else{
807     /* Setting a possibly new output stream. */
808     PerStreamTags *ppst = isKnownWritable(pf);
809     if( ppst != 0 ){
810       PerStreamTags pst = *ppst;
811       consoleInfo.pstDesignated[chix] = pst;
812     }else streamOfConsole(pf, &consoleInfo.pstDesignated[chix]);
813   }
814   return rv;
815 }
816 
setOutputStream(FILE * pf)817 SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf){
818   return designateEmitStream(pf, 1);
819 }
820 # ifdef CONSIO_SET_ERROR_STREAM
setErrorStream(FILE * pf)821 SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf){
822   return designateEmitStream(pf, 2);
823 }
824 # endif
825 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
826 
827 #ifndef SQLITE_CIO_NO_SETMODE
828 # if CIO_WIN_WC_XLATE
setModeFlushQ(FILE * pf,short bFlush,int mode)829 static void setModeFlushQ(FILE *pf, short bFlush, int mode){
830   if( bFlush ) fflush(pf);
831   _setmode(_fileno(pf), mode);
832 }
833 # else
834 #  define setModeFlushQ(f, b, m) if(b) fflush(f)
835 # endif
836 
setBinaryMode(FILE * pf,short bFlush)837 SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *pf, short bFlush){
838   setModeFlushQ(pf, bFlush, _O_BINARY);
839 }
setTextMode(FILE * pf,short bFlush)840 SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *pf, short bFlush){
841   setModeFlushQ(pf, bFlush, _O_TEXT);
842 }
843 # undef setModeFlushQ
844 
845 #else /* defined(SQLITE_CIO_NO_SETMODE) */
846 # define setBinaryMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
847 # define setTextMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
848 #endif /* defined(SQLITE_CIO_NO_SETMODE) */
849 
850 #ifndef SQLITE_CIO_NO_TRANSLATE
851 # if CIO_WIN_WC_XLATE
852 /* Write buffer cBuf as output to stream known to reach console,
853 ** limited to ncTake char's. Return ncTake on success, else 0. */
conZstrEmit(PerStreamTags * ppst,const char * z,int ncTake)854 static int conZstrEmit(PerStreamTags *ppst, const char *z, int ncTake){
855   int rv = 0;
856   if( z!=NULL ){
857     int nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, 0,0);
858     if( nwc > 0 ){
859       WCHAR *zw = sqlite3_malloc64(nwc*sizeof(WCHAR));
860       if( zw!=NULL ){
861         nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, zw,nwc);
862         if( nwc > 0 ){
863           /* Translation from UTF-8 to UTF-16, then WCHARs out. */
864           if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){
865             rv = ncTake;
866           }
867         }
868         sqlite3_free(zw);
869       }
870     }
871   }
872   return rv;
873 }
874 
875 /* For {f,o,e}PrintfUtf8() when stream is known to reach console. */
conioVmPrintf(PerStreamTags * ppst,const char * zFormat,va_list ap)876 static int conioVmPrintf(PerStreamTags *ppst, const char *zFormat, va_list ap){
877   char *z = sqlite3_vmprintf(zFormat, ap);
878   if( z ){
879     int rv = conZstrEmit(ppst, z, (int)strlen(z));
880     sqlite3_free(z);
881     return rv;
882   }else return 0;
883 }
884 # endif /* CIO_WIN_WC_XLATE */
885 
886 # ifdef CONSIO_GET_EMIT_STREAM
getDesignatedEmitStream(FILE * pf,unsigned chix,PerStreamTags * ppst)887 static PerStreamTags * getDesignatedEmitStream(FILE *pf, unsigned chix,
888                                                PerStreamTags *ppst){
889   PerStreamTags *rv = isKnownWritable(pf);
890   short isValid = (rv!=0)? isValidStreamInfo(rv) : 0;
891   if( rv != 0 && isValid ) return rv;
892   streamOfConsole(pf, ppst);
893   return ppst;
894 }
895 # endif
896 
897 /* Get stream info, either for designated output or error stream when
898 ** chix equals 1 or 2, or for an arbitrary stream when chix == 0.
899 ** In either case, ppst references a caller-owned PerStreamTags
900 ** struct which may be filled in if none of the known writable
901 ** streams is being held by consoleInfo. The ppf parameter is a
902 ** byref output when chix!=0 and a byref input when chix==0.
903  */
904 static PerStreamTags *
getEmitStreamInfo(unsigned chix,PerStreamTags * ppst,FILE ** ppf)905 getEmitStreamInfo(unsigned chix, PerStreamTags *ppst,
906                   /* in/out */ FILE **ppf){
907   PerStreamTags *ppstTry;
908   FILE *pfEmit;
909   if( chix > 0 ){
910     ppstTry = &consoleInfo.pstDesignated[chix];
911     if( !isValidStreamInfo(ppstTry) ){
912       ppstTry = &consoleInfo.pstSetup[chix];
913       pfEmit = ppst->pf;
914     }else pfEmit = ppstTry->pf;
915     if( !isValidStreamInfo(ppstTry) ){
916       pfEmit = (chix > 1)? stderr : stdout;
917       ppstTry = ppst;
918       streamOfConsole(pfEmit, ppstTry);
919     }
920     *ppf = pfEmit;
921   }else{
922     ppstTry = isKnownWritable(*ppf);
923     if( ppstTry != 0 ) return ppstTry;
924     streamOfConsole(*ppf, ppst);
925     return ppst;
926   }
927   return ppstTry;
928 }
929 
oPrintfUtf8(const char * zFormat,...)930 SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...){
931   va_list ap;
932   int rv;
933   FILE *pfOut;
934   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
935 # if CIO_WIN_WC_XLATE
936   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
937 # else
938   getEmitStreamInfo(1, &pst, &pfOut);
939 # endif
940   assert(zFormat!=0);
941   va_start(ap, zFormat);
942 # if CIO_WIN_WC_XLATE
943   if( pstReachesConsole(ppst) ){
944     rv = conioVmPrintf(ppst, zFormat, ap);
945   }else{
946 # endif
947     rv = vfprintf(pfOut, zFormat, ap);
948 # if CIO_WIN_WC_XLATE
949   }
950 # endif
951   va_end(ap);
952   return rv;
953 }
954 
ePrintfUtf8(const char * zFormat,...)955 SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...){
956   va_list ap;
957   int rv;
958   FILE *pfErr;
959   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
960 # if CIO_WIN_WC_XLATE
961   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
962 # else
963   getEmitStreamInfo(2, &pst, &pfErr);
964 # endif
965   assert(zFormat!=0);
966   va_start(ap, zFormat);
967 # if CIO_WIN_WC_XLATE
968   if( pstReachesConsole(ppst) ){
969     rv = conioVmPrintf(ppst, zFormat, ap);
970   }else{
971 # endif
972     rv = vfprintf(pfErr, zFormat, ap);
973 # if CIO_WIN_WC_XLATE
974   }
975 # endif
976   va_end(ap);
977   return rv;
978 }
979 
fPrintfUtf8(FILE * pfO,const char * zFormat,...)980 SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...){
981   va_list ap;
982   int rv;
983   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
984 # if CIO_WIN_WC_XLATE
985   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
986 # else
987   getEmitStreamInfo(0, &pst, &pfO);
988 # endif
989   assert(zFormat!=0);
990   va_start(ap, zFormat);
991 # if CIO_WIN_WC_XLATE
992   if( pstReachesConsole(ppst) ){
993     maybeSetupAsConsole(ppst, 1);
994     rv = conioVmPrintf(ppst, zFormat, ap);
995     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
996   }else{
997 # endif
998     rv = vfprintf(pfO, zFormat, ap);
999 # if CIO_WIN_WC_XLATE
1000   }
1001 # endif
1002   va_end(ap);
1003   return rv;
1004 }
1005 
fPutsUtf8(const char * z,FILE * pfO)1006 SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO){
1007   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1008 # if CIO_WIN_WC_XLATE
1009   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1010 # else
1011   getEmitStreamInfo(0, &pst, &pfO);
1012 # endif
1013   assert(z!=0);
1014 # if CIO_WIN_WC_XLATE
1015   if( pstReachesConsole(ppst) ){
1016     int rv;
1017     maybeSetupAsConsole(ppst, 1);
1018     rv = conZstrEmit(ppst, z, (int)strlen(z));
1019     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1020     return rv;
1021   }else {
1022 # endif
1023     return (fputs(z, pfO)<0)? 0 : (int)strlen(z);
1024 # if CIO_WIN_WC_XLATE
1025   }
1026 # endif
1027 }
1028 
ePutsUtf8(const char * z)1029 SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z){
1030   FILE *pfErr;
1031   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1032 # if CIO_WIN_WC_XLATE
1033   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1034 # else
1035   getEmitStreamInfo(2, &pst, &pfErr);
1036 # endif
1037   assert(z!=0);
1038 # if CIO_WIN_WC_XLATE
1039   if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1040   else {
1041 # endif
1042     return (fputs(z, pfErr)<0)? 0 : (int)strlen(z);
1043 # if CIO_WIN_WC_XLATE
1044   }
1045 # endif
1046 }
1047 
oPutsUtf8(const char * z)1048 SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z){
1049   FILE *pfOut;
1050   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1051 # if CIO_WIN_WC_XLATE
1052   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1053 # else
1054   getEmitStreamInfo(1, &pst, &pfOut);
1055 # endif
1056   assert(z!=0);
1057 # if CIO_WIN_WC_XLATE
1058   if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1059   else {
1060 # endif
1061     return (fputs(z, pfOut)<0)? 0 : (int)strlen(z);
1062 # if CIO_WIN_WC_XLATE
1063   }
1064 # endif
1065 }
1066 
1067 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1068 
1069 #if !(defined(SQLITE_CIO_NO_UTF8SCAN) && defined(SQLITE_CIO_NO_TRANSLATE))
1070 /* Skip over as much z[] input char sequence as is valid UTF-8,
1071 ** limited per nAccept char's or whole characters and containing
1072 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
1073 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
1074 ** Limit: nAccept>=0 => char count, nAccept<0 => character
1075  */
1076 SQLITE_INTERNAL_LINKAGE const char*
zSkipValidUtf8(const char * z,int nAccept,long ccm)1077 zSkipValidUtf8(const char *z, int nAccept, long ccm){
1078   int ng = (nAccept<0)? -nAccept : 0;
1079   const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
1080   assert(z!=0);
1081   while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
1082     char c = *z;
1083     if( (c & 0x80) == 0 ){
1084       if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
1085       ++z; /* ASCII */
1086     }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
1087     else{
1088       const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
1089       do{
1090         if( pcLimit && zt >= pcLimit ) return z;
1091         else{
1092           char ct = *zt++;
1093           if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
1094             /* Trailing bytes are too few, too many, or invalid. */
1095             return z;
1096           }
1097         }
1098       } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
1099       z = zt;
1100     }
1101   }
1102   return z;
1103 }
1104 #endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
1105 
1106 #ifndef SQLITE_CIO_NO_TRANSLATE
1107 # ifdef CONSIO_SPUTB
1108 SQLITE_INTERNAL_LINKAGE int
fPutbUtf8(FILE * pfO,const char * cBuf,int nAccept)1109 fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
1110   assert(pfO!=0);
1111 #  if CIO_WIN_WC_XLATE
1112   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1113   PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1114   if( pstReachesConsole(ppst) ){
1115     int rv;
1116     maybeSetupAsConsole(ppst, 1);
1117     rv = conZstrEmit(ppst, cBuf, nAccept);
1118     if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1119     return rv;
1120   }else {
1121 #  endif
1122     return (int)fwrite(cBuf, 1, nAccept, pfO);
1123 #  if CIO_WIN_WC_XLATE
1124   }
1125 #  endif
1126 }
1127 # endif
1128 
1129 SQLITE_INTERNAL_LINKAGE int
oPutbUtf8(const char * cBuf,int nAccept)1130 oPutbUtf8(const char *cBuf, int nAccept){
1131   FILE *pfOut;
1132   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1133 # if CIO_WIN_WC_XLATE
1134   PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1135 # else
1136   getEmitStreamInfo(1, &pst, &pfOut);
1137 # endif
1138 # if CIO_WIN_WC_XLATE
1139   if( pstReachesConsole(ppst) ){
1140     return conZstrEmit(ppst, cBuf, nAccept);
1141   }else {
1142 # endif
1143     return (int)fwrite(cBuf, 1, nAccept, pfOut);
1144 # if CIO_WIN_WC_XLATE
1145   }
1146 # endif
1147 }
1148 
1149 # ifdef CONSIO_EPUTB
1150 SQLITE_INTERNAL_LINKAGE int
ePutbUtf8(const char * cBuf,int nAccept)1151 ePutbUtf8(const char *cBuf, int nAccept){
1152   FILE *pfErr;
1153   PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1154   PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1155 #  if CIO_WIN_WC_XLATE
1156   if( pstReachesConsole(ppst) ){
1157     return conZstrEmit(ppst, cBuf, nAccept);
1158   }else {
1159 #  endif
1160     return (int)fwrite(cBuf, 1, nAccept, pfErr);
1161 #  if CIO_WIN_WC_XLATE
1162   }
1163 #  endif
1164 }
1165 # endif /* defined(CONSIO_EPUTB) */
1166 
fGetsUtf8(char * cBuf,int ncMax,FILE * pfIn)1167 SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn){
1168   if( pfIn==0 ) pfIn = stdin;
1169 # if CIO_WIN_WC_XLATE
1170   if( pfIn == consoleInfo.pstSetup[0].pf
1171       && (consoleInfo.sacSetup & SAC_InConsole)!=0 ){
1172 #  if CIO_WIN_WC_XLATE==1
1173 #   define SHELL_GULP 150 /* Count of WCHARS to be gulped at a time */
1174     WCHAR wcBuf[SHELL_GULP+1];
1175     int lend = 0, noc = 0;
1176     if( ncMax > 0 ) cBuf[0] = 0;
1177     while( noc < ncMax-8-1 && !lend ){
1178       /* There is room for at least 2 more characters and a 0-terminator. */
1179       int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4;
1180 #   undef SHELL_GULP
1181       DWORD nbr = 0;
1182       BOOL bRC = ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf, na, &nbr, 0);
1183       if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){
1184         /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */
1185         DWORD nbrx;
1186         bRC &= ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf+nbr, 1, &nbrx, 0);
1187         if( bRC ) nbr += nbrx;
1188       }
1189       if( !bRC || (noc==0 && nbr==0) ) return 0;
1190       if( nbr > 0 ){
1191         int nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,0,0,0,0);
1192         if( nmb != 0 && noc+nmb <= ncMax ){
1193           int iseg = noc;
1194           nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,cBuf+noc,nmb,0,0);
1195           noc += nmb;
1196           /* Fixup line-ends as coded by Windows for CR (or "Enter".)
1197           ** This is done without regard for any setMode{Text,Binary}()
1198           ** call that might have been done on the interactive input.
1199           */
1200           if( noc > 0 ){
1201             if( cBuf[noc-1]=='\n' ){
1202               lend = 1;
1203               if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n';
1204             }
1205           }
1206           /* Check for ^Z (anywhere in line) too, to act as EOF. */
1207           while( iseg < noc ){
1208             if( cBuf[iseg]=='\x1a' ){
1209               noc = iseg; /* Chop ^Z and anything following. */
1210               lend = 1; /* Counts as end of line too. */
1211               break;
1212             }
1213             ++iseg;
1214           }
1215         }else break; /* Drop apparent garbage in. (Could assert.) */
1216       }else break;
1217     }
1218     /* If got nothing, (after ^Z chop), must be at end-of-file. */
1219     if( noc > 0 ){
1220       cBuf[noc] = 0;
1221       return cBuf;
1222     }else return 0;
1223 #  endif
1224   }else{
1225 # endif
1226     return fgets(cBuf, ncMax, pfIn);
1227 # if CIO_WIN_WC_XLATE
1228   }
1229 # endif
1230 }
1231 #endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1232 
1233 #if defined(_MSC_VER)
1234 # pragma warning(default : 4204)
1235 #endif
1236 
1237 #undef SHELL_INVALID_FILE_PTR
1238 
1239 /************************* End ../ext/consio/console_io.c ********************/
1240 
1241 #ifndef SQLITE_SHELL_FIDDLE
1242 
1243 /* From here onward, fgets() is redirected to the console_io library. */
1244 # define fgets(b,n,f) fGetsUtf8(b,n,f)
1245 /*
1246  * Define macros for emitting output text in various ways:
1247  *  sputz(s, z)      => emit 0-terminated string z to given stream s
1248  *  sputf(s, f, ...) => emit varargs per format f to given stream s
1249  *  oputz(z)         => emit 0-terminated string z to default stream
1250  *  oputf(f, ...)    => emit varargs per format f to default stream
1251  *  eputz(z)         => emit 0-terminated string z to error stream
1252  *  eputf(f, ...)    => emit varargs per format f to error stream
1253  *  oputb(b, n)      => emit char buffer b[0..n-1] to default stream
1254  *
1255  * Note that the default stream is whatever has been last set via:
1256  *   setOutputStream(FILE *pf)
1257  * This is normally the stream that CLI normal output goes to.
1258  * For the stand-alone CLI, it is stdout with no .output redirect.
1259  *
1260  * The ?putz(z) forms are required for the Fiddle builds for string literal
1261  * output, in aid of enforcing format string to argument correspondence.
1262  */
1263 # define sputz(s,z) fPutsUtf8(z,s)
1264 # define sputf fPrintfUtf8
1265 # define oputz(z) oPutsUtf8(z)
1266 # define oputf oPrintfUtf8
1267 # define eputz(z) ePutsUtf8(z)
1268 # define eputf ePrintfUtf8
1269 # define oputb(buf,na) oPutbUtf8(buf,na)
1270 
1271 #else
1272 /* For Fiddle, all console handling and emit redirection is omitted. */
1273 /* These next 3 macros are for emitting formatted output. When complaints
1274  * from the WASM build are issued for non-formatted output, (when a mere
1275  * string literal is to be emitted, the ?putz(z) forms should be used.
1276  * (This permits compile-time checking of format string / argument mismatch.)
1277  */
1278 # define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
1279 # define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
1280 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
1281 /* These next 3 macros are for emitting simple string literals. */
1282 # define oputz(z) fputs(z,stdout)
1283 # define eputz(z) fputs(z,stderr)
1284 # define sputz(fp,z) fputs(z,fp)
1285 # define oputb(buf,na) fwrite(buf,1,na,stdout)
1286 #endif
1287 
1288 /* True if the timer is enabled */
1289 static int enableTimer = 0;
1290 
1291 /* A version of strcmp() that works with NULL values */
cli_strcmp(const char * a,const char * b)1292 static int cli_strcmp(const char *a, const char *b){
1293   if( a==0 ) a = "";
1294   if( b==0 ) b = "";
1295   return strcmp(a,b);
1296 }
cli_strncmp(const char * a,const char * b,size_t n)1297 static int cli_strncmp(const char *a, const char *b, size_t n){
1298   if( a==0 ) a = "";
1299   if( b==0 ) b = "";
1300   return strncmp(a,b,n);
1301 }
1302 
1303 /* Return the current wall-clock time */
timeOfDay(void)1304 static sqlite3_int64 timeOfDay(void){
1305   static sqlite3_vfs *clockVfs = 0;
1306   sqlite3_int64 t;
1307   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
1308   if( clockVfs==0 ) return 0;  /* Never actually happens */
1309   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
1310     clockVfs->xCurrentTimeInt64(clockVfs, &t);
1311   }else{
1312     double r;
1313     clockVfs->xCurrentTime(clockVfs, &r);
1314     t = (sqlite3_int64)(r*86400000.0);
1315   }
1316   return t;
1317 }
1318 
1319 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
1320 #include <sys/time.h>
1321 #include <sys/resource.h>
1322 
1323 /* VxWorks does not support getrusage() as far as we can determine */
1324 #if defined(_WRS_KERNEL) || defined(__RTP__)
1325 struct rusage {
1326   struct timeval ru_utime; /* user CPU time used */
1327   struct timeval ru_stime; /* system CPU time used */
1328 };
1329 #define getrusage(A,B) memset(B,0,sizeof(*B))
1330 #endif
1331 
1332 /* Saved resource information for the beginning of an operation */
1333 static struct rusage sBegin;  /* CPU time at start */
1334 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
1335 
1336 /*
1337 ** Begin timing an operation
1338 */
beginTimer(void)1339 static void beginTimer(void){
1340   if( enableTimer ){
1341     getrusage(RUSAGE_SELF, &sBegin);
1342     iBegin = timeOfDay();
1343   }
1344 }
1345 
1346 /* Return the difference of two time_structs in seconds */
timeDiff(struct timeval * pStart,struct timeval * pEnd)1347 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
1348   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
1349          (double)(pEnd->tv_sec - pStart->tv_sec);
1350 }
1351 
1352 /*
1353 ** Print the timing results.
1354 */
endTimer(void)1355 static void endTimer(void){
1356   if( enableTimer ){
1357     sqlite3_int64 iEnd = timeOfDay();
1358     struct rusage sEnd;
1359     getrusage(RUSAGE_SELF, &sEnd);
1360     sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1361           (iEnd - iBegin)*0.001,
1362           timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
1363           timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
1364   }
1365 }
1366 
1367 #define BEGIN_TIMER beginTimer()
1368 #define END_TIMER endTimer()
1369 #define HAS_TIMER 1
1370 
1371 #elif (defined(_WIN32) || defined(WIN32))
1372 
1373 /* Saved resource information for the beginning of an operation */
1374 static HANDLE hProcess;
1375 static FILETIME ftKernelBegin;
1376 static FILETIME ftUserBegin;
1377 static sqlite3_int64 ftWallBegin;
1378 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
1379                                     LPFILETIME, LPFILETIME);
1380 static GETPROCTIMES getProcessTimesAddr = NULL;
1381 
1382 /*
1383 ** Check to see if we have timer support.  Return 1 if necessary
1384 ** support found (or found previously).
1385 */
hasTimer(void)1386 static int hasTimer(void){
1387   if( getProcessTimesAddr ){
1388     return 1;
1389   } else {
1390 #if !SQLITE_OS_WINRT
1391     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
1392     ** versions. See if the version we are running on has it, and if it
1393     ** does, save off a pointer to it and the current process handle.
1394     */
1395     hProcess = GetCurrentProcess();
1396     if( hProcess ){
1397       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
1398       if( NULL != hinstLib ){
1399         getProcessTimesAddr =
1400             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
1401         if( NULL != getProcessTimesAddr ){
1402           return 1;
1403         }
1404         FreeLibrary(hinstLib);
1405       }
1406     }
1407 #endif
1408   }
1409   return 0;
1410 }
1411 
1412 /*
1413 ** Begin timing an operation
1414 */
beginTimer(void)1415 static void beginTimer(void){
1416   if( enableTimer && getProcessTimesAddr ){
1417     FILETIME ftCreation, ftExit;
1418     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
1419                         &ftKernelBegin,&ftUserBegin);
1420     ftWallBegin = timeOfDay();
1421   }
1422 }
1423 
1424 /* Return the difference of two FILETIME structs in seconds */
timeDiff(FILETIME * pStart,FILETIME * pEnd)1425 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
1426   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
1427   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
1428   return (double) ((i64End - i64Start) / 10000000.0);
1429 }
1430 
1431 /*
1432 ** Print the timing results.
1433 */
endTimer(void)1434 static void endTimer(void){
1435   if( enableTimer && getProcessTimesAddr){
1436     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
1437     sqlite3_int64 ftWallEnd = timeOfDay();
1438     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1439     sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1440           (ftWallEnd - ftWallBegin)*0.001,
1441           timeDiff(&ftUserBegin, &ftUserEnd),
1442           timeDiff(&ftKernelBegin, &ftKernelEnd));
1443   }
1444 }
1445 
1446 #define BEGIN_TIMER beginTimer()
1447 #define END_TIMER endTimer()
1448 #define HAS_TIMER hasTimer()
1449 
1450 #else
1451 #define BEGIN_TIMER
1452 #define END_TIMER
1453 #define HAS_TIMER 0
1454 #endif
1455 
1456 /*
1457 ** Used to prevent warnings about unused parameters
1458 */
1459 #define UNUSED_PARAMETER(x) (void)(x)
1460 
1461 /*
1462 ** Number of elements in an array
1463 */
1464 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
1465 
1466 /*
1467 ** If the following flag is set, then command execution stops
1468 ** at an error if we are not interactive.
1469 */
1470 static int bail_on_error = 0;
1471 
1472 /*
1473 ** Treat stdin as an interactive input if the following variable
1474 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
1475 */
1476 static int stdin_is_interactive = 1;
1477 
1478 /*
1479 ** On Windows systems we need to know if standard output is a console
1480 ** in order to show that UTF-16 translation is done in the sign-on
1481 ** banner. The following variable is true if it is the console.
1482 */
1483 static int stdout_is_console = 1;
1484 
1485 /*
1486 ** The following is the open SQLite database.  We make a pointer
1487 ** to this database a static variable so that it can be accessed
1488 ** by the SIGINT handler to interrupt database processing.
1489 */
1490 static sqlite3 *globalDb = 0;
1491 
1492 /*
1493 ** True if an interrupt (Control-C) has been received.
1494 */
1495 static volatile int seenInterrupt = 0;
1496 
1497 /*
1498 ** This is the name of our program. It is set in main(), used
1499 ** in a number of other places, mostly for error messages.
1500 */
1501 static char *Argv0;
1502 
1503 /*
1504 ** Prompt strings. Initialized in main. Settable with
1505 **   .prompt main continue
1506 */
1507 #define PROMPT_LEN_MAX 20
1508 /* First line prompt.   default: "sqlite> " */
1509 static char mainPrompt[PROMPT_LEN_MAX];
1510 /* Continuation prompt. default: "   ...> " */
1511 static char continuePrompt[PROMPT_LEN_MAX];
1512 
1513 /* This is variant of the standard-library strncpy() routine with the
1514 ** one change that the destination string is always zero-terminated, even
1515 ** if there is no zero-terminator in the first n-1 characters of the source
1516 ** string.
1517 */
shell_strncpy(char * dest,const char * src,size_t n)1518 static char *shell_strncpy(char *dest, const char *src, size_t n){
1519   size_t i;
1520   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
1521   dest[i] = 0;
1522   return dest;
1523 }
1524 
1525 /*
1526 ** Optionally disable dynamic continuation prompt.
1527 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
1528 ** or open parentheses level if non-zero, or continuation prompt as set.
1529 ** This facility interacts with the scanner and process_input() where the
1530 ** below 5 macros are used.
1531 */
1532 #ifdef SQLITE_OMIT_DYNAPROMPT
1533 # define CONTINUATION_PROMPT continuePrompt
1534 # define CONTINUE_PROMPT_RESET
1535 # define CONTINUE_PROMPT_AWAITS(p,s)
1536 # define CONTINUE_PROMPT_AWAITC(p,c)
1537 # define CONTINUE_PAREN_INCR(p,n)
1538 # define CONTINUE_PROMPT_PSTATE 0
1539 typedef void *t_NoDynaPrompt;
1540 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
1541 #else
1542 # define CONTINUATION_PROMPT dynamicContinuePrompt()
1543 # define CONTINUE_PROMPT_RESET \
1544   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
1545 # define CONTINUE_PROMPT_AWAITS(p,s) \
1546   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
1547 # define CONTINUE_PROMPT_AWAITC(p,c) \
1548   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
1549 # define CONTINUE_PAREN_INCR(p,n) \
1550   if(p && stdin_is_interactive) (trackParenLevel(p,n))
1551 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
1552 typedef struct DynaPrompt *t_DynaPromptRef;
1553 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
1554 
1555 static struct DynaPrompt {
1556   char dynamicPrompt[PROMPT_LEN_MAX];
1557   char acAwait[2];
1558   int inParenLevel;
1559   char *zScannerAwaits;
1560 } dynPrompt = { {0}, {0}, 0, 0 };
1561 
1562 /* Record parenthesis nesting level change, or force level to 0. */
trackParenLevel(struct DynaPrompt * p,int ni)1563 static void trackParenLevel(struct DynaPrompt *p, int ni){
1564   p->inParenLevel += ni;
1565   if( ni==0 ) p->inParenLevel = 0;
1566   p->zScannerAwaits = 0;
1567 }
1568 
1569 /* Record that a lexeme is opened, or closed with args==0. */
setLexemeOpen(struct DynaPrompt * p,char * s,char c)1570 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
1571   if( s!=0 || c==0 ){
1572     p->zScannerAwaits = s;
1573     p->acAwait[0] = 0;
1574   }else{
1575     p->acAwait[0] = c;
1576     p->zScannerAwaits = p->acAwait;
1577   }
1578 }
1579 
1580 /* Upon demand, derive the continuation prompt to display. */
dynamicContinuePrompt(void)1581 static char *dynamicContinuePrompt(void){
1582   if( continuePrompt[0]==0
1583       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
1584     return continuePrompt;
1585   }else{
1586     if( dynPrompt.zScannerAwaits ){
1587       size_t ncp = strlen(continuePrompt);
1588       size_t ndp = strlen(dynPrompt.zScannerAwaits);
1589       if( ndp > ncp-3 ) return continuePrompt;
1590       strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
1591       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
1592       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1593               PROMPT_LEN_MAX-4);
1594     }else{
1595       if( dynPrompt.inParenLevel>9 ){
1596         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
1597       }else if( dynPrompt.inParenLevel<0 ){
1598         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
1599       }else{
1600         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
1601         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
1602       }
1603       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1604                     PROMPT_LEN_MAX-4);
1605     }
1606   }
1607   return dynPrompt.dynamicPrompt;
1608 }
1609 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
1610 
1611 /* Indicate out-of-memory and exit. */
shell_out_of_memory(void)1612 static void shell_out_of_memory(void){
1613   eputz("Error: out of memory\n");
1614   exit(1);
1615 }
1616 
1617 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
1618 ** out-of-memory error.
1619 */
shell_check_oom(const void * p)1620 static void shell_check_oom(const void *p){
1621   if( p==0 ) shell_out_of_memory();
1622 }
1623 
1624 /*
1625 ** Write I/O traces to the following stream.
1626 */
1627 #ifdef SQLITE_ENABLE_IOTRACE
1628 static FILE *iotrace = 0;
1629 #endif
1630 
1631 /*
1632 ** This routine works like printf in that its first argument is a
1633 ** format string and subsequent arguments are values to be substituted
1634 ** in place of % fields.  The result of formatting this string
1635 ** is written to iotrace.
1636 */
1637 #ifdef SQLITE_ENABLE_IOTRACE
iotracePrintf(const char * zFormat,...)1638 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
1639   va_list ap;
1640   char *z;
1641   if( iotrace==0 ) return;
1642   va_start(ap, zFormat);
1643   z = sqlite3_vmprintf(zFormat, ap);
1644   va_end(ap);
1645   sputf(iotrace, "%s", z);
1646   sqlite3_free(z);
1647 }
1648 #endif
1649 
1650 /*
1651 ** Output string zUtf to Out stream as w characters.  If w is negative,
1652 ** then right-justify the text.  W is the width in UTF-8 characters, not
1653 ** in bytes.  This is different from the %*.*s specification in printf
1654 ** since with %*.*s the width is measured in bytes, not characters.
1655 */
utf8_width_print(int w,const char * zUtf)1656 static void utf8_width_print(int w, const char *zUtf){
1657   int i;
1658   int n;
1659   int aw = w<0 ? -w : w;
1660   if( zUtf==0 ) zUtf = "";
1661   for(i=n=0; zUtf[i]; i++){
1662     if( (zUtf[i]&0xc0)!=0x80 ){
1663       n++;
1664       if( n==aw ){
1665         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
1666         break;
1667       }
1668     }
1669   }
1670   if( n>=aw ){
1671     oputf("%.*s", i, zUtf);
1672   }else if( w<0 ){
1673     oputf("%*s%s", aw-n, "", zUtf);
1674   }else{
1675     oputf("%s%*s", zUtf, aw-n, "");
1676   }
1677 }
1678 
1679 
1680 /*
1681 ** Determines if a string is a number of not.
1682 */
isNumber(const char * z,int * realnum)1683 static int isNumber(const char *z, int *realnum){
1684   if( *z=='-' || *z=='+' ) z++;
1685   if( !IsDigit(*z) ){
1686     return 0;
1687   }
1688   z++;
1689   if( realnum ) *realnum = 0;
1690   while( IsDigit(*z) ){ z++; }
1691   if( *z=='.' ){
1692     z++;
1693     if( !IsDigit(*z) ) return 0;
1694     while( IsDigit(*z) ){ z++; }
1695     if( realnum ) *realnum = 1;
1696   }
1697   if( *z=='e' || *z=='E' ){
1698     z++;
1699     if( *z=='+' || *z=='-' ) z++;
1700     if( !IsDigit(*z) ) return 0;
1701     while( IsDigit(*z) ){ z++; }
1702     if( realnum ) *realnum = 1;
1703   }
1704   return *z==0;
1705 }
1706 
1707 /*
1708 ** Compute a string length that is limited to what can be stored in
1709 ** lower 30 bits of a 32-bit signed integer.
1710 */
strlen30(const char * z)1711 static int strlen30(const char *z){
1712   const char *z2 = z;
1713   while( *z2 ){ z2++; }
1714   return 0x3fffffff & (int)(z2 - z);
1715 }
1716 
1717 /*
1718 ** Return the length of a string in characters.  Multibyte UTF8 characters
1719 ** count as a single character.
1720 */
strlenChar(const char * z)1721 static int strlenChar(const char *z){
1722   int n = 0;
1723   while( *z ){
1724     if( (0xc0&*(z++))!=0x80 ) n++;
1725   }
1726   return n;
1727 }
1728 
1729 /*
1730 ** Return open FILE * if zFile exists, can be opened for read
1731 ** and is an ordinary file or a character stream source.
1732 ** Otherwise return 0.
1733 */
openChrSource(const char * zFile)1734 static FILE * openChrSource(const char *zFile){
1735 #if defined(_WIN32) || defined(WIN32)
1736   struct __stat64 x = {0};
1737 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1738   /* On Windows, open first, then check the stream nature. This order
1739   ** is necessary because _stat() and sibs, when checking a named pipe,
1740   ** effectively break the pipe as its supplier sees it. */
1741   FILE *rv = fopen(zFile, "rb");
1742   if( rv==0 ) return 0;
1743   if( _fstat64(_fileno(rv), &x) != 0
1744       || !STAT_CHR_SRC(x.st_mode)){
1745     fclose(rv);
1746     rv = 0;
1747   }
1748   return rv;
1749 #else
1750   struct stat x = {0};
1751   int rc = stat(zFile, &x);
1752 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
1753   if( rc!=0 ) return 0;
1754   if( STAT_CHR_SRC(x.st_mode) ){
1755     return fopen(zFile, "rb");
1756   }else{
1757     return 0;
1758   }
1759 #endif
1760 #undef STAT_CHR_SRC
1761 }
1762 
1763 /*
1764 ** This routine reads a line of text from FILE in, stores
1765 ** the text in memory obtained from malloc() and returns a pointer
1766 ** to the text.  NULL is returned at end of file, or if malloc()
1767 ** fails.
1768 **
1769 ** If zLine is not NULL then it is a malloced buffer returned from
1770 ** a previous call to this routine that may be reused.
1771 */
local_getline(char * zLine,FILE * in)1772 static char *local_getline(char *zLine, FILE *in){
1773   int nLine = zLine==0 ? 0 : 100;
1774   int n = 0;
1775 
1776   while( 1 ){
1777     if( n+100>nLine ){
1778       nLine = nLine*2 + 100;
1779       zLine = realloc(zLine, nLine);
1780       shell_check_oom(zLine);
1781     }
1782     if( fgets(&zLine[n], nLine - n, in)==0 ){
1783       if( n==0 ){
1784         free(zLine);
1785         return 0;
1786       }
1787       zLine[n] = 0;
1788       break;
1789     }
1790     while( zLine[n] ) n++;
1791     if( n>0 && zLine[n-1]=='\n' ){
1792       n--;
1793       if( n>0 && zLine[n-1]=='\r' ) n--;
1794       zLine[n] = 0;
1795       break;
1796     }
1797   }
1798   return zLine;
1799 }
1800 
1801 /*
1802 ** Retrieve a single line of input text.
1803 **
1804 ** If in==0 then read from standard input and prompt before each line.
1805 ** If isContinuation is true, then a continuation prompt is appropriate.
1806 ** If isContinuation is zero, then the main prompt should be used.
1807 **
1808 ** If zPrior is not NULL then it is a buffer from a prior call to this
1809 ** routine that can be reused.
1810 **
1811 ** The result is stored in space obtained from malloc() and must either
1812 ** be freed by the caller or else passed back into this routine via the
1813 ** zPrior argument for reuse.
1814 */
1815 #ifndef SQLITE_SHELL_FIDDLE
one_input_line(FILE * in,char * zPrior,int isContinuation)1816 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1817   char *zPrompt;
1818   char *zResult;
1819   if( in!=0 ){
1820     zResult = local_getline(zPrior, in);
1821   }else{
1822     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1823 #if SHELL_USE_LOCAL_GETLINE
1824     sputz(stdout, zPrompt);
1825     fflush(stdout);
1826     do{
1827       zResult = local_getline(zPrior, stdin);
1828       zPrior = 0;
1829       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1830       if( zResult==0 ) sqlite3_sleep(50);
1831     }while( zResult==0 && seenInterrupt>0 );
1832 #else
1833     free(zPrior);
1834     zResult = shell_readline(zPrompt);
1835     while( zResult==0 ){
1836       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1837       sqlite3_sleep(50);
1838       if( seenInterrupt==0 ) break;
1839       zResult = shell_readline("");
1840     }
1841     if( zResult && *zResult ) shell_add_history(zResult);
1842 #endif
1843   }
1844   return zResult;
1845 }
1846 #endif /* !SQLITE_SHELL_FIDDLE */
1847 
1848 /*
1849 ** Return the value of a hexadecimal digit.  Return -1 if the input
1850 ** is not a hex digit.
1851 */
hexDigitValue(char c)1852 static int hexDigitValue(char c){
1853   if( c>='0' && c<='9' ) return c - '0';
1854   if( c>='a' && c<='f' ) return c - 'a' + 10;
1855   if( c>='A' && c<='F' ) return c - 'A' + 10;
1856   return -1;
1857 }
1858 
1859 /*
1860 ** Interpret zArg as an integer value, possibly with suffixes.
1861 */
integerValue(const char * zArg)1862 static sqlite3_int64 integerValue(const char *zArg){
1863   sqlite3_int64 v = 0;
1864   static const struct { char *zSuffix; int iMult; } aMult[] = {
1865     { "KiB", 1024 },
1866     { "MiB", 1024*1024 },
1867     { "GiB", 1024*1024*1024 },
1868     { "KB",  1000 },
1869     { "MB",  1000000 },
1870     { "GB",  1000000000 },
1871     { "K",   1000 },
1872     { "M",   1000000 },
1873     { "G",   1000000000 },
1874   };
1875   int i;
1876   int isNeg = 0;
1877   if( zArg[0]=='-' ){
1878     isNeg = 1;
1879     zArg++;
1880   }else if( zArg[0]=='+' ){
1881     zArg++;
1882   }
1883   if( zArg[0]=='0' && zArg[1]=='x' ){
1884     int x;
1885     zArg += 2;
1886     while( (x = hexDigitValue(zArg[0]))>=0 ){
1887       v = (v<<4) + x;
1888       zArg++;
1889     }
1890   }else{
1891     while( IsDigit(zArg[0]) ){
1892       v = v*10 + zArg[0] - '0';
1893       zArg++;
1894     }
1895   }
1896   for(i=0; i<ArraySize(aMult); i++){
1897     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1898       v *= aMult[i].iMult;
1899       break;
1900     }
1901   }
1902   return isNeg? -v : v;
1903 }
1904 
1905 /*
1906 ** A variable length string to which one can append text.
1907 */
1908 typedef struct ShellText ShellText;
1909 struct ShellText {
1910   char *z;
1911   int n;
1912   int nAlloc;
1913 };
1914 
1915 /*
1916 ** Initialize and destroy a ShellText object
1917 */
initText(ShellText * p)1918 static void initText(ShellText *p){
1919   memset(p, 0, sizeof(*p));
1920 }
freeText(ShellText * p)1921 static void freeText(ShellText *p){
1922   free(p->z);
1923   initText(p);
1924 }
1925 
1926 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1927 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1928 ** added to zIn, and the result returned in memory obtained from malloc().
1929 ** zIn, if it was not NULL, is freed.
1930 **
1931 ** If the third argument, quote, is not '\0', then it is used as a
1932 ** quote character for zAppend.
1933 */
appendText(ShellText * p,const char * zAppend,char quote)1934 static void appendText(ShellText *p, const char *zAppend, char quote){
1935   i64 len;
1936   i64 i;
1937   i64 nAppend = strlen30(zAppend);
1938 
1939   len = nAppend+p->n+1;
1940   if( quote ){
1941     len += 2;
1942     for(i=0; i<nAppend; i++){
1943       if( zAppend[i]==quote ) len++;
1944     }
1945   }
1946 
1947   if( p->z==0 || p->n+len>=p->nAlloc ){
1948     p->nAlloc = p->nAlloc*2 + len + 20;
1949     p->z = realloc(p->z, p->nAlloc);
1950     shell_check_oom(p->z);
1951   }
1952 
1953   if( quote ){
1954     char *zCsr = p->z+p->n;
1955     *zCsr++ = quote;
1956     for(i=0; i<nAppend; i++){
1957       *zCsr++ = zAppend[i];
1958       if( zAppend[i]==quote ) *zCsr++ = quote;
1959     }
1960     *zCsr++ = quote;
1961     p->n = (int)(zCsr - p->z);
1962     *zCsr = '\0';
1963   }else{
1964     memcpy(p->z+p->n, zAppend, nAppend);
1965     p->n += nAppend;
1966     p->z[p->n] = '\0';
1967   }
1968 }
1969 
1970 /*
1971 ** Attempt to determine if identifier zName needs to be quoted, either
1972 ** because it contains non-alphanumeric characters, or because it is an
1973 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1974 ** that quoting is required.
1975 **
1976 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1977 */
quoteChar(const char * zName)1978 static char quoteChar(const char *zName){
1979   int i;
1980   if( zName==0 ) return '"';
1981   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1982   for(i=0; zName[i]; i++){
1983     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1984   }
1985   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1986 }
1987 
1988 /*
1989 ** Construct a fake object name and column list to describe the structure
1990 ** of the view, virtual table, or table valued function zSchema.zName.
1991 */
shellFakeSchema(sqlite3 * db,const char * zSchema,const char * zName)1992 static char *shellFakeSchema(
1993   sqlite3 *db,            /* The database connection containing the vtab */
1994   const char *zSchema,    /* Schema of the database holding the vtab */
1995   const char *zName       /* The name of the virtual table */
1996 ){
1997   sqlite3_stmt *pStmt = 0;
1998   char *zSql;
1999   ShellText s;
2000   char cQuote;
2001   char *zDiv = "(";
2002   int nRow = 0;
2003 
2004   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
2005                          zSchema ? zSchema : "main", zName);
2006   shell_check_oom(zSql);
2007   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
2008   sqlite3_free(zSql);
2009   initText(&s);
2010   if( zSchema ){
2011     cQuote = quoteChar(zSchema);
2012     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
2013     appendText(&s, zSchema, cQuote);
2014     appendText(&s, ".", 0);
2015   }
2016   cQuote = quoteChar(zName);
2017   appendText(&s, zName, cQuote);
2018   while( sqlite3_step(pStmt)==SQLITE_ROW ){
2019     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
2020     nRow++;
2021     appendText(&s, zDiv, 0);
2022     zDiv = ",";
2023     if( zCol==0 ) zCol = "";
2024     cQuote = quoteChar(zCol);
2025     appendText(&s, zCol, cQuote);
2026   }
2027   appendText(&s, ")", 0);
2028   sqlite3_finalize(pStmt);
2029   if( nRow==0 ){
2030     freeText(&s);
2031     s.z = 0;
2032   }
2033   return s.z;
2034 }
2035 
2036 /*
2037 ** SQL function:  strtod(X)
2038 **
2039 ** Use the C-library strtod() function to convert string X into a double.
2040 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
2041 ** routines against the C-library.
2042 */
shellStrtod(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2043 static void shellStrtod(
2044   sqlite3_context *pCtx,
2045   int nVal,
2046   sqlite3_value **apVal
2047 ){
2048   char *z = (char*)sqlite3_value_text(apVal[0]);
2049   UNUSED_PARAMETER(nVal);
2050   if( z==0 ) return;
2051   sqlite3_result_double(pCtx, strtod(z,0));
2052 }
2053 
2054 /*
2055 ** SQL function:  dtostr(X)
2056 **
2057 ** Use the C-library printf() function to convert real value X into a string.
2058 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
2059 ** routines against the C-library.
2060 */
shellDtostr(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2061 static void shellDtostr(
2062   sqlite3_context *pCtx,
2063   int nVal,
2064   sqlite3_value **apVal
2065 ){
2066   double r = sqlite3_value_double(apVal[0]);
2067   int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
2068   char z[400];
2069   if( n<1 ) n = 1;
2070   if( n>350 ) n = 350;
2071   sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
2072   sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
2073 }
2074 
2075 
2076 /*
2077 ** SQL function:  shell_module_schema(X)
2078 **
2079 ** Return a fake schema for the table-valued function or eponymous virtual
2080 ** table X.
2081 */
shellModuleSchema(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2082 static void shellModuleSchema(
2083   sqlite3_context *pCtx,
2084   int nVal,
2085   sqlite3_value **apVal
2086 ){
2087   const char *zName;
2088   char *zFake;
2089   UNUSED_PARAMETER(nVal);
2090   zName = (const char*)sqlite3_value_text(apVal[0]);
2091   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
2092   if( zFake ){
2093     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
2094                         -1, sqlite3_free);
2095     free(zFake);
2096   }
2097 }
2098 
2099 /*
2100 ** SQL function:  shell_add_schema(S,X)
2101 **
2102 ** Add the schema name X to the CREATE statement in S and return the result.
2103 ** Examples:
2104 **
2105 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
2106 **
2107 ** Also works on
2108 **
2109 **    CREATE INDEX
2110 **    CREATE UNIQUE INDEX
2111 **    CREATE VIEW
2112 **    CREATE TRIGGER
2113 **    CREATE VIRTUAL TABLE
2114 **
2115 ** This UDF is used by the .schema command to insert the schema name of
2116 ** attached databases into the middle of the sqlite_schema.sql field.
2117 */
shellAddSchemaName(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)2118 static void shellAddSchemaName(
2119   sqlite3_context *pCtx,
2120   int nVal,
2121   sqlite3_value **apVal
2122 ){
2123   static const char *aPrefix[] = {
2124      "TABLE",
2125      "INDEX",
2126      "UNIQUE INDEX",
2127      "VIEW",
2128      "TRIGGER",
2129      "VIRTUAL TABLE"
2130   };
2131   int i = 0;
2132   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
2133   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
2134   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
2135   sqlite3 *db = sqlite3_context_db_handle(pCtx);
2136   UNUSED_PARAMETER(nVal);
2137   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
2138     for(i=0; i<ArraySize(aPrefix); i++){
2139       int n = strlen30(aPrefix[i]);
2140       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
2141         char *z = 0;
2142         char *zFake = 0;
2143         if( zSchema ){
2144           char cQuote = quoteChar(zSchema);
2145           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
2146             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
2147           }else{
2148             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
2149           }
2150         }
2151         if( zName
2152          && aPrefix[i][0]=='V'
2153          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
2154         ){
2155           if( z==0 ){
2156             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
2157           }else{
2158             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
2159           }
2160           free(zFake);
2161         }
2162         if( z ){
2163           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
2164           return;
2165         }
2166       }
2167     }
2168   }
2169   sqlite3_result_value(pCtx, apVal[0]);
2170 }
2171 
2172 /*
2173 ** The source code for several run-time loadable extensions is inserted
2174 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
2175 ** code, we need to override some macros to make the included program code
2176 ** work here in the middle of this regular program.
2177 */
2178 #define SQLITE_EXTENSION_INIT1
2179 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
2180 
2181 #if defined(_WIN32) && defined(_MSC_VER)
2182 /************************* Begin test_windirent.h ******************/
2183 /*
2184 ** 2015 November 30
2185 **
2186 ** The author disclaims copyright to this source code.  In place of
2187 ** a legal notice, here is a blessing:
2188 **
2189 **    May you do good and not evil.
2190 **    May you find forgiveness for yourself and forgive others.
2191 **    May you share freely, never taking more than you give.
2192 **
2193 *************************************************************************
2194 ** This file contains declarations for most of the opendir() family of
2195 ** POSIX functions on Win32 using the MSVCRT.
2196 */
2197 
2198 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
2199 #define SQLITE_WINDIRENT_H
2200 
2201 /*
2202 ** We need several data types from the Windows SDK header.
2203 */
2204 
2205 #ifndef WIN32_LEAN_AND_MEAN
2206 #define WIN32_LEAN_AND_MEAN
2207 #endif
2208 
2209 #include "windows.h"
2210 
2211 /*
2212 ** We need several support functions from the SQLite core.
2213 */
2214 
2215 /* #include "sqlite3.h" */
2216 
2217 /*
2218 ** We need several things from the ANSI and MSVCRT headers.
2219 */
2220 
2221 #include <stdio.h>
2222 #include <stdlib.h>
2223 #include <errno.h>
2224 #include <io.h>
2225 #include <limits.h>
2226 #include <sys/types.h>
2227 #include <sys/stat.h>
2228 
2229 /*
2230 ** We may need several defines that should have been in "sys/stat.h".
2231 */
2232 
2233 #ifndef S_ISREG
2234 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
2235 #endif
2236 
2237 #ifndef S_ISDIR
2238 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
2239 #endif
2240 
2241 #ifndef S_ISLNK
2242 #define S_ISLNK(mode) (0)
2243 #endif
2244 
2245 /*
2246 ** We may need to provide the "mode_t" type.
2247 */
2248 
2249 #ifndef MODE_T_DEFINED
2250   #define MODE_T_DEFINED
2251   typedef unsigned short mode_t;
2252 #endif
2253 
2254 /*
2255 ** We may need to provide the "ino_t" type.
2256 */
2257 
2258 #ifndef INO_T_DEFINED
2259   #define INO_T_DEFINED
2260   typedef unsigned short ino_t;
2261 #endif
2262 
2263 /*
2264 ** We need to define "NAME_MAX" if it was not present in "limits.h".
2265 */
2266 
2267 #ifndef NAME_MAX
2268 #  ifdef FILENAME_MAX
2269 #    define NAME_MAX (FILENAME_MAX)
2270 #  else
2271 #    define NAME_MAX (260)
2272 #  endif
2273 #endif
2274 
2275 /*
2276 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
2277 */
2278 
2279 #ifndef NULL_INTPTR_T
2280 #  define NULL_INTPTR_T ((intptr_t)(0))
2281 #endif
2282 
2283 #ifndef BAD_INTPTR_T
2284 #  define BAD_INTPTR_T ((intptr_t)(-1))
2285 #endif
2286 
2287 /*
2288 ** We need to provide the necessary structures and related types.
2289 */
2290 
2291 #ifndef DIRENT_DEFINED
2292 #define DIRENT_DEFINED
2293 typedef struct DIRENT DIRENT;
2294 typedef DIRENT *LPDIRENT;
2295 struct DIRENT {
2296   ino_t d_ino;               /* Sequence number, do not use. */
2297   unsigned d_attributes;     /* Win32 file attributes. */
2298   char d_name[NAME_MAX + 1]; /* Name within the directory. */
2299 };
2300 #endif
2301 
2302 #ifndef DIR_DEFINED
2303 #define DIR_DEFINED
2304 typedef struct DIR DIR;
2305 typedef DIR *LPDIR;
2306 struct DIR {
2307   intptr_t d_handle; /* Value returned by "_findfirst". */
2308   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
2309   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
2310 };
2311 #endif
2312 
2313 /*
2314 ** Provide a macro, for use by the implementation, to determine if a
2315 ** particular directory entry should be skipped over when searching for
2316 ** the next directory entry that should be returned by the readdir() or
2317 ** readdir_r() functions.
2318 */
2319 
2320 #ifndef is_filtered
2321 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
2322 #endif
2323 
2324 /*
2325 ** Provide the function prototype for the POSIX compatible getenv()
2326 ** function.  This function is not thread-safe.
2327 */
2328 
2329 extern const char *windirent_getenv(const char *name);
2330 
2331 /*
2332 ** Finally, we can provide the function prototypes for the opendir(),
2333 ** readdir(), readdir_r(), and closedir() POSIX functions.
2334 */
2335 
2336 extern LPDIR opendir(const char *dirname);
2337 extern LPDIRENT readdir(LPDIR dirp);
2338 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
2339 extern INT closedir(LPDIR dirp);
2340 
2341 #endif /* defined(WIN32) && defined(_MSC_VER) */
2342 
2343 /************************* End test_windirent.h ********************/
2344 /************************* Begin test_windirent.c ******************/
2345 /*
2346 ** 2015 November 30
2347 **
2348 ** The author disclaims copyright to this source code.  In place of
2349 ** a legal notice, here is a blessing:
2350 **
2351 **    May you do good and not evil.
2352 **    May you find forgiveness for yourself and forgive others.
2353 **    May you share freely, never taking more than you give.
2354 **
2355 *************************************************************************
2356 ** This file contains code to implement most of the opendir() family of
2357 ** POSIX functions on Win32 using the MSVCRT.
2358 */
2359 
2360 #if defined(_WIN32) && defined(_MSC_VER)
2361 /* #include "test_windirent.h" */
2362 
2363 /*
2364 ** Implementation of the POSIX getenv() function using the Win32 API.
2365 ** This function is not thread-safe.
2366 */
windirent_getenv(const char * name)2367 const char *windirent_getenv(
2368   const char *name
2369 ){
2370   static char value[32768]; /* Maximum length, per MSDN */
2371   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
2372   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
2373 
2374   memset(value, 0, sizeof(value));
2375   dwRet = GetEnvironmentVariableA(name, value, dwSize);
2376   if( dwRet==0 || dwRet>dwSize ){
2377     /*
2378     ** The function call to GetEnvironmentVariableA() failed -OR-
2379     ** the buffer is not large enough.  Either way, return NULL.
2380     */
2381     return 0;
2382   }else{
2383     /*
2384     ** The function call to GetEnvironmentVariableA() succeeded
2385     ** -AND- the buffer contains the entire value.
2386     */
2387     return value;
2388   }
2389 }
2390 
2391 /*
2392 ** Implementation of the POSIX opendir() function using the MSVCRT.
2393 */
opendir(const char * dirname)2394 LPDIR opendir(
2395   const char *dirname
2396 ){
2397   struct _finddata_t data;
2398   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
2399   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
2400 
2401   if( dirp==NULL ) return NULL;
2402   memset(dirp, 0, sizeof(DIR));
2403 
2404   /* TODO: Remove this if Unix-style root paths are not used. */
2405   if( sqlite3_stricmp(dirname, "/")==0 ){
2406     dirname = windirent_getenv("SystemDrive");
2407   }
2408 
2409   memset(&data, 0, sizeof(struct _finddata_t));
2410   _snprintf(data.name, namesize, "%s\\*", dirname);
2411   dirp->d_handle = _findfirst(data.name, &data);
2412 
2413   if( dirp->d_handle==BAD_INTPTR_T ){
2414     closedir(dirp);
2415     return NULL;
2416   }
2417 
2418   /* TODO: Remove this block to allow hidden and/or system files. */
2419   if( is_filtered(data) ){
2420 next:
2421 
2422     memset(&data, 0, sizeof(struct _finddata_t));
2423     if( _findnext(dirp->d_handle, &data)==-1 ){
2424       closedir(dirp);
2425       return NULL;
2426     }
2427 
2428     /* TODO: Remove this block to allow hidden and/or system files. */
2429     if( is_filtered(data) ) goto next;
2430   }
2431 
2432   dirp->d_first.d_attributes = data.attrib;
2433   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
2434   dirp->d_first.d_name[NAME_MAX] = '\0';
2435 
2436   return dirp;
2437 }
2438 
2439 /*
2440 ** Implementation of the POSIX readdir() function using the MSVCRT.
2441 */
readdir(LPDIR dirp)2442 LPDIRENT readdir(
2443   LPDIR dirp
2444 ){
2445   struct _finddata_t data;
2446 
2447   if( dirp==NULL ) return NULL;
2448 
2449   if( dirp->d_first.d_ino==0 ){
2450     dirp->d_first.d_ino++;
2451     dirp->d_next.d_ino++;
2452 
2453     return &dirp->d_first;
2454   }
2455 
2456 next:
2457 
2458   memset(&data, 0, sizeof(struct _finddata_t));
2459   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
2460 
2461   /* TODO: Remove this block to allow hidden and/or system files. */
2462   if( is_filtered(data) ) goto next;
2463 
2464   dirp->d_next.d_ino++;
2465   dirp->d_next.d_attributes = data.attrib;
2466   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
2467   dirp->d_next.d_name[NAME_MAX] = '\0';
2468 
2469   return &dirp->d_next;
2470 }
2471 
2472 /*
2473 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
2474 */
readdir_r(LPDIR dirp,LPDIRENT entry,LPDIRENT * result)2475 INT readdir_r(
2476   LPDIR dirp,
2477   LPDIRENT entry,
2478   LPDIRENT *result
2479 ){
2480   struct _finddata_t data;
2481 
2482   if( dirp==NULL ) return EBADF;
2483 
2484   if( dirp->d_first.d_ino==0 ){
2485     dirp->d_first.d_ino++;
2486     dirp->d_next.d_ino++;
2487 
2488     entry->d_ino = dirp->d_first.d_ino;
2489     entry->d_attributes = dirp->d_first.d_attributes;
2490     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
2491     entry->d_name[NAME_MAX] = '\0';
2492 
2493     *result = entry;
2494     return 0;
2495   }
2496 
2497 next:
2498 
2499   memset(&data, 0, sizeof(struct _finddata_t));
2500   if( _findnext(dirp->d_handle, &data)==-1 ){
2501     *result = NULL;
2502     return ENOENT;
2503   }
2504 
2505   /* TODO: Remove this block to allow hidden and/or system files. */
2506   if( is_filtered(data) ) goto next;
2507 
2508   entry->d_ino = (ino_t)-1; /* not available */
2509   entry->d_attributes = data.attrib;
2510   strncpy(entry->d_name, data.name, NAME_MAX);
2511   entry->d_name[NAME_MAX] = '\0';
2512 
2513   *result = entry;
2514   return 0;
2515 }
2516 
2517 /*
2518 ** Implementation of the POSIX closedir() function using the MSVCRT.
2519 */
closedir(LPDIR dirp)2520 INT closedir(
2521   LPDIR dirp
2522 ){
2523   INT result = 0;
2524 
2525   if( dirp==NULL ) return EINVAL;
2526 
2527   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
2528     result = _findclose(dirp->d_handle);
2529   }
2530 
2531   sqlite3_free(dirp);
2532   return result;
2533 }
2534 
2535 #endif /* defined(WIN32) && defined(_MSC_VER) */
2536 
2537 /************************* End test_windirent.c ********************/
2538 #define dirent DIRENT
2539 #endif
2540 /************************* Begin ../ext/misc/memtrace.c ******************/
2541 /*
2542 ** 2019-01-21
2543 **
2544 ** The author disclaims copyright to this source code.  In place of
2545 ** a legal notice, here is a blessing:
2546 **
2547 **    May you do good and not evil.
2548 **    May you find forgiveness for yourself and forgive others.
2549 **    May you share freely, never taking more than you give.
2550 **
2551 *************************************************************************
2552 **
2553 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
2554 ** mechanism to add a tracing layer on top of SQLite.  If this extension
2555 ** is registered prior to sqlite3_initialize(), it will cause all memory
2556 ** allocation activities to be logged on standard output, or to some other
2557 ** FILE specified by the initializer.
2558 **
2559 ** This file needs to be compiled into the application that uses it.
2560 **
2561 ** This extension is used to implement the --memtrace option of the
2562 ** command-line shell.
2563 */
2564 #include <assert.h>
2565 #include <string.h>
2566 #include <stdio.h>
2567 
2568 /* The original memory allocation routines */
2569 static sqlite3_mem_methods memtraceBase;
2570 static FILE *memtraceOut;
2571 
2572 /* Methods that trace memory allocations */
memtraceMalloc(int n)2573 static void *memtraceMalloc(int n){
2574   if( memtraceOut ){
2575     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
2576             memtraceBase.xRoundup(n));
2577   }
2578   return memtraceBase.xMalloc(n);
2579 }
memtraceFree(void * p)2580 static void memtraceFree(void *p){
2581   if( p==0 ) return;
2582   if( memtraceOut ){
2583     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
2584   }
2585   memtraceBase.xFree(p);
2586 }
memtraceRealloc(void * p,int n)2587 static void *memtraceRealloc(void *p, int n){
2588   if( p==0 ) return memtraceMalloc(n);
2589   if( n==0 ){
2590     memtraceFree(p);
2591     return 0;
2592   }
2593   if( memtraceOut ){
2594     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
2595             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
2596   }
2597   return memtraceBase.xRealloc(p, n);
2598 }
memtraceSize(void * p)2599 static int memtraceSize(void *p){
2600   return memtraceBase.xSize(p);
2601 }
memtraceRoundup(int n)2602 static int memtraceRoundup(int n){
2603   return memtraceBase.xRoundup(n);
2604 }
memtraceInit(void * p)2605 static int memtraceInit(void *p){
2606   return memtraceBase.xInit(p);
2607 }
memtraceShutdown(void * p)2608 static void memtraceShutdown(void *p){
2609   memtraceBase.xShutdown(p);
2610 }
2611 
2612 /* The substitute memory allocator */
2613 static sqlite3_mem_methods ersaztMethods = {
2614   memtraceMalloc,
2615   memtraceFree,
2616   memtraceRealloc,
2617   memtraceSize,
2618   memtraceRoundup,
2619   memtraceInit,
2620   memtraceShutdown,
2621   0
2622 };
2623 
2624 /* Begin tracing memory allocations to out. */
sqlite3MemTraceActivate(FILE * out)2625 int sqlite3MemTraceActivate(FILE *out){
2626   int rc = SQLITE_OK;
2627   if( memtraceBase.xMalloc==0 ){
2628     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
2629     if( rc==SQLITE_OK ){
2630       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
2631     }
2632   }
2633   memtraceOut = out;
2634   return rc;
2635 }
2636 
2637 /* Deactivate memory tracing */
sqlite3MemTraceDeactivate(void)2638 int sqlite3MemTraceDeactivate(void){
2639   int rc = SQLITE_OK;
2640   if( memtraceBase.xMalloc!=0 ){
2641     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
2642     if( rc==SQLITE_OK ){
2643       memset(&memtraceBase, 0, sizeof(memtraceBase));
2644     }
2645   }
2646   memtraceOut = 0;
2647   return rc;
2648 }
2649 
2650 /************************* End ../ext/misc/memtrace.c ********************/
2651 /************************* Begin ../ext/misc/pcachetrace.c ******************/
2652 /*
2653 ** 2023-06-21
2654 **
2655 ** The author disclaims copyright to this source code.  In place of
2656 ** a legal notice, here is a blessing:
2657 **
2658 **    May you do good and not evil.
2659 **    May you find forgiveness for yourself and forgive others.
2660 **    May you share freely, never taking more than you give.
2661 **
2662 *************************************************************************
2663 **
2664 ** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
2665 ** mechanism to add a tracing layer on top of pluggable page cache of
2666 ** SQLite.  If this extension is registered prior to sqlite3_initialize(),
2667 ** it will cause all page cache activities to be logged on standard output,
2668 ** or to some other FILE specified by the initializer.
2669 **
2670 ** This file needs to be compiled into the application that uses it.
2671 **
2672 ** This extension is used to implement the --pcachetrace option of the
2673 ** command-line shell.
2674 */
2675 #include <assert.h>
2676 #include <string.h>
2677 #include <stdio.h>
2678 
2679 /* The original page cache routines */
2680 static sqlite3_pcache_methods2 pcacheBase;
2681 static FILE *pcachetraceOut;
2682 
2683 /* Methods that trace pcache activity */
pcachetraceInit(void * pArg)2684 static int pcachetraceInit(void *pArg){
2685   int nRes;
2686   if( pcachetraceOut ){
2687     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
2688   }
2689   nRes = pcacheBase.xInit(pArg);
2690   if( pcachetraceOut ){
2691     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
2692   }
2693   return nRes;
2694 }
pcachetraceShutdown(void * pArg)2695 static void pcachetraceShutdown(void *pArg){
2696   if( pcachetraceOut ){
2697     fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
2698   }
2699   pcacheBase.xShutdown(pArg);
2700 }
pcachetraceCreate(int szPage,int szExtra,int bPurge)2701 static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
2702   sqlite3_pcache *pRes;
2703   if( pcachetraceOut ){
2704     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
2705             szPage, szExtra, bPurge);
2706   }
2707   pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
2708   if( pcachetraceOut ){
2709     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
2710             szPage, szExtra, bPurge, pRes);
2711   }
2712   return pRes;
2713 }
pcachetraceCachesize(sqlite3_pcache * p,int nCachesize)2714 static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
2715   if( pcachetraceOut ){
2716     fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
2717   }
2718   pcacheBase.xCachesize(p, nCachesize);
2719 }
pcachetracePagecount(sqlite3_pcache * p)2720 static int pcachetracePagecount(sqlite3_pcache *p){
2721   int nRes;
2722   if( pcachetraceOut ){
2723     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
2724   }
2725   nRes = pcacheBase.xPagecount(p);
2726   if( pcachetraceOut ){
2727     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
2728   }
2729   return nRes;
2730 }
pcachetraceFetch(sqlite3_pcache * p,unsigned key,int crFg)2731 static sqlite3_pcache_page *pcachetraceFetch(
2732   sqlite3_pcache *p,
2733   unsigned key,
2734   int crFg
2735 ){
2736   sqlite3_pcache_page *pRes;
2737   if( pcachetraceOut ){
2738     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
2739   }
2740   pRes = pcacheBase.xFetch(p, key, crFg);
2741   if( pcachetraceOut ){
2742     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
2743             p, key, crFg, pRes);
2744   }
2745   return pRes;
2746 }
pcachetraceUnpin(sqlite3_pcache * p,sqlite3_pcache_page * pPg,int bDiscard)2747 static void pcachetraceUnpin(
2748   sqlite3_pcache *p,
2749   sqlite3_pcache_page *pPg,
2750   int bDiscard
2751 ){
2752   if( pcachetraceOut ){
2753     fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
2754             p, pPg, bDiscard);
2755   }
2756   pcacheBase.xUnpin(p, pPg, bDiscard);
2757 }
pcachetraceRekey(sqlite3_pcache * p,sqlite3_pcache_page * pPg,unsigned oldKey,unsigned newKey)2758 static void pcachetraceRekey(
2759   sqlite3_pcache *p,
2760   sqlite3_pcache_page *pPg,
2761   unsigned oldKey,
2762   unsigned newKey
2763 ){
2764   if( pcachetraceOut ){
2765     fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
2766         p, pPg, oldKey, newKey);
2767   }
2768   pcacheBase.xRekey(p, pPg, oldKey, newKey);
2769 }
pcachetraceTruncate(sqlite3_pcache * p,unsigned n)2770 static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
2771   if( pcachetraceOut ){
2772     fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
2773   }
2774   pcacheBase.xTruncate(p, n);
2775 }
pcachetraceDestroy(sqlite3_pcache * p)2776 static void pcachetraceDestroy(sqlite3_pcache *p){
2777   if( pcachetraceOut ){
2778     fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
2779   }
2780   pcacheBase.xDestroy(p);
2781 }
pcachetraceShrink(sqlite3_pcache * p)2782 static void pcachetraceShrink(sqlite3_pcache *p){
2783   if( pcachetraceOut ){
2784     fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
2785   }
2786   pcacheBase.xShrink(p);
2787 }
2788 
2789 /* The substitute pcache methods */
2790 static sqlite3_pcache_methods2 ersaztPcacheMethods = {
2791   0,
2792   0,
2793   pcachetraceInit,
2794   pcachetraceShutdown,
2795   pcachetraceCreate,
2796   pcachetraceCachesize,
2797   pcachetracePagecount,
2798   pcachetraceFetch,
2799   pcachetraceUnpin,
2800   pcachetraceRekey,
2801   pcachetraceTruncate,
2802   pcachetraceDestroy,
2803   pcachetraceShrink
2804 };
2805 
2806 /* Begin tracing memory allocations to out. */
sqlite3PcacheTraceActivate(FILE * out)2807 int sqlite3PcacheTraceActivate(FILE *out){
2808   int rc = SQLITE_OK;
2809   if( pcacheBase.xFetch==0 ){
2810     rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
2811     if( rc==SQLITE_OK ){
2812       rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
2813     }
2814   }
2815   pcachetraceOut = out;
2816   return rc;
2817 }
2818 
2819 /* Deactivate memory tracing */
sqlite3PcacheTraceDeactivate(void)2820 int sqlite3PcacheTraceDeactivate(void){
2821   int rc = SQLITE_OK;
2822   if( pcacheBase.xFetch!=0 ){
2823     rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
2824     if( rc==SQLITE_OK ){
2825       memset(&pcacheBase, 0, sizeof(pcacheBase));
2826     }
2827   }
2828   pcachetraceOut = 0;
2829   return rc;
2830 }
2831 
2832 /************************* End ../ext/misc/pcachetrace.c ********************/
2833 /************************* Begin ../ext/misc/shathree.c ******************/
2834 /*
2835 ** 2017-03-08
2836 **
2837 ** The author disclaims copyright to this source code.  In place of
2838 ** a legal notice, here is a blessing:
2839 **
2840 **    May you do good and not evil.
2841 **    May you find forgiveness for yourself and forgive others.
2842 **    May you share freely, never taking more than you give.
2843 **
2844 ******************************************************************************
2845 **
2846 ** This SQLite extension implements functions that compute SHA3 hashes
2847 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2848 ** Two SQL functions are implemented:
2849 **
2850 **     sha3(X,SIZE)
2851 **     sha3_query(Y,SIZE)
2852 **
2853 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
2854 ** X is NULL.
2855 **
2856 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
2857 ** and returns a hash of their results.
2858 **
2859 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
2860 ** is used.  If SIZE is included it must be one of the integers 224, 256,
2861 ** 384, or 512, to determine SHA3 hash variant that is computed.
2862 */
2863 /* #include "sqlite3ext.h" */
2864 SQLITE_EXTENSION_INIT1
2865 #include <assert.h>
2866 #include <string.h>
2867 #include <stdarg.h>
2868 
2869 #ifndef SQLITE_AMALGAMATION
2870 /* typedef sqlite3_uint64 u64; */
2871 #endif /* SQLITE_AMALGAMATION */
2872 
2873 /******************************************************************************
2874 ** The Hash Engine
2875 */
2876 /*
2877 ** Macros to determine whether the machine is big or little endian,
2878 ** and whether or not that determination is run-time or compile-time.
2879 **
2880 ** For best performance, an attempt is made to guess at the byte-order
2881 ** using C-preprocessor macros.  If that is unsuccessful, or if
2882 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2883 ** at run-time.
2884 */
2885 #ifndef SHA3_BYTEORDER
2886 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
2887      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
2888      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
2889      defined(__arm__)
2890 #   define SHA3_BYTEORDER    1234
2891 # elif defined(sparc)    || defined(__ppc__)
2892 #   define SHA3_BYTEORDER    4321
2893 # else
2894 #   define SHA3_BYTEORDER 0
2895 # endif
2896 #endif
2897 
2898 
2899 /*
2900 ** State structure for a SHA3 hash in progress
2901 */
2902 typedef struct SHA3Context SHA3Context;
2903 struct SHA3Context {
2904   union {
2905     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
2906     unsigned char x[1600];    /* ... or 1600 bytes */
2907   } u;
2908   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
2909   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
2910   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
2911 };
2912 
2913 /*
2914 ** A single step of the Keccak mixing function for a 1600-bit state
2915 */
KeccakF1600Step(SHA3Context * p)2916 static void KeccakF1600Step(SHA3Context *p){
2917   int i;
2918   u64 b0, b1, b2, b3, b4;
2919   u64 c0, c1, c2, c3, c4;
2920   u64 d0, d1, d2, d3, d4;
2921   static const u64 RC[] = {
2922     0x0000000000000001ULL,  0x0000000000008082ULL,
2923     0x800000000000808aULL,  0x8000000080008000ULL,
2924     0x000000000000808bULL,  0x0000000080000001ULL,
2925     0x8000000080008081ULL,  0x8000000000008009ULL,
2926     0x000000000000008aULL,  0x0000000000000088ULL,
2927     0x0000000080008009ULL,  0x000000008000000aULL,
2928     0x000000008000808bULL,  0x800000000000008bULL,
2929     0x8000000000008089ULL,  0x8000000000008003ULL,
2930     0x8000000000008002ULL,  0x8000000000000080ULL,
2931     0x000000000000800aULL,  0x800000008000000aULL,
2932     0x8000000080008081ULL,  0x8000000000008080ULL,
2933     0x0000000080000001ULL,  0x8000000080008008ULL
2934   };
2935 # define a00 (p->u.s[0])
2936 # define a01 (p->u.s[1])
2937 # define a02 (p->u.s[2])
2938 # define a03 (p->u.s[3])
2939 # define a04 (p->u.s[4])
2940 # define a10 (p->u.s[5])
2941 # define a11 (p->u.s[6])
2942 # define a12 (p->u.s[7])
2943 # define a13 (p->u.s[8])
2944 # define a14 (p->u.s[9])
2945 # define a20 (p->u.s[10])
2946 # define a21 (p->u.s[11])
2947 # define a22 (p->u.s[12])
2948 # define a23 (p->u.s[13])
2949 # define a24 (p->u.s[14])
2950 # define a30 (p->u.s[15])
2951 # define a31 (p->u.s[16])
2952 # define a32 (p->u.s[17])
2953 # define a33 (p->u.s[18])
2954 # define a34 (p->u.s[19])
2955 # define a40 (p->u.s[20])
2956 # define a41 (p->u.s[21])
2957 # define a42 (p->u.s[22])
2958 # define a43 (p->u.s[23])
2959 # define a44 (p->u.s[24])
2960 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
2961 
2962   for(i=0; i<24; i+=4){
2963     c0 = a00^a10^a20^a30^a40;
2964     c1 = a01^a11^a21^a31^a41;
2965     c2 = a02^a12^a22^a32^a42;
2966     c3 = a03^a13^a23^a33^a43;
2967     c4 = a04^a14^a24^a34^a44;
2968     d0 = c4^ROL64(c1, 1);
2969     d1 = c0^ROL64(c2, 1);
2970     d2 = c1^ROL64(c3, 1);
2971     d3 = c2^ROL64(c4, 1);
2972     d4 = c3^ROL64(c0, 1);
2973 
2974     b0 = (a00^d0);
2975     b1 = ROL64((a11^d1), 44);
2976     b2 = ROL64((a22^d2), 43);
2977     b3 = ROL64((a33^d3), 21);
2978     b4 = ROL64((a44^d4), 14);
2979     a00 =   b0 ^((~b1)&  b2 );
2980     a00 ^= RC[i];
2981     a11 =   b1 ^((~b2)&  b3 );
2982     a22 =   b2 ^((~b3)&  b4 );
2983     a33 =   b3 ^((~b4)&  b0 );
2984     a44 =   b4 ^((~b0)&  b1 );
2985 
2986     b2 = ROL64((a20^d0), 3);
2987     b3 = ROL64((a31^d1), 45);
2988     b4 = ROL64((a42^d2), 61);
2989     b0 = ROL64((a03^d3), 28);
2990     b1 = ROL64((a14^d4), 20);
2991     a20 =   b0 ^((~b1)&  b2 );
2992     a31 =   b1 ^((~b2)&  b3 );
2993     a42 =   b2 ^((~b3)&  b4 );
2994     a03 =   b3 ^((~b4)&  b0 );
2995     a14 =   b4 ^((~b0)&  b1 );
2996 
2997     b4 = ROL64((a40^d0), 18);
2998     b0 = ROL64((a01^d1), 1);
2999     b1 = ROL64((a12^d2), 6);
3000     b2 = ROL64((a23^d3), 25);
3001     b3 = ROL64((a34^d4), 8);
3002     a40 =   b0 ^((~b1)&  b2 );
3003     a01 =   b1 ^((~b2)&  b3 );
3004     a12 =   b2 ^((~b3)&  b4 );
3005     a23 =   b3 ^((~b4)&  b0 );
3006     a34 =   b4 ^((~b0)&  b1 );
3007 
3008     b1 = ROL64((a10^d0), 36);
3009     b2 = ROL64((a21^d1), 10);
3010     b3 = ROL64((a32^d2), 15);
3011     b4 = ROL64((a43^d3), 56);
3012     b0 = ROL64((a04^d4), 27);
3013     a10 =   b0 ^((~b1)&  b2 );
3014     a21 =   b1 ^((~b2)&  b3 );
3015     a32 =   b2 ^((~b3)&  b4 );
3016     a43 =   b3 ^((~b4)&  b0 );
3017     a04 =   b4 ^((~b0)&  b1 );
3018 
3019     b3 = ROL64((a30^d0), 41);
3020     b4 = ROL64((a41^d1), 2);
3021     b0 = ROL64((a02^d2), 62);
3022     b1 = ROL64((a13^d3), 55);
3023     b2 = ROL64((a24^d4), 39);
3024     a30 =   b0 ^((~b1)&  b2 );
3025     a41 =   b1 ^((~b2)&  b3 );
3026     a02 =   b2 ^((~b3)&  b4 );
3027     a13 =   b3 ^((~b4)&  b0 );
3028     a24 =   b4 ^((~b0)&  b1 );
3029 
3030     c0 = a00^a20^a40^a10^a30;
3031     c1 = a11^a31^a01^a21^a41;
3032     c2 = a22^a42^a12^a32^a02;
3033     c3 = a33^a03^a23^a43^a13;
3034     c4 = a44^a14^a34^a04^a24;
3035     d0 = c4^ROL64(c1, 1);
3036     d1 = c0^ROL64(c2, 1);
3037     d2 = c1^ROL64(c3, 1);
3038     d3 = c2^ROL64(c4, 1);
3039     d4 = c3^ROL64(c0, 1);
3040 
3041     b0 = (a00^d0);
3042     b1 = ROL64((a31^d1), 44);
3043     b2 = ROL64((a12^d2), 43);
3044     b3 = ROL64((a43^d3), 21);
3045     b4 = ROL64((a24^d4), 14);
3046     a00 =   b0 ^((~b1)&  b2 );
3047     a00 ^= RC[i+1];
3048     a31 =   b1 ^((~b2)&  b3 );
3049     a12 =   b2 ^((~b3)&  b4 );
3050     a43 =   b3 ^((~b4)&  b0 );
3051     a24 =   b4 ^((~b0)&  b1 );
3052 
3053     b2 = ROL64((a40^d0), 3);
3054     b3 = ROL64((a21^d1), 45);
3055     b4 = ROL64((a02^d2), 61);
3056     b0 = ROL64((a33^d3), 28);
3057     b1 = ROL64((a14^d4), 20);
3058     a40 =   b0 ^((~b1)&  b2 );
3059     a21 =   b1 ^((~b2)&  b3 );
3060     a02 =   b2 ^((~b3)&  b4 );
3061     a33 =   b3 ^((~b4)&  b0 );
3062     a14 =   b4 ^((~b0)&  b1 );
3063 
3064     b4 = ROL64((a30^d0), 18);
3065     b0 = ROL64((a11^d1), 1);
3066     b1 = ROL64((a42^d2), 6);
3067     b2 = ROL64((a23^d3), 25);
3068     b3 = ROL64((a04^d4), 8);
3069     a30 =   b0 ^((~b1)&  b2 );
3070     a11 =   b1 ^((~b2)&  b3 );
3071     a42 =   b2 ^((~b3)&  b4 );
3072     a23 =   b3 ^((~b4)&  b0 );
3073     a04 =   b4 ^((~b0)&  b1 );
3074 
3075     b1 = ROL64((a20^d0), 36);
3076     b2 = ROL64((a01^d1), 10);
3077     b3 = ROL64((a32^d2), 15);
3078     b4 = ROL64((a13^d3), 56);
3079     b0 = ROL64((a44^d4), 27);
3080     a20 =   b0 ^((~b1)&  b2 );
3081     a01 =   b1 ^((~b2)&  b3 );
3082     a32 =   b2 ^((~b3)&  b4 );
3083     a13 =   b3 ^((~b4)&  b0 );
3084     a44 =   b4 ^((~b0)&  b1 );
3085 
3086     b3 = ROL64((a10^d0), 41);
3087     b4 = ROL64((a41^d1), 2);
3088     b0 = ROL64((a22^d2), 62);
3089     b1 = ROL64((a03^d3), 55);
3090     b2 = ROL64((a34^d4), 39);
3091     a10 =   b0 ^((~b1)&  b2 );
3092     a41 =   b1 ^((~b2)&  b3 );
3093     a22 =   b2 ^((~b3)&  b4 );
3094     a03 =   b3 ^((~b4)&  b0 );
3095     a34 =   b4 ^((~b0)&  b1 );
3096 
3097     c0 = a00^a40^a30^a20^a10;
3098     c1 = a31^a21^a11^a01^a41;
3099     c2 = a12^a02^a42^a32^a22;
3100     c3 = a43^a33^a23^a13^a03;
3101     c4 = a24^a14^a04^a44^a34;
3102     d0 = c4^ROL64(c1, 1);
3103     d1 = c0^ROL64(c2, 1);
3104     d2 = c1^ROL64(c3, 1);
3105     d3 = c2^ROL64(c4, 1);
3106     d4 = c3^ROL64(c0, 1);
3107 
3108     b0 = (a00^d0);
3109     b1 = ROL64((a21^d1), 44);
3110     b2 = ROL64((a42^d2), 43);
3111     b3 = ROL64((a13^d3), 21);
3112     b4 = ROL64((a34^d4), 14);
3113     a00 =   b0 ^((~b1)&  b2 );
3114     a00 ^= RC[i+2];
3115     a21 =   b1 ^((~b2)&  b3 );
3116     a42 =   b2 ^((~b3)&  b4 );
3117     a13 =   b3 ^((~b4)&  b0 );
3118     a34 =   b4 ^((~b0)&  b1 );
3119 
3120     b2 = ROL64((a30^d0), 3);
3121     b3 = ROL64((a01^d1), 45);
3122     b4 = ROL64((a22^d2), 61);
3123     b0 = ROL64((a43^d3), 28);
3124     b1 = ROL64((a14^d4), 20);
3125     a30 =   b0 ^((~b1)&  b2 );
3126     a01 =   b1 ^((~b2)&  b3 );
3127     a22 =   b2 ^((~b3)&  b4 );
3128     a43 =   b3 ^((~b4)&  b0 );
3129     a14 =   b4 ^((~b0)&  b1 );
3130 
3131     b4 = ROL64((a10^d0), 18);
3132     b0 = ROL64((a31^d1), 1);
3133     b1 = ROL64((a02^d2), 6);
3134     b2 = ROL64((a23^d3), 25);
3135     b3 = ROL64((a44^d4), 8);
3136     a10 =   b0 ^((~b1)&  b2 );
3137     a31 =   b1 ^((~b2)&  b3 );
3138     a02 =   b2 ^((~b3)&  b4 );
3139     a23 =   b3 ^((~b4)&  b0 );
3140     a44 =   b4 ^((~b0)&  b1 );
3141 
3142     b1 = ROL64((a40^d0), 36);
3143     b2 = ROL64((a11^d1), 10);
3144     b3 = ROL64((a32^d2), 15);
3145     b4 = ROL64((a03^d3), 56);
3146     b0 = ROL64((a24^d4), 27);
3147     a40 =   b0 ^((~b1)&  b2 );
3148     a11 =   b1 ^((~b2)&  b3 );
3149     a32 =   b2 ^((~b3)&  b4 );
3150     a03 =   b3 ^((~b4)&  b0 );
3151     a24 =   b4 ^((~b0)&  b1 );
3152 
3153     b3 = ROL64((a20^d0), 41);
3154     b4 = ROL64((a41^d1), 2);
3155     b0 = ROL64((a12^d2), 62);
3156     b1 = ROL64((a33^d3), 55);
3157     b2 = ROL64((a04^d4), 39);
3158     a20 =   b0 ^((~b1)&  b2 );
3159     a41 =   b1 ^((~b2)&  b3 );
3160     a12 =   b2 ^((~b3)&  b4 );
3161     a33 =   b3 ^((~b4)&  b0 );
3162     a04 =   b4 ^((~b0)&  b1 );
3163 
3164     c0 = a00^a30^a10^a40^a20;
3165     c1 = a21^a01^a31^a11^a41;
3166     c2 = a42^a22^a02^a32^a12;
3167     c3 = a13^a43^a23^a03^a33;
3168     c4 = a34^a14^a44^a24^a04;
3169     d0 = c4^ROL64(c1, 1);
3170     d1 = c0^ROL64(c2, 1);
3171     d2 = c1^ROL64(c3, 1);
3172     d3 = c2^ROL64(c4, 1);
3173     d4 = c3^ROL64(c0, 1);
3174 
3175     b0 = (a00^d0);
3176     b1 = ROL64((a01^d1), 44);
3177     b2 = ROL64((a02^d2), 43);
3178     b3 = ROL64((a03^d3), 21);
3179     b4 = ROL64((a04^d4), 14);
3180     a00 =   b0 ^((~b1)&  b2 );
3181     a00 ^= RC[i+3];
3182     a01 =   b1 ^((~b2)&  b3 );
3183     a02 =   b2 ^((~b3)&  b4 );
3184     a03 =   b3 ^((~b4)&  b0 );
3185     a04 =   b4 ^((~b0)&  b1 );
3186 
3187     b2 = ROL64((a10^d0), 3);
3188     b3 = ROL64((a11^d1), 45);
3189     b4 = ROL64((a12^d2), 61);
3190     b0 = ROL64((a13^d3), 28);
3191     b1 = ROL64((a14^d4), 20);
3192     a10 =   b0 ^((~b1)&  b2 );
3193     a11 =   b1 ^((~b2)&  b3 );
3194     a12 =   b2 ^((~b3)&  b4 );
3195     a13 =   b3 ^((~b4)&  b0 );
3196     a14 =   b4 ^((~b0)&  b1 );
3197 
3198     b4 = ROL64((a20^d0), 18);
3199     b0 = ROL64((a21^d1), 1);
3200     b1 = ROL64((a22^d2), 6);
3201     b2 = ROL64((a23^d3), 25);
3202     b3 = ROL64((a24^d4), 8);
3203     a20 =   b0 ^((~b1)&  b2 );
3204     a21 =   b1 ^((~b2)&  b3 );
3205     a22 =   b2 ^((~b3)&  b4 );
3206     a23 =   b3 ^((~b4)&  b0 );
3207     a24 =   b4 ^((~b0)&  b1 );
3208 
3209     b1 = ROL64((a30^d0), 36);
3210     b2 = ROL64((a31^d1), 10);
3211     b3 = ROL64((a32^d2), 15);
3212     b4 = ROL64((a33^d3), 56);
3213     b0 = ROL64((a34^d4), 27);
3214     a30 =   b0 ^((~b1)&  b2 );
3215     a31 =   b1 ^((~b2)&  b3 );
3216     a32 =   b2 ^((~b3)&  b4 );
3217     a33 =   b3 ^((~b4)&  b0 );
3218     a34 =   b4 ^((~b0)&  b1 );
3219 
3220     b3 = ROL64((a40^d0), 41);
3221     b4 = ROL64((a41^d1), 2);
3222     b0 = ROL64((a42^d2), 62);
3223     b1 = ROL64((a43^d3), 55);
3224     b2 = ROL64((a44^d4), 39);
3225     a40 =   b0 ^((~b1)&  b2 );
3226     a41 =   b1 ^((~b2)&  b3 );
3227     a42 =   b2 ^((~b3)&  b4 );
3228     a43 =   b3 ^((~b4)&  b0 );
3229     a44 =   b4 ^((~b0)&  b1 );
3230   }
3231 }
3232 
3233 /*
3234 ** Initialize a new hash.  iSize determines the size of the hash
3235 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
3236 ** can be zero to use the default hash size of 256 bits.
3237 */
SHA3Init(SHA3Context * p,int iSize)3238 static void SHA3Init(SHA3Context *p, int iSize){
3239   memset(p, 0, sizeof(*p));
3240   if( iSize>=128 && iSize<=512 ){
3241     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
3242   }else{
3243     p->nRate = (1600 - 2*256)/8;
3244   }
3245 #if SHA3_BYTEORDER==1234
3246   /* Known to be little-endian at compile-time. No-op */
3247 #elif SHA3_BYTEORDER==4321
3248   p->ixMask = 7;  /* Big-endian */
3249 #else
3250   {
3251     static unsigned int one = 1;
3252     if( 1==*(unsigned char*)&one ){
3253       /* Little endian.  No byte swapping. */
3254       p->ixMask = 0;
3255     }else{
3256       /* Big endian.  Byte swap. */
3257       p->ixMask = 7;
3258     }
3259   }
3260 #endif
3261 }
3262 
3263 /*
3264 ** Make consecutive calls to the SHA3Update function to add new content
3265 ** to the hash
3266 */
SHA3Update(SHA3Context * p,const unsigned char * aData,unsigned int nData)3267 static void SHA3Update(
3268   SHA3Context *p,
3269   const unsigned char *aData,
3270   unsigned int nData
3271 ){
3272   unsigned int i = 0;
3273   if( aData==0 ) return;
3274 #if SHA3_BYTEORDER==1234
3275   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
3276     for(; i+7<nData; i+=8){
3277       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
3278       p->nLoaded += 8;
3279       if( p->nLoaded>=p->nRate ){
3280         KeccakF1600Step(p);
3281         p->nLoaded = 0;
3282       }
3283     }
3284   }
3285 #endif
3286   for(; i<nData; i++){
3287 #if SHA3_BYTEORDER==1234
3288     p->u.x[p->nLoaded] ^= aData[i];
3289 #elif SHA3_BYTEORDER==4321
3290     p->u.x[p->nLoaded^0x07] ^= aData[i];
3291 #else
3292     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
3293 #endif
3294     p->nLoaded++;
3295     if( p->nLoaded==p->nRate ){
3296       KeccakF1600Step(p);
3297       p->nLoaded = 0;
3298     }
3299   }
3300 }
3301 
3302 /*
3303 ** After all content has been added, invoke SHA3Final() to compute
3304 ** the final hash.  The function returns a pointer to the binary
3305 ** hash value.
3306 */
SHA3Final(SHA3Context * p)3307 static unsigned char *SHA3Final(SHA3Context *p){
3308   unsigned int i;
3309   if( p->nLoaded==p->nRate-1 ){
3310     const unsigned char c1 = 0x86;
3311     SHA3Update(p, &c1, 1);
3312   }else{
3313     const unsigned char c2 = 0x06;
3314     const unsigned char c3 = 0x80;
3315     SHA3Update(p, &c2, 1);
3316     p->nLoaded = p->nRate - 1;
3317     SHA3Update(p, &c3, 1);
3318   }
3319   for(i=0; i<p->nRate; i++){
3320     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
3321   }
3322   return &p->u.x[p->nRate];
3323 }
3324 /* End of the hashing logic
3325 *****************************************************************************/
3326 
3327 /*
3328 ** Implementation of the sha3(X,SIZE) function.
3329 **
3330 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
3331 ** size is 256.  If X is a BLOB, it is hashed as is.
3332 ** For all other non-NULL types of input, X is converted into a UTF-8 string
3333 ** and the string is hashed without the trailing 0x00 terminator.  The hash
3334 ** of a NULL value is NULL.
3335 */
sha3Func(sqlite3_context * context,int argc,sqlite3_value ** argv)3336 static void sha3Func(
3337   sqlite3_context *context,
3338   int argc,
3339   sqlite3_value **argv
3340 ){
3341   SHA3Context cx;
3342   int eType = sqlite3_value_type(argv[0]);
3343   int nByte = sqlite3_value_bytes(argv[0]);
3344   int iSize;
3345   if( argc==1 ){
3346     iSize = 256;
3347   }else{
3348     iSize = sqlite3_value_int(argv[1]);
3349     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3350       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3351                                     "384 512", -1);
3352       return;
3353     }
3354   }
3355   if( eType==SQLITE_NULL ) return;
3356   SHA3Init(&cx, iSize);
3357   if( eType==SQLITE_BLOB ){
3358     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
3359   }else{
3360     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
3361   }
3362   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3363 }
3364 
3365 /* Compute a string using sqlite3_vsnprintf() with a maximum length
3366 ** of 50 bytes and add it to the hash.
3367 */
sha3_step_vformat(SHA3Context * p,const char * zFormat,...)3368 static void sha3_step_vformat(
3369   SHA3Context *p,                 /* Add content to this context */
3370   const char *zFormat,
3371   ...
3372 ){
3373   va_list ap;
3374   int n;
3375   char zBuf[50];
3376   va_start(ap, zFormat);
3377   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
3378   va_end(ap);
3379   n = (int)strlen(zBuf);
3380   SHA3Update(p, (unsigned char*)zBuf, n);
3381 }
3382 
3383 /*
3384 ** Implementation of the sha3_query(SQL,SIZE) function.
3385 **
3386 ** This function compiles and runs the SQL statement(s) given in the
3387 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
3388 ** size is 256.
3389 **
3390 ** The format of the byte stream that is hashed is summarized as follows:
3391 **
3392 **       S<n>:<sql>
3393 **       R
3394 **       N
3395 **       I<int>
3396 **       F<ieee-float>
3397 **       B<size>:<bytes>
3398 **       T<size>:<text>
3399 **
3400 ** <sql> is the original SQL text for each statement run and <n> is
3401 ** the size of that text.  The SQL text is UTF-8.  A single R character
3402 ** occurs before the start of each row.  N means a NULL value.
3403 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
3404 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3405 ** B means blobs of <size> bytes.  T means text rendered as <size>
3406 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
3407 ** text integers.
3408 **
3409 ** For each SQL statement in the X input, there is one S segment.  Each
3410 ** S segment is followed by zero or more R segments, one for each row in the
3411 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
3412 ** one for each column in the result set.  Segments are concatentated directly
3413 ** with no delimiters of any kind.
3414 */
sha3QueryFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)3415 static void sha3QueryFunc(
3416   sqlite3_context *context,
3417   int argc,
3418   sqlite3_value **argv
3419 ){
3420   sqlite3 *db = sqlite3_context_db_handle(context);
3421   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
3422   sqlite3_stmt *pStmt = 0;
3423   int nCol;                   /* Number of columns in the result set */
3424   int i;                      /* Loop counter */
3425   int rc;
3426   int n;
3427   const char *z;
3428   SHA3Context cx;
3429   int iSize;
3430 
3431   if( argc==1 ){
3432     iSize = 256;
3433   }else{
3434     iSize = sqlite3_value_int(argv[1]);
3435     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3436       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3437                                     "384 512", -1);
3438       return;
3439     }
3440   }
3441   if( zSql==0 ) return;
3442   SHA3Init(&cx, iSize);
3443   while( zSql[0] ){
3444     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
3445     if( rc ){
3446       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
3447                                    zSql, sqlite3_errmsg(db));
3448       sqlite3_finalize(pStmt);
3449       sqlite3_result_error(context, zMsg, -1);
3450       sqlite3_free(zMsg);
3451       return;
3452     }
3453     if( !sqlite3_stmt_readonly(pStmt) ){
3454       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
3455       sqlite3_finalize(pStmt);
3456       sqlite3_result_error(context, zMsg, -1);
3457       sqlite3_free(zMsg);
3458       return;
3459     }
3460     nCol = sqlite3_column_count(pStmt);
3461     z = sqlite3_sql(pStmt);
3462     if( z ){
3463       n = (int)strlen(z);
3464       sha3_step_vformat(&cx,"S%d:",n);
3465       SHA3Update(&cx,(unsigned char*)z,n);
3466     }
3467 
3468     /* Compute a hash over the result of the query */
3469     while( SQLITE_ROW==sqlite3_step(pStmt) ){
3470       SHA3Update(&cx,(const unsigned char*)"R",1);
3471       for(i=0; i<nCol; i++){
3472         switch( sqlite3_column_type(pStmt,i) ){
3473           case SQLITE_NULL: {
3474             SHA3Update(&cx, (const unsigned char*)"N",1);
3475             break;
3476           }
3477           case SQLITE_INTEGER: {
3478             sqlite3_uint64 u;
3479             int j;
3480             unsigned char x[9];
3481             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
3482             memcpy(&u, &v, 8);
3483             for(j=8; j>=1; j--){
3484               x[j] = u & 0xff;
3485               u >>= 8;
3486             }
3487             x[0] = 'I';
3488             SHA3Update(&cx, x, 9);
3489             break;
3490           }
3491           case SQLITE_FLOAT: {
3492             sqlite3_uint64 u;
3493             int j;
3494             unsigned char x[9];
3495             double r = sqlite3_column_double(pStmt,i);
3496             memcpy(&u, &r, 8);
3497             for(j=8; j>=1; j--){
3498               x[j] = u & 0xff;
3499               u >>= 8;
3500             }
3501             x[0] = 'F';
3502             SHA3Update(&cx,x,9);
3503             break;
3504           }
3505           case SQLITE_TEXT: {
3506             int n2 = sqlite3_column_bytes(pStmt, i);
3507             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
3508             sha3_step_vformat(&cx,"T%d:",n2);
3509             SHA3Update(&cx, z2, n2);
3510             break;
3511           }
3512           case SQLITE_BLOB: {
3513             int n2 = sqlite3_column_bytes(pStmt, i);
3514             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
3515             sha3_step_vformat(&cx,"B%d:",n2);
3516             SHA3Update(&cx, z2, n2);
3517             break;
3518           }
3519         }
3520       }
3521     }
3522     sqlite3_finalize(pStmt);
3523   }
3524   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3525 }
3526 
3527 
3528 #ifdef _WIN32
3529 
3530 #endif
sqlite3_shathree_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3531 int sqlite3_shathree_init(
3532   sqlite3 *db,
3533   char **pzErrMsg,
3534   const sqlite3_api_routines *pApi
3535 ){
3536   int rc = SQLITE_OK;
3537   SQLITE_EXTENSION_INIT2(pApi);
3538   (void)pzErrMsg;  /* Unused parameter */
3539   rc = sqlite3_create_function(db, "sha3", 1,
3540                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3541                       0, sha3Func, 0, 0);
3542   if( rc==SQLITE_OK ){
3543     rc = sqlite3_create_function(db, "sha3", 2,
3544                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3545                       0, sha3Func, 0, 0);
3546   }
3547   if( rc==SQLITE_OK ){
3548     rc = sqlite3_create_function(db, "sha3_query", 1,
3549                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3550                       0, sha3QueryFunc, 0, 0);
3551   }
3552   if( rc==SQLITE_OK ){
3553     rc = sqlite3_create_function(db, "sha3_query", 2,
3554                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
3555                       0, sha3QueryFunc, 0, 0);
3556   }
3557   return rc;
3558 }
3559 
3560 /************************* End ../ext/misc/shathree.c ********************/
3561 /************************* Begin ../ext/misc/uint.c ******************/
3562 /*
3563 ** 2020-04-14
3564 **
3565 ** The author disclaims copyright to this source code.  In place of
3566 ** a legal notice, here is a blessing:
3567 **
3568 **    May you do good and not evil.
3569 **    May you find forgiveness for yourself and forgive others.
3570 **    May you share freely, never taking more than you give.
3571 **
3572 ******************************************************************************
3573 **
3574 ** This SQLite extension implements the UINT collating sequence.
3575 **
3576 ** UINT works like BINARY for text, except that embedded strings
3577 ** of digits compare in numeric order.
3578 **
3579 **     *   Leading zeros are handled properly, in the sense that
3580 **         they do not mess of the maginitude comparison of embedded
3581 **         strings of digits.  "x00123y" is equal to "x123y".
3582 **
3583 **     *   Only unsigned integers are recognized.  Plus and minus
3584 **         signs are ignored.  Decimal points and exponential notation
3585 **         are ignored.
3586 **
3587 **     *   Embedded integers can be of arbitrary length.  Comparison
3588 **         is *not* limited integers that can be expressed as a
3589 **         64-bit machine integer.
3590 */
3591 /* #include "sqlite3ext.h" */
3592 SQLITE_EXTENSION_INIT1
3593 #include <assert.h>
3594 #include <string.h>
3595 #include <ctype.h>
3596 
3597 /*
3598 ** Compare text in lexicographic order, except strings of digits
3599 ** compare in numeric order.
3600 */
uintCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)3601 static int uintCollFunc(
3602   void *notUsed,
3603   int nKey1, const void *pKey1,
3604   int nKey2, const void *pKey2
3605 ){
3606   const unsigned char *zA = (const unsigned char*)pKey1;
3607   const unsigned char *zB = (const unsigned char*)pKey2;
3608   int i=0, j=0, x;
3609   (void)notUsed;
3610   while( i<nKey1 && j<nKey2 ){
3611     x = zA[i] - zB[j];
3612     if( isdigit(zA[i]) ){
3613       int k;
3614       if( !isdigit(zB[j]) ) return x;
3615       while( i<nKey1 && zA[i]=='0' ){ i++; }
3616       while( j<nKey2 && zB[j]=='0' ){ j++; }
3617       k = 0;
3618       while( i+k<nKey1 && isdigit(zA[i+k])
3619              && j+k<nKey2 && isdigit(zB[j+k]) ){
3620         k++;
3621       }
3622       if( i+k<nKey1 && isdigit(zA[i+k]) ){
3623         return +1;
3624       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
3625         return -1;
3626       }else{
3627         x = memcmp(zA+i, zB+j, k);
3628         if( x ) return x;
3629         i += k;
3630         j += k;
3631       }
3632     }else if( x ){
3633       return x;
3634     }else{
3635       i++;
3636       j++;
3637     }
3638   }
3639   return (nKey1 - i) - (nKey2 - j);
3640 }
3641 
3642 #ifdef _WIN32
3643 
3644 #endif
sqlite3_uint_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)3645 int sqlite3_uint_init(
3646   sqlite3 *db,
3647   char **pzErrMsg,
3648   const sqlite3_api_routines *pApi
3649 ){
3650   SQLITE_EXTENSION_INIT2(pApi);
3651   (void)pzErrMsg;  /* Unused parameter */
3652   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
3653 }
3654 
3655 /************************* End ../ext/misc/uint.c ********************/
3656 /************************* Begin ../ext/misc/decimal.c ******************/
3657 /*
3658 ** 2020-06-22
3659 **
3660 ** The author disclaims copyright to this source code.  In place of
3661 ** a legal notice, here is a blessing:
3662 **
3663 **    May you do good and not evil.
3664 **    May you find forgiveness for yourself and forgive others.
3665 **    May you share freely, never taking more than you give.
3666 **
3667 ******************************************************************************
3668 **
3669 ** Routines to implement arbitrary-precision decimal math.
3670 **
3671 ** The focus here is on simplicity and correctness, not performance.
3672 */
3673 /* #include "sqlite3ext.h" */
3674 SQLITE_EXTENSION_INIT1
3675 #include <assert.h>
3676 #include <string.h>
3677 #include <ctype.h>
3678 #include <stdlib.h>
3679 
3680 /* Mark a function parameter as unused, to suppress nuisance compiler
3681 ** warnings. */
3682 #ifndef UNUSED_PARAMETER
3683 # define UNUSED_PARAMETER(X)  (void)(X)
3684 #endif
3685 
3686 
3687 /* A decimal object */
3688 typedef struct Decimal Decimal;
3689 struct Decimal {
3690   char sign;        /* 0 for positive, 1 for negative */
3691   char oom;         /* True if an OOM is encountered */
3692   char isNull;      /* True if holds a NULL rather than a number */
3693   char isInit;      /* True upon initialization */
3694   int nDigit;       /* Total number of digits */
3695   int nFrac;        /* Number of digits to the right of the decimal point */
3696   signed char *a;   /* Array of digits.  Most significant first. */
3697 };
3698 
3699 /*
3700 ** Release memory held by a Decimal, but do not free the object itself.
3701 */
decimal_clear(Decimal * p)3702 static void decimal_clear(Decimal *p){
3703   sqlite3_free(p->a);
3704 }
3705 
3706 /*
3707 ** Destroy a Decimal object
3708 */
decimal_free(Decimal * p)3709 static void decimal_free(Decimal *p){
3710   if( p ){
3711     decimal_clear(p);
3712     sqlite3_free(p);
3713   }
3714 }
3715 
3716 /*
3717 ** Allocate a new Decimal object initialized to the text in zIn[].
3718 ** Return NULL if any kind of error occurs.
3719 */
decimalNewFromText(const char * zIn,int n)3720 static Decimal *decimalNewFromText(const char *zIn, int n){
3721   Decimal *p = 0;
3722   int i;
3723   int iExp = 0;
3724 
3725   p = sqlite3_malloc( sizeof(*p) );
3726   if( p==0 ) goto new_from_text_failed;
3727   p->sign = 0;
3728   p->oom = 0;
3729   p->isInit = 1;
3730   p->isNull = 0;
3731   p->nDigit = 0;
3732   p->nFrac = 0;
3733   p->a = sqlite3_malloc64( n+1 );
3734   if( p->a==0 ) goto new_from_text_failed;
3735   for(i=0; isspace(zIn[i]); i++){}
3736   if( zIn[i]=='-' ){
3737     p->sign = 1;
3738     i++;
3739   }else if( zIn[i]=='+' ){
3740     i++;
3741   }
3742   while( i<n && zIn[i]=='0' ) i++;
3743   while( i<n ){
3744     char c = zIn[i];
3745     if( c>='0' && c<='9' ){
3746       p->a[p->nDigit++] = c - '0';
3747     }else if( c=='.' ){
3748       p->nFrac = p->nDigit + 1;
3749     }else if( c=='e' || c=='E' ){
3750       int j = i+1;
3751       int neg = 0;
3752       if( j>=n ) break;
3753       if( zIn[j]=='-' ){
3754         neg = 1;
3755         j++;
3756       }else if( zIn[j]=='+' ){
3757         j++;
3758       }
3759       while( j<n && iExp<1000000 ){
3760         if( zIn[j]>='0' && zIn[j]<='9' ){
3761           iExp = iExp*10 + zIn[j] - '0';
3762         }
3763         j++;
3764       }
3765       if( neg ) iExp = -iExp;
3766       break;
3767     }
3768     i++;
3769   }
3770   if( p->nFrac ){
3771     p->nFrac = p->nDigit - (p->nFrac - 1);
3772   }
3773   if( iExp>0 ){
3774     if( p->nFrac>0 ){
3775       if( iExp<=p->nFrac ){
3776         p->nFrac -= iExp;
3777         iExp = 0;
3778       }else{
3779         iExp -= p->nFrac;
3780         p->nFrac = 0;
3781       }
3782     }
3783     if( iExp>0 ){
3784       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3785       if( p->a==0 ) goto new_from_text_failed;
3786       memset(p->a+p->nDigit, 0, iExp);
3787       p->nDigit += iExp;
3788     }
3789   }else if( iExp<0 ){
3790     int nExtra;
3791     iExp = -iExp;
3792     nExtra = p->nDigit - p->nFrac - 1;
3793     if( nExtra ){
3794       if( nExtra>=iExp ){
3795         p->nFrac += iExp;
3796         iExp  = 0;
3797       }else{
3798         iExp -= nExtra;
3799         p->nFrac = p->nDigit - 1;
3800       }
3801     }
3802     if( iExp>0 ){
3803       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3804       if( p->a==0 ) goto new_from_text_failed;
3805       memmove(p->a+iExp, p->a, p->nDigit);
3806       memset(p->a, 0, iExp);
3807       p->nDigit += iExp;
3808       p->nFrac += iExp;
3809     }
3810   }
3811   return p;
3812 
3813 new_from_text_failed:
3814   if( p ){
3815     if( p->a ) sqlite3_free(p->a);
3816     sqlite3_free(p);
3817   }
3818   return 0;
3819 }
3820 
3821 /* Forward reference */
3822 static Decimal *decimalFromDouble(double);
3823 
3824 /*
3825 ** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
3826 ** to the new object, or NULL if there is an error.  If the pCtx argument
3827 ** is not NULL, then errors are reported on it as well.
3828 **
3829 ** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3830 ** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
3831 ** 8 bytes, the resulting double value is expanded into its decimal equivalent.
3832 ** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3833 ** then NULL is returned.
3834 */
decimal_new(sqlite3_context * pCtx,sqlite3_value * pIn,int bTextOnly)3835 static Decimal *decimal_new(
3836   sqlite3_context *pCtx,       /* Report error here, if not null */
3837   sqlite3_value *pIn,          /* Construct the decimal object from this */
3838   int bTextOnly                /* Always interpret pIn as text if true */
3839 ){
3840   Decimal *p = 0;
3841   int eType = sqlite3_value_type(pIn);
3842   if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
3843     eType = SQLITE_TEXT;
3844   }
3845   switch( eType ){
3846     case SQLITE_TEXT:
3847     case SQLITE_INTEGER: {
3848       const char *zIn = (const char*)sqlite3_value_text(pIn);
3849       int n = sqlite3_value_bytes(pIn);
3850       p = decimalNewFromText(zIn, n);
3851       if( p==0 ) goto new_failed;
3852       break;
3853     }
3854 
3855     case SQLITE_FLOAT: {
3856       p = decimalFromDouble(sqlite3_value_double(pIn));
3857       break;
3858     }
3859 
3860     case SQLITE_BLOB: {
3861       const unsigned char *x;
3862       unsigned int i;
3863       sqlite3_uint64 v = 0;
3864       double r;
3865 
3866       if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
3867       x = sqlite3_value_blob(pIn);
3868       for(i=0; i<sizeof(r); i++){
3869         v = (v<<8) | x[i];
3870       }
3871       memcpy(&r, &v, sizeof(r));
3872       p = decimalFromDouble(r);
3873       break;
3874     }
3875 
3876     case SQLITE_NULL: {
3877       break;
3878     }
3879   }
3880   return p;
3881 
3882 new_failed:
3883   if( pCtx ) sqlite3_result_error_nomem(pCtx);
3884   sqlite3_free(p);
3885   return 0;
3886 }
3887 
3888 /*
3889 ** Make the given Decimal the result.
3890 */
decimal_result(sqlite3_context * pCtx,Decimal * p)3891 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
3892   char *z;
3893   int i, j;
3894   int n;
3895   if( p==0 || p->oom ){
3896     sqlite3_result_error_nomem(pCtx);
3897     return;
3898   }
3899   if( p->isNull ){
3900     sqlite3_result_null(pCtx);
3901     return;
3902   }
3903   z = sqlite3_malloc( p->nDigit+4 );
3904   if( z==0 ){
3905     sqlite3_result_error_nomem(pCtx);
3906     return;
3907   }
3908   i = 0;
3909   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
3910     p->sign = 0;
3911   }
3912   if( p->sign ){
3913     z[0] = '-';
3914     i = 1;
3915   }
3916   n = p->nDigit - p->nFrac;
3917   if( n<=0 ){
3918     z[i++] = '0';
3919   }
3920   j = 0;
3921   while( n>1 && p->a[j]==0 ){
3922     j++;
3923     n--;
3924   }
3925   while( n>0  ){
3926     z[i++] = p->a[j] + '0';
3927     j++;
3928     n--;
3929   }
3930   if( p->nFrac ){
3931     z[i++] = '.';
3932     do{
3933       z[i++] = p->a[j] + '0';
3934       j++;
3935     }while( j<p->nDigit );
3936   }
3937   z[i] = 0;
3938   sqlite3_result_text(pCtx, z, i, sqlite3_free);
3939 }
3940 
3941 /*
3942 ** Make the given Decimal the result in an format similar to  '%+#e'.
3943 ** In other words, show exponential notation with leading and trailing
3944 ** zeros omitted.
3945 */
decimal_result_sci(sqlite3_context * pCtx,Decimal * p)3946 static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){
3947   char *z;       /* The output buffer */
3948   int i;         /* Loop counter */
3949   int nZero;     /* Number of leading zeros */
3950   int nDigit;    /* Number of digits not counting trailing zeros */
3951   int nFrac;     /* Digits to the right of the decimal point */
3952   int exp;       /* Exponent value */
3953   signed char zero;     /* Zero value */
3954   signed char *a;       /* Array of digits */
3955 
3956   if( p==0 || p->oom ){
3957     sqlite3_result_error_nomem(pCtx);
3958     return;
3959   }
3960   if( p->isNull ){
3961     sqlite3_result_null(pCtx);
3962     return;
3963   }
3964   for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){}
3965   for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
3966   nFrac = p->nFrac + (nDigit - p->nDigit);
3967   nDigit -= nZero;
3968   z = sqlite3_malloc( nDigit+20 );
3969   if( z==0 ){
3970     sqlite3_result_error_nomem(pCtx);
3971     return;
3972   }
3973   if( nDigit==0 ){
3974     zero = 0;
3975     a = &zero;
3976     nDigit = 1;
3977     nFrac = 0;
3978   }else{
3979     a = &p->a[nZero];
3980   }
3981   if( p->sign && nDigit>0 ){
3982     z[0] = '-';
3983   }else{
3984     z[0] = '+';
3985   }
3986   z[1] = a[0]+'0';
3987   z[2] = '.';
3988   if( nDigit==1 ){
3989     z[3] = '0';
3990     i = 4;
3991   }else{
3992     for(i=1; i<nDigit; i++){
3993       z[2+i] = a[i]+'0';
3994     }
3995     i = nDigit+2;
3996   }
3997   exp = nDigit - nFrac - 1;
3998   sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
3999   sqlite3_result_text(pCtx, z, -1, sqlite3_free);
4000 }
4001 
4002 /*
4003 ** Compare to Decimal objects.  Return negative, 0, or positive if the
4004 ** first object is less than, equal to, or greater than the second.
4005 **
4006 ** Preconditions for this routine:
4007 **
4008 **    pA!=0
4009 **    pA->isNull==0
4010 **    pB!=0
4011 **    pB->isNull==0
4012 */
decimal_cmp(const Decimal * pA,const Decimal * pB)4013 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4014   int nASig, nBSig, rc, n;
4015   if( pA->sign!=pB->sign ){
4016     return pA->sign ? -1 : +1;
4017   }
4018   if( pA->sign ){
4019     const Decimal *pTemp = pA;
4020     pA = pB;
4021     pB = pTemp;
4022   }
4023   nASig = pA->nDigit - pA->nFrac;
4024   nBSig = pB->nDigit - pB->nFrac;
4025   if( nASig!=nBSig ){
4026     return nASig - nBSig;
4027   }
4028   n = pA->nDigit;
4029   if( n>pB->nDigit ) n = pB->nDigit;
4030   rc = memcmp(pA->a, pB->a, n);
4031   if( rc==0 ){
4032     rc = pA->nDigit - pB->nDigit;
4033   }
4034   return rc;
4035 }
4036 
4037 /*
4038 ** SQL Function:   decimal_cmp(X, Y)
4039 **
4040 ** Return negative, zero, or positive if X is less then, equal to, or
4041 ** greater than Y.
4042 */
decimalCmpFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4043 static void decimalCmpFunc(
4044   sqlite3_context *context,
4045   int argc,
4046   sqlite3_value **argv
4047 ){
4048   Decimal *pA = 0, *pB = 0;
4049   int rc;
4050 
4051   UNUSED_PARAMETER(argc);
4052   pA = decimal_new(context, argv[0], 1);
4053   if( pA==0 || pA->isNull ) goto cmp_done;
4054   pB = decimal_new(context, argv[1], 1);
4055   if( pB==0 || pB->isNull ) goto cmp_done;
4056   rc = decimal_cmp(pA, pB);
4057   if( rc<0 ) rc = -1;
4058   else if( rc>0 ) rc = +1;
4059   sqlite3_result_int(context, rc);
4060 cmp_done:
4061   decimal_free(pA);
4062   decimal_free(pB);
4063 }
4064 
4065 /*
4066 ** Expand the Decimal so that it has a least nDigit digits and nFrac
4067 ** digits to the right of the decimal point.
4068 */
decimal_expand(Decimal * p,int nDigit,int nFrac)4069 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4070   int nAddSig;
4071   int nAddFrac;
4072   if( p==0 ) return;
4073   nAddFrac = nFrac - p->nFrac;
4074   nAddSig = (nDigit - p->nDigit) - nAddFrac;
4075   if( nAddFrac==0 && nAddSig==0 ) return;
4076   p->a = sqlite3_realloc64(p->a, nDigit+1);
4077   if( p->a==0 ){
4078     p->oom = 1;
4079     return;
4080   }
4081   if( nAddSig ){
4082     memmove(p->a+nAddSig, p->a, p->nDigit);
4083     memset(p->a, 0, nAddSig);
4084     p->nDigit += nAddSig;
4085   }
4086   if( nAddFrac ){
4087     memset(p->a+p->nDigit, 0, nAddFrac);
4088     p->nDigit += nAddFrac;
4089     p->nFrac += nAddFrac;
4090   }
4091 }
4092 
4093 /*
4094 ** Add the value pB into pA.   A := A + B.
4095 **
4096 ** Both pA and pB might become denormalized by this routine.
4097 */
decimal_add(Decimal * pA,Decimal * pB)4098 static void decimal_add(Decimal *pA, Decimal *pB){
4099   int nSig, nFrac, nDigit;
4100   int i, rc;
4101   if( pA==0 ){
4102     return;
4103   }
4104   if( pA->oom || pB==0 || pB->oom ){
4105     pA->oom = 1;
4106     return;
4107   }
4108   if( pA->isNull || pB->isNull ){
4109     pA->isNull = 1;
4110     return;
4111   }
4112   nSig = pA->nDigit - pA->nFrac;
4113   if( nSig && pA->a[0]==0 ) nSig--;
4114   if( nSig<pB->nDigit-pB->nFrac ){
4115     nSig = pB->nDigit - pB->nFrac;
4116   }
4117   nFrac = pA->nFrac;
4118   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4119   nDigit = nSig + nFrac + 1;
4120   decimal_expand(pA, nDigit, nFrac);
4121   decimal_expand(pB, nDigit, nFrac);
4122   if( pA->oom || pB->oom ){
4123     pA->oom = 1;
4124   }else{
4125     if( pA->sign==pB->sign ){
4126       int carry = 0;
4127       for(i=nDigit-1; i>=0; i--){
4128         int x = pA->a[i] + pB->a[i] + carry;
4129         if( x>=10 ){
4130           carry = 1;
4131           pA->a[i] = x - 10;
4132         }else{
4133           carry = 0;
4134           pA->a[i] = x;
4135         }
4136       }
4137     }else{
4138       signed char *aA, *aB;
4139       int borrow = 0;
4140       rc = memcmp(pA->a, pB->a, nDigit);
4141       if( rc<0 ){
4142         aA = pB->a;
4143         aB = pA->a;
4144         pA->sign = !pA->sign;
4145       }else{
4146         aA = pA->a;
4147         aB = pB->a;
4148       }
4149       for(i=nDigit-1; i>=0; i--){
4150         int x = aA[i] - aB[i] - borrow;
4151         if( x<0 ){
4152           pA->a[i] = x+10;
4153           borrow = 1;
4154         }else{
4155           pA->a[i] = x;
4156           borrow = 0;
4157         }
4158       }
4159     }
4160   }
4161 }
4162 
4163 /*
4164 ** Multiply A by B.   A := A * B
4165 **
4166 ** All significant digits after the decimal point are retained.
4167 ** Trailing zeros after the decimal point are omitted as long as
4168 ** the number of digits after the decimal point is no less than
4169 ** either the number of digits in either input.
4170 */
decimalMul(Decimal * pA,Decimal * pB)4171 static void decimalMul(Decimal *pA, Decimal *pB){
4172   signed char *acc = 0;
4173   int i, j, k;
4174   int minFrac;
4175 
4176   if( pA==0 || pA->oom || pA->isNull
4177    || pB==0 || pB->oom || pB->isNull
4178   ){
4179     goto mul_end;
4180   }
4181   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
4182   if( acc==0 ){
4183     pA->oom = 1;
4184     goto mul_end;
4185   }
4186   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
4187   minFrac = pA->nFrac;
4188   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
4189   for(i=pA->nDigit-1; i>=0; i--){
4190     signed char f = pA->a[i];
4191     int carry = 0, x;
4192     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
4193       x = acc[k] + f*pB->a[j] + carry;
4194       acc[k] = x%10;
4195       carry = x/10;
4196     }
4197     x = acc[k] + carry;
4198     acc[k] = x%10;
4199     acc[k-1] += x/10;
4200   }
4201   sqlite3_free(pA->a);
4202   pA->a = acc;
4203   acc = 0;
4204   pA->nDigit += pB->nDigit + 2;
4205   pA->nFrac += pB->nFrac;
4206   pA->sign ^= pB->sign;
4207   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
4208     pA->nFrac--;
4209     pA->nDigit--;
4210   }
4211 
4212 mul_end:
4213   sqlite3_free(acc);
4214 }
4215 
4216 /*
4217 ** Create a new Decimal object that contains an integer power of 2.
4218 */
decimalPow2(int N)4219 static Decimal *decimalPow2(int N){
4220   Decimal *pA = 0;      /* The result to be returned */
4221   Decimal *pX = 0;      /* Multiplier */
4222   if( N<-20000 || N>20000 ) goto pow2_fault;
4223   pA = decimalNewFromText("1.0", 3);
4224   if( pA==0 || pA->oom ) goto pow2_fault;
4225   if( N==0 ) return pA;
4226   if( N>0 ){
4227     pX = decimalNewFromText("2.0", 3);
4228   }else{
4229     N = -N;
4230     pX = decimalNewFromText("0.5", 3);
4231   }
4232   if( pX==0 || pX->oom ) goto pow2_fault;
4233   while( 1 /* Exit by break */ ){
4234     if( N & 1 ){
4235       decimalMul(pA, pX);
4236       if( pA->oom ) goto pow2_fault;
4237     }
4238     N >>= 1;
4239     if( N==0 ) break;
4240     decimalMul(pX, pX);
4241   }
4242   decimal_free(pX);
4243   return pA;
4244 
4245 pow2_fault:
4246   decimal_free(pA);
4247   decimal_free(pX);
4248   return 0;
4249 }
4250 
4251 /*
4252 ** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
4253 */
decimalFromDouble(double r)4254 static Decimal *decimalFromDouble(double r){
4255   sqlite3_int64 m, a;
4256   int e;
4257   int isNeg;
4258   Decimal *pA;
4259   Decimal *pX;
4260   char zNum[100];
4261   if( r<0.0 ){
4262     isNeg = 1;
4263     r = -r;
4264   }else{
4265     isNeg = 0;
4266   }
4267   memcpy(&a,&r,sizeof(a));
4268   if( a==0 ){
4269     e = 0;
4270     m = 0;
4271   }else{
4272     e = a>>52;
4273     m = a & ((((sqlite3_int64)1)<<52)-1);
4274     if( e==0 ){
4275       m <<= 1;
4276     }else{
4277       m |= ((sqlite3_int64)1)<<52;
4278     }
4279     while( e<1075 && m>0 && (m&1)==0 ){
4280       m >>= 1;
4281       e++;
4282     }
4283     if( isNeg ) m = -m;
4284     e = e - 1075;
4285     if( e>971 ){
4286       return 0;  /* A NaN or an Infinity */
4287     }
4288   }
4289 
4290   /* At this point m is the integer significand and e is the exponent */
4291   sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
4292   pA = decimalNewFromText(zNum, (int)strlen(zNum));
4293   pX = decimalPow2(e);
4294   decimalMul(pA, pX);
4295   decimal_free(pX);
4296   return pA;
4297 }
4298 
4299 /*
4300 ** SQL Function:   decimal(X)
4301 ** OR:             decimal_exp(X)
4302 **
4303 ** Convert input X into decimal and then back into text.
4304 **
4305 ** If X is originally a float, then a full decimal expansion of that floating
4306 ** point value is done.  Or if X is an 8-byte blob, it is interpreted
4307 ** as a float and similarly expanded.
4308 **
4309 ** The decimal_exp(X) function returns the result in exponential notation.
4310 ** decimal(X) returns a complete decimal, without the e+NNN at the end.
4311 */
decimalFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4312 static void decimalFunc(
4313   sqlite3_context *context,
4314   int argc,
4315   sqlite3_value **argv
4316 ){
4317   Decimal *p =  decimal_new(context, argv[0], 0);
4318   UNUSED_PARAMETER(argc);
4319   if( p ){
4320     if( sqlite3_user_data(context)!=0 ){
4321       decimal_result_sci(context, p);
4322     }else{
4323       decimal_result(context, p);
4324     }
4325     decimal_free(p);
4326   }
4327 }
4328 
4329 /*
4330 ** Compare text in decimal order.
4331 */
decimalCollFunc(void * notUsed,int nKey1,const void * pKey1,int nKey2,const void * pKey2)4332 static int decimalCollFunc(
4333   void *notUsed,
4334   int nKey1, const void *pKey1,
4335   int nKey2, const void *pKey2
4336 ){
4337   const unsigned char *zA = (const unsigned char*)pKey1;
4338   const unsigned char *zB = (const unsigned char*)pKey2;
4339   Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
4340   Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
4341   int rc;
4342   UNUSED_PARAMETER(notUsed);
4343   if( pA==0 || pB==0 ){
4344     rc = 0;
4345   }else{
4346     rc = decimal_cmp(pA, pB);
4347   }
4348   decimal_free(pA);
4349   decimal_free(pB);
4350   return rc;
4351 }
4352 
4353 
4354 /*
4355 ** SQL Function:   decimal_add(X, Y)
4356 **                 decimal_sub(X, Y)
4357 **
4358 ** Return the sum or difference of X and Y.
4359 */
decimalAddFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4360 static void decimalAddFunc(
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   decimal_add(pA, pB);
4369   decimal_result(context, pA);
4370   decimal_free(pA);
4371   decimal_free(pB);
4372 }
decimalSubFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4373 static void decimalSubFunc(
4374   sqlite3_context *context,
4375   int argc,
4376   sqlite3_value **argv
4377 ){
4378   Decimal *pA = decimal_new(context, argv[0], 1);
4379   Decimal *pB = decimal_new(context, argv[1], 1);
4380   UNUSED_PARAMETER(argc);
4381   if( pB ){
4382     pB->sign = !pB->sign;
4383     decimal_add(pA, pB);
4384     decimal_result(context, pA);
4385   }
4386   decimal_free(pA);
4387   decimal_free(pB);
4388 }
4389 
4390 /* Aggregate funcion:   decimal_sum(X)
4391 **
4392 ** Works like sum() except that it uses decimal arithmetic for unlimited
4393 ** precision.
4394 */
decimalSumStep(sqlite3_context * context,int argc,sqlite3_value ** argv)4395 static void decimalSumStep(
4396   sqlite3_context *context,
4397   int argc,
4398   sqlite3_value **argv
4399 ){
4400   Decimal *p;
4401   Decimal *pArg;
4402   UNUSED_PARAMETER(argc);
4403   p = sqlite3_aggregate_context(context, sizeof(*p));
4404   if( p==0 ) return;
4405   if( !p->isInit ){
4406     p->isInit = 1;
4407     p->a = sqlite3_malloc(2);
4408     if( p->a==0 ){
4409       p->oom = 1;
4410     }else{
4411       p->a[0] = 0;
4412     }
4413     p->nDigit = 1;
4414     p->nFrac = 0;
4415   }
4416   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4417   pArg = decimal_new(context, argv[0], 1);
4418   decimal_add(p, pArg);
4419   decimal_free(pArg);
4420 }
decimalSumInverse(sqlite3_context * context,int argc,sqlite3_value ** argv)4421 static void decimalSumInverse(
4422   sqlite3_context *context,
4423   int argc,
4424   sqlite3_value **argv
4425 ){
4426   Decimal *p;
4427   Decimal *pArg;
4428   UNUSED_PARAMETER(argc);
4429   p = sqlite3_aggregate_context(context, sizeof(*p));
4430   if( p==0 ) return;
4431   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4432   pArg = decimal_new(context, argv[0], 1);
4433   if( pArg ) pArg->sign = !pArg->sign;
4434   decimal_add(p, pArg);
4435   decimal_free(pArg);
4436 }
decimalSumValue(sqlite3_context * context)4437 static void decimalSumValue(sqlite3_context *context){
4438   Decimal *p = sqlite3_aggregate_context(context, 0);
4439   if( p==0 ) return;
4440   decimal_result(context, p);
4441 }
decimalSumFinalize(sqlite3_context * context)4442 static void decimalSumFinalize(sqlite3_context *context){
4443   Decimal *p = sqlite3_aggregate_context(context, 0);
4444   if( p==0 ) return;
4445   decimal_result(context, p);
4446   decimal_clear(p);
4447 }
4448 
4449 /*
4450 ** SQL Function:   decimal_mul(X, Y)
4451 **
4452 ** Return the product of X and Y.
4453 */
decimalMulFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4454 static void decimalMulFunc(
4455   sqlite3_context *context,
4456   int argc,
4457   sqlite3_value **argv
4458 ){
4459   Decimal *pA = decimal_new(context, argv[0], 1);
4460   Decimal *pB = decimal_new(context, argv[1], 1);
4461   UNUSED_PARAMETER(argc);
4462   if( pA==0 || pA->oom || pA->isNull
4463    || pB==0 || pB->oom || pB->isNull
4464   ){
4465     goto mul_end;
4466   }
4467   decimalMul(pA, pB);
4468   if( pA->oom ){
4469     goto mul_end;
4470   }
4471   decimal_result(context, pA);
4472 
4473 mul_end:
4474   decimal_free(pA);
4475   decimal_free(pB);
4476 }
4477 
4478 /*
4479 ** SQL Function:   decimal_pow2(N)
4480 **
4481 ** Return the N-th power of 2.  N must be an integer.
4482 */
decimalPow2Func(sqlite3_context * context,int argc,sqlite3_value ** argv)4483 static void decimalPow2Func(
4484   sqlite3_context *context,
4485   int argc,
4486   sqlite3_value **argv
4487 ){
4488   UNUSED_PARAMETER(argc);
4489   if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
4490     Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
4491     decimal_result_sci(context, pA);
4492     decimal_free(pA);
4493   }
4494 }
4495 
4496 #ifdef _WIN32
4497 
4498 #endif
sqlite3_decimal_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)4499 int sqlite3_decimal_init(
4500   sqlite3 *db,
4501   char **pzErrMsg,
4502   const sqlite3_api_routines *pApi
4503 ){
4504   int rc = SQLITE_OK;
4505   static const struct {
4506     const char *zFuncName;
4507     int nArg;
4508     int iArg;
4509     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4510   } aFunc[] = {
4511     { "decimal",       1, 0,  decimalFunc        },
4512     { "decimal_exp",   1, 1,  decimalFunc        },
4513     { "decimal_cmp",   2, 0,  decimalCmpFunc     },
4514     { "decimal_add",   2, 0,  decimalAddFunc     },
4515     { "decimal_sub",   2, 0,  decimalSubFunc     },
4516     { "decimal_mul",   2, 0,  decimalMulFunc     },
4517     { "decimal_pow2",  1, 0,  decimalPow2Func    },
4518   };
4519   unsigned int i;
4520   (void)pzErrMsg;  /* Unused parameter */
4521 
4522   SQLITE_EXTENSION_INIT2(pApi);
4523 
4524   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
4525     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
4526                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4527                    aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
4528   }
4529   if( rc==SQLITE_OK ){
4530     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
4531                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
4532                    decimalSumStep, decimalSumFinalize,
4533                    decimalSumValue, decimalSumInverse, 0);
4534   }
4535   if( rc==SQLITE_OK ){
4536     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
4537                                   0, decimalCollFunc);
4538   }
4539   return rc;
4540 }
4541 
4542 /************************* End ../ext/misc/decimal.c ********************/
4543 #undef sqlite3_base_init
4544 #define sqlite3_base_init sqlite3_base64_init
4545 /************************* Begin ../ext/misc/base64.c ******************/
4546 /*
4547 ** 2022-11-18
4548 **
4549 ** The author disclaims copyright to this source code.  In place of
4550 ** a legal notice, here is a blessing:
4551 **
4552 **    May you do good and not evil.
4553 **    May you find forgiveness for yourself and forgive others.
4554 **    May you share freely, never taking more than you give.
4555 **
4556 *************************************************************************
4557 **
4558 ** This is a SQLite extension for converting in either direction
4559 ** between a (binary) blob and base64 text. Base64 can transit a
4560 ** sane USASCII channel unmolested. It also plays nicely in CSV or
4561 ** written as TCL brace-enclosed literals or SQL string literals,
4562 ** and can be used unmodified in XML-like documents.
4563 **
4564 ** This is an independent implementation of conversions specified in
4565 ** RFC 4648, done on the above date by the author (Larry Brasfield)
4566 ** who thereby has the right to put this into the public domain.
4567 **
4568 ** The conversions meet RFC 4648 requirements, provided that this
4569 ** C source specifies that line-feeds are included in the encoded
4570 ** data to limit visible line lengths to 72 characters and to
4571 ** terminate any encoded blob having non-zero length.
4572 **
4573 ** Length limitations are not imposed except that the runtime
4574 ** SQLite string or blob length limits are respected. Otherwise,
4575 ** any length binary sequence can be represented and recovered.
4576 ** Generated base64 sequences, with their line-feeds included,
4577 ** can be concatenated; the result converted back to binary will
4578 ** be the concatenation of the represented binary sequences.
4579 **
4580 ** This SQLite3 extension creates a function, base64(x), which
4581 ** either: converts text x containing base64 to a returned blob;
4582 ** or converts a blob x to returned text containing base64. An
4583 ** error will be thrown for other input argument types.
4584 **
4585 ** This code relies on UTF-8 encoding only with respect to the
4586 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
4587 ** It will fail miserably if somehow made to try to convert EBCDIC.
4588 ** Because it is table-driven, it could be enhanced to handle that,
4589 ** but the world and SQLite have moved on from that anachronism.
4590 **
4591 ** To build the extension:
4592 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4593 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
4594 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
4595 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
4596 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
4597 */
4598 
4599 #include <assert.h>
4600 
4601 /* #include "sqlite3ext.h" */
4602 
4603 #ifndef deliberate_fall_through
4604 /* Quiet some compilers about some of our intentional code. */
4605 # if GCC_VERSION>=7000000
4606 #  define deliberate_fall_through __attribute__((fallthrough));
4607 # else
4608 #  define deliberate_fall_through
4609 # endif
4610 #endif
4611 
4612 SQLITE_EXTENSION_INIT1;
4613 
4614 #define PC 0x80 /* pad character */
4615 #define WS 0x81 /* whitespace */
4616 #define ND 0x82 /* Not above or digit-value */
4617 #define PAD_CHAR '='
4618 
4619 #ifndef U8_TYPEDEF
4620 /* typedef unsigned char u8; */
4621 #define U8_TYPEDEF
4622 #endif
4623 
4624 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
4625 static const u8 b64DigitValues[128] = {
4626   /*                             HT LF VT  FF CR       */
4627     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
4628   /*                                                US */
4629     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
4630   /*sp                                  +            / */
4631     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
4632   /* 0  1            5            9            =       */
4633     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
4634   /*    A                                            O */
4635     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
4636   /* P                               Z                 */
4637     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
4638   /*    a                                            o */
4639     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
4640   /* p                               z                 */
4641     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
4642 };
4643 
4644 static const char b64Numerals[64+1]
4645 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4646 
4647 #define BX_DV_PROTO(c) \
4648   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
4649 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
4650 #define IS_BX_WS(bdp) ((bdp)==WS)
4651 #define IS_BX_PAD(bdp) ((bdp)==PC)
4652 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
4653 /* Width of base64 lines. Should be an integer multiple of 4. */
4654 #define B64_DARK_MAX 72
4655 
4656 /* Encode a byte buffer into base64 text with linefeeds appended to limit
4657 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
4658 */
toBase64(u8 * pIn,int nbIn,char * pOut)4659 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
4660   int nCol = 0;
4661   while( nbIn >= 3 ){
4662     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
4663     pOut[0] = BX_NUMERAL(pIn[0]>>2);
4664     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
4665     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
4666     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
4667     pOut += 4;
4668     nbIn -= 3;
4669     pIn += 3;
4670     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
4671       *pOut++ = '\n';
4672       nCol = 0;
4673     }
4674   }
4675   if( nbIn > 0 ){
4676     signed char nco = nbIn+1;
4677     int nbe;
4678     unsigned long qv = *pIn++;
4679     for( nbe=1; nbe<3; ++nbe ){
4680       qv <<= 8;
4681       if( nbe<nbIn ) qv |= *pIn++;
4682     }
4683     for( nbe=3; nbe>=0; --nbe ){
4684       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
4685       qv >>= 6;
4686       pOut[nbe] = ce;
4687     }
4688     pOut += 4;
4689     *pOut++ = '\n';
4690   }
4691   *pOut = 0;
4692   return pOut;
4693 }
4694 
4695 /* Skip over text which is not base64 numeral(s). */
skipNonB64(char * s,int nc)4696 static char * skipNonB64( char *s, int nc ){
4697   char c;
4698   while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
4699   return s;
4700 }
4701 
4702 /* Decode base64 text into a byte buffer. */
fromBase64(char * pIn,int ncIn,u8 * pOut)4703 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
4704   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
4705   while( ncIn>0 && *pIn!=PAD_CHAR ){
4706     static signed char nboi[] = { 0, 0, 1, 2, 3 };
4707     char *pUse = skipNonB64(pIn, ncIn);
4708     unsigned long qv = 0L;
4709     int nti, nbo, nac;
4710     ncIn -= (pUse - pIn);
4711     pIn = pUse;
4712     nti = (ncIn>4)? 4 : ncIn;
4713     ncIn -= nti;
4714     nbo = nboi[nti];
4715     if( nbo==0 ) break;
4716     for( nac=0; nac<4; ++nac ){
4717       char c = (nac<nti)? *pIn++ : b64Numerals[0];
4718       u8 bdp = BX_DV_PROTO(c);
4719       switch( bdp ){
4720       case ND:
4721         /*  Treat dark non-digits as pad, but they terminate decode too. */
4722         ncIn = 0;
4723         deliberate_fall_through;
4724       case WS:
4725         /* Treat whitespace as pad and terminate this group.*/
4726         nti = nac;
4727         deliberate_fall_through;
4728       case PC:
4729         bdp = 0;
4730         --nbo;
4731         deliberate_fall_through;
4732       default: /* bdp is the digit value. */
4733         qv = qv<<6 | bdp;
4734         break;
4735       }
4736     }
4737     switch( nbo ){
4738     case 3:
4739       pOut[2] = (qv) & 0xff;
4740     case 2:
4741       pOut[1] = (qv>>8) & 0xff;
4742     case 1:
4743       pOut[0] = (qv>>16) & 0xff;
4744     }
4745     pOut += nbo;
4746   }
4747   return pOut;
4748 }
4749 
4750 /* This function does the work for the SQLite base64(x) UDF. */
base64(sqlite3_context * context,int na,sqlite3_value * av[])4751 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
4752   int nb, nc, nv = sqlite3_value_bytes(av[0]);
4753   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
4754                             SQLITE_LIMIT_LENGTH, -1);
4755   char *cBuf;
4756   u8 *bBuf;
4757   assert(na==1);
4758   switch( sqlite3_value_type(av[0]) ){
4759   case SQLITE_BLOB:
4760     nb = nv;
4761     nc = 4*(nv+2/3); /* quads needed */
4762     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
4763     if( nvMax < nc ){
4764       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
4765       return;
4766     }
4767     bBuf = (u8*)sqlite3_value_blob(av[0]);
4768     if( !bBuf ){
4769       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4770         goto memFail;
4771       }
4772       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
4773       break;
4774     }
4775     cBuf = sqlite3_malloc(nc);
4776     if( !cBuf ) goto memFail;
4777     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
4778     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
4779     break;
4780   case SQLITE_TEXT:
4781     nc = nv;
4782     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
4783     if( nvMax < nb ){
4784       sqlite3_result_error(context, "blob from base64 may be too big", -1);
4785       return;
4786     }else if( nb<1 ){
4787       nb = 1;
4788     }
4789     cBuf = (char *)sqlite3_value_text(av[0]);
4790     if( !cBuf ){
4791       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4792         goto memFail;
4793       }
4794       sqlite3_result_zeroblob(context, 0);
4795       break;
4796     }
4797     bBuf = sqlite3_malloc(nb);
4798     if( !bBuf ) goto memFail;
4799     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
4800     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
4801     break;
4802   default:
4803     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
4804     return;
4805   }
4806   return;
4807  memFail:
4808   sqlite3_result_error(context, "base64 OOM", -1);
4809 }
4810 
4811 /*
4812 ** Establish linkage to running SQLite library.
4813 */
4814 #ifndef SQLITE_SHELL_EXTFUNCS
4815 #ifdef _WIN32
4816 
4817 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)4818 int sqlite3_base_init
4819 #else
4820 static int sqlite3_base64_init
4821 #endif
4822 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
4823   SQLITE_EXTENSION_INIT2(pApi);
4824   (void)pzErr;
4825   return sqlite3_create_function
4826     (db, "base64", 1,
4827      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
4828      0, base64, 0, 0);
4829 }
4830 
4831 /*
4832 ** Define some macros to allow this extension to be built into the shell
4833 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
4834 ** allows shell.c, as distributed, to have this extension built in.
4835 */
4836 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
4837 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
4838 
4839 /************************* End ../ext/misc/base64.c ********************/
4840 #undef sqlite3_base_init
4841 #define sqlite3_base_init sqlite3_base85_init
4842 #define OMIT_BASE85_CHECKER
4843 /************************* Begin ../ext/misc/base85.c ******************/
4844 /*
4845 ** 2022-11-16
4846 **
4847 ** The author disclaims copyright to this source code.  In place of
4848 ** a legal notice, here is a blessing:
4849 **
4850 **    May you do good and not evil.
4851 **    May you find forgiveness for yourself and forgive others.
4852 **    May you share freely, never taking more than you give.
4853 **
4854 *************************************************************************
4855 **
4856 ** This is a utility for converting binary to base85 or vice-versa.
4857 ** It can be built as a standalone program or an SQLite3 extension.
4858 **
4859 ** Much like base64 representations, base85 can be sent through a
4860 ** sane USASCII channel unmolested. It also plays nicely in CSV or
4861 ** written as TCL brace-enclosed literals or SQL string literals.
4862 ** It is not suited for unmodified use in XML-like documents.
4863 **
4864 ** The encoding used resembles Ascii85, but was devised by the author
4865 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
4866 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
4867 ** Further, this is an independent implementation of a base85 system.
4868 ** Hence, the author has rightfully put this into the public domain.
4869 **
4870 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
4871 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
4872 ** in code order representing digit values 0 to 84 (base 10.)
4873 **
4874 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4875 ** are represented as 5-digit base85 numbers with MS to LS digit
4876 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
4877 ** still big-endian but 8-24 bit values. (Using big-endian yields
4878 ** the simplest transition to byte groups smaller than 4 bytes.
4879 ** These byte groups can also be considered base-256 numbers.)
4880 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
4881 ** No pad characters are used; Encoded base85 numeral sequence
4882 ** (aka "group") length maps 1-to-1 to the decoded binary length.
4883 **
4884 ** Any character not in the base85 numeral set delimits groups.
4885 ** When base85 is streamed or stored in containers of indefinite
4886 ** size, newline is used to separate it into sub-sequences of no
4887 ** more than 80 digits so that fgets() can be used to read it.
4888 **
4889 ** Length limitations are not imposed except that the runtime
4890 ** SQLite string or blob length limits are respected. Otherwise,
4891 ** any length binary sequence can be represented and recovered.
4892 ** Base85 sequences can be concatenated by separating them with
4893 ** a non-base85 character; the conversion to binary will then
4894 ** be the concatenation of the represented binary sequences.
4895 
4896 ** The standalone program either converts base85 on stdin to create
4897 ** a binary file or converts a binary file to base85 on stdout.
4898 ** Read or make it blurt its help for invocation details.
4899 **
4900 ** The SQLite3 extension creates a function, base85(x), which will
4901 ** either convert text base85 to a blob or a blob to text base85
4902 ** and return the result (or throw an error for other types.)
4903 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
4904 ** function, is_base85(t), which returns 1 iff the text t contains
4905 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
4906 **
4907 ** To build the extension:
4908 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4909 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4910 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4911 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4912 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4913 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4914 **
4915 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
4916 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4917 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4918 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4919 */
4920 
4921 #include <stdio.h>
4922 #include <memory.h>
4923 #include <string.h>
4924 #include <assert.h>
4925 #ifndef OMIT_BASE85_CHECKER
4926 # include <ctype.h>
4927 #endif
4928 
4929 #ifndef BASE85_STANDALONE
4930 
4931 /* # include "sqlite3ext.h" */
4932 
4933 SQLITE_EXTENSION_INIT1;
4934 
4935 #else
4936 
4937 # ifdef _WIN32
4938 #  include <io.h>
4939 #  include <fcntl.h>
4940 # else
4941 #  define setmode(fd,m)
4942 # endif
4943 
4944 static char *zHelp =
4945   "Usage: base85 <dirFlag> <binFile>\n"
4946   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4947   "   content to be converted to/from base85 on stdout/stdin.\n"
4948   " <binFile> names a binary file to be rendered or created.\n"
4949   "   Or, the name '-' refers to the stdin or stdout stream.\n"
4950   ;
4951 
sayHelp()4952 static void sayHelp(){
4953   printf("%s", zHelp);
4954 }
4955 #endif
4956 
4957 #ifndef U8_TYPEDEF
4958 /* typedef unsigned char u8; */
4959 #define U8_TYPEDEF
4960 #endif
4961 
4962 /* Classify c according to interval within USASCII set w.r.t. base85
4963  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
4964  */
4965 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
4966 
4967 /* Provide digitValue to b85Numeral offset as a function of above class. */
4968 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4969 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
4970 
4971 /* Say whether c is a base85 numeral. */
4972 #define IS_B85( c ) (B85_CLASS(c) & 1)
4973 
4974 #if 0 /* Not used, */
4975 static u8 base85DigitValue( char c ){
4976   u8 dv = (u8)(c - '#');
4977   if( dv>87 ) return 0xff;
4978   return (dv > 3)? dv-3 : dv;
4979 }
4980 #endif
4981 
4982 /* Width of base64 lines. Should be an integer multiple of 5. */
4983 #define B85_DARK_MAX 80
4984 
4985 
skipNonB85(char * s,int nc)4986 static char * skipNonB85( char *s, int nc ){
4987   char c;
4988   while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
4989   return s;
4990 }
4991 
4992 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
4993  * Do not use the macro form with argument expression having a side-effect.*/
4994 #if 0
4995 static char base85Numeral( u8 b ){
4996   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
4997 }
4998 #else
4999 # define base85Numeral( dn )\
5000   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
5001 #endif
5002 
putcs(char * pc,char * s)5003 static char *putcs(char *pc, char *s){
5004   char c;
5005   while( (c = *s++)!=0 ) *pc++ = c;
5006   return pc;
5007 }
5008 
5009 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
5010 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
5011 ** or to terminate the last group (to aid concatenation.)
5012 */
toBase85(u8 * pIn,int nbIn,char * pOut,char * pSep)5013 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
5014   int nCol = 0;
5015   while( nbIn >= 4 ){
5016     int nco = 5;
5017     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
5018                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
5019     while( nco > 0 ){
5020       unsigned nqv = (unsigned)(qbv/85UL);
5021       unsigned char dv = qbv - 85UL*nqv;
5022       qbv = nqv;
5023       pOut[--nco] = base85Numeral(dv);
5024     }
5025     nbIn -= 4;
5026     pIn += 4;
5027     pOut += 5;
5028     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
5029       pOut = putcs(pOut, pSep);
5030       nCol = 0;
5031     }
5032   }
5033   if( nbIn > 0 ){
5034     int nco = nbIn + 1;
5035     unsigned long qv = *pIn++;
5036     int nbe = 1;
5037     while( nbe++ < nbIn ){
5038       qv = (qv<<8) | *pIn++;
5039     }
5040     nCol += nco;
5041     while( nco > 0 ){
5042       u8 dv = (u8)(qv % 85);
5043       qv /= 85;
5044       pOut[--nco] = base85Numeral(dv);
5045     }
5046     pOut += (nbIn+1);
5047   }
5048   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
5049   *pOut = 0;
5050   return pOut;
5051 }
5052 
5053 /* Decode base85 text into a byte buffer. */
fromBase85(char * pIn,int ncIn,u8 * pOut)5054 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
5055   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
5056   while( ncIn>0 ){
5057     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
5058     char *pUse = skipNonB85(pIn, ncIn);
5059     unsigned long qv = 0L;
5060     int nti, nbo;
5061     ncIn -= (pUse - pIn);
5062     pIn = pUse;
5063     nti = (ncIn>5)? 5 : ncIn;
5064     nbo = nboi[nti];
5065     if( nbo==0 ) break;
5066     while( nti>0 ){
5067       char c = *pIn++;
5068       u8 cdo = B85_DNOS(c);
5069       --ncIn;
5070       if( cdo==0 ) break;
5071       qv = 85 * qv + (c - cdo);
5072       --nti;
5073     }
5074     nbo -= nti; /* Adjust for early (non-digit) end of group. */
5075     switch( nbo ){
5076     case 4:
5077       *pOut++ = (qv >> 24)&0xff;
5078     case 3:
5079       *pOut++ = (qv >> 16)&0xff;
5080     case 2:
5081       *pOut++ = (qv >> 8)&0xff;
5082     case 1:
5083       *pOut++ = qv&0xff;
5084     case 0:
5085       break;
5086     }
5087   }
5088   return pOut;
5089 }
5090 
5091 #ifndef OMIT_BASE85_CHECKER
5092 /* Say whether input char sequence is all (base85 and/or whitespace).*/
allBase85(char * p,int len)5093 static int allBase85( char *p, int len ){
5094   char c;
5095   while( len-- > 0 && (c = *p++) != 0 ){
5096     if( !IS_B85(c) && !isspace(c) ) return 0;
5097   }
5098   return 1;
5099 }
5100 #endif
5101 
5102 #ifndef BASE85_STANDALONE
5103 
5104 # ifndef OMIT_BASE85_CHECKER
5105 /* This function does the work for the SQLite is_base85(t) UDF. */
is_base85(sqlite3_context * context,int na,sqlite3_value * av[])5106 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5107   assert(na==1);
5108   switch( sqlite3_value_type(av[0]) ){
5109   case SQLITE_TEXT:
5110     {
5111       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
5112                           sqlite3_value_bytes(av[0]) );
5113       sqlite3_result_int(context, rv);
5114     }
5115     break;
5116   case SQLITE_NULL:
5117     sqlite3_result_null(context);
5118     break;
5119   default:
5120     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
5121     return;
5122   }
5123 }
5124 # endif
5125 
5126 /* This function does the work for the SQLite base85(x) UDF. */
base85(sqlite3_context * context,int na,sqlite3_value * av[])5127 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5128   int nb, nc, nv = sqlite3_value_bytes(av[0]);
5129   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
5130                             SQLITE_LIMIT_LENGTH, -1);
5131   char *cBuf;
5132   u8 *bBuf;
5133   assert(na==1);
5134   switch( sqlite3_value_type(av[0]) ){
5135   case SQLITE_BLOB:
5136     nb = nv;
5137     /*    ulongs    tail   newlines  tailenc+nul*/
5138     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
5139     if( nvMax < nc ){
5140       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
5141       return;
5142     }
5143     bBuf = (u8*)sqlite3_value_blob(av[0]);
5144     if( !bBuf ){
5145       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5146         goto memFail;
5147       }
5148       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
5149       break;
5150     }
5151     cBuf = sqlite3_malloc(nc);
5152     if( !cBuf ) goto memFail;
5153     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
5154     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
5155     break;
5156   case SQLITE_TEXT:
5157     nc = nv;
5158     nb = 4*(nv/5) + nv%5; /* may overestimate */
5159     if( nvMax < nb ){
5160       sqlite3_result_error(context, "blob from base85 may be too big", -1);
5161       return;
5162     }else if( nb<1 ){
5163       nb = 1;
5164     }
5165     cBuf = (char *)sqlite3_value_text(av[0]);
5166     if( !cBuf ){
5167       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5168         goto memFail;
5169       }
5170       sqlite3_result_zeroblob(context, 0);
5171       break;
5172     }
5173     bBuf = sqlite3_malloc(nb);
5174     if( !bBuf ) goto memFail;
5175     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
5176     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
5177     break;
5178   default:
5179     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
5180     return;
5181   }
5182   return;
5183  memFail:
5184   sqlite3_result_error(context, "base85 OOM", -1);
5185 }
5186 
5187 /*
5188 ** Establish linkage to running SQLite library.
5189 */
5190 #ifndef SQLITE_SHELL_EXTFUNCS
5191 #ifdef _WIN32
5192 
5193 #endif
sqlite3_base_init(sqlite3 * db,char ** pzErr,const sqlite3_api_routines * pApi)5194 int sqlite3_base_init
5195 #else
5196 static int sqlite3_base85_init
5197 #endif
5198 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
5199   SQLITE_EXTENSION_INIT2(pApi);
5200   (void)pzErr;
5201 # ifndef OMIT_BASE85_CHECKER
5202   {
5203     int rc = sqlite3_create_function
5204       (db, "is_base85", 1,
5205        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
5206        0, is_base85, 0, 0);
5207     if( rc!=SQLITE_OK ) return rc;
5208   }
5209 # endif
5210   return sqlite3_create_function
5211     (db, "base85", 1,
5212      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
5213      0, base85, 0, 0);
5214 }
5215 
5216 /*
5217 ** Define some macros to allow this extension to be built into the shell
5218 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
5219 ** allows shell.c, as distributed, to have this extension built in.
5220 */
5221 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
5222 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
5223 
5224 #else /* standalone program */
5225 
main(int na,char * av[])5226 int main(int na, char *av[]){
5227   int cin;
5228   int rc = 0;
5229   u8 bBuf[4*(B85_DARK_MAX/5)];
5230   char cBuf[5*(sizeof(bBuf)/4)+2];
5231   size_t nio;
5232 # ifndef OMIT_BASE85_CHECKER
5233   int b85Clean = 1;
5234 # endif
5235   char rw;
5236   FILE *fb = 0, *foc = 0;
5237   char fmode[3] = "xb";
5238   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
5239     sayHelp();
5240     return 0;
5241   }
5242   fmode[0] = rw;
5243   if( av[2][0]=='-' && av[2][1]==0 ){
5244     switch( rw ){
5245     case 'r':
5246       fb = stdin;
5247       setmode(fileno(stdin), O_BINARY);
5248       break;
5249     case 'w':
5250       fb = stdout;
5251       setmode(fileno(stdout), O_BINARY);
5252       break;
5253     }
5254   }else{
5255     fb = fopen(av[2], fmode);
5256     foc = fb;
5257   }
5258   if( !fb ){
5259     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
5260     rc = 1;
5261   }else{
5262     switch( rw ){
5263     case 'r':
5264       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
5265         toBase85( bBuf, (int)nio, cBuf, 0 );
5266         fprintf(stdout, "%s\n", cBuf);
5267       }
5268       break;
5269     case 'w':
5270       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
5271         int nc = strlen(cBuf);
5272         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
5273         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
5274 # ifndef OMIT_BASE85_CHECKER
5275         b85Clean &= allBase85( cBuf, nc );
5276 # endif
5277       }
5278       break;
5279     default:
5280       sayHelp();
5281       rc = 1;
5282     }
5283     if( foc ) fclose(foc);
5284   }
5285 # ifndef OMIT_BASE85_CHECKER
5286   if( !b85Clean ){
5287     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
5288   }
5289 # endif
5290   return rc;
5291 }
5292 
5293 #endif
5294 
5295 /************************* End ../ext/misc/base85.c ********************/
5296 /************************* Begin ../ext/misc/ieee754.c ******************/
5297 /*
5298 ** 2013-04-17
5299 **
5300 ** The author disclaims copyright to this source code.  In place of
5301 ** a legal notice, here is a blessing:
5302 **
5303 **    May you do good and not evil.
5304 **    May you find forgiveness for yourself and forgive others.
5305 **    May you share freely, never taking more than you give.
5306 **
5307 ******************************************************************************
5308 **
5309 ** This SQLite extension implements functions for the exact display
5310 ** and input of IEEE754 Binary64 floating-point numbers.
5311 **
5312 **   ieee754(X)
5313 **   ieee754(Y,Z)
5314 **
5315 ** In the first form, the value X should be a floating-point number.
5316 ** The function will return a string of the form 'ieee754(Y,Z)' where
5317 ** Y and Z are integers such that X==Y*pow(2,Z).
5318 **
5319 ** In the second form, Y and Z are integers which are the mantissa and
5320 ** base-2 exponent of a new floating point number.  The function returns
5321 ** a floating-point value equal to Y*pow(2,Z).
5322 **
5323 ** Examples:
5324 **
5325 **     ieee754(2.0)             ->     'ieee754(2,0)'
5326 **     ieee754(45.25)           ->     'ieee754(181,-2)'
5327 **     ieee754(2, 0)            ->     2.0
5328 **     ieee754(181, -2)         ->     45.25
5329 **
5330 ** Two additional functions break apart the one-argument ieee754()
5331 ** result into separate integer values:
5332 **
5333 **     ieee754_mantissa(45.25)  ->     181
5334 **     ieee754_exponent(45.25)  ->     -2
5335 **
5336 ** These functions convert binary64 numbers into blobs and back again.
5337 **
5338 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5339 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5340 **
5341 ** In all single-argument functions, if the argument is an 8-byte blob
5342 ** then that blob is interpreted as a big-endian binary64 value.
5343 **
5344 **
5345 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5346 ** -----------------------------------------------
5347 **
5348 ** This extension in combination with the separate 'decimal' extension
5349 ** can be used to compute the exact decimal representation of binary64
5350 ** values.  To begin, first compute a table of exponent values:
5351 **
5352 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5353 **    WITH RECURSIVE c(x,v) AS (
5354 **      VALUES(0,'1')
5355 **      UNION ALL
5356 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5357 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5358 **    WITH RECURSIVE c(x,v) AS (
5359 **      VALUES(-1,'0.5')
5360 **      UNION ALL
5361 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5362 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5363 **
5364 ** Then, to compute the exact decimal representation of a floating
5365 ** point value (the value 47.49 is used in the example) do:
5366 **
5367 **    WITH c(n) AS (VALUES(47.49))
5368 **          ---------------^^^^^---- Replace with whatever you want
5369 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5370 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5371 **
5372 ** Here is a query to show various boundry values for the binary64
5373 ** number format:
5374 **
5375 **    WITH c(name,bin) AS (VALUES
5376 **       ('minimum positive value',        x'0000000000000001'),
5377 **       ('maximum subnormal value',       x'000fffffffffffff'),
5378 **       ('mininum positive nornal value', x'0010000000000000'),
5379 **       ('maximum value',                 x'7fefffffffffffff'))
5380 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5381 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5382 **
5383 */
5384 /* #include "sqlite3ext.h" */
5385 SQLITE_EXTENSION_INIT1
5386 #include <assert.h>
5387 #include <string.h>
5388 
5389 /* Mark a function parameter as unused, to suppress nuisance compiler
5390 ** warnings. */
5391 #ifndef UNUSED_PARAMETER
5392 # define UNUSED_PARAMETER(X)  (void)(X)
5393 #endif
5394 
5395 /*
5396 ** Implementation of the ieee754() function
5397 */
ieee754func(sqlite3_context * context,int argc,sqlite3_value ** argv)5398 static void ieee754func(
5399   sqlite3_context *context,
5400   int argc,
5401   sqlite3_value **argv
5402 ){
5403   if( argc==1 ){
5404     sqlite3_int64 m, a;
5405     double r;
5406     int e;
5407     int isNeg;
5408     char zResult[100];
5409     assert( sizeof(m)==sizeof(r) );
5410     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5411      && sqlite3_value_bytes(argv[0])==sizeof(r)
5412     ){
5413       const unsigned char *x = sqlite3_value_blob(argv[0]);
5414       unsigned int i;
5415       sqlite3_uint64 v = 0;
5416       for(i=0; i<sizeof(r); i++){
5417         v = (v<<8) | x[i];
5418       }
5419       memcpy(&r, &v, sizeof(r));
5420     }else{
5421       r = sqlite3_value_double(argv[0]);
5422     }
5423     if( r<0.0 ){
5424       isNeg = 1;
5425       r = -r;
5426     }else{
5427       isNeg = 0;
5428     }
5429     memcpy(&a,&r,sizeof(a));
5430     if( a==0 ){
5431       e = 0;
5432       m = 0;
5433     }else{
5434       e = a>>52;
5435       m = a & ((((sqlite3_int64)1)<<52)-1);
5436       if( e==0 ){
5437         m <<= 1;
5438       }else{
5439         m |= ((sqlite3_int64)1)<<52;
5440       }
5441       while( e<1075 && m>0 && (m&1)==0 ){
5442         m >>= 1;
5443         e++;
5444       }
5445       if( isNeg ) m = -m;
5446     }
5447     switch( *(int*)sqlite3_user_data(context) ){
5448       case 0:
5449         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5450                          m, e-1075);
5451         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5452         break;
5453       case 1:
5454         sqlite3_result_int64(context, m);
5455         break;
5456       case 2:
5457         sqlite3_result_int(context, e-1075);
5458         break;
5459     }
5460   }else{
5461     sqlite3_int64 m, e, a;
5462     double r;
5463     int isNeg = 0;
5464     m = sqlite3_value_int64(argv[0]);
5465     e = sqlite3_value_int64(argv[1]);
5466 
5467     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
5468     if( e>10000 ){
5469       e = 10000;
5470     }else if( e<-10000 ){
5471       e = -10000;
5472     }
5473 
5474     if( m<0 ){
5475       isNeg = 1;
5476       m = -m;
5477       if( m<0 ) return;
5478     }else if( m==0 && e>-1000 && e<1000 ){
5479       sqlite3_result_double(context, 0.0);
5480       return;
5481     }
5482     while( (m>>32)&0xffe00000 ){
5483       m >>= 1;
5484       e++;
5485     }
5486     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5487       m <<= 1;
5488       e--;
5489     }
5490     e += 1075;
5491     if( e<=0 ){
5492       /* Subnormal */
5493       if( 1-e >= 64 ){
5494         m = 0;
5495       }else{
5496         m >>= 1-e;
5497       }
5498       e = 0;
5499     }else if( e>0x7ff ){
5500       e = 0x7ff;
5501     }
5502     a = m & ((((sqlite3_int64)1)<<52)-1);
5503     a |= e<<52;
5504     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5505     memcpy(&r, &a, sizeof(r));
5506     sqlite3_result_double(context, r);
5507   }
5508 }
5509 
5510 /*
5511 ** Functions to convert between blobs and floats.
5512 */
ieee754func_from_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5513 static void ieee754func_from_blob(
5514   sqlite3_context *context,
5515   int argc,
5516   sqlite3_value **argv
5517 ){
5518   UNUSED_PARAMETER(argc);
5519   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5520    && sqlite3_value_bytes(argv[0])==sizeof(double)
5521   ){
5522     double r;
5523     const unsigned char *x = sqlite3_value_blob(argv[0]);
5524     unsigned int i;
5525     sqlite3_uint64 v = 0;
5526     for(i=0; i<sizeof(r); i++){
5527       v = (v<<8) | x[i];
5528     }
5529     memcpy(&r, &v, sizeof(r));
5530     sqlite3_result_double(context, r);
5531   }
5532 }
ieee754func_to_blob(sqlite3_context * context,int argc,sqlite3_value ** argv)5533 static void ieee754func_to_blob(
5534   sqlite3_context *context,
5535   int argc,
5536   sqlite3_value **argv
5537 ){
5538   UNUSED_PARAMETER(argc);
5539   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5540    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5541   ){
5542     double r = sqlite3_value_double(argv[0]);
5543     sqlite3_uint64 v;
5544     unsigned char a[sizeof(r)];
5545     unsigned int i;
5546     memcpy(&v, &r, sizeof(r));
5547     for(i=1; i<=sizeof(r); i++){
5548       a[sizeof(r)-i] = v&0xff;
5549       v >>= 8;
5550     }
5551     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5552   }
5553 }
5554 
5555 /*
5556 ** SQL Function:   ieee754_inc(r,N)
5557 **
5558 ** Move the floating point value r by N quantums and return the new
5559 ** values.
5560 **
5561 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
5562 ** integer, adds N, then casts the value back into float.
5563 **
5564 ** Example:  To find the smallest positive number:
5565 **
5566 **     SELECT ieee754_inc(0.0,+1);
5567 */
ieee754inc(sqlite3_context * context,int argc,sqlite3_value ** argv)5568 static void ieee754inc(
5569   sqlite3_context *context,
5570   int argc,
5571   sqlite3_value **argv
5572 ){
5573   double r;
5574   sqlite3_int64 N;
5575   sqlite3_uint64 m1, m2;
5576   double r2;
5577   UNUSED_PARAMETER(argc);
5578   r = sqlite3_value_double(argv[0]);
5579   N = sqlite3_value_int64(argv[1]);
5580   memcpy(&m1, &r, 8);
5581   m2 = m1 + N;
5582   memcpy(&r2, &m2, 8);
5583   sqlite3_result_double(context, r2);
5584 }
5585 
5586 
5587 #ifdef _WIN32
5588 
5589 #endif
sqlite3_ieee_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)5590 int sqlite3_ieee_init(
5591   sqlite3 *db,
5592   char **pzErrMsg,
5593   const sqlite3_api_routines *pApi
5594 ){
5595   static const struct {
5596     char *zFName;
5597     int nArg;
5598     int iAux;
5599     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5600   } aFunc[] = {
5601     { "ieee754",           1,   0, ieee754func },
5602     { "ieee754",           2,   0, ieee754func },
5603     { "ieee754_mantissa",  1,   1, ieee754func },
5604     { "ieee754_exponent",  1,   2, ieee754func },
5605     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5606     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5607     { "ieee754_inc",       2,   0, ieee754inc  },
5608   };
5609   unsigned int i;
5610   int rc = SQLITE_OK;
5611   SQLITE_EXTENSION_INIT2(pApi);
5612   (void)pzErrMsg;  /* Unused parameter */
5613   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5614     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
5615                                SQLITE_UTF8|SQLITE_INNOCUOUS,
5616                                (void*)&aFunc[i].iAux,
5617                                aFunc[i].xFunc, 0, 0);
5618   }
5619   return rc;
5620 }
5621 
5622 /************************* End ../ext/misc/ieee754.c ********************/
5623 /************************* Begin ../ext/misc/series.c ******************/
5624 /*
5625 ** 2015-08-18, 2023-04-28
5626 **
5627 ** The author disclaims copyright to this source code.  In place of
5628 ** a legal notice, here is a blessing:
5629 **
5630 **    May you do good and not evil.
5631 **    May you find forgiveness for yourself and forgive others.
5632 **    May you share freely, never taking more than you give.
5633 **
5634 *************************************************************************
5635 **
5636 ** This file demonstrates how to create a table-valued-function using
5637 ** a virtual table.  This demo implements the generate_series() function
5638 ** which gives the same results as the eponymous function in PostgreSQL,
5639 ** within the limitation that its arguments are signed 64-bit integers.
5640 **
5641 ** Considering its equivalents to generate_series(start,stop,step): A
5642 ** value V[n] sequence is produced for integer n ascending from 0 where
5643 **  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
5644 ** for each produced value (independent of production time ordering.)
5645 **
5646 ** All parameters must be either integer or convertable to integer.
5647 ** The start parameter is required.
5648 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
5649 ** The step parameter defaults to 1 and 0 is treated as 1.
5650 **
5651 ** Examples:
5652 **
5653 **      SELECT * FROM generate_series(0,100,5);
5654 **
5655 ** The query above returns integers from 0 through 100 counting by steps
5656 ** of 5.
5657 **
5658 **      SELECT * FROM generate_series(0,100);
5659 **
5660 ** Integers from 0 through 100 with a step size of 1.
5661 **
5662 **      SELECT * FROM generate_series(20) LIMIT 10;
5663 **
5664 ** Integers 20 through 29.
5665 **
5666 **      SELECT * FROM generate_series(0,-100,-5);
5667 **
5668 ** Integers 0 -5 -10 ... -100.
5669 **
5670 **      SELECT * FROM generate_series(0,-1);
5671 **
5672 ** Empty sequence.
5673 **
5674 ** HOW IT WORKS
5675 **
5676 ** The generate_series "function" is really a virtual table with the
5677 ** following schema:
5678 **
5679 **     CREATE TABLE generate_series(
5680 **       value,
5681 **       start HIDDEN,
5682 **       stop HIDDEN,
5683 **       step HIDDEN
5684 **     );
5685 **
5686 ** The virtual table also has a rowid, logically equivalent to n+1 where
5687 ** "n" is the ascending integer in the aforesaid production definition.
5688 **
5689 ** Function arguments in queries against this virtual table are translated
5690 ** into equality constraints against successive hidden columns.  In other
5691 ** words, the following pairs of queries are equivalent to each other:
5692 **
5693 **    SELECT * FROM generate_series(0,100,5);
5694 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5695 **
5696 **    SELECT * FROM generate_series(0,100);
5697 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5698 **
5699 **    SELECT * FROM generate_series(20) LIMIT 10;
5700 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5701 **
5702 ** The generate_series virtual table implementation leaves the xCreate method
5703 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5704 ** TABLE command with "generate_series" as the USING argument.  Instead, there
5705 ** is a single generate_series virtual table that is always available without
5706 ** having to be created first.
5707 **
5708 ** The xBestIndex method looks for equality constraints against the hidden
5709 ** start, stop, and step columns, and if present, it uses those constraints
5710 ** to bound the sequence of generated values.  If the equality constraints
5711 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5712 ** xBestIndex returns a small cost when both start and stop are available,
5713 ** and a very large cost if either start or stop are unavailable.  This
5714 ** encourages the query planner to order joins such that the bounds of the
5715 ** series are well-defined.
5716 */
5717 /* #include "sqlite3ext.h" */
5718 SQLITE_EXTENSION_INIT1
5719 #include <assert.h>
5720 #include <string.h>
5721 #include <limits.h>
5722 
5723 #ifndef SQLITE_OMIT_VIRTUALTABLE
5724 /*
5725 ** Return that member of a generate_series(...) sequence whose 0-based
5726 ** index is ix. The 0th member is given by smBase. The sequence members
5727 ** progress per ix increment by smStep.
5728 */
genSeqMember(sqlite3_int64 smBase,sqlite3_int64 smStep,sqlite3_uint64 ix)5729 static sqlite3_int64 genSeqMember(
5730   sqlite3_int64 smBase,
5731   sqlite3_int64 smStep,
5732   sqlite3_uint64 ix
5733 ){
5734   static const sqlite3_uint64 mxI64 =
5735       ((sqlite3_uint64)0x7fffffff)<<32 | 0xffffffff;
5736   if( ix>=mxI64 ){
5737     /* Get ix into signed i64 range. */
5738     ix -= mxI64;
5739     /* With 2's complement ALU, this next can be 1 step, but is split into
5740      * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
5741     smBase += (mxI64/2) * smStep;
5742     smBase += (mxI64 - mxI64/2) * smStep;
5743   }
5744   /* Under UBSAN (or on 1's complement machines), must do this last term
5745    * in steps to avoid the dreaded (and harmless) signed multiply overlow. */
5746   if( ix>=2 ){
5747     sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
5748     smBase += ix2*smStep;
5749     ix -= ix2;
5750   }
5751   return smBase + ((sqlite3_int64)ix)*smStep;
5752 }
5753 
5754 /* typedef unsigned char u8; */
5755 
5756 typedef struct SequenceSpec {
5757   sqlite3_int64 iBase;         /* Starting value ("start") */
5758   sqlite3_int64 iTerm;         /* Given terminal value ("stop") */
5759   sqlite3_int64 iStep;         /* Increment ("step") */
5760   sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
5761   sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
5762   sqlite3_int64 iValueNow;     /* Current value during generation */
5763   u8 isNotEOF;                 /* Sequence generation not exhausted */
5764   u8 isReversing;              /* Sequence is being reverse generated */
5765 } SequenceSpec;
5766 
5767 /*
5768 ** Prepare a SequenceSpec for use in generating an integer series
5769 ** given initialized iBase, iTerm and iStep values. Sequence is
5770 ** initialized per given isReversing. Other members are computed.
5771 */
setupSequence(SequenceSpec * pss)5772 static void setupSequence( SequenceSpec *pss ){
5773   int bSameSigns;
5774   pss->uSeqIndexMax = 0;
5775   pss->isNotEOF = 0;
5776   bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
5777   if( pss->iTerm < pss->iBase ){
5778     sqlite3_uint64 nuspan = 0;
5779     if( bSameSigns ){
5780       nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
5781     }else{
5782       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5783        * In this clause, iBase>=0 and iTerm<0 . */
5784       nuspan = 1;
5785       nuspan += pss->iBase;
5786       nuspan += -(pss->iTerm+1);
5787     }
5788     if( pss->iStep<0 ){
5789       pss->isNotEOF = 1;
5790       if( nuspan==ULONG_MAX ){
5791         pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
5792       }else if( pss->iStep>LLONG_MIN ){
5793         pss->uSeqIndexMax = nuspan/-pss->iStep;
5794       }
5795     }
5796   }else if( pss->iTerm > pss->iBase ){
5797     sqlite3_uint64 puspan = 0;
5798     if( bSameSigns ){
5799       puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
5800     }else{
5801       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5802        * In this clause, iTerm>=0 and iBase<0 . */
5803       puspan = 1;
5804       puspan += pss->iTerm;
5805       puspan += -(pss->iBase+1);
5806     }
5807     if( pss->iStep>0 ){
5808       pss->isNotEOF = 1;
5809       pss->uSeqIndexMax = puspan/pss->iStep;
5810     }
5811   }else if( pss->iTerm == pss->iBase ){
5812       pss->isNotEOF = 1;
5813       pss->uSeqIndexMax = 0;
5814   }
5815   pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
5816   pss->iValueNow = (pss->isReversing)
5817     ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
5818     : pss->iBase;
5819 }
5820 
5821 /*
5822 ** Progress sequence generator to yield next value, if any.
5823 ** Leave its state to either yield next value or be at EOF.
5824 ** Return whether there is a next value, or 0 at EOF.
5825 */
progressSequence(SequenceSpec * pss)5826 static int progressSequence( SequenceSpec *pss ){
5827   if( !pss->isNotEOF ) return 0;
5828   if( pss->isReversing ){
5829     if( pss->uSeqIndexNow > 0 ){
5830       pss->uSeqIndexNow--;
5831       pss->iValueNow -= pss->iStep;
5832     }else{
5833       pss->isNotEOF = 0;
5834     }
5835   }else{
5836     if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
5837       pss->uSeqIndexNow++;
5838       pss->iValueNow += pss->iStep;
5839     }else{
5840       pss->isNotEOF = 0;
5841     }
5842   }
5843   return pss->isNotEOF;
5844 }
5845 
5846 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
5847 ** serve as the underlying representation of a cursor that scans
5848 ** over rows of the result
5849 */
5850 typedef struct series_cursor series_cursor;
5851 struct series_cursor {
5852   sqlite3_vtab_cursor base;  /* Base class - must be first */
5853   SequenceSpec ss;           /* (this) Derived class data */
5854 };
5855 
5856 /*
5857 ** The seriesConnect() method is invoked to create a new
5858 ** series_vtab that describes the generate_series virtual table.
5859 **
5860 ** Think of this routine as the constructor for series_vtab objects.
5861 **
5862 ** All this routine needs to do is:
5863 **
5864 **    (1) Allocate the series_vtab object and initialize all fields.
5865 **
5866 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5867 **        result set of queries against generate_series will look like.
5868 */
seriesConnect(sqlite3 * db,void * pUnused,int argcUnused,const char * const * argvUnused,sqlite3_vtab ** ppVtab,char ** pzErrUnused)5869 static int seriesConnect(
5870   sqlite3 *db,
5871   void *pUnused,
5872   int argcUnused, const char *const*argvUnused,
5873   sqlite3_vtab **ppVtab,
5874   char **pzErrUnused
5875 ){
5876   sqlite3_vtab *pNew;
5877   int rc;
5878 
5879 /* Column numbers */
5880 #define SERIES_COLUMN_VALUE 0
5881 #define SERIES_COLUMN_START 1
5882 #define SERIES_COLUMN_STOP  2
5883 #define SERIES_COLUMN_STEP  3
5884 
5885   (void)pUnused;
5886   (void)argcUnused;
5887   (void)argvUnused;
5888   (void)pzErrUnused;
5889   rc = sqlite3_declare_vtab(db,
5890      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5891   if( rc==SQLITE_OK ){
5892     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5893     if( pNew==0 ) return SQLITE_NOMEM;
5894     memset(pNew, 0, sizeof(*pNew));
5895     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5896   }
5897   return rc;
5898 }
5899 
5900 /*
5901 ** This method is the destructor for series_cursor objects.
5902 */
seriesDisconnect(sqlite3_vtab * pVtab)5903 static int seriesDisconnect(sqlite3_vtab *pVtab){
5904   sqlite3_free(pVtab);
5905   return SQLITE_OK;
5906 }
5907 
5908 /*
5909 ** Constructor for a new series_cursor object.
5910 */
seriesOpen(sqlite3_vtab * pUnused,sqlite3_vtab_cursor ** ppCursor)5911 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5912   series_cursor *pCur;
5913   (void)pUnused;
5914   pCur = sqlite3_malloc( sizeof(*pCur) );
5915   if( pCur==0 ) return SQLITE_NOMEM;
5916   memset(pCur, 0, sizeof(*pCur));
5917   *ppCursor = &pCur->base;
5918   return SQLITE_OK;
5919 }
5920 
5921 /*
5922 ** Destructor for a series_cursor.
5923 */
seriesClose(sqlite3_vtab_cursor * cur)5924 static int seriesClose(sqlite3_vtab_cursor *cur){
5925   sqlite3_free(cur);
5926   return SQLITE_OK;
5927 }
5928 
5929 
5930 /*
5931 ** Advance a series_cursor to its next row of output.
5932 */
seriesNext(sqlite3_vtab_cursor * cur)5933 static int seriesNext(sqlite3_vtab_cursor *cur){
5934   series_cursor *pCur = (series_cursor*)cur;
5935   progressSequence( & pCur->ss );
5936   return SQLITE_OK;
5937 }
5938 
5939 /*
5940 ** Return values of columns for the row at which the series_cursor
5941 ** is currently pointing.
5942 */
seriesColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)5943 static int seriesColumn(
5944   sqlite3_vtab_cursor *cur,   /* The cursor */
5945   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5946   int i                       /* Which column to return */
5947 ){
5948   series_cursor *pCur = (series_cursor*)cur;
5949   sqlite3_int64 x = 0;
5950   switch( i ){
5951     case SERIES_COLUMN_START:  x = pCur->ss.iBase; break;
5952     case SERIES_COLUMN_STOP:   x = pCur->ss.iTerm; break;
5953     case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;   break;
5954     default:                   x = pCur->ss.iValueNow;  break;
5955   }
5956   sqlite3_result_int64(ctx, x);
5957   return SQLITE_OK;
5958 }
5959 
5960 #ifndef LARGEST_UINT64
5961 #define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32))
5962 #endif
5963 
5964 /*
5965 ** Return the rowid for the current row, logically equivalent to n+1 where
5966 ** "n" is the ascending integer in the aforesaid production definition.
5967 */
seriesRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)5968 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5969   series_cursor *pCur = (series_cursor*)cur;
5970   sqlite3_uint64 n = pCur->ss.uSeqIndexNow;
5971   *pRowid = (sqlite3_int64)((n<LARGEST_UINT64)? n+1 : 0);
5972   return SQLITE_OK;
5973 }
5974 
5975 /*
5976 ** Return TRUE if the cursor has been moved off of the last
5977 ** row of output.
5978 */
seriesEof(sqlite3_vtab_cursor * cur)5979 static int seriesEof(sqlite3_vtab_cursor *cur){
5980   series_cursor *pCur = (series_cursor*)cur;
5981   return !pCur->ss.isNotEOF;
5982 }
5983 
5984 /* True to cause run-time checking of the start=, stop=, and/or step=
5985 ** parameters.  The only reason to do this is for testing the
5986 ** constraint checking logic for virtual tables in the SQLite core.
5987 */
5988 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5989 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5990 #endif
5991 
5992 /*
5993 ** This method is called to "rewind" the series_cursor object back
5994 ** to the first row of output.  This method is always called at least
5995 ** once prior to any call to seriesColumn() or seriesRowid() or
5996 ** seriesEof().
5997 **
5998 ** The query plan selected by seriesBestIndex is passed in the idxNum
5999 ** parameter.  (idxStr is not used in this implementation.)  idxNum
6000 ** is a bitmask showing which constraints are available:
6001 **
6002 **   0x01:    start=VALUE
6003 **   0x02:    stop=VALUE
6004 **   0x04:    step=VALUE
6005 **   0x08:    descending order
6006 **   0x10:    ascending order
6007 **   0x20:    LIMIT  VALUE
6008 **   0x40:    OFFSET  VALUE
6009 **
6010 ** This routine should initialize the cursor and position it so that it
6011 ** is pointing at the first row, or pointing off the end of the table
6012 ** (so that seriesEof() will return true) if the table is empty.
6013 */
seriesFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStrUnused,int argc,sqlite3_value ** argv)6014 static int seriesFilter(
6015   sqlite3_vtab_cursor *pVtabCursor,
6016   int idxNum, const char *idxStrUnused,
6017   int argc, sqlite3_value **argv
6018 ){
6019   series_cursor *pCur = (series_cursor *)pVtabCursor;
6020   int i = 0;
6021   (void)idxStrUnused;
6022   if( idxNum & 0x01 ){
6023     pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
6024   }else{
6025     pCur->ss.iBase = 0;
6026   }
6027   if( idxNum & 0x02 ){
6028     pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
6029   }else{
6030     pCur->ss.iTerm = 0xffffffff;
6031   }
6032   if( idxNum & 0x04 ){
6033     pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
6034     if( pCur->ss.iStep==0 ){
6035       pCur->ss.iStep = 1;
6036     }else if( pCur->ss.iStep<0 ){
6037       if( (idxNum & 0x10)==0 ) idxNum |= 0x08;
6038     }
6039   }else{
6040     pCur->ss.iStep = 1;
6041   }
6042   if( idxNum & 0x20 ){
6043     sqlite3_int64 iLimit = sqlite3_value_int64(argv[i++]);
6044     sqlite3_int64 iTerm;
6045     if( idxNum & 0x40 ){
6046       sqlite3_int64 iOffset = sqlite3_value_int64(argv[i++]);
6047       if( iOffset>0 ){
6048         pCur->ss.iBase += pCur->ss.iStep*iOffset;
6049       }
6050     }
6051     if( iLimit>=0 ){
6052       iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep;
6053       if( pCur->ss.iStep<0 ){
6054         if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
6055       }else{
6056         if( iTerm<pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
6057       }
6058     }
6059   }
6060   for(i=0; i<argc; i++){
6061     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
6062       /* If any of the constraints have a NULL value, then return no rows.
6063       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
6064       pCur->ss.iBase = 1;
6065       pCur->ss.iTerm = 0;
6066       pCur->ss.iStep = 1;
6067       break;
6068     }
6069   }
6070   if( idxNum & 0x08 ){
6071     pCur->ss.isReversing = pCur->ss.iStep > 0;
6072   }else{
6073     pCur->ss.isReversing = pCur->ss.iStep < 0;
6074   }
6075   setupSequence( &pCur->ss );
6076   return SQLITE_OK;
6077 }
6078 
6079 /*
6080 ** SQLite will invoke this method one or more times while planning a query
6081 ** that uses the generate_series virtual table.  This routine needs to create
6082 ** a query plan for each invocation and compute an estimated cost for that
6083 ** plan.
6084 **
6085 ** In this implementation idxNum is used to represent the
6086 ** query plan.  idxStr is unused.
6087 **
6088 ** The query plan is represented by bits in idxNum:
6089 **
6090 **   0x01  start = $value  -- constraint exists
6091 **   0x02  stop = $value   -- constraint exists
6092 **   0x04  step = $value   -- constraint exists
6093 **   0x08  output is in descending order
6094 **   0x10  output is in ascending order
6095 **   0x20  LIMIT $value    -- constraint exists
6096 **   0x40  OFFSET $value   -- constraint exists
6097 */
seriesBestIndex(sqlite3_vtab * pVTab,sqlite3_index_info * pIdxInfo)6098 static int seriesBestIndex(
6099   sqlite3_vtab *pVTab,
6100   sqlite3_index_info *pIdxInfo
6101 ){
6102   int i, j;              /* Loop over constraints */
6103   int idxNum = 0;        /* The query plan bitmask */
6104 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6105   int bStartSeen = 0;    /* EQ constraint seen on the START column */
6106 #endif
6107   int unusableMask = 0;  /* Mask of unusable constraints */
6108   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
6109   int aIdx[5];           /* Constraints on start, stop, step, LIMIT, OFFSET */
6110   const struct sqlite3_index_constraint *pConstraint;
6111 
6112   /* This implementation assumes that the start, stop, and step columns
6113   ** are the last three columns in the virtual table. */
6114   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
6115   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
6116 
6117   aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = -1;
6118   pConstraint = pIdxInfo->aConstraint;
6119   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6120     int iCol;    /* 0 for start, 1 for stop, 2 for step */
6121     int iMask;   /* bitmask for those column */
6122     int op = pConstraint->op;
6123     if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
6124      && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
6125     ){
6126       if( pConstraint->usable==0 ){
6127         /* do nothing */
6128       }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
6129         aIdx[3] = i;
6130         idxNum |= 0x20;
6131       }else{
6132         assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
6133         aIdx[4] = i;
6134         idxNum |= 0x40;
6135       }
6136       continue;
6137     }
6138     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
6139     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
6140     assert( iCol>=0 && iCol<=2 );
6141     iMask = 1 << iCol;
6142 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6143     if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
6144       bStartSeen = 1;
6145     }
6146 #endif
6147     if( pConstraint->usable==0 ){
6148       unusableMask |=  iMask;
6149       continue;
6150     }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
6151       idxNum |= iMask;
6152       aIdx[iCol] = i;
6153     }
6154   }
6155   if( aIdx[3]==0 ){
6156     /* Ignore OFFSET if LIMIT is omitted */
6157     idxNum &= ~0x60;
6158     aIdx[4] = 0;
6159   }
6160   for(i=0; i<5; i++){
6161     if( (j = aIdx[i])>=0 ){
6162       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
6163       pIdxInfo->aConstraintUsage[j].omit =
6164          !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
6165     }
6166   }
6167   /* The current generate_column() implementation requires at least one
6168   ** argument (the START value).  Legacy versions assumed START=0 if the
6169   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
6170   ** to obtain the legacy behavior */
6171 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
6172   if( !bStartSeen ){
6173     sqlite3_free(pVTab->zErrMsg);
6174     pVTab->zErrMsg = sqlite3_mprintf(
6175         "first argument to \"generate_series()\" missing or unusable");
6176     return SQLITE_ERROR;
6177   }
6178 #endif
6179   if( (unusableMask & ~idxNum)!=0 ){
6180     /* The start, stop, and step columns are inputs.  Therefore if there
6181     ** are unusable constraints on any of start, stop, or step then
6182     ** this plan is unusable */
6183     return SQLITE_CONSTRAINT;
6184   }
6185   if( (idxNum & 0x03)==0x03 ){
6186     /* Both start= and stop= boundaries are available.  This is the
6187     ** the preferred case */
6188     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
6189     pIdxInfo->estimatedRows = 1000;
6190     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
6191       if( pIdxInfo->aOrderBy[0].desc ){
6192         idxNum |= 0x08;
6193       }else{
6194         idxNum |= 0x10;
6195       }
6196       pIdxInfo->orderByConsumed = 1;
6197     }
6198   }else if( (idxNum & 0x21)==0x21 ){
6199     /* We have start= and LIMIT */
6200     pIdxInfo->estimatedRows = 2500;
6201   }else{
6202     /* If either boundary is missing, we have to generate a huge span
6203     ** of numbers.  Make this case very expensive so that the query
6204     ** planner will work hard to avoid it. */
6205     pIdxInfo->estimatedRows = 2147483647;
6206   }
6207   pIdxInfo->idxNum = idxNum;
6208   return SQLITE_OK;
6209 }
6210 
6211 /*
6212 ** This following structure defines all the methods for the
6213 ** generate_series virtual table.
6214 */
6215 static sqlite3_module seriesModule = {
6216   0,                         /* iVersion */
6217   0,                         /* xCreate */
6218   seriesConnect,             /* xConnect */
6219   seriesBestIndex,           /* xBestIndex */
6220   seriesDisconnect,          /* xDisconnect */
6221   0,                         /* xDestroy */
6222   seriesOpen,                /* xOpen - open a cursor */
6223   seriesClose,               /* xClose - close a cursor */
6224   seriesFilter,              /* xFilter - configure scan constraints */
6225   seriesNext,                /* xNext - advance a cursor */
6226   seriesEof,                 /* xEof - check for end of scan */
6227   seriesColumn,              /* xColumn - read data */
6228   seriesRowid,               /* xRowid - read data */
6229   0,                         /* xUpdate */
6230   0,                         /* xBegin */
6231   0,                         /* xSync */
6232   0,                         /* xCommit */
6233   0,                         /* xRollback */
6234   0,                         /* xFindMethod */
6235   0,                         /* xRename */
6236   0,                         /* xSavepoint */
6237   0,                         /* xRelease */
6238   0,                         /* xRollbackTo */
6239   0,                         /* xShadowName */
6240   0                          /* xIntegrity */
6241 };
6242 
6243 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6244 
6245 #ifdef _WIN32
6246 
6247 #endif
sqlite3_series_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)6248 int sqlite3_series_init(
6249   sqlite3 *db,
6250   char **pzErrMsg,
6251   const sqlite3_api_routines *pApi
6252 ){
6253   int rc = SQLITE_OK;
6254   SQLITE_EXTENSION_INIT2(pApi);
6255 #ifndef SQLITE_OMIT_VIRTUALTABLE
6256   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
6257     *pzErrMsg = sqlite3_mprintf(
6258         "generate_series() requires SQLite 3.8.12 or later");
6259     return SQLITE_ERROR;
6260   }
6261   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
6262 #endif
6263   return rc;
6264 }
6265 
6266 /************************* End ../ext/misc/series.c ********************/
6267 /************************* Begin ../ext/misc/regexp.c ******************/
6268 /*
6269 ** 2012-11-13
6270 **
6271 ** The author disclaims copyright to this source code.  In place of
6272 ** a legal notice, here is a blessing:
6273 **
6274 **    May you do good and not evil.
6275 **    May you find forgiveness for yourself and forgive others.
6276 **    May you share freely, never taking more than you give.
6277 **
6278 ******************************************************************************
6279 **
6280 ** The code in this file implements a compact but reasonably
6281 ** efficient regular-expression matcher for posix extended regular
6282 ** expressions against UTF8 text.
6283 **
6284 ** This file is an SQLite extension.  It registers a single function
6285 ** named "regexp(A,B)" where A is the regular expression and B is the
6286 ** string to be matched.  By registering this function, SQLite will also
6287 ** then implement the "B regexp A" operator.  Note that with the function
6288 ** the regular expression comes first, but with the operator it comes
6289 ** second.
6290 **
6291 **  The following regular expression syntax is supported:
6292 **
6293 **     X*      zero or more occurrences of X
6294 **     X+      one or more occurrences of X
6295 **     X?      zero or one occurrences of X
6296 **     X{p,q}  between p and q occurrences of X
6297 **     (X)     match X
6298 **     X|Y     X or Y
6299 **     ^X      X occurring at the beginning of the string
6300 **     X$      X occurring at the end of the string
6301 **     .       Match any single character
6302 **     \c      Character c where c is one of \{}()[]|*+?.
6303 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
6304 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
6305 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
6306 **     [abc]   Any single character from the set abc
6307 **     [^abc]  Any single character not in the set abc
6308 **     [a-z]   Any single character in the range a-z
6309 **     [^a-z]  Any single character not in the range a-z
6310 **     \b      Word boundary
6311 **     \w      Word character.  [A-Za-z0-9_]
6312 **     \W      Non-word character
6313 **     \d      Digit
6314 **     \D      Non-digit
6315 **     \s      Whitespace character
6316 **     \S      Non-whitespace character
6317 **
6318 ** A nondeterministic finite automaton (NFA) is used for matching, so the
6319 ** performance is bounded by O(N*M) where N is the size of the regular
6320 ** expression and M is the size of the input string.  The matcher never
6321 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
6322 ** to p copies of X following by q-p copies of X? and that the size of the
6323 ** regular expression in the O(N*M) performance bound is computed after
6324 ** this expansion.
6325 */
6326 #include <string.h>
6327 #include <stdlib.h>
6328 /* #include "sqlite3ext.h" */
6329 SQLITE_EXTENSION_INIT1
6330 
6331 /*
6332 ** The following #defines change the names of some functions implemented in
6333 ** this file to prevent name collisions with C-library functions of the
6334 ** same name.
6335 */
6336 #define re_match   sqlite3re_match
6337 #define re_compile sqlite3re_compile
6338 #define re_free    sqlite3re_free
6339 
6340 /* The end-of-input character */
6341 #define RE_EOF            0    /* End of input */
6342 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
6343 
6344 /* The NFA is implemented as sequence of opcodes taken from the following
6345 ** set.  Each opcode has a single integer argument.
6346 */
6347 #define RE_OP_MATCH       1    /* Match the one character in the argument */
6348 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
6349 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
6350 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
6351 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
6352 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
6353 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
6354 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
6355 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
6356 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
6357 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
6358 #define RE_OP_NOTWORD    12    /* Not a perl word character */
6359 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
6360 #define RE_OP_NOTDIGIT   14    /* Not a digit */
6361 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
6362 #define RE_OP_NOTSPACE   16    /* Not a digit */
6363 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
6364 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
6365 
6366 #if defined(SQLITE_DEBUG)
6367 /* Opcode names used for symbolic debugging */
6368 static const char *ReOpName[] = {
6369   "EOF",
6370   "MATCH",
6371   "ANY",
6372   "ANYSTAR",
6373   "FORK",
6374   "GOTO",
6375   "ACCEPT",
6376   "CC_INC",
6377   "CC_EXC",
6378   "CC_VALUE",
6379   "CC_RANGE",
6380   "WORD",
6381   "NOTWORD",
6382   "DIGIT",
6383   "NOTDIGIT",
6384   "SPACE",
6385   "NOTSPACE",
6386   "BOUNDARY",
6387   "ATSTART",
6388 };
6389 #endif /* SQLITE_DEBUG */
6390 
6391 
6392 /* Each opcode is a "state" in the NFA */
6393 typedef unsigned short ReStateNumber;
6394 
6395 /* Because this is an NFA and not a DFA, multiple states can be active at
6396 ** once.  An instance of the following object records all active states in
6397 ** the NFA.  The implementation is optimized for the common case where the
6398 ** number of actives states is small.
6399 */
6400 typedef struct ReStateSet {
6401   unsigned nState;            /* Number of current states */
6402   ReStateNumber *aState;      /* Current states */
6403 } ReStateSet;
6404 
6405 /* An input string read one character at a time.
6406 */
6407 typedef struct ReInput ReInput;
6408 struct ReInput {
6409   const unsigned char *z;  /* All text */
6410   int i;                   /* Next byte to read */
6411   int mx;                  /* EOF when i>=mx */
6412 };
6413 
6414 /* A compiled NFA (or an NFA that is in the process of being compiled) is
6415 ** an instance of the following object.
6416 */
6417 typedef struct ReCompiled ReCompiled;
6418 struct ReCompiled {
6419   ReInput sIn;                /* Regular expression text */
6420   const char *zErr;           /* Error message to return */
6421   char *aOp;                  /* Operators for the virtual machine */
6422   int *aArg;                  /* Arguments to each operator */
6423   unsigned (*xNextChar)(ReInput*);  /* Next character function */
6424   unsigned char zInit[12];    /* Initial text to match */
6425   int nInit;                  /* Number of bytes in zInit */
6426   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
6427   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
6428 };
6429 
6430 /* Add a state to the given state set if it is not already there */
re_add_state(ReStateSet * pSet,int newState)6431 static void re_add_state(ReStateSet *pSet, int newState){
6432   unsigned i;
6433   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
6434   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
6435 }
6436 
6437 /* Extract the next unicode character from *pzIn and return it.  Advance
6438 ** *pzIn to the first byte past the end of the character returned.  To
6439 ** be clear:  this routine converts utf8 to unicode.  This routine is
6440 ** optimized for the common case where the next character is a single byte.
6441 */
re_next_char(ReInput * p)6442 static unsigned re_next_char(ReInput *p){
6443   unsigned c;
6444   if( p->i>=p->mx ) return 0;
6445   c = p->z[p->i++];
6446   if( c>=0x80 ){
6447     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
6448       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
6449       if( c<0x80 ) c = 0xfffd;
6450     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
6451            && (p->z[p->i+1]&0xc0)==0x80 ){
6452       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
6453       p->i += 2;
6454       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
6455     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
6456            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
6457       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
6458                        | (p->z[p->i+2]&0x3f);
6459       p->i += 3;
6460       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
6461     }else{
6462       c = 0xfffd;
6463     }
6464   }
6465   return c;
6466 }
re_next_char_nocase(ReInput * p)6467 static unsigned re_next_char_nocase(ReInput *p){
6468   unsigned c = re_next_char(p);
6469   if( c>='A' && c<='Z' ) c += 'a' - 'A';
6470   return c;
6471 }
6472 
6473 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
re_word_char(int c)6474 static int re_word_char(int c){
6475   return (c>='0' && c<='9') || (c>='a' && c<='z')
6476       || (c>='A' && c<='Z') || c=='_';
6477 }
6478 
6479 /* Return true if c is a "digit" character:  [0-9] */
re_digit_char(int c)6480 static int re_digit_char(int c){
6481   return (c>='0' && c<='9');
6482 }
6483 
6484 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
re_space_char(int c)6485 static int re_space_char(int c){
6486   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
6487 }
6488 
6489 /* Run a compiled regular expression on the zero-terminated input
6490 ** string zIn[].  Return true on a match and false if there is no match.
6491 */
re_match(ReCompiled * pRe,const unsigned char * zIn,int nIn)6492 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
6493   ReStateSet aStateSet[2], *pThis, *pNext;
6494   ReStateNumber aSpace[100];
6495   ReStateNumber *pToFree;
6496   unsigned int i = 0;
6497   unsigned int iSwap = 0;
6498   int c = RE_START;
6499   int cPrev = 0;
6500   int rc = 0;
6501   ReInput in;
6502 
6503   in.z = zIn;
6504   in.i = 0;
6505   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
6506 
6507   /* Look for the initial prefix match, if there is one. */
6508   if( pRe->nInit ){
6509     unsigned char x = pRe->zInit[0];
6510     while( in.i+pRe->nInit<=in.mx
6511      && (zIn[in.i]!=x ||
6512          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
6513     ){
6514       in.i++;
6515     }
6516     if( in.i+pRe->nInit>in.mx ) return 0;
6517     c = RE_START-1;
6518   }
6519 
6520   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
6521     pToFree = 0;
6522     aStateSet[0].aState = aSpace;
6523   }else{
6524     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
6525     if( pToFree==0 ) return -1;
6526     aStateSet[0].aState = pToFree;
6527   }
6528   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
6529   pNext = &aStateSet[1];
6530   pNext->nState = 0;
6531   re_add_state(pNext, 0);
6532   while( c!=RE_EOF && pNext->nState>0 ){
6533     cPrev = c;
6534     c = pRe->xNextChar(&in);
6535     pThis = pNext;
6536     pNext = &aStateSet[iSwap];
6537     iSwap = 1 - iSwap;
6538     pNext->nState = 0;
6539     for(i=0; i<pThis->nState; i++){
6540       int x = pThis->aState[i];
6541       switch( pRe->aOp[x] ){
6542         case RE_OP_MATCH: {
6543           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
6544           break;
6545         }
6546         case RE_OP_ATSTART: {
6547           if( cPrev==RE_START ) re_add_state(pThis, x+1);
6548           break;
6549         }
6550         case RE_OP_ANY: {
6551           if( c!=0 ) re_add_state(pNext, x+1);
6552           break;
6553         }
6554         case RE_OP_WORD: {
6555           if( re_word_char(c) ) re_add_state(pNext, x+1);
6556           break;
6557         }
6558         case RE_OP_NOTWORD: {
6559           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
6560           break;
6561         }
6562         case RE_OP_DIGIT: {
6563           if( re_digit_char(c) ) re_add_state(pNext, x+1);
6564           break;
6565         }
6566         case RE_OP_NOTDIGIT: {
6567           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
6568           break;
6569         }
6570         case RE_OP_SPACE: {
6571           if( re_space_char(c) ) re_add_state(pNext, x+1);
6572           break;
6573         }
6574         case RE_OP_NOTSPACE: {
6575           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
6576           break;
6577         }
6578         case RE_OP_BOUNDARY: {
6579           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
6580           break;
6581         }
6582         case RE_OP_ANYSTAR: {
6583           re_add_state(pNext, x);
6584           re_add_state(pThis, x+1);
6585           break;
6586         }
6587         case RE_OP_FORK: {
6588           re_add_state(pThis, x+pRe->aArg[x]);
6589           re_add_state(pThis, x+1);
6590           break;
6591         }
6592         case RE_OP_GOTO: {
6593           re_add_state(pThis, x+pRe->aArg[x]);
6594           break;
6595         }
6596         case RE_OP_ACCEPT: {
6597           rc = 1;
6598           goto re_match_end;
6599         }
6600         case RE_OP_CC_EXC: {
6601           if( c==0 ) break;
6602           /* fall-through */ goto re_op_cc_inc;
6603         }
6604         case RE_OP_CC_INC: re_op_cc_inc: {
6605           int j = 1;
6606           int n = pRe->aArg[x];
6607           int hit = 0;
6608           for(j=1; j>0 && j<n; j++){
6609             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
6610               if( pRe->aArg[x+j]==c ){
6611                 hit = 1;
6612                 j = -1;
6613               }
6614             }else{
6615               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
6616                 hit = 1;
6617                 j = -1;
6618               }else{
6619                 j++;
6620               }
6621             }
6622           }
6623           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
6624           if( hit ) re_add_state(pNext, x+n);
6625           break;
6626         }
6627       }
6628     }
6629   }
6630   for(i=0; i<pNext->nState; i++){
6631     int x = pNext->aState[i];
6632     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
6633     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
6634   }
6635 re_match_end:
6636   sqlite3_free(pToFree);
6637   return rc;
6638 }
6639 
6640 /* Resize the opcode and argument arrays for an RE under construction.
6641 */
re_resize(ReCompiled * p,int N)6642 static int re_resize(ReCompiled *p, int N){
6643   char *aOp;
6644   int *aArg;
6645   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
6646   if( aOp==0 ) return 1;
6647   p->aOp = aOp;
6648   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
6649   if( aArg==0 ) return 1;
6650   p->aArg = aArg;
6651   p->nAlloc = N;
6652   return 0;
6653 }
6654 
6655 /* Insert a new opcode and argument into an RE under construction.  The
6656 ** insertion point is just prior to existing opcode iBefore.
6657 */
re_insert(ReCompiled * p,int iBefore,int op,int arg)6658 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
6659   int i;
6660   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
6661   for(i=p->nState; i>iBefore; i--){
6662     p->aOp[i] = p->aOp[i-1];
6663     p->aArg[i] = p->aArg[i-1];
6664   }
6665   p->nState++;
6666   p->aOp[iBefore] = (char)op;
6667   p->aArg[iBefore] = arg;
6668   return iBefore;
6669 }
6670 
6671 /* Append a new opcode and argument to the end of the RE under construction.
6672 */
re_append(ReCompiled * p,int op,int arg)6673 static int re_append(ReCompiled *p, int op, int arg){
6674   return re_insert(p, p->nState, op, arg);
6675 }
6676 
6677 /* Make a copy of N opcodes starting at iStart onto the end of the RE
6678 ** under construction.
6679 */
re_copy(ReCompiled * p,int iStart,int N)6680 static void re_copy(ReCompiled *p, int iStart, int N){
6681   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
6682   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
6683   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
6684   p->nState += N;
6685 }
6686 
6687 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
6688 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
6689 ** c is not a hex digit *pV is unchanged.
6690 */
re_hex(int c,int * pV)6691 static int re_hex(int c, int *pV){
6692   if( c>='0' && c<='9' ){
6693     c -= '0';
6694   }else if( c>='a' && c<='f' ){
6695     c -= 'a' - 10;
6696   }else if( c>='A' && c<='F' ){
6697     c -= 'A' - 10;
6698   }else{
6699     return 0;
6700   }
6701   *pV = (*pV)*16 + (c & 0xff);
6702   return 1;
6703 }
6704 
6705 /* A backslash character has been seen, read the next character and
6706 ** return its interpretation.
6707 */
re_esc_char(ReCompiled * p)6708 static unsigned re_esc_char(ReCompiled *p){
6709   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
6710   static const char zTrans[] = "\a\f\n\r\t\v";
6711   int i, v = 0;
6712   char c;
6713   if( p->sIn.i>=p->sIn.mx ) return 0;
6714   c = p->sIn.z[p->sIn.i];
6715   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
6716     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6717     if( re_hex(zIn[1],&v)
6718      && re_hex(zIn[2],&v)
6719      && re_hex(zIn[3],&v)
6720      && re_hex(zIn[4],&v)
6721     ){
6722       p->sIn.i += 5;
6723       return v;
6724     }
6725   }
6726   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
6727     const unsigned char *zIn = p->sIn.z + p->sIn.i;
6728     if( re_hex(zIn[1],&v)
6729      && re_hex(zIn[2],&v)
6730     ){
6731       p->sIn.i += 3;
6732       return v;
6733     }
6734   }
6735   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
6736   if( zEsc[i] ){
6737     if( i<6 ) c = zTrans[i];
6738     p->sIn.i++;
6739   }else{
6740     p->zErr = "unknown \\ escape";
6741   }
6742   return c;
6743 }
6744 
6745 /* Forward declaration */
6746 static const char *re_subcompile_string(ReCompiled*);
6747 
6748 /* Peek at the next byte of input */
rePeek(ReCompiled * p)6749 static unsigned char rePeek(ReCompiled *p){
6750   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
6751 }
6752 
6753 /* Compile RE text into a sequence of opcodes.  Continue up to the
6754 ** first unmatched ")" character, then return.  If an error is found,
6755 ** return a pointer to the error message string.
6756 */
re_subcompile_re(ReCompiled * p)6757 static const char *re_subcompile_re(ReCompiled *p){
6758   const char *zErr;
6759   int iStart, iEnd, iGoto;
6760   iStart = p->nState;
6761   zErr = re_subcompile_string(p);
6762   if( zErr ) return zErr;
6763   while( rePeek(p)=='|' ){
6764     iEnd = p->nState;
6765     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
6766     iGoto = re_append(p, RE_OP_GOTO, 0);
6767     p->sIn.i++;
6768     zErr = re_subcompile_string(p);
6769     if( zErr ) return zErr;
6770     p->aArg[iGoto] = p->nState - iGoto;
6771   }
6772   return 0;
6773 }
6774 
6775 /* Compile an element of regular expression text (anything that can be
6776 ** an operand to the "|" operator).  Return NULL on success or a pointer
6777 ** to the error message if there is a problem.
6778 */
re_subcompile_string(ReCompiled * p)6779 static const char *re_subcompile_string(ReCompiled *p){
6780   int iPrev = -1;
6781   int iStart;
6782   unsigned c;
6783   const char *zErr;
6784   while( (c = p->xNextChar(&p->sIn))!=0 ){
6785     iStart = p->nState;
6786     switch( c ){
6787       case '|':
6788       case ')': {
6789         p->sIn.i--;
6790         return 0;
6791       }
6792       case '(': {
6793         zErr = re_subcompile_re(p);
6794         if( zErr ) return zErr;
6795         if( rePeek(p)!=')' ) return "unmatched '('";
6796         p->sIn.i++;
6797         break;
6798       }
6799       case '.': {
6800         if( rePeek(p)=='*' ){
6801           re_append(p, RE_OP_ANYSTAR, 0);
6802           p->sIn.i++;
6803         }else{
6804           re_append(p, RE_OP_ANY, 0);
6805         }
6806         break;
6807       }
6808       case '*': {
6809         if( iPrev<0 ) return "'*' without operand";
6810         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
6811         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
6812         break;
6813       }
6814       case '+': {
6815         if( iPrev<0 ) return "'+' without operand";
6816         re_append(p, RE_OP_FORK, iPrev - p->nState);
6817         break;
6818       }
6819       case '?': {
6820         if( iPrev<0 ) return "'?' without operand";
6821         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
6822         break;
6823       }
6824       case '$': {
6825         re_append(p, RE_OP_MATCH, RE_EOF);
6826         break;
6827       }
6828       case '^': {
6829         re_append(p, RE_OP_ATSTART, 0);
6830         break;
6831       }
6832       case '{': {
6833         int m = 0, n = 0;
6834         int sz, j;
6835         if( iPrev<0 ) return "'{m,n}' without operand";
6836         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
6837         n = m;
6838         if( c==',' ){
6839           p->sIn.i++;
6840           n = 0;
6841           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
6842         }
6843         if( c!='}' ) return "unmatched '{'";
6844         if( n>0 && n<m ) return "n less than m in '{m,n}'";
6845         p->sIn.i++;
6846         sz = p->nState - iPrev;
6847         if( m==0 ){
6848           if( n==0 ) return "both m and n are zero in '{m,n}'";
6849           re_insert(p, iPrev, RE_OP_FORK, sz+1);
6850           iPrev++;
6851           n--;
6852         }else{
6853           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
6854         }
6855         for(j=m; j<n; j++){
6856           re_append(p, RE_OP_FORK, sz+1);
6857           re_copy(p, iPrev, sz);
6858         }
6859         if( n==0 && m>0 ){
6860           re_append(p, RE_OP_FORK, -sz);
6861         }
6862         break;
6863       }
6864       case '[': {
6865         unsigned int iFirst = p->nState;
6866         if( rePeek(p)=='^' ){
6867           re_append(p, RE_OP_CC_EXC, 0);
6868           p->sIn.i++;
6869         }else{
6870           re_append(p, RE_OP_CC_INC, 0);
6871         }
6872         while( (c = p->xNextChar(&p->sIn))!=0 ){
6873           if( c=='[' && rePeek(p)==':' ){
6874             return "POSIX character classes not supported";
6875           }
6876           if( c=='\\' ) c = re_esc_char(p);
6877           if( rePeek(p)=='-' ){
6878             re_append(p, RE_OP_CC_RANGE, c);
6879             p->sIn.i++;
6880             c = p->xNextChar(&p->sIn);
6881             if( c=='\\' ) c = re_esc_char(p);
6882             re_append(p, RE_OP_CC_RANGE, c);
6883           }else{
6884             re_append(p, RE_OP_CC_VALUE, c);
6885           }
6886           if( rePeek(p)==']' ){ p->sIn.i++; break; }
6887         }
6888         if( c==0 ) return "unclosed '['";
6889         if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
6890         break;
6891       }
6892       case '\\': {
6893         int specialOp = 0;
6894         switch( rePeek(p) ){
6895           case 'b': specialOp = RE_OP_BOUNDARY;   break;
6896           case 'd': specialOp = RE_OP_DIGIT;      break;
6897           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
6898           case 's': specialOp = RE_OP_SPACE;      break;
6899           case 'S': specialOp = RE_OP_NOTSPACE;   break;
6900           case 'w': specialOp = RE_OP_WORD;       break;
6901           case 'W': specialOp = RE_OP_NOTWORD;    break;
6902         }
6903         if( specialOp ){
6904           p->sIn.i++;
6905           re_append(p, specialOp, 0);
6906         }else{
6907           c = re_esc_char(p);
6908           re_append(p, RE_OP_MATCH, c);
6909         }
6910         break;
6911       }
6912       default: {
6913         re_append(p, RE_OP_MATCH, c);
6914         break;
6915       }
6916     }
6917     iPrev = iStart;
6918   }
6919   return 0;
6920 }
6921 
6922 /* Free and reclaim all the memory used by a previously compiled
6923 ** regular expression.  Applications should invoke this routine once
6924 ** for every call to re_compile() to avoid memory leaks.
6925 */
re_free(ReCompiled * pRe)6926 static void re_free(ReCompiled *pRe){
6927   if( pRe ){
6928     sqlite3_free(pRe->aOp);
6929     sqlite3_free(pRe->aArg);
6930     sqlite3_free(pRe);
6931   }
6932 }
6933 
6934 /*
6935 ** Compile a textual regular expression in zIn[] into a compiled regular
6936 ** expression suitable for us by re_match() and return a pointer to the
6937 ** compiled regular expression in *ppRe.  Return NULL on success or an
6938 ** error message if something goes wrong.
6939 */
re_compile(ReCompiled ** ppRe,const char * zIn,int noCase)6940 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
6941   ReCompiled *pRe;
6942   const char *zErr;
6943   int i, j;
6944 
6945   *ppRe = 0;
6946   pRe = sqlite3_malloc( sizeof(*pRe) );
6947   if( pRe==0 ){
6948     return "out of memory";
6949   }
6950   memset(pRe, 0, sizeof(*pRe));
6951   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
6952   if( re_resize(pRe, 30) ){
6953     re_free(pRe);
6954     return "out of memory";
6955   }
6956   if( zIn[0]=='^' ){
6957     zIn++;
6958   }else{
6959     re_append(pRe, RE_OP_ANYSTAR, 0);
6960   }
6961   pRe->sIn.z = (unsigned char*)zIn;
6962   pRe->sIn.i = 0;
6963   pRe->sIn.mx = (int)strlen(zIn);
6964   zErr = re_subcompile_re(pRe);
6965   if( zErr ){
6966     re_free(pRe);
6967     return zErr;
6968   }
6969   if( pRe->sIn.i>=pRe->sIn.mx ){
6970     re_append(pRe, RE_OP_ACCEPT, 0);
6971     *ppRe = pRe;
6972   }else{
6973     re_free(pRe);
6974     return "unrecognized character";
6975   }
6976 
6977   /* The following is a performance optimization.  If the regex begins with
6978   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
6979   ** one or more matching characters, enter those matching characters into
6980   ** zInit[].  The re_match() routine can then search ahead in the input
6981   ** string looking for the initial match without having to run the whole
6982   ** regex engine over the string.  Do not worry about trying to match
6983   ** unicode characters beyond plane 0 - those are very rare and this is
6984   ** just an optimization. */
6985   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
6986     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
6987       unsigned x = pRe->aArg[i];
6988       if( x<=0x7f ){
6989         pRe->zInit[j++] = (unsigned char)x;
6990       }else if( x<=0x7ff ){
6991         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
6992         pRe->zInit[j++] = 0x80 | (x&0x3f);
6993       }else if( x<=0xffff ){
6994         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
6995         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
6996         pRe->zInit[j++] = 0x80 | (x&0x3f);
6997       }else{
6998         break;
6999       }
7000     }
7001     if( j>0 && pRe->zInit[j-1]==0 ) j--;
7002     pRe->nInit = j;
7003   }
7004   return pRe->zErr;
7005 }
7006 
7007 /*
7008 ** Implementation of the regexp() SQL function.  This function implements
7009 ** the build-in REGEXP operator.  The first argument to the function is the
7010 ** pattern and the second argument is the string.  So, the SQL statements:
7011 **
7012 **       A REGEXP B
7013 **
7014 ** is implemented as regexp(B,A).
7015 */
re_sql_func(sqlite3_context * context,int argc,sqlite3_value ** argv)7016 static void re_sql_func(
7017   sqlite3_context *context,
7018   int argc,
7019   sqlite3_value **argv
7020 ){
7021   ReCompiled *pRe;          /* Compiled regular expression */
7022   const char *zPattern;     /* The regular expression */
7023   const unsigned char *zStr;/* String being searched */
7024   const char *zErr;         /* Compile error message */
7025   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
7026 
7027   (void)argc;  /* Unused */
7028   pRe = sqlite3_get_auxdata(context, 0);
7029   if( pRe==0 ){
7030     zPattern = (const char*)sqlite3_value_text(argv[0]);
7031     if( zPattern==0 ) return;
7032     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7033     if( zErr ){
7034       re_free(pRe);
7035       sqlite3_result_error(context, zErr, -1);
7036       return;
7037     }
7038     if( pRe==0 ){
7039       sqlite3_result_error_nomem(context);
7040       return;
7041     }
7042     setAux = 1;
7043   }
7044   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
7045   if( zStr!=0 ){
7046     sqlite3_result_int(context, re_match(pRe, zStr, -1));
7047   }
7048   if( setAux ){
7049     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
7050   }
7051 }
7052 
7053 #if defined(SQLITE_DEBUG)
7054 /*
7055 ** This function is used for testing and debugging only.  It is only available
7056 ** if the SQLITE_DEBUG compile-time option is used.
7057 **
7058 ** Compile a regular expression and then convert the compiled expression into
7059 ** text and return that text.
7060 */
re_bytecode_func(sqlite3_context * context,int argc,sqlite3_value ** argv)7061 static void re_bytecode_func(
7062   sqlite3_context *context,
7063   int argc,
7064   sqlite3_value **argv
7065 ){
7066   const char *zPattern;
7067   const char *zErr;
7068   ReCompiled *pRe;
7069   sqlite3_str *pStr;
7070   int i;
7071   int n;
7072   char *z;
7073   (void)argc;
7074 
7075   zPattern = (const char*)sqlite3_value_text(argv[0]);
7076   if( zPattern==0 ) return;
7077   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7078   if( zErr ){
7079     re_free(pRe);
7080     sqlite3_result_error(context, zErr, -1);
7081     return;
7082   }
7083   if( pRe==0 ){
7084     sqlite3_result_error_nomem(context);
7085     return;
7086   }
7087   pStr = sqlite3_str_new(0);
7088   if( pStr==0 ) goto re_bytecode_func_err;
7089   if( pRe->nInit>0 ){
7090     sqlite3_str_appendf(pStr, "INIT     ");
7091     for(i=0; i<pRe->nInit; i++){
7092       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
7093     }
7094     sqlite3_str_appendf(pStr, "\n");
7095   }
7096   for(i=0; (unsigned)i<pRe->nState; i++){
7097     sqlite3_str_appendf(pStr, "%-8s %4d\n",
7098          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
7099   }
7100   n = sqlite3_str_length(pStr);
7101   z = sqlite3_str_finish(pStr);
7102   if( n==0 ){
7103     sqlite3_free(z);
7104   }else{
7105     sqlite3_result_text(context, z, n-1, sqlite3_free);
7106   }
7107 
7108 re_bytecode_func_err:
7109   re_free(pRe);
7110 }
7111 
7112 #endif /* SQLITE_DEBUG */
7113 
7114 
7115 /*
7116 ** Invoke this routine to register the regexp() function with the
7117 ** SQLite database connection.
7118 */
7119 #ifdef _WIN32
7120 
7121 #endif
sqlite3_regexp_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)7122 int sqlite3_regexp_init(
7123   sqlite3 *db,
7124   char **pzErrMsg,
7125   const sqlite3_api_routines *pApi
7126 ){
7127   int rc = SQLITE_OK;
7128   SQLITE_EXTENSION_INIT2(pApi);
7129   (void)pzErrMsg;  /* Unused */
7130   rc = sqlite3_create_function(db, "regexp", 2,
7131                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7132                             0, re_sql_func, 0, 0);
7133   if( rc==SQLITE_OK ){
7134     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
7135     ** of regexp(PATTERN,STRING). */
7136     rc = sqlite3_create_function(db, "regexpi", 2,
7137                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7138                             (void*)db, re_sql_func, 0, 0);
7139 #if defined(SQLITE_DEBUG)
7140     if( rc==SQLITE_OK ){
7141       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
7142                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7143                             0, re_bytecode_func, 0, 0);
7144     }
7145 #endif /* SQLITE_DEBUG */
7146   }
7147   return rc;
7148 }
7149 
7150 /************************* End ../ext/misc/regexp.c ********************/
7151 #ifndef SQLITE_SHELL_FIDDLE
7152 /************************* Begin ../ext/misc/fileio.c ******************/
7153 /*
7154 ** 2014-06-13
7155 **
7156 ** The author disclaims copyright to this source code.  In place of
7157 ** a legal notice, here is a blessing:
7158 **
7159 **    May you do good and not evil.
7160 **    May you find forgiveness for yourself and forgive others.
7161 **    May you share freely, never taking more than you give.
7162 **
7163 ******************************************************************************
7164 **
7165 ** This SQLite extension implements SQL functions readfile() and
7166 ** writefile(), and eponymous virtual type "fsdir".
7167 **
7168 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
7169 **
7170 **   If neither of the optional arguments is present, then this UDF
7171 **   function writes blob DATA to file FILE. If successful, the number
7172 **   of bytes written is returned. If an error occurs, NULL is returned.
7173 **
7174 **   If the first option argument - MODE - is present, then it must
7175 **   be passed an integer value that corresponds to a POSIX mode
7176 **   value (file type + permissions, as returned in the stat.st_mode
7177 **   field by the stat() system call). Three types of files may
7178 **   be written/created:
7179 **
7180 **     regular files:  (mode & 0170000)==0100000
7181 **     symbolic links: (mode & 0170000)==0120000
7182 **     directories:    (mode & 0170000)==0040000
7183 **
7184 **   For a directory, the DATA is ignored. For a symbolic link, it is
7185 **   interpreted as text and used as the target of the link. For a
7186 **   regular file, it is interpreted as a blob and written into the
7187 **   named file. Regardless of the type of file, its permissions are
7188 **   set to (mode & 0777) before returning.
7189 **
7190 **   If the optional MTIME argument is present, then it is interpreted
7191 **   as an integer - the number of seconds since the unix epoch. The
7192 **   modification-time of the target file is set to this value before
7193 **   returning.
7194 **
7195 **   If three or more arguments are passed to this function and an
7196 **   error is encountered, an exception is raised.
7197 **
7198 ** READFILE(FILE):
7199 **
7200 **   Read and return the contents of file FILE (type blob) from disk.
7201 **
7202 ** FSDIR:
7203 **
7204 **   Used as follows:
7205 **
7206 **     SELECT * FROM fsdir($path [, $dir]);
7207 **
7208 **   Parameter $path is an absolute or relative pathname. If the file that it
7209 **   refers to does not exist, it is an error. If the path refers to a regular
7210 **   file or symbolic link, it returns a single row. Or, if the path refers
7211 **   to a directory, it returns one row for the directory, and one row for each
7212 **   file within the hierarchy rooted at $path.
7213 **
7214 **   Each row has the following columns:
7215 **
7216 **     name:  Path to file or directory (text value).
7217 **     mode:  Value of stat.st_mode for directory entry (an integer).
7218 **     mtime: Value of stat.st_mtime for directory entry (an integer).
7219 **     data:  For a regular file, a blob containing the file data. For a
7220 **            symlink, a text value containing the text of the link. For a
7221 **            directory, NULL.
7222 **
7223 **   If a non-NULL value is specified for the optional $dir parameter and
7224 **   $path is a relative path, then $path is interpreted relative to $dir.
7225 **   And the paths returned in the "name" column of the table are also
7226 **   relative to directory $dir.
7227 **
7228 ** Notes on building this extension for Windows:
7229 **   Unless linked statically with the SQLite library, a preprocessor
7230 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
7231 **   DLL form of this extension for WIN32. See its use below for details.
7232 */
7233 /* #include "sqlite3ext.h" */
7234 SQLITE_EXTENSION_INIT1
7235 #include <stdio.h>
7236 #include <string.h>
7237 #include <assert.h>
7238 
7239 #include <sys/types.h>
7240 #include <sys/stat.h>
7241 #include <fcntl.h>
7242 #if !defined(_WIN32) && !defined(WIN32)
7243 #  include <unistd.h>
7244 #  include <dirent.h>
7245 #  include <utime.h>
7246 #  include <sys/time.h>
7247 #else
7248 #  include "windows.h"
7249 #  include <io.h>
7250 #  include <direct.h>
7251 /* #  include "test_windirent.h" */
7252 #  define dirent DIRENT
7253 #  ifndef chmod
7254 #    define chmod _chmod
7255 #  endif
7256 #  ifndef stat
7257 #    define stat _stat
7258 #  endif
7259 #  define mkdir(path,mode) _mkdir(path)
7260 #  define lstat(path,buf) stat(path,buf)
7261 #endif
7262 #include <time.h>
7263 #include <errno.h>
7264 
7265 
7266 /*
7267 ** Structure of the fsdir() table-valued function
7268 */
7269                  /*    0    1    2     3    4           5             */
7270 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
7271 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
7272 #define FSDIR_COLUMN_MODE     1     /* Access mode */
7273 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
7274 #define FSDIR_COLUMN_DATA     3     /* File content */
7275 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
7276 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
7277 
7278 
7279 /*
7280 ** Set the result stored by context ctx to a blob containing the
7281 ** contents of file zName.  Or, leave the result unchanged (NULL)
7282 ** if the file does not exist or is unreadable.
7283 **
7284 ** If the file exceeds the SQLite blob size limit, through an
7285 ** SQLITE_TOOBIG error.
7286 **
7287 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
7288 ** off of disk.
7289 */
readFileContents(sqlite3_context * ctx,const char * zName)7290 static void readFileContents(sqlite3_context *ctx, const char *zName){
7291   FILE *in;
7292   sqlite3_int64 nIn;
7293   void *pBuf;
7294   sqlite3 *db;
7295   int mxBlob;
7296 
7297   in = fopen(zName, "rb");
7298   if( in==0 ){
7299     /* File does not exist or is unreadable. Leave the result set to NULL. */
7300     return;
7301   }
7302   fseek(in, 0, SEEK_END);
7303   nIn = ftell(in);
7304   rewind(in);
7305   db = sqlite3_context_db_handle(ctx);
7306   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
7307   if( nIn>mxBlob ){
7308     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
7309     fclose(in);
7310     return;
7311   }
7312   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
7313   if( pBuf==0 ){
7314     sqlite3_result_error_nomem(ctx);
7315     fclose(in);
7316     return;
7317   }
7318   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
7319     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
7320   }else{
7321     sqlite3_result_error_code(ctx, SQLITE_IOERR);
7322     sqlite3_free(pBuf);
7323   }
7324   fclose(in);
7325 }
7326 
7327 /*
7328 ** Implementation of the "readfile(X)" SQL function.  The entire content
7329 ** of the file named X is read and returned as a BLOB.  NULL is returned
7330 ** if the file does not exist or is unreadable.
7331 */
readfileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7332 static void readfileFunc(
7333   sqlite3_context *context,
7334   int argc,
7335   sqlite3_value **argv
7336 ){
7337   const char *zName;
7338   (void)(argc);  /* Unused parameter */
7339   zName = (const char*)sqlite3_value_text(argv[0]);
7340   if( zName==0 ) return;
7341   readFileContents(context, zName);
7342 }
7343 
7344 /*
7345 ** Set the error message contained in context ctx to the results of
7346 ** vprintf(zFmt, ...).
7347 */
ctxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)7348 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7349   char *zMsg = 0;
7350   va_list ap;
7351   va_start(ap, zFmt);
7352   zMsg = sqlite3_vmprintf(zFmt, ap);
7353   sqlite3_result_error(ctx, zMsg, -1);
7354   sqlite3_free(zMsg);
7355   va_end(ap);
7356 }
7357 
7358 #if defined(_WIN32)
7359 /*
7360 ** This function is designed to convert a Win32 FILETIME structure into the
7361 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
7362 */
fileTimeToUnixTime(LPFILETIME pFileTime)7363 static sqlite3_uint64 fileTimeToUnixTime(
7364   LPFILETIME pFileTime
7365 ){
7366   SYSTEMTIME epochSystemTime;
7367   ULARGE_INTEGER epochIntervals;
7368   FILETIME epochFileTime;
7369   ULARGE_INTEGER fileIntervals;
7370 
7371   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
7372   epochSystemTime.wYear = 1970;
7373   epochSystemTime.wMonth = 1;
7374   epochSystemTime.wDay = 1;
7375   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
7376   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
7377   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
7378 
7379   fileIntervals.LowPart = pFileTime->dwLowDateTime;
7380   fileIntervals.HighPart = pFileTime->dwHighDateTime;
7381 
7382   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
7383 }
7384 
7385 
7386 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
7387 #  /* To allow a standalone DLL, use this next replacement function: */
7388 #  undef sqlite3_win32_utf8_to_unicode
7389 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
7390 #
utf8_to_utf16(const char * z)7391 LPWSTR utf8_to_utf16(const char *z){
7392   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
7393   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
7394   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
7395     return rv;
7396   sqlite3_free(rv);
7397   return 0;
7398 }
7399 #endif
7400 
7401 /*
7402 ** This function attempts to normalize the time values found in the stat()
7403 ** buffer to UTC.  This is necessary on Win32, where the runtime library
7404 ** appears to return these values as local times.
7405 */
statTimesToUtc(const char * zPath,struct stat * pStatBuf)7406 static void statTimesToUtc(
7407   const char *zPath,
7408   struct stat *pStatBuf
7409 ){
7410   HANDLE hFindFile;
7411   WIN32_FIND_DATAW fd;
7412   LPWSTR zUnicodeName;
7413   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7414   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
7415   if( zUnicodeName ){
7416     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
7417     hFindFile = FindFirstFileW(zUnicodeName, &fd);
7418     if( hFindFile!=NULL ){
7419       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
7420       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
7421       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
7422       FindClose(hFindFile);
7423     }
7424     sqlite3_free(zUnicodeName);
7425   }
7426 }
7427 #endif
7428 
7429 /*
7430 ** This function is used in place of stat().  On Windows, special handling
7431 ** is required in order for the included time to be returned as UTC.  On all
7432 ** other systems, this function simply calls stat().
7433 */
fileStat(const char * zPath,struct stat * pStatBuf)7434 static int fileStat(
7435   const char *zPath,
7436   struct stat *pStatBuf
7437 ){
7438 #if defined(_WIN32)
7439   int rc = stat(zPath, pStatBuf);
7440   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7441   return rc;
7442 #else
7443   return stat(zPath, pStatBuf);
7444 #endif
7445 }
7446 
7447 /*
7448 ** This function is used in place of lstat().  On Windows, special handling
7449 ** is required in order for the included time to be returned as UTC.  On all
7450 ** other systems, this function simply calls lstat().
7451 */
fileLinkStat(const char * zPath,struct stat * pStatBuf)7452 static int fileLinkStat(
7453   const char *zPath,
7454   struct stat *pStatBuf
7455 ){
7456 #if defined(_WIN32)
7457   int rc = lstat(zPath, pStatBuf);
7458   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7459   return rc;
7460 #else
7461   return lstat(zPath, pStatBuf);
7462 #endif
7463 }
7464 
7465 /*
7466 ** Argument zFile is the name of a file that will be created and/or written
7467 ** by SQL function writefile(). This function ensures that the directory
7468 ** zFile will be written to exists, creating it if required. The permissions
7469 ** for any path components created by this function are set in accordance
7470 ** with the current umask.
7471 **
7472 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
7473 ** SQLITE_OK is returned if the directory is successfully created, or
7474 ** SQLITE_ERROR otherwise.
7475 */
makeDirectory(const char * zFile)7476 static int makeDirectory(
7477   const char *zFile
7478 ){
7479   char *zCopy = sqlite3_mprintf("%s", zFile);
7480   int rc = SQLITE_OK;
7481 
7482   if( zCopy==0 ){
7483     rc = SQLITE_NOMEM;
7484   }else{
7485     int nCopy = (int)strlen(zCopy);
7486     int i = 1;
7487 
7488     while( rc==SQLITE_OK ){
7489       struct stat sStat;
7490       int rc2;
7491 
7492       for(; zCopy[i]!='/' && i<nCopy; i++);
7493       if( i==nCopy ) break;
7494       zCopy[i] = '\0';
7495 
7496       rc2 = fileStat(zCopy, &sStat);
7497       if( rc2!=0 ){
7498         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
7499       }else{
7500         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
7501       }
7502       zCopy[i] = '/';
7503       i++;
7504     }
7505 
7506     sqlite3_free(zCopy);
7507   }
7508 
7509   return rc;
7510 }
7511 
7512 /*
7513 ** This function does the work for the writefile() UDF. Refer to
7514 ** header comments at the top of this file for details.
7515 */
writeFile(sqlite3_context * pCtx,const char * zFile,sqlite3_value * pData,mode_t mode,sqlite3_int64 mtime)7516 static int writeFile(
7517   sqlite3_context *pCtx,          /* Context to return bytes written in */
7518   const char *zFile,              /* File to write */
7519   sqlite3_value *pData,           /* Data to write */
7520   mode_t mode,                    /* MODE parameter passed to writefile() */
7521   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
7522 ){
7523   if( zFile==0 ) return 1;
7524 #if !defined(_WIN32) && !defined(WIN32)
7525   if( S_ISLNK(mode) ){
7526     const char *zTo = (const char*)sqlite3_value_text(pData);
7527     if( zTo==0 ) return 1;
7528     unlink(zFile);
7529     if( symlink(zTo, zFile)<0 ) return 1;
7530   }else
7531 #endif
7532   {
7533     if( S_ISDIR(mode) ){
7534       if( mkdir(zFile, mode) ){
7535         /* The mkdir() call to create the directory failed. This might not
7536         ** be an error though - if there is already a directory at the same
7537         ** path and either the permissions already match or can be changed
7538         ** to do so using chmod(), it is not an error.  */
7539         struct stat sStat;
7540         if( errno!=EEXIST
7541          || 0!=fileStat(zFile, &sStat)
7542          || !S_ISDIR(sStat.st_mode)
7543          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
7544         ){
7545           return 1;
7546         }
7547       }
7548     }else{
7549       sqlite3_int64 nWrite = 0;
7550       const char *z;
7551       int rc = 0;
7552       FILE *out = fopen(zFile, "wb");
7553       if( out==0 ) return 1;
7554       z = (const char*)sqlite3_value_blob(pData);
7555       if( z ){
7556         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
7557         nWrite = sqlite3_value_bytes(pData);
7558         if( nWrite!=n ){
7559           rc = 1;
7560         }
7561       }
7562       fclose(out);
7563       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
7564         rc = 1;
7565       }
7566       if( rc ) return 2;
7567       sqlite3_result_int64(pCtx, nWrite);
7568     }
7569   }
7570 
7571   if( mtime>=0 ){
7572 #if defined(_WIN32)
7573 #if !SQLITE_OS_WINRT
7574     /* Windows */
7575     FILETIME lastAccess;
7576     FILETIME lastWrite;
7577     SYSTEMTIME currentTime;
7578     LONGLONG intervals;
7579     HANDLE hFile;
7580     LPWSTR zUnicodeName;
7581     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7582 
7583     GetSystemTime(&currentTime);
7584     SystemTimeToFileTime(&currentTime, &lastAccess);
7585     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
7586     lastWrite.dwLowDateTime = (DWORD)intervals;
7587     lastWrite.dwHighDateTime = intervals >> 32;
7588     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
7589     if( zUnicodeName==0 ){
7590       return 1;
7591     }
7592     hFile = CreateFileW(
7593       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
7594       FILE_FLAG_BACKUP_SEMANTICS, NULL
7595     );
7596     sqlite3_free(zUnicodeName);
7597     if( hFile!=INVALID_HANDLE_VALUE ){
7598       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
7599       CloseHandle(hFile);
7600       return !bResult;
7601     }else{
7602       return 1;
7603     }
7604 #endif
7605 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
7606     /* Recent unix */
7607     struct timespec times[2];
7608     times[0].tv_nsec = times[1].tv_nsec = 0;
7609     times[0].tv_sec = time(0);
7610     times[1].tv_sec = mtime;
7611     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
7612       return 1;
7613     }
7614 #else
7615     /* Legacy unix.
7616     **
7617     ** Do not use utimes() on a symbolic link - it sees through the link and
7618     ** modifies the timestamps on the target. Or fails if the target does
7619     ** not exist.  */
7620     if( 0==S_ISLNK(mode) ){
7621       struct timeval times[2];
7622       times[0].tv_usec = times[1].tv_usec = 0;
7623       times[0].tv_sec = time(0);
7624       times[1].tv_sec = mtime;
7625       if( utimes(zFile, times) ){
7626         return 1;
7627       }
7628     }
7629 #endif
7630   }
7631 
7632   return 0;
7633 }
7634 
7635 /*
7636 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
7637 ** Refer to header comments at the top of this file for details.
7638 */
writefileFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7639 static void writefileFunc(
7640   sqlite3_context *context,
7641   int argc,
7642   sqlite3_value **argv
7643 ){
7644   const char *zFile;
7645   mode_t mode = 0;
7646   int res;
7647   sqlite3_int64 mtime = -1;
7648 
7649   if( argc<2 || argc>4 ){
7650     sqlite3_result_error(context,
7651         "wrong number of arguments to function writefile()", -1
7652     );
7653     return;
7654   }
7655 
7656   zFile = (const char*)sqlite3_value_text(argv[0]);
7657   if( zFile==0 ) return;
7658   if( argc>=3 ){
7659     mode = (mode_t)sqlite3_value_int(argv[2]);
7660   }
7661   if( argc==4 ){
7662     mtime = sqlite3_value_int64(argv[3]);
7663   }
7664 
7665   res = writeFile(context, zFile, argv[1], mode, mtime);
7666   if( res==1 && errno==ENOENT ){
7667     if( makeDirectory(zFile)==SQLITE_OK ){
7668       res = writeFile(context, zFile, argv[1], mode, mtime);
7669     }
7670   }
7671 
7672   if( argc>2 && res!=0 ){
7673     if( S_ISLNK(mode) ){
7674       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
7675     }else if( S_ISDIR(mode) ){
7676       ctxErrorMsg(context, "failed to create directory: %s", zFile);
7677     }else{
7678       ctxErrorMsg(context, "failed to write file: %s", zFile);
7679     }
7680   }
7681 }
7682 
7683 /*
7684 ** SQL function:   lsmode(MODE)
7685 **
7686 ** Given a numberic st_mode from stat(), convert it into a human-readable
7687 ** text string in the style of "ls -l".
7688 */
lsModeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)7689 static void lsModeFunc(
7690   sqlite3_context *context,
7691   int argc,
7692   sqlite3_value **argv
7693 ){
7694   int i;
7695   int iMode = sqlite3_value_int(argv[0]);
7696   char z[16];
7697   (void)argc;
7698   if( S_ISLNK(iMode) ){
7699     z[0] = 'l';
7700   }else if( S_ISREG(iMode) ){
7701     z[0] = '-';
7702   }else if( S_ISDIR(iMode) ){
7703     z[0] = 'd';
7704   }else{
7705     z[0] = '?';
7706   }
7707   for(i=0; i<3; i++){
7708     int m = (iMode >> ((2-i)*3));
7709     char *a = &z[1 + i*3];
7710     a[0] = (m & 0x4) ? 'r' : '-';
7711     a[1] = (m & 0x2) ? 'w' : '-';
7712     a[2] = (m & 0x1) ? 'x' : '-';
7713   }
7714   z[10] = '\0';
7715   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
7716 }
7717 
7718 #ifndef SQLITE_OMIT_VIRTUALTABLE
7719 
7720 /*
7721 ** Cursor type for recursively iterating through a directory structure.
7722 */
7723 typedef struct fsdir_cursor fsdir_cursor;
7724 typedef struct FsdirLevel FsdirLevel;
7725 
7726 struct FsdirLevel {
7727   DIR *pDir;                 /* From opendir() */
7728   char *zDir;                /* Name of directory (nul-terminated) */
7729 };
7730 
7731 struct fsdir_cursor {
7732   sqlite3_vtab_cursor base;  /* Base class - must be first */
7733 
7734   int nLvl;                  /* Number of entries in aLvl[] array */
7735   int iLvl;                  /* Index of current entry */
7736   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
7737 
7738   const char *zBase;
7739   int nBase;
7740 
7741   struct stat sStat;         /* Current lstat() results */
7742   char *zPath;               /* Path to current entry */
7743   sqlite3_int64 iRowid;      /* Current rowid */
7744 };
7745 
7746 typedef struct fsdir_tab fsdir_tab;
7747 struct fsdir_tab {
7748   sqlite3_vtab base;         /* Base class - must be first */
7749 };
7750 
7751 /*
7752 ** Construct a new fsdir virtual table object.
7753 */
fsdirConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)7754 static int fsdirConnect(
7755   sqlite3 *db,
7756   void *pAux,
7757   int argc, const char *const*argv,
7758   sqlite3_vtab **ppVtab,
7759   char **pzErr
7760 ){
7761   fsdir_tab *pNew = 0;
7762   int rc;
7763   (void)pAux;
7764   (void)argc;
7765   (void)argv;
7766   (void)pzErr;
7767   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
7768   if( rc==SQLITE_OK ){
7769     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
7770     if( pNew==0 ) return SQLITE_NOMEM;
7771     memset(pNew, 0, sizeof(*pNew));
7772     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
7773   }
7774   *ppVtab = (sqlite3_vtab*)pNew;
7775   return rc;
7776 }
7777 
7778 /*
7779 ** This method is the destructor for fsdir vtab objects.
7780 */
fsdirDisconnect(sqlite3_vtab * pVtab)7781 static int fsdirDisconnect(sqlite3_vtab *pVtab){
7782   sqlite3_free(pVtab);
7783   return SQLITE_OK;
7784 }
7785 
7786 /*
7787 ** Constructor for a new fsdir_cursor object.
7788 */
fsdirOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)7789 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
7790   fsdir_cursor *pCur;
7791   (void)p;
7792   pCur = sqlite3_malloc( sizeof(*pCur) );
7793   if( pCur==0 ) return SQLITE_NOMEM;
7794   memset(pCur, 0, sizeof(*pCur));
7795   pCur->iLvl = -1;
7796   *ppCursor = &pCur->base;
7797   return SQLITE_OK;
7798 }
7799 
7800 /*
7801 ** Reset a cursor back to the state it was in when first returned
7802 ** by fsdirOpen().
7803 */
fsdirResetCursor(fsdir_cursor * pCur)7804 static void fsdirResetCursor(fsdir_cursor *pCur){
7805   int i;
7806   for(i=0; i<=pCur->iLvl; i++){
7807     FsdirLevel *pLvl = &pCur->aLvl[i];
7808     if( pLvl->pDir ) closedir(pLvl->pDir);
7809     sqlite3_free(pLvl->zDir);
7810   }
7811   sqlite3_free(pCur->zPath);
7812   sqlite3_free(pCur->aLvl);
7813   pCur->aLvl = 0;
7814   pCur->zPath = 0;
7815   pCur->zBase = 0;
7816   pCur->nBase = 0;
7817   pCur->nLvl = 0;
7818   pCur->iLvl = -1;
7819   pCur->iRowid = 1;
7820 }
7821 
7822 /*
7823 ** Destructor for an fsdir_cursor.
7824 */
fsdirClose(sqlite3_vtab_cursor * cur)7825 static int fsdirClose(sqlite3_vtab_cursor *cur){
7826   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7827 
7828   fsdirResetCursor(pCur);
7829   sqlite3_free(pCur);
7830   return SQLITE_OK;
7831 }
7832 
7833 /*
7834 ** Set the error message for the virtual table associated with cursor
7835 ** pCur to the results of vprintf(zFmt, ...).
7836 */
fsdirSetErrmsg(fsdir_cursor * pCur,const char * zFmt,...)7837 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
7838   va_list ap;
7839   va_start(ap, zFmt);
7840   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7841   va_end(ap);
7842 }
7843 
7844 
7845 /*
7846 ** Advance an fsdir_cursor to its next row of output.
7847 */
fsdirNext(sqlite3_vtab_cursor * cur)7848 static int fsdirNext(sqlite3_vtab_cursor *cur){
7849   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7850   mode_t m = pCur->sStat.st_mode;
7851 
7852   pCur->iRowid++;
7853   if( S_ISDIR(m) ){
7854     /* Descend into this directory */
7855     int iNew = pCur->iLvl + 1;
7856     FsdirLevel *pLvl;
7857     if( iNew>=pCur->nLvl ){
7858       int nNew = iNew+1;
7859       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
7860       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
7861       if( aNew==0 ) return SQLITE_NOMEM;
7862       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
7863       pCur->aLvl = aNew;
7864       pCur->nLvl = nNew;
7865     }
7866     pCur->iLvl = iNew;
7867     pLvl = &pCur->aLvl[iNew];
7868 
7869     pLvl->zDir = pCur->zPath;
7870     pCur->zPath = 0;
7871     pLvl->pDir = opendir(pLvl->zDir);
7872     if( pLvl->pDir==0 ){
7873       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
7874       return SQLITE_ERROR;
7875     }
7876   }
7877 
7878   while( pCur->iLvl>=0 ){
7879     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
7880     struct dirent *pEntry = readdir(pLvl->pDir);
7881     if( pEntry ){
7882       if( pEntry->d_name[0]=='.' ){
7883        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
7884        if( pEntry->d_name[1]=='\0' ) continue;
7885       }
7886       sqlite3_free(pCur->zPath);
7887       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
7888       if( pCur->zPath==0 ) return SQLITE_NOMEM;
7889       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7890         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7891         return SQLITE_ERROR;
7892       }
7893       return SQLITE_OK;
7894     }
7895     closedir(pLvl->pDir);
7896     sqlite3_free(pLvl->zDir);
7897     pLvl->pDir = 0;
7898     pLvl->zDir = 0;
7899     pCur->iLvl--;
7900   }
7901 
7902   /* EOF */
7903   sqlite3_free(pCur->zPath);
7904   pCur->zPath = 0;
7905   return SQLITE_OK;
7906 }
7907 
7908 /*
7909 ** Return values of columns for the row at which the series_cursor
7910 ** is currently pointing.
7911 */
fsdirColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)7912 static int fsdirColumn(
7913   sqlite3_vtab_cursor *cur,   /* The cursor */
7914   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7915   int i                       /* Which column to return */
7916 ){
7917   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7918   switch( i ){
7919     case FSDIR_COLUMN_NAME: {
7920       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
7921       break;
7922     }
7923 
7924     case FSDIR_COLUMN_MODE:
7925       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
7926       break;
7927 
7928     case FSDIR_COLUMN_MTIME:
7929       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
7930       break;
7931 
7932     case FSDIR_COLUMN_DATA: {
7933       mode_t m = pCur->sStat.st_mode;
7934       if( S_ISDIR(m) ){
7935         sqlite3_result_null(ctx);
7936 #if !defined(_WIN32) && !defined(WIN32)
7937       }else if( S_ISLNK(m) ){
7938         char aStatic[64];
7939         char *aBuf = aStatic;
7940         sqlite3_int64 nBuf = 64;
7941         int n;
7942 
7943         while( 1 ){
7944           n = readlink(pCur->zPath, aBuf, nBuf);
7945           if( n<nBuf ) break;
7946           if( aBuf!=aStatic ) sqlite3_free(aBuf);
7947           nBuf = nBuf*2;
7948           aBuf = sqlite3_malloc64(nBuf);
7949           if( aBuf==0 ){
7950             sqlite3_result_error_nomem(ctx);
7951             return SQLITE_NOMEM;
7952           }
7953         }
7954 
7955         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
7956         if( aBuf!=aStatic ) sqlite3_free(aBuf);
7957 #endif
7958       }else{
7959         readFileContents(ctx, pCur->zPath);
7960       }
7961     }
7962     case FSDIR_COLUMN_PATH:
7963     default: {
7964       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
7965       ** always return their values as NULL */
7966       break;
7967     }
7968   }
7969   return SQLITE_OK;
7970 }
7971 
7972 /*
7973 ** Return the rowid for the current row. In this implementation, the
7974 ** first row returned is assigned rowid value 1, and each subsequent
7975 ** row a value 1 more than that of the previous.
7976 */
fsdirRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)7977 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7978   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7979   *pRowid = pCur->iRowid;
7980   return SQLITE_OK;
7981 }
7982 
7983 /*
7984 ** Return TRUE if the cursor has been moved off of the last
7985 ** row of output.
7986 */
fsdirEof(sqlite3_vtab_cursor * cur)7987 static int fsdirEof(sqlite3_vtab_cursor *cur){
7988   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7989   return (pCur->zPath==0);
7990 }
7991 
7992 /*
7993 ** xFilter callback.
7994 **
7995 ** idxNum==1   PATH parameter only
7996 ** idxNum==2   Both PATH and DIR supplied
7997 */
fsdirFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)7998 static int fsdirFilter(
7999   sqlite3_vtab_cursor *cur,
8000   int idxNum, const char *idxStr,
8001   int argc, sqlite3_value **argv
8002 ){
8003   const char *zDir = 0;
8004   fsdir_cursor *pCur = (fsdir_cursor*)cur;
8005   (void)idxStr;
8006   fsdirResetCursor(pCur);
8007 
8008   if( idxNum==0 ){
8009     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
8010     return SQLITE_ERROR;
8011   }
8012 
8013   assert( argc==idxNum && (argc==1 || argc==2) );
8014   zDir = (const char*)sqlite3_value_text(argv[0]);
8015   if( zDir==0 ){
8016     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
8017     return SQLITE_ERROR;
8018   }
8019   if( argc==2 ){
8020     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
8021   }
8022   if( pCur->zBase ){
8023     pCur->nBase = (int)strlen(pCur->zBase)+1;
8024     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
8025   }else{
8026     pCur->zPath = sqlite3_mprintf("%s", zDir);
8027   }
8028 
8029   if( pCur->zPath==0 ){
8030     return SQLITE_NOMEM;
8031   }
8032   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
8033     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
8034     return SQLITE_ERROR;
8035   }
8036 
8037   return SQLITE_OK;
8038 }
8039 
8040 /*
8041 ** SQLite will invoke this method one or more times while planning a query
8042 ** that uses the generate_series virtual table.  This routine needs to create
8043 ** a query plan for each invocation and compute an estimated cost for that
8044 ** plan.
8045 **
8046 ** In this implementation idxNum is used to represent the
8047 ** query plan.  idxStr is unused.
8048 **
8049 ** The query plan is represented by values of idxNum:
8050 **
8051 **  (1)  The path value is supplied by argv[0]
8052 **  (2)  Path is in argv[0] and dir is in argv[1]
8053 */
fsdirBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)8054 static int fsdirBestIndex(
8055   sqlite3_vtab *tab,
8056   sqlite3_index_info *pIdxInfo
8057 ){
8058   int i;                 /* Loop over constraints */
8059   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
8060   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
8061   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
8062   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
8063   const struct sqlite3_index_constraint *pConstraint;
8064 
8065   (void)tab;
8066   pConstraint = pIdxInfo->aConstraint;
8067   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8068     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8069     switch( pConstraint->iColumn ){
8070       case FSDIR_COLUMN_PATH: {
8071         if( pConstraint->usable ){
8072           idxPath = i;
8073           seenPath = 0;
8074         }else if( idxPath<0 ){
8075           seenPath = 1;
8076         }
8077         break;
8078       }
8079       case FSDIR_COLUMN_DIR: {
8080         if( pConstraint->usable ){
8081           idxDir = i;
8082           seenDir = 0;
8083         }else if( idxDir<0 ){
8084           seenDir = 1;
8085         }
8086         break;
8087       }
8088     }
8089   }
8090   if( seenPath || seenDir ){
8091     /* If input parameters are unusable, disallow this plan */
8092     return SQLITE_CONSTRAINT;
8093   }
8094 
8095   if( idxPath<0 ){
8096     pIdxInfo->idxNum = 0;
8097     /* The pIdxInfo->estimatedCost should have been initialized to a huge
8098     ** number.  Leave it unchanged. */
8099     pIdxInfo->estimatedRows = 0x7fffffff;
8100   }else{
8101     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
8102     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
8103     if( idxDir>=0 ){
8104       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
8105       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
8106       pIdxInfo->idxNum = 2;
8107       pIdxInfo->estimatedCost = 10.0;
8108     }else{
8109       pIdxInfo->idxNum = 1;
8110       pIdxInfo->estimatedCost = 100.0;
8111     }
8112   }
8113 
8114   return SQLITE_OK;
8115 }
8116 
8117 /*
8118 ** Register the "fsdir" virtual table.
8119 */
fsdirRegister(sqlite3 * db)8120 static int fsdirRegister(sqlite3 *db){
8121   static sqlite3_module fsdirModule = {
8122     0,                         /* iVersion */
8123     0,                         /* xCreate */
8124     fsdirConnect,              /* xConnect */
8125     fsdirBestIndex,            /* xBestIndex */
8126     fsdirDisconnect,           /* xDisconnect */
8127     0,                         /* xDestroy */
8128     fsdirOpen,                 /* xOpen - open a cursor */
8129     fsdirClose,                /* xClose - close a cursor */
8130     fsdirFilter,               /* xFilter - configure scan constraints */
8131     fsdirNext,                 /* xNext - advance a cursor */
8132     fsdirEof,                  /* xEof - check for end of scan */
8133     fsdirColumn,               /* xColumn - read data */
8134     fsdirRowid,                /* xRowid - read data */
8135     0,                         /* xUpdate */
8136     0,                         /* xBegin */
8137     0,                         /* xSync */
8138     0,                         /* xCommit */
8139     0,                         /* xRollback */
8140     0,                         /* xFindMethod */
8141     0,                         /* xRename */
8142     0,                         /* xSavepoint */
8143     0,                         /* xRelease */
8144     0,                         /* xRollbackTo */
8145     0,                         /* xShadowName */
8146     0                          /* xIntegrity */
8147   };
8148 
8149   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
8150   return rc;
8151 }
8152 #else         /* SQLITE_OMIT_VIRTUALTABLE */
8153 # define fsdirRegister(x) SQLITE_OK
8154 #endif
8155 
8156 #ifdef _WIN32
8157 
8158 #endif
sqlite3_fileio_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8159 int sqlite3_fileio_init(
8160   sqlite3 *db,
8161   char **pzErrMsg,
8162   const sqlite3_api_routines *pApi
8163 ){
8164   int rc = SQLITE_OK;
8165   SQLITE_EXTENSION_INIT2(pApi);
8166   (void)pzErrMsg;  /* Unused parameter */
8167   rc = sqlite3_create_function(db, "readfile", 1,
8168                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8169                                readfileFunc, 0, 0);
8170   if( rc==SQLITE_OK ){
8171     rc = sqlite3_create_function(db, "writefile", -1,
8172                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8173                                  writefileFunc, 0, 0);
8174   }
8175   if( rc==SQLITE_OK ){
8176     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
8177                                  lsModeFunc, 0, 0);
8178   }
8179   if( rc==SQLITE_OK ){
8180     rc = fsdirRegister(db);
8181   }
8182   return rc;
8183 }
8184 
8185 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
8186 /* To allow a standalone DLL, make test_windirent.c use the same
8187  * redefined SQLite API calls as the above extension code does.
8188  * Just pull in this .c to accomplish this. As a beneficial side
8189  * effect, this extension becomes a single translation unit. */
8190 #  include "test_windirent.c"
8191 #endif
8192 
8193 /************************* End ../ext/misc/fileio.c ********************/
8194 /************************* Begin ../ext/misc/completion.c ******************/
8195 /*
8196 ** 2017-07-10
8197 **
8198 ** The author disclaims copyright to this source code.  In place of
8199 ** a legal notice, here is a blessing:
8200 **
8201 **    May you do good and not evil.
8202 **    May you find forgiveness for yourself and forgive others.
8203 **    May you share freely, never taking more than you give.
8204 **
8205 *************************************************************************
8206 **
8207 ** This file implements an eponymous virtual table that returns suggested
8208 ** completions for a partial SQL input.
8209 **
8210 ** Suggested usage:
8211 **
8212 **     SELECT DISTINCT candidate COLLATE nocase
8213 **       FROM completion($prefix,$wholeline)
8214 **      ORDER BY 1;
8215 **
8216 ** The two query parameters are optional.  $prefix is the text of the
8217 ** current word being typed and that is to be completed.  $wholeline is
8218 ** the complete input line, used for context.
8219 **
8220 ** The raw completion() table might return the same candidate multiple
8221 ** times, for example if the same column name is used to two or more
8222 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
8223 ** the DISTINCT and ORDER BY are recommended.
8224 **
8225 ** This virtual table operates at the speed of human typing, and so there
8226 ** is no attempt to make it fast.  Even a slow implementation will be much
8227 ** faster than any human can type.
8228 **
8229 */
8230 /* #include "sqlite3ext.h" */
8231 SQLITE_EXTENSION_INIT1
8232 #include <assert.h>
8233 #include <string.h>
8234 #include <ctype.h>
8235 
8236 #ifndef SQLITE_OMIT_VIRTUALTABLE
8237 
8238 /* completion_vtab is a subclass of sqlite3_vtab which will
8239 ** serve as the underlying representation of a completion virtual table
8240 */
8241 typedef struct completion_vtab completion_vtab;
8242 struct completion_vtab {
8243   sqlite3_vtab base;  /* Base class - must be first */
8244   sqlite3 *db;        /* Database connection for this completion vtab */
8245 };
8246 
8247 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
8248 ** serve as the underlying representation of a cursor that scans
8249 ** over rows of the result
8250 */
8251 typedef struct completion_cursor completion_cursor;
8252 struct completion_cursor {
8253   sqlite3_vtab_cursor base;  /* Base class - must be first */
8254   sqlite3 *db;               /* Database connection for this cursor */
8255   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
8256   char *zPrefix;             /* The prefix for the word we want to complete */
8257   char *zLine;               /* The whole that we want to complete */
8258   const char *zCurrentRow;   /* Current output row */
8259   int szRow;                 /* Length of the zCurrentRow string */
8260   sqlite3_stmt *pStmt;       /* Current statement */
8261   sqlite3_int64 iRowid;      /* The rowid */
8262   int ePhase;                /* Current phase */
8263   int j;                     /* inter-phase counter */
8264 };
8265 
8266 /* Values for ePhase:
8267 */
8268 #define COMPLETION_FIRST_PHASE   1
8269 #define COMPLETION_KEYWORDS      1
8270 #define COMPLETION_PRAGMAS       2
8271 #define COMPLETION_FUNCTIONS     3
8272 #define COMPLETION_COLLATIONS    4
8273 #define COMPLETION_INDEXES       5
8274 #define COMPLETION_TRIGGERS      6
8275 #define COMPLETION_DATABASES     7
8276 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
8277 #define COMPLETION_COLUMNS       9
8278 #define COMPLETION_MODULES       10
8279 #define COMPLETION_EOF           11
8280 
8281 /*
8282 ** The completionConnect() method is invoked to create a new
8283 ** completion_vtab that describes the completion virtual table.
8284 **
8285 ** Think of this routine as the constructor for completion_vtab objects.
8286 **
8287 ** All this routine needs to do is:
8288 **
8289 **    (1) Allocate the completion_vtab object and initialize all fields.
8290 **
8291 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
8292 **        result set of queries against completion will look like.
8293 */
completionConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)8294 static int completionConnect(
8295   sqlite3 *db,
8296   void *pAux,
8297   int argc, const char *const*argv,
8298   sqlite3_vtab **ppVtab,
8299   char **pzErr
8300 ){
8301   completion_vtab *pNew;
8302   int rc;
8303 
8304   (void)(pAux);    /* Unused parameter */
8305   (void)(argc);    /* Unused parameter */
8306   (void)(argv);    /* Unused parameter */
8307   (void)(pzErr);   /* Unused parameter */
8308 
8309 /* Column numbers */
8310 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
8311 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
8312 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
8313 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
8314 
8315   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
8316   rc = sqlite3_declare_vtab(db,
8317       "CREATE TABLE x("
8318       "  candidate TEXT,"
8319       "  prefix TEXT HIDDEN,"
8320       "  wholeline TEXT HIDDEN,"
8321       "  phase INT HIDDEN"        /* Used for debugging only */
8322       ")");
8323   if( rc==SQLITE_OK ){
8324     pNew = sqlite3_malloc( sizeof(*pNew) );
8325     *ppVtab = (sqlite3_vtab*)pNew;
8326     if( pNew==0 ) return SQLITE_NOMEM;
8327     memset(pNew, 0, sizeof(*pNew));
8328     pNew->db = db;
8329   }
8330   return rc;
8331 }
8332 
8333 /*
8334 ** This method is the destructor for completion_cursor objects.
8335 */
completionDisconnect(sqlite3_vtab * pVtab)8336 static int completionDisconnect(sqlite3_vtab *pVtab){
8337   sqlite3_free(pVtab);
8338   return SQLITE_OK;
8339 }
8340 
8341 /*
8342 ** Constructor for a new completion_cursor object.
8343 */
completionOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCursor)8344 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
8345   completion_cursor *pCur;
8346   pCur = sqlite3_malloc( sizeof(*pCur) );
8347   if( pCur==0 ) return SQLITE_NOMEM;
8348   memset(pCur, 0, sizeof(*pCur));
8349   pCur->db = ((completion_vtab*)p)->db;
8350   *ppCursor = &pCur->base;
8351   return SQLITE_OK;
8352 }
8353 
8354 /*
8355 ** Reset the completion_cursor.
8356 */
completionCursorReset(completion_cursor * pCur)8357 static void completionCursorReset(completion_cursor *pCur){
8358   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
8359   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
8360   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
8361   pCur->j = 0;
8362 }
8363 
8364 /*
8365 ** Destructor for a completion_cursor.
8366 */
completionClose(sqlite3_vtab_cursor * cur)8367 static int completionClose(sqlite3_vtab_cursor *cur){
8368   completionCursorReset((completion_cursor*)cur);
8369   sqlite3_free(cur);
8370   return SQLITE_OK;
8371 }
8372 
8373 /*
8374 ** Advance a completion_cursor to its next row of output.
8375 **
8376 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
8377 ** record the current state of the scan.  This routine sets ->zCurrentRow
8378 ** to the current row of output and then returns.  If no more rows remain,
8379 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
8380 ** table that has reached the end of its scan.
8381 **
8382 ** The current implementation just lists potential identifiers and
8383 ** keywords and filters them by zPrefix.  Future enhancements should
8384 ** take zLine into account to try to restrict the set of identifiers and
8385 ** keywords based on what would be legal at the current point of input.
8386 */
completionNext(sqlite3_vtab_cursor * cur)8387 static int completionNext(sqlite3_vtab_cursor *cur){
8388   completion_cursor *pCur = (completion_cursor*)cur;
8389   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
8390   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
8391   pCur->iRowid++;
8392   while( pCur->ePhase!=COMPLETION_EOF ){
8393     switch( pCur->ePhase ){
8394       case COMPLETION_KEYWORDS: {
8395         if( pCur->j >= sqlite3_keyword_count() ){
8396           pCur->zCurrentRow = 0;
8397           pCur->ePhase = COMPLETION_DATABASES;
8398         }else{
8399           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
8400         }
8401         iCol = -1;
8402         break;
8403       }
8404       case COMPLETION_DATABASES: {
8405         if( pCur->pStmt==0 ){
8406           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
8407                              &pCur->pStmt, 0);
8408         }
8409         iCol = 1;
8410         eNextPhase = COMPLETION_TABLES;
8411         break;
8412       }
8413       case COMPLETION_TABLES: {
8414         if( pCur->pStmt==0 ){
8415           sqlite3_stmt *pS2;
8416           char *zSql = 0;
8417           const char *zSep = "";
8418           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8419           while( sqlite3_step(pS2)==SQLITE_ROW ){
8420             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8421             zSql = sqlite3_mprintf(
8422                "%z%s"
8423                "SELECT name FROM \"%w\".sqlite_schema",
8424                zSql, zSep, zDb
8425             );
8426             if( zSql==0 ) return SQLITE_NOMEM;
8427             zSep = " UNION ";
8428           }
8429           sqlite3_finalize(pS2);
8430           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8431           sqlite3_free(zSql);
8432         }
8433         iCol = 0;
8434         eNextPhase = COMPLETION_COLUMNS;
8435         break;
8436       }
8437       case COMPLETION_COLUMNS: {
8438         if( pCur->pStmt==0 ){
8439           sqlite3_stmt *pS2;
8440           char *zSql = 0;
8441           const char *zSep = "";
8442           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8443           while( sqlite3_step(pS2)==SQLITE_ROW ){
8444             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8445             zSql = sqlite3_mprintf(
8446                "%z%s"
8447                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
8448                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
8449                " WHERE sm.type='table'",
8450                zSql, zSep, zDb, zDb
8451             );
8452             if( zSql==0 ) return SQLITE_NOMEM;
8453             zSep = " UNION ";
8454           }
8455           sqlite3_finalize(pS2);
8456           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8457           sqlite3_free(zSql);
8458         }
8459         iCol = 0;
8460         eNextPhase = COMPLETION_EOF;
8461         break;
8462       }
8463     }
8464     if( iCol<0 ){
8465       /* This case is when the phase presets zCurrentRow */
8466       if( pCur->zCurrentRow==0 ) continue;
8467     }else{
8468       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
8469         /* Extract the next row of content */
8470         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
8471         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
8472       }else{
8473         /* When all rows are finished, advance to the next phase */
8474         sqlite3_finalize(pCur->pStmt);
8475         pCur->pStmt = 0;
8476         pCur->ePhase = eNextPhase;
8477         continue;
8478       }
8479     }
8480     if( pCur->nPrefix==0 ) break;
8481     if( pCur->nPrefix<=pCur->szRow
8482      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
8483     ){
8484       break;
8485     }
8486   }
8487 
8488   return SQLITE_OK;
8489 }
8490 
8491 /*
8492 ** Return values of columns for the row at which the completion_cursor
8493 ** is currently pointing.
8494 */
completionColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)8495 static int completionColumn(
8496   sqlite3_vtab_cursor *cur,   /* The cursor */
8497   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8498   int i                       /* Which column to return */
8499 ){
8500   completion_cursor *pCur = (completion_cursor*)cur;
8501   switch( i ){
8502     case COMPLETION_COLUMN_CANDIDATE: {
8503       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
8504       break;
8505     }
8506     case COMPLETION_COLUMN_PREFIX: {
8507       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
8508       break;
8509     }
8510     case COMPLETION_COLUMN_WHOLELINE: {
8511       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
8512       break;
8513     }
8514     case COMPLETION_COLUMN_PHASE: {
8515       sqlite3_result_int(ctx, pCur->ePhase);
8516       break;
8517     }
8518   }
8519   return SQLITE_OK;
8520 }
8521 
8522 /*
8523 ** Return the rowid for the current row.  In this implementation, the
8524 ** rowid is the same as the output value.
8525 */
completionRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)8526 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8527   completion_cursor *pCur = (completion_cursor*)cur;
8528   *pRowid = pCur->iRowid;
8529   return SQLITE_OK;
8530 }
8531 
8532 /*
8533 ** Return TRUE if the cursor has been moved off of the last
8534 ** row of output.
8535 */
completionEof(sqlite3_vtab_cursor * cur)8536 static int completionEof(sqlite3_vtab_cursor *cur){
8537   completion_cursor *pCur = (completion_cursor*)cur;
8538   return pCur->ePhase >= COMPLETION_EOF;
8539 }
8540 
8541 /*
8542 ** This method is called to "rewind" the completion_cursor object back
8543 ** to the first row of output.  This method is always called at least
8544 ** once prior to any call to completionColumn() or completionRowid() or
8545 ** completionEof().
8546 */
completionFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)8547 static int completionFilter(
8548   sqlite3_vtab_cursor *pVtabCursor,
8549   int idxNum, const char *idxStr,
8550   int argc, sqlite3_value **argv
8551 ){
8552   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
8553   int iArg = 0;
8554   (void)(idxStr);   /* Unused parameter */
8555   (void)(argc);     /* Unused parameter */
8556   completionCursorReset(pCur);
8557   if( idxNum & 1 ){
8558     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
8559     if( pCur->nPrefix>0 ){
8560       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8561       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8562     }
8563     iArg = 1;
8564   }
8565   if( idxNum & 2 ){
8566     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
8567     if( pCur->nLine>0 ){
8568       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8569       if( pCur->zLine==0 ) return SQLITE_NOMEM;
8570     }
8571   }
8572   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
8573     int i = pCur->nLine;
8574     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
8575       i--;
8576     }
8577     pCur->nPrefix = pCur->nLine - i;
8578     if( pCur->nPrefix>0 ){
8579       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
8580       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8581     }
8582   }
8583   pCur->iRowid = 0;
8584   pCur->ePhase = COMPLETION_FIRST_PHASE;
8585   return completionNext(pVtabCursor);
8586 }
8587 
8588 /*
8589 ** SQLite will invoke this method one or more times while planning a query
8590 ** that uses the completion virtual table.  This routine needs to create
8591 ** a query plan for each invocation and compute an estimated cost for that
8592 ** plan.
8593 **
8594 ** There are two hidden parameters that act as arguments to the table-valued
8595 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
8596 ** is available and bit 1 is set if "wholeline" is available.
8597 */
completionBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)8598 static int completionBestIndex(
8599   sqlite3_vtab *tab,
8600   sqlite3_index_info *pIdxInfo
8601 ){
8602   int i;                 /* Loop over constraints */
8603   int idxNum = 0;        /* The query plan bitmask */
8604   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
8605   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
8606   int nArg = 0;          /* Number of arguments that completeFilter() expects */
8607   const struct sqlite3_index_constraint *pConstraint;
8608 
8609   (void)(tab);    /* Unused parameter */
8610   pConstraint = pIdxInfo->aConstraint;
8611   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8612     if( pConstraint->usable==0 ) continue;
8613     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8614     switch( pConstraint->iColumn ){
8615       case COMPLETION_COLUMN_PREFIX:
8616         prefixIdx = i;
8617         idxNum |= 1;
8618         break;
8619       case COMPLETION_COLUMN_WHOLELINE:
8620         wholelineIdx = i;
8621         idxNum |= 2;
8622         break;
8623     }
8624   }
8625   if( prefixIdx>=0 ){
8626     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
8627     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
8628   }
8629   if( wholelineIdx>=0 ){
8630     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
8631     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
8632   }
8633   pIdxInfo->idxNum = idxNum;
8634   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
8635   pIdxInfo->estimatedRows = 500 - 100*nArg;
8636   return SQLITE_OK;
8637 }
8638 
8639 /*
8640 ** This following structure defines all the methods for the
8641 ** completion virtual table.
8642 */
8643 static sqlite3_module completionModule = {
8644   0,                         /* iVersion */
8645   0,                         /* xCreate */
8646   completionConnect,         /* xConnect */
8647   completionBestIndex,       /* xBestIndex */
8648   completionDisconnect,      /* xDisconnect */
8649   0,                         /* xDestroy */
8650   completionOpen,            /* xOpen - open a cursor */
8651   completionClose,           /* xClose - close a cursor */
8652   completionFilter,          /* xFilter - configure scan constraints */
8653   completionNext,            /* xNext - advance a cursor */
8654   completionEof,             /* xEof - check for end of scan */
8655   completionColumn,          /* xColumn - read data */
8656   completionRowid,           /* xRowid - read data */
8657   0,                         /* xUpdate */
8658   0,                         /* xBegin */
8659   0,                         /* xSync */
8660   0,                         /* xCommit */
8661   0,                         /* xRollback */
8662   0,                         /* xFindMethod */
8663   0,                         /* xRename */
8664   0,                         /* xSavepoint */
8665   0,                         /* xRelease */
8666   0,                         /* xRollbackTo */
8667   0,                         /* xShadowName */
8668   0                          /* xIntegrity */
8669 };
8670 
8671 #endif /* SQLITE_OMIT_VIRTUALTABLE */
8672 
sqlite3CompletionVtabInit(sqlite3 * db)8673 int sqlite3CompletionVtabInit(sqlite3 *db){
8674   int rc = SQLITE_OK;
8675 #ifndef SQLITE_OMIT_VIRTUALTABLE
8676   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
8677 #endif
8678   return rc;
8679 }
8680 
8681 #ifdef _WIN32
8682 
8683 #endif
sqlite3_completion_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)8684 int sqlite3_completion_init(
8685   sqlite3 *db,
8686   char **pzErrMsg,
8687   const sqlite3_api_routines *pApi
8688 ){
8689   int rc = SQLITE_OK;
8690   SQLITE_EXTENSION_INIT2(pApi);
8691   (void)(pzErrMsg);  /* Unused parameter */
8692 #ifndef SQLITE_OMIT_VIRTUALTABLE
8693   rc = sqlite3CompletionVtabInit(db);
8694 #endif
8695   return rc;
8696 }
8697 
8698 /************************* End ../ext/misc/completion.c ********************/
8699 /************************* Begin ../ext/misc/appendvfs.c ******************/
8700 /*
8701 ** 2017-10-20
8702 **
8703 ** The author disclaims copyright to this source code.  In place of
8704 ** a legal notice, here is a blessing:
8705 **
8706 **    May you do good and not evil.
8707 **    May you find forgiveness for yourself and forgive others.
8708 **    May you share freely, never taking more than you give.
8709 **
8710 ******************************************************************************
8711 **
8712 ** This file implements a VFS shim that allows an SQLite database to be
8713 ** appended onto the end of some other file, such as an executable.
8714 **
8715 ** A special record must appear at the end of the file that identifies the
8716 ** file as an appended database and provides the offset to the first page
8717 ** of the exposed content. (Or, it is the length of the content prefix.)
8718 ** For best performance page 1 should be located at a disk page boundary,
8719 ** though that is not required.
8720 **
8721 ** When opening a database using this VFS, the connection might treat
8722 ** the file as an ordinary SQLite database, or it might treat it as a
8723 ** database appended onto some other file.  The decision is made by
8724 ** applying the following rules in order:
8725 **
8726 **  (1)  An empty file is an ordinary database.
8727 **
8728 **  (2)  If the file ends with the appendvfs trailer string
8729 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
8730 **
8731 **  (3)  If the file begins with the standard SQLite prefix string
8732 **       "SQLite format 3", that file is an ordinary database.
8733 **
8734 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
8735 **       set, then a new database is appended to the already existing file.
8736 **
8737 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
8738 **
8739 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
8740 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
8741 ** This VFS will not read or write past the 1GiB mark.  This restriction
8742 ** might be lifted in future versions.  For now, if you need a larger
8743 ** database, then keep it in a separate file.
8744 **
8745 ** If the file being opened is a plain database (not an appended one), then
8746 ** this shim is a pass-through into the default underlying VFS. (rule 3)
8747 **/
8748 /* #include "sqlite3ext.h" */
8749 SQLITE_EXTENSION_INIT1
8750 #include <string.h>
8751 #include <assert.h>
8752 
8753 /* The append mark at the end of the database is:
8754 **
8755 **     Start-Of-SQLite3-NNNNNNNN
8756 **     123456789 123456789 12345
8757 **
8758 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
8759 ** the offset to page 1, and also the length of the prefix content.
8760 */
8761 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
8762 #define APND_MARK_PREFIX_SZ  17
8763 #define APND_MARK_FOS_SZ      8
8764 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
8765 
8766 /*
8767 ** Maximum size of the combined prefix + database + append-mark.  This
8768 ** must be less than 0x40000000 to avoid locking issues on Windows.
8769 */
8770 #define APND_MAX_SIZE  (0x40000000)
8771 
8772 /*
8773 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
8774 */
8775 #ifndef APND_ROUNDUP
8776 #define APND_ROUNDUP 4096
8777 #endif
8778 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
8779 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
8780 
8781 /*
8782 ** Forward declaration of objects used by this utility
8783 */
8784 typedef struct sqlite3_vfs ApndVfs;
8785 typedef struct ApndFile ApndFile;
8786 
8787 /* Access to a lower-level VFS that (might) implement dynamic loading,
8788 ** access to randomness, etc.
8789 */
8790 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
8791 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
8792 
8793 /* An open appendvfs file
8794 **
8795 ** An instance of this structure describes the appended database file.
8796 ** A separate sqlite3_file object is always appended. The appended
8797 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
8798 ** the entire file, including the prefix, the database, and the
8799 ** append-mark.
8800 **
8801 ** The structure of an AppendVFS database is like this:
8802 **
8803 **   +-------------+---------+----------+-------------+
8804 **   | prefix-file | padding | database | append-mark |
8805 **   +-------------+---------+----------+-------------+
8806 **                           ^          ^
8807 **                           |          |
8808 **                         iPgOne      iMark
8809 **
8810 **
8811 ** "prefix file" -  file onto which the database has been appended.
8812 ** "padding"     -  zero or more bytes inserted so that "database"
8813 **                  starts on an APND_ROUNDUP boundary
8814 ** "database"    -  The SQLite database file
8815 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8816 **                  the offset from the start of prefix-file to the start
8817 **                  of "database".
8818 **
8819 ** The size of the database is iMark - iPgOne.
8820 **
8821 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8822 ** of iPgOne stored as a big-ending 64-bit integer.
8823 **
8824 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
8825 ** Or, iMark is -1 to indicate that it has not yet been written.
8826 */
8827 struct ApndFile {
8828   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
8829   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
8830   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
8831   /* Always followed by another sqlite3_file that describes the whole file */
8832 };
8833 
8834 /*
8835 ** Methods for ApndFile
8836 */
8837 static int apndClose(sqlite3_file*);
8838 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
8839 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
8840 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
8841 static int apndSync(sqlite3_file*, int flags);
8842 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
8843 static int apndLock(sqlite3_file*, int);
8844 static int apndUnlock(sqlite3_file*, int);
8845 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
8846 static int apndFileControl(sqlite3_file*, int op, void *pArg);
8847 static int apndSectorSize(sqlite3_file*);
8848 static int apndDeviceCharacteristics(sqlite3_file*);
8849 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
8850 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
8851 static void apndShmBarrier(sqlite3_file*);
8852 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
8853 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
8854 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
8855 
8856 /*
8857 ** Methods for ApndVfs
8858 */
8859 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
8860 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
8861 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
8862 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
8863 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
8864 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
8865 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
8866 static void apndDlClose(sqlite3_vfs*, void*);
8867 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
8868 static int apndSleep(sqlite3_vfs*, int microseconds);
8869 static int apndCurrentTime(sqlite3_vfs*, double*);
8870 static int apndGetLastError(sqlite3_vfs*, int, char *);
8871 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
8872 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
8873 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
8874 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
8875 
8876 static sqlite3_vfs apnd_vfs = {
8877   3,                            /* iVersion (set when registered) */
8878   0,                            /* szOsFile (set when registered) */
8879   1024,                         /* mxPathname */
8880   0,                            /* pNext */
8881   "apndvfs",                    /* zName */
8882   0,                            /* pAppData (set when registered) */
8883   apndOpen,                     /* xOpen */
8884   apndDelete,                   /* xDelete */
8885   apndAccess,                   /* xAccess */
8886   apndFullPathname,             /* xFullPathname */
8887   apndDlOpen,                   /* xDlOpen */
8888   apndDlError,                  /* xDlError */
8889   apndDlSym,                    /* xDlSym */
8890   apndDlClose,                  /* xDlClose */
8891   apndRandomness,               /* xRandomness */
8892   apndSleep,                    /* xSleep */
8893   apndCurrentTime,              /* xCurrentTime */
8894   apndGetLastError,             /* xGetLastError */
8895   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
8896   apndSetSystemCall,            /* xSetSystemCall */
8897   apndGetSystemCall,            /* xGetSystemCall */
8898   apndNextSystemCall            /* xNextSystemCall */
8899 };
8900 
8901 static const sqlite3_io_methods apnd_io_methods = {
8902   3,                              /* iVersion */
8903   apndClose,                      /* xClose */
8904   apndRead,                       /* xRead */
8905   apndWrite,                      /* xWrite */
8906   apndTruncate,                   /* xTruncate */
8907   apndSync,                       /* xSync */
8908   apndFileSize,                   /* xFileSize */
8909   apndLock,                       /* xLock */
8910   apndUnlock,                     /* xUnlock */
8911   apndCheckReservedLock,          /* xCheckReservedLock */
8912   apndFileControl,                /* xFileControl */
8913   apndSectorSize,                 /* xSectorSize */
8914   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
8915   apndShmMap,                     /* xShmMap */
8916   apndShmLock,                    /* xShmLock */
8917   apndShmBarrier,                 /* xShmBarrier */
8918   apndShmUnmap,                   /* xShmUnmap */
8919   apndFetch,                      /* xFetch */
8920   apndUnfetch                     /* xUnfetch */
8921 };
8922 
8923 /*
8924 ** Close an apnd-file.
8925 */
apndClose(sqlite3_file * pFile)8926 static int apndClose(sqlite3_file *pFile){
8927   pFile = ORIGFILE(pFile);
8928   return pFile->pMethods->xClose(pFile);
8929 }
8930 
8931 /*
8932 ** Read data from an apnd-file.
8933 */
apndRead(sqlite3_file * pFile,void * zBuf,int iAmt,sqlite_int64 iOfst)8934 static int apndRead(
8935   sqlite3_file *pFile,
8936   void *zBuf,
8937   int iAmt,
8938   sqlite_int64 iOfst
8939 ){
8940   ApndFile *paf = (ApndFile *)pFile;
8941   pFile = ORIGFILE(pFile);
8942   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8943 }
8944 
8945 /*
8946 ** Add the append-mark onto what should become the end of the file.
8947 *  If and only if this succeeds, internal ApndFile.iMark is updated.
8948 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8949 */
apndWriteMark(ApndFile * paf,sqlite3_file * pFile,sqlite_int64 iWriteEnd)8950 static int apndWriteMark(
8951   ApndFile *paf,
8952   sqlite3_file *pFile,
8953   sqlite_int64 iWriteEnd
8954 ){
8955   sqlite_int64 iPgOne = paf->iPgOne;
8956   unsigned char a[APND_MARK_SIZE];
8957   int i = APND_MARK_FOS_SZ;
8958   int rc;
8959   assert(pFile == ORIGFILE(paf));
8960   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
8961   while( --i >= 0 ){
8962     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
8963     iPgOne >>= 8;
8964   }
8965   iWriteEnd += paf->iPgOne;
8966   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
8967                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
8968     paf->iMark = iWriteEnd;
8969   }
8970   return rc;
8971 }
8972 
8973 /*
8974 ** Write data to an apnd-file.
8975 */
apndWrite(sqlite3_file * pFile,const void * zBuf,int iAmt,sqlite_int64 iOfst)8976 static int apndWrite(
8977   sqlite3_file *pFile,
8978   const void *zBuf,
8979   int iAmt,
8980   sqlite_int64 iOfst
8981 ){
8982   ApndFile *paf = (ApndFile *)pFile;
8983   sqlite_int64 iWriteEnd = iOfst + iAmt;
8984   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
8985   pFile = ORIGFILE(pFile);
8986   /* If append-mark is absent or will be overwritten, write it. */
8987   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
8988     int rc = apndWriteMark(paf, pFile, iWriteEnd);
8989     if( SQLITE_OK!=rc ) return rc;
8990   }
8991   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8992 }
8993 
8994 /*
8995 ** Truncate an apnd-file.
8996 */
apndTruncate(sqlite3_file * pFile,sqlite_int64 size)8997 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
8998   ApndFile *paf = (ApndFile *)pFile;
8999   pFile = ORIGFILE(pFile);
9000   /* The append mark goes out first so truncate failure does not lose it. */
9001   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
9002   /* Truncate underlying file just past append mark */
9003   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
9004 }
9005 
9006 /*
9007 ** Sync an apnd-file.
9008 */
apndSync(sqlite3_file * pFile,int flags)9009 static int apndSync(sqlite3_file *pFile, int flags){
9010   pFile = ORIGFILE(pFile);
9011   return pFile->pMethods->xSync(pFile, flags);
9012 }
9013 
9014 /*
9015 ** Return the current file-size of an apnd-file.
9016 ** If the append mark is not yet there, the file-size is 0.
9017 */
apndFileSize(sqlite3_file * pFile,sqlite_int64 * pSize)9018 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
9019   ApndFile *paf = (ApndFile *)pFile;
9020   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
9021   return SQLITE_OK;
9022 }
9023 
9024 /*
9025 ** Lock an apnd-file.
9026 */
apndLock(sqlite3_file * pFile,int eLock)9027 static int apndLock(sqlite3_file *pFile, int eLock){
9028   pFile = ORIGFILE(pFile);
9029   return pFile->pMethods->xLock(pFile, eLock);
9030 }
9031 
9032 /*
9033 ** Unlock an apnd-file.
9034 */
apndUnlock(sqlite3_file * pFile,int eLock)9035 static int apndUnlock(sqlite3_file *pFile, int eLock){
9036   pFile = ORIGFILE(pFile);
9037   return pFile->pMethods->xUnlock(pFile, eLock);
9038 }
9039 
9040 /*
9041 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
9042 */
apndCheckReservedLock(sqlite3_file * pFile,int * pResOut)9043 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
9044   pFile = ORIGFILE(pFile);
9045   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
9046 }
9047 
9048 /*
9049 ** File control method. For custom operations on an apnd-file.
9050 */
apndFileControl(sqlite3_file * pFile,int op,void * pArg)9051 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
9052   ApndFile *paf = (ApndFile *)pFile;
9053   int rc;
9054   pFile = ORIGFILE(pFile);
9055   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
9056   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
9057   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
9058     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
9059   }
9060   return rc;
9061 }
9062 
9063 /*
9064 ** Return the sector-size in bytes for an apnd-file.
9065 */
apndSectorSize(sqlite3_file * pFile)9066 static int apndSectorSize(sqlite3_file *pFile){
9067   pFile = ORIGFILE(pFile);
9068   return pFile->pMethods->xSectorSize(pFile);
9069 }
9070 
9071 /*
9072 ** Return the device characteristic flags supported by an apnd-file.
9073 */
apndDeviceCharacteristics(sqlite3_file * pFile)9074 static int apndDeviceCharacteristics(sqlite3_file *pFile){
9075   pFile = ORIGFILE(pFile);
9076   return pFile->pMethods->xDeviceCharacteristics(pFile);
9077 }
9078 
9079 /* Create a shared memory file mapping */
apndShmMap(sqlite3_file * pFile,int iPg,int pgsz,int bExtend,void volatile ** pp)9080 static int apndShmMap(
9081   sqlite3_file *pFile,
9082   int iPg,
9083   int pgsz,
9084   int bExtend,
9085   void volatile **pp
9086 ){
9087   pFile = ORIGFILE(pFile);
9088   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
9089 }
9090 
9091 /* Perform locking on a shared-memory segment */
apndShmLock(sqlite3_file * pFile,int offset,int n,int flags)9092 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
9093   pFile = ORIGFILE(pFile);
9094   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
9095 }
9096 
9097 /* Memory barrier operation on shared memory */
apndShmBarrier(sqlite3_file * pFile)9098 static void apndShmBarrier(sqlite3_file *pFile){
9099   pFile = ORIGFILE(pFile);
9100   pFile->pMethods->xShmBarrier(pFile);
9101 }
9102 
9103 /* Unmap a shared memory segment */
apndShmUnmap(sqlite3_file * pFile,int deleteFlag)9104 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
9105   pFile = ORIGFILE(pFile);
9106   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
9107 }
9108 
9109 /* Fetch a page of a memory-mapped file */
apndFetch(sqlite3_file * pFile,sqlite3_int64 iOfst,int iAmt,void ** pp)9110 static int apndFetch(
9111   sqlite3_file *pFile,
9112   sqlite3_int64 iOfst,
9113   int iAmt,
9114   void **pp
9115 ){
9116   ApndFile *p = (ApndFile *)pFile;
9117   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
9118     return SQLITE_IOERR; /* Cannot read what is not yet there. */
9119   }
9120   pFile = ORIGFILE(pFile);
9121   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
9122 }
9123 
9124 /* Release a memory-mapped page */
apndUnfetch(sqlite3_file * pFile,sqlite3_int64 iOfst,void * pPage)9125 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
9126   ApndFile *p = (ApndFile *)pFile;
9127   pFile = ORIGFILE(pFile);
9128   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
9129 }
9130 
9131 /*
9132 ** Try to read the append-mark off the end of a file.  Return the
9133 ** start of the appended database if the append-mark is present.
9134 ** If there is no valid append-mark, return -1;
9135 **
9136 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
9137 ** indicates that the appended database contains at least one page.  The
9138 ** start-of-database value must be a multiple of 512.
9139 */
apndReadMark(sqlite3_int64 sz,sqlite3_file * pFile)9140 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
9141   int rc, i;
9142   sqlite3_int64 iMark;
9143   int msbs = 8 * (APND_MARK_FOS_SZ-1);
9144   unsigned char a[APND_MARK_SIZE];
9145 
9146   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
9147   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
9148   if( rc ) return -1;
9149   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
9150   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
9151   for(i=1; i<8; i++){
9152     msbs -= 8;
9153     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
9154   }
9155   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
9156   if( iMark & 0x1ff ) return -1;
9157   return iMark;
9158 }
9159 
9160 static const char apvfsSqliteHdr[] = "SQLite format 3";
9161 /*
9162 ** Check to see if the file is an appendvfs SQLite database file.
9163 ** Return true iff it is such. Parameter sz is the file's size.
9164 */
apndIsAppendvfsDatabase(sqlite3_int64 sz,sqlite3_file * pFile)9165 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
9166   int rc;
9167   char zHdr[16];
9168   sqlite3_int64 iMark = apndReadMark(sz, pFile);
9169   if( iMark>=0 ){
9170     /* If file has the correct end-marker, the expected odd size, and the
9171     ** SQLite DB type marker where the end-marker puts it, then it
9172     ** is an appendvfs database.
9173     */
9174     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
9175     if( SQLITE_OK==rc
9176      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
9177      && (sz & 0x1ff) == APND_MARK_SIZE
9178      && sz>=512+APND_MARK_SIZE
9179     ){
9180       return 1; /* It's an appendvfs database */
9181     }
9182   }
9183   return 0;
9184 }
9185 
9186 /*
9187 ** Check to see if the file is an ordinary SQLite database file.
9188 ** Return true iff so. Parameter sz is the file's size.
9189 */
apndIsOrdinaryDatabaseFile(sqlite3_int64 sz,sqlite3_file * pFile)9190 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
9191   char zHdr[16];
9192   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
9193    || (sz & 0x1ff) != 0
9194    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
9195    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
9196   ){
9197     return 0;
9198   }else{
9199     return 1;
9200   }
9201 }
9202 
9203 /*
9204 ** Open an apnd file handle.
9205 */
apndOpen(sqlite3_vfs * pApndVfs,const char * zName,sqlite3_file * pFile,int flags,int * pOutFlags)9206 static int apndOpen(
9207   sqlite3_vfs *pApndVfs,
9208   const char *zName,
9209   sqlite3_file *pFile,
9210   int flags,
9211   int *pOutFlags
9212 ){
9213   ApndFile *pApndFile = (ApndFile*)pFile;
9214   sqlite3_file *pBaseFile = ORIGFILE(pFile);
9215   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
9216   int rc;
9217   sqlite3_int64 sz = 0;
9218   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
9219     /* The appendvfs is not to be used for transient or temporary databases.
9220     ** Just use the base VFS open to initialize the given file object and
9221     ** open the underlying file. (Appendvfs is then unused for this file.)
9222     */
9223     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
9224   }
9225   memset(pApndFile, 0, sizeof(ApndFile));
9226   pFile->pMethods = &apnd_io_methods;
9227   pApndFile->iMark = -1;    /* Append mark not yet written */
9228 
9229   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
9230   if( rc==SQLITE_OK ){
9231     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
9232     if( rc ){
9233       pBaseFile->pMethods->xClose(pBaseFile);
9234     }
9235   }
9236   if( rc ){
9237     pFile->pMethods = 0;
9238     return rc;
9239   }
9240   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
9241     /* The file being opened appears to be just an ordinary DB. Copy
9242     ** the base dispatch-table so this instance mimics the base VFS.
9243     */
9244     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
9245     return SQLITE_OK;
9246   }
9247   pApndFile->iPgOne = apndReadMark(sz, pFile);
9248   if( pApndFile->iPgOne>=0 ){
9249     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
9250     return SQLITE_OK;
9251   }
9252   if( (flags & SQLITE_OPEN_CREATE)==0 ){
9253     pBaseFile->pMethods->xClose(pBaseFile);
9254     rc = SQLITE_CANTOPEN;
9255     pFile->pMethods = 0;
9256   }else{
9257     /* Round newly added appendvfs location to #define'd page boundary.
9258     ** Note that nothing has yet been written to the underlying file.
9259     ** The append mark will be written along with first content write.
9260     ** Until then, paf->iMark value indicates it is not yet written.
9261     */
9262     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
9263   }
9264   return rc;
9265 }
9266 
9267 /*
9268 ** Delete an apnd file.
9269 ** For an appendvfs, this could mean delete the appendvfs portion,
9270 ** leaving the appendee as it was before it gained an appendvfs.
9271 ** For now, this code deletes the underlying file too.
9272 */
apndDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)9273 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
9274   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
9275 }
9276 
9277 /*
9278 ** All other VFS methods are pass-thrus.
9279 */
apndAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)9280 static int apndAccess(
9281   sqlite3_vfs *pVfs,
9282   const char *zPath,
9283   int flags,
9284   int *pResOut
9285 ){
9286   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
9287 }
apndFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nOut,char * zOut)9288 static int apndFullPathname(
9289   sqlite3_vfs *pVfs,
9290   const char *zPath,
9291   int nOut,
9292   char *zOut
9293 ){
9294   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
9295 }
apndDlOpen(sqlite3_vfs * pVfs,const char * zPath)9296 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
9297   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
9298 }
apndDlError(sqlite3_vfs * pVfs,int nByte,char * zErrMsg)9299 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
9300   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
9301 }
apndDlSym(sqlite3_vfs * pVfs,void * p,const char * zSym)9302 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
9303   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
9304 }
apndDlClose(sqlite3_vfs * pVfs,void * pHandle)9305 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
9306   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
9307 }
apndRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)9308 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
9309   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
9310 }
apndSleep(sqlite3_vfs * pVfs,int nMicro)9311 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
9312   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
9313 }
apndCurrentTime(sqlite3_vfs * pVfs,double * pTimeOut)9314 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
9315   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
9316 }
apndGetLastError(sqlite3_vfs * pVfs,int a,char * b)9317 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
9318   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
9319 }
apndCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * p)9320 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
9321   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
9322 }
apndSetSystemCall(sqlite3_vfs * pVfs,const char * zName,sqlite3_syscall_ptr pCall)9323 static int apndSetSystemCall(
9324   sqlite3_vfs *pVfs,
9325   const char *zName,
9326   sqlite3_syscall_ptr pCall
9327 ){
9328   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
9329 }
apndGetSystemCall(sqlite3_vfs * pVfs,const char * zName)9330 static sqlite3_syscall_ptr apndGetSystemCall(
9331   sqlite3_vfs *pVfs,
9332   const char *zName
9333 ){
9334   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
9335 }
apndNextSystemCall(sqlite3_vfs * pVfs,const char * zName)9336 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
9337   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
9338 }
9339 
9340 
9341 #ifdef _WIN32
9342 
9343 #endif
9344 /*
9345 ** This routine is called when the extension is loaded.
9346 ** Register the new VFS.
9347 */
sqlite3_appendvfs_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)9348 int sqlite3_appendvfs_init(
9349   sqlite3 *db,
9350   char **pzErrMsg,
9351   const sqlite3_api_routines *pApi
9352 ){
9353   int rc = SQLITE_OK;
9354   sqlite3_vfs *pOrig;
9355   SQLITE_EXTENSION_INIT2(pApi);
9356   (void)pzErrMsg;
9357   (void)db;
9358   pOrig = sqlite3_vfs_find(0);
9359   if( pOrig==0 ) return SQLITE_ERROR;
9360   apnd_vfs.iVersion = pOrig->iVersion;
9361   apnd_vfs.pAppData = pOrig;
9362   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
9363   rc = sqlite3_vfs_register(&apnd_vfs, 0);
9364 #ifdef APPENDVFS_TEST
9365   if( rc==SQLITE_OK ){
9366     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
9367   }
9368 #endif
9369   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
9370   return rc;
9371 }
9372 
9373 /************************* End ../ext/misc/appendvfs.c ********************/
9374 #endif
9375 #ifdef SQLITE_HAVE_ZLIB
9376 /************************* Begin ../ext/misc/zipfile.c ******************/
9377 /*
9378 ** 2017-12-26
9379 **
9380 ** The author disclaims copyright to this source code.  In place of
9381 ** a legal notice, here is a blessing:
9382 **
9383 **    May you do good and not evil.
9384 **    May you find forgiveness for yourself and forgive others.
9385 **    May you share freely, never taking more than you give.
9386 **
9387 ******************************************************************************
9388 **
9389 ** This file implements a virtual table for reading and writing ZIP archive
9390 ** files.
9391 **
9392 ** Usage example:
9393 **
9394 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
9395 **
9396 ** Current limitations:
9397 **
9398 **    *  No support for encryption
9399 **    *  No support for ZIP archives spanning multiple files
9400 **    *  No support for zip64 extensions
9401 **    *  Only the "inflate/deflate" (zlib) compression method is supported
9402 */
9403 /* #include "sqlite3ext.h" */
9404 SQLITE_EXTENSION_INIT1
9405 #include <stdio.h>
9406 #include <string.h>
9407 #include <assert.h>
9408 #include <stdint.h>
9409 
9410 #include <zlib.h>
9411 
9412 #ifndef SQLITE_OMIT_VIRTUALTABLE
9413 
9414 #ifndef SQLITE_AMALGAMATION
9415 
9416 #ifndef UINT32_TYPE
9417 # ifdef HAVE_UINT32_T
9418 #  define UINT32_TYPE uint32_t
9419 # else
9420 #  define UINT32_TYPE unsigned int
9421 # endif
9422 #endif
9423 #ifndef UINT16_TYPE
9424 # ifdef HAVE_UINT16_T
9425 #  define UINT16_TYPE uint16_t
9426 # else
9427 #  define UINT16_TYPE unsigned short int
9428 # endif
9429 #endif
9430 /* typedef sqlite3_int64 i64; */
9431 /* typedef unsigned char u8; */
9432 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
9433 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
9434 #define MIN(a,b) ((a)<(b) ? (a) : (b))
9435 
9436 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
9437 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
9438 #endif
9439 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
9440 # define ALWAYS(X)      (1)
9441 # define NEVER(X)       (0)
9442 #elif !defined(NDEBUG)
9443 # define ALWAYS(X)      ((X)?1:(assert(0),0))
9444 # define NEVER(X)       ((X)?(assert(0),1):0)
9445 #else
9446 # define ALWAYS(X)      (X)
9447 # define NEVER(X)       (X)
9448 #endif
9449 
9450 #endif   /* SQLITE_AMALGAMATION */
9451 
9452 /*
9453 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
9454 **
9455 ** In some ways it would be better to obtain these values from system
9456 ** header files. But, the dependency is undesirable and (a) these
9457 ** have been stable for decades, (b) the values are part of POSIX and
9458 ** are also made explicit in [man stat], and (c) are part of the
9459 ** file format for zip archives.
9460 */
9461 #ifndef S_IFDIR
9462 # define S_IFDIR 0040000
9463 #endif
9464 #ifndef S_IFREG
9465 # define S_IFREG 0100000
9466 #endif
9467 #ifndef S_IFLNK
9468 # define S_IFLNK 0120000
9469 #endif
9470 
9471 static const char ZIPFILE_SCHEMA[] =
9472   "CREATE TABLE y("
9473     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
9474     "mode,"              /* 1: POSIX mode for file */
9475     "mtime,"             /* 2: Last modification time (secs since 1970)*/
9476     "sz,"                /* 3: Size of object */
9477     "rawdata,"           /* 4: Raw data */
9478     "data,"              /* 5: Uncompressed data */
9479     "method,"            /* 6: Compression method (integer) */
9480     "z HIDDEN"           /* 7: Name of zip file */
9481   ") WITHOUT ROWID;";
9482 
9483 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
9484 #define ZIPFILE_BUFFER_SIZE (64*1024)
9485 
9486 
9487 /*
9488 ** Magic numbers used to read and write zip files.
9489 **
9490 ** ZIPFILE_NEWENTRY_MADEBY:
9491 **   Use this value for the "version-made-by" field in new zip file
9492 **   entries. The upper byte indicates "unix", and the lower byte
9493 **   indicates that the zip file matches pkzip specification 3.0.
9494 **   This is what info-zip seems to do.
9495 **
9496 ** ZIPFILE_NEWENTRY_REQUIRED:
9497 **   Value for "version-required-to-extract" field of new entries.
9498 **   Version 2.0 is required to support folders and deflate compression.
9499 **
9500 ** ZIPFILE_NEWENTRY_FLAGS:
9501 **   Value for "general-purpose-bit-flags" field of new entries. Bit
9502 **   11 means "utf-8 filename and comment".
9503 **
9504 ** ZIPFILE_SIGNATURE_CDS:
9505 **   First 4 bytes of a valid CDS record.
9506 **
9507 ** ZIPFILE_SIGNATURE_LFH:
9508 **   First 4 bytes of a valid LFH record.
9509 **
9510 ** ZIPFILE_SIGNATURE_EOCD
9511 **   First 4 bytes of a valid EOCD record.
9512 */
9513 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
9514 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
9515 #define ZIPFILE_NEWENTRY_REQUIRED 20
9516 #define ZIPFILE_NEWENTRY_FLAGS    0x800
9517 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
9518 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
9519 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
9520 
9521 /*
9522 ** The sizes of the fixed-size part of each of the three main data
9523 ** structures in a zip archive.
9524 */
9525 #define ZIPFILE_LFH_FIXED_SZ      30
9526 #define ZIPFILE_EOCD_FIXED_SZ     22
9527 #define ZIPFILE_CDS_FIXED_SZ      46
9528 
9529 /*
9530 *** 4.3.16  End of central directory record:
9531 ***
9532 ***   end of central dir signature    4 bytes  (0x06054b50)
9533 ***   number of this disk             2 bytes
9534 ***   number of the disk with the
9535 ***   start of the central directory  2 bytes
9536 ***   total number of entries in the
9537 ***   central directory on this disk  2 bytes
9538 ***   total number of entries in
9539 ***   the central directory           2 bytes
9540 ***   size of the central directory   4 bytes
9541 ***   offset of start of central
9542 ***   directory with respect to
9543 ***   the starting disk number        4 bytes
9544 ***   .ZIP file comment length        2 bytes
9545 ***   .ZIP file comment       (variable size)
9546 */
9547 typedef struct ZipfileEOCD ZipfileEOCD;
9548 struct ZipfileEOCD {
9549   u16 iDisk;
9550   u16 iFirstDisk;
9551   u16 nEntry;
9552   u16 nEntryTotal;
9553   u32 nSize;
9554   u32 iOffset;
9555 };
9556 
9557 /*
9558 *** 4.3.12  Central directory structure:
9559 ***
9560 *** ...
9561 ***
9562 ***   central file header signature   4 bytes  (0x02014b50)
9563 ***   version made by                 2 bytes
9564 ***   version needed to extract       2 bytes
9565 ***   general purpose bit flag        2 bytes
9566 ***   compression method              2 bytes
9567 ***   last mod file time              2 bytes
9568 ***   last mod file date              2 bytes
9569 ***   crc-32                          4 bytes
9570 ***   compressed size                 4 bytes
9571 ***   uncompressed size               4 bytes
9572 ***   file name length                2 bytes
9573 ***   extra field length              2 bytes
9574 ***   file comment length             2 bytes
9575 ***   disk number start               2 bytes
9576 ***   internal file attributes        2 bytes
9577 ***   external file attributes        4 bytes
9578 ***   relative offset of local header 4 bytes
9579 */
9580 typedef struct ZipfileCDS ZipfileCDS;
9581 struct ZipfileCDS {
9582   u16 iVersionMadeBy;
9583   u16 iVersionExtract;
9584   u16 flags;
9585   u16 iCompression;
9586   u16 mTime;
9587   u16 mDate;
9588   u32 crc32;
9589   u32 szCompressed;
9590   u32 szUncompressed;
9591   u16 nFile;
9592   u16 nExtra;
9593   u16 nComment;
9594   u16 iDiskStart;
9595   u16 iInternalAttr;
9596   u32 iExternalAttr;
9597   u32 iOffset;
9598   char *zFile;                    /* Filename (sqlite3_malloc()) */
9599 };
9600 
9601 /*
9602 *** 4.3.7  Local file header:
9603 ***
9604 ***   local file header signature     4 bytes  (0x04034b50)
9605 ***   version needed to extract       2 bytes
9606 ***   general purpose bit flag        2 bytes
9607 ***   compression method              2 bytes
9608 ***   last mod file time              2 bytes
9609 ***   last mod file date              2 bytes
9610 ***   crc-32                          4 bytes
9611 ***   compressed size                 4 bytes
9612 ***   uncompressed size               4 bytes
9613 ***   file name length                2 bytes
9614 ***   extra field length              2 bytes
9615 ***
9616 */
9617 typedef struct ZipfileLFH ZipfileLFH;
9618 struct ZipfileLFH {
9619   u16 iVersionExtract;
9620   u16 flags;
9621   u16 iCompression;
9622   u16 mTime;
9623   u16 mDate;
9624   u32 crc32;
9625   u32 szCompressed;
9626   u32 szUncompressed;
9627   u16 nFile;
9628   u16 nExtra;
9629 };
9630 
9631 typedef struct ZipfileEntry ZipfileEntry;
9632 struct ZipfileEntry {
9633   ZipfileCDS cds;            /* Parsed CDS record */
9634   u32 mUnixTime;             /* Modification time, in UNIX format */
9635   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
9636   i64 iDataOff;              /* Offset to data in file (if aData==0) */
9637   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
9638   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
9639 };
9640 
9641 /*
9642 ** Cursor type for zipfile tables.
9643 */
9644 typedef struct ZipfileCsr ZipfileCsr;
9645 struct ZipfileCsr {
9646   sqlite3_vtab_cursor base;  /* Base class - must be first */
9647   i64 iId;                   /* Cursor ID */
9648   u8 bEof;                   /* True when at EOF */
9649   u8 bNoop;                  /* If next xNext() call is no-op */
9650 
9651   /* Used outside of write transactions */
9652   FILE *pFile;               /* Zip file */
9653   i64 iNextOff;              /* Offset of next record in central directory */
9654   ZipfileEOCD eocd;          /* Parse of central directory record */
9655 
9656   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
9657   ZipfileEntry *pCurrent;    /* Current entry */
9658   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
9659 };
9660 
9661 typedef struct ZipfileTab ZipfileTab;
9662 struct ZipfileTab {
9663   sqlite3_vtab base;         /* Base class - must be first */
9664   char *zFile;               /* Zip file this table accesses (may be NULL) */
9665   sqlite3 *db;               /* Host database connection */
9666   u8 *aBuffer;               /* Temporary buffer used for various tasks */
9667 
9668   ZipfileCsr *pCsrList;      /* List of cursors */
9669   i64 iNextCsrid;
9670 
9671   /* The following are used by write transactions only */
9672   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
9673   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
9674   FILE *pWriteFd;            /* File handle open on zip archive */
9675   i64 szCurrent;             /* Current size of zip archive */
9676   i64 szOrig;                /* Size of archive at start of transaction */
9677 };
9678 
9679 /*
9680 ** Set the error message contained in context ctx to the results of
9681 ** vprintf(zFmt, ...).
9682 */
zipfileCtxErrorMsg(sqlite3_context * ctx,const char * zFmt,...)9683 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
9684   char *zMsg = 0;
9685   va_list ap;
9686   va_start(ap, zFmt);
9687   zMsg = sqlite3_vmprintf(zFmt, ap);
9688   sqlite3_result_error(ctx, zMsg, -1);
9689   sqlite3_free(zMsg);
9690   va_end(ap);
9691 }
9692 
9693 /*
9694 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
9695 ** is not quoted, do nothing.
9696 */
zipfileDequote(char * zIn)9697 static void zipfileDequote(char *zIn){
9698   char q = zIn[0];
9699   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
9700     int iIn = 1;
9701     int iOut = 0;
9702     if( q=='[' ) q = ']';
9703     while( ALWAYS(zIn[iIn]) ){
9704       char c = zIn[iIn++];
9705       if( c==q && zIn[iIn++]!=q ) break;
9706       zIn[iOut++] = c;
9707     }
9708     zIn[iOut] = '\0';
9709   }
9710 }
9711 
9712 /*
9713 ** Construct a new ZipfileTab virtual table object.
9714 **
9715 **   argv[0]   -> module name  ("zipfile")
9716 **   argv[1]   -> database name
9717 **   argv[2]   -> table name
9718 **   argv[...] -> "column name" and other module argument fields.
9719 */
zipfileConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)9720 static int zipfileConnect(
9721   sqlite3 *db,
9722   void *pAux,
9723   int argc, const char *const*argv,
9724   sqlite3_vtab **ppVtab,
9725   char **pzErr
9726 ){
9727   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
9728   int nFile = 0;
9729   const char *zFile = 0;
9730   ZipfileTab *pNew = 0;
9731   int rc;
9732   (void)pAux;
9733 
9734   /* If the table name is not "zipfile", require that the argument be
9735   ** specified. This stops zipfile tables from being created as:
9736   **
9737   **   CREATE VIRTUAL TABLE zzz USING zipfile();
9738   **
9739   ** It does not prevent:
9740   **
9741   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
9742   */
9743   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
9744   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
9745     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
9746     return SQLITE_ERROR;
9747   }
9748 
9749   if( argc>3 ){
9750     zFile = argv[3];
9751     nFile = (int)strlen(zFile)+1;
9752   }
9753 
9754   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
9755   if( rc==SQLITE_OK ){
9756     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
9757     if( pNew==0 ) return SQLITE_NOMEM;
9758     memset(pNew, 0, nByte+nFile);
9759     pNew->db = db;
9760     pNew->aBuffer = (u8*)&pNew[1];
9761     if( zFile ){
9762       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
9763       memcpy(pNew->zFile, zFile, nFile);
9764       zipfileDequote(pNew->zFile);
9765     }
9766   }
9767   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
9768   *ppVtab = (sqlite3_vtab*)pNew;
9769   return rc;
9770 }
9771 
9772 /*
9773 ** Free the ZipfileEntry structure indicated by the only argument.
9774 */
zipfileEntryFree(ZipfileEntry * p)9775 static void zipfileEntryFree(ZipfileEntry *p){
9776   if( p ){
9777     sqlite3_free(p->cds.zFile);
9778     sqlite3_free(p);
9779   }
9780 }
9781 
9782 /*
9783 ** Release resources that should be freed at the end of a write
9784 ** transaction.
9785 */
zipfileCleanupTransaction(ZipfileTab * pTab)9786 static void zipfileCleanupTransaction(ZipfileTab *pTab){
9787   ZipfileEntry *pEntry;
9788   ZipfileEntry *pNext;
9789 
9790   if( pTab->pWriteFd ){
9791     fclose(pTab->pWriteFd);
9792     pTab->pWriteFd = 0;
9793   }
9794   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
9795     pNext = pEntry->pNext;
9796     zipfileEntryFree(pEntry);
9797   }
9798   pTab->pFirstEntry = 0;
9799   pTab->pLastEntry = 0;
9800   pTab->szCurrent = 0;
9801   pTab->szOrig = 0;
9802 }
9803 
9804 /*
9805 ** This method is the destructor for zipfile vtab objects.
9806 */
zipfileDisconnect(sqlite3_vtab * pVtab)9807 static int zipfileDisconnect(sqlite3_vtab *pVtab){
9808   zipfileCleanupTransaction((ZipfileTab*)pVtab);
9809   sqlite3_free(pVtab);
9810   return SQLITE_OK;
9811 }
9812 
9813 /*
9814 ** Constructor for a new ZipfileCsr object.
9815 */
zipfileOpen(sqlite3_vtab * p,sqlite3_vtab_cursor ** ppCsr)9816 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
9817   ZipfileTab *pTab = (ZipfileTab*)p;
9818   ZipfileCsr *pCsr;
9819   pCsr = sqlite3_malloc(sizeof(*pCsr));
9820   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
9821   if( pCsr==0 ){
9822     return SQLITE_NOMEM;
9823   }
9824   memset(pCsr, 0, sizeof(*pCsr));
9825   pCsr->iId = ++pTab->iNextCsrid;
9826   pCsr->pCsrNext = pTab->pCsrList;
9827   pTab->pCsrList = pCsr;
9828   return SQLITE_OK;
9829 }
9830 
9831 /*
9832 ** Reset a cursor back to the state it was in when first returned
9833 ** by zipfileOpen().
9834 */
zipfileResetCursor(ZipfileCsr * pCsr)9835 static void zipfileResetCursor(ZipfileCsr *pCsr){
9836   ZipfileEntry *p;
9837   ZipfileEntry *pNext;
9838 
9839   pCsr->bEof = 0;
9840   if( pCsr->pFile ){
9841     fclose(pCsr->pFile);
9842     pCsr->pFile = 0;
9843     zipfileEntryFree(pCsr->pCurrent);
9844     pCsr->pCurrent = 0;
9845   }
9846 
9847   for(p=pCsr->pFreeEntry; p; p=pNext){
9848     pNext = p->pNext;
9849     zipfileEntryFree(p);
9850   }
9851 }
9852 
9853 /*
9854 ** Destructor for an ZipfileCsr.
9855 */
zipfileClose(sqlite3_vtab_cursor * cur)9856 static int zipfileClose(sqlite3_vtab_cursor *cur){
9857   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9858   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
9859   ZipfileCsr **pp;
9860   zipfileResetCursor(pCsr);
9861 
9862   /* Remove this cursor from the ZipfileTab.pCsrList list. */
9863   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
9864   *pp = pCsr->pCsrNext;
9865 
9866   sqlite3_free(pCsr);
9867   return SQLITE_OK;
9868 }
9869 
9870 /*
9871 ** Set the error message for the virtual table associated with cursor
9872 ** pCsr to the results of vprintf(zFmt, ...).
9873 */
zipfileTableErr(ZipfileTab * pTab,const char * zFmt,...)9874 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
9875   va_list ap;
9876   va_start(ap, zFmt);
9877   sqlite3_free(pTab->base.zErrMsg);
9878   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
9879   va_end(ap);
9880 }
zipfileCursorErr(ZipfileCsr * pCsr,const char * zFmt,...)9881 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
9882   va_list ap;
9883   va_start(ap, zFmt);
9884   sqlite3_free(pCsr->base.pVtab->zErrMsg);
9885   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
9886   va_end(ap);
9887 }
9888 
9889 /*
9890 ** Read nRead bytes of data from offset iOff of file pFile into buffer
9891 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
9892 ** otherwise.
9893 **
9894 ** If an error does occur, output variable (*pzErrmsg) may be set to point
9895 ** to an English language error message. It is the responsibility of the
9896 ** caller to eventually free this buffer using
9897 ** sqlite3_free().
9898 */
zipfileReadData(FILE * pFile,u8 * aRead,int nRead,i64 iOff,char ** pzErrmsg)9899 static int zipfileReadData(
9900   FILE *pFile,                    /* Read from this file */
9901   u8 *aRead,                      /* Read into this buffer */
9902   int nRead,                      /* Number of bytes to read */
9903   i64 iOff,                       /* Offset to read from */
9904   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
9905 ){
9906   size_t n;
9907   fseek(pFile, (long)iOff, SEEK_SET);
9908   n = fread(aRead, 1, nRead, pFile);
9909   if( (int)n!=nRead ){
9910     *pzErrmsg = sqlite3_mprintf("error in fread()");
9911     return SQLITE_ERROR;
9912   }
9913   return SQLITE_OK;
9914 }
9915 
zipfileAppendData(ZipfileTab * pTab,const u8 * aWrite,int nWrite)9916 static int zipfileAppendData(
9917   ZipfileTab *pTab,
9918   const u8 *aWrite,
9919   int nWrite
9920 ){
9921   if( nWrite>0 ){
9922     size_t n = nWrite;
9923     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
9924     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
9925     if( (int)n!=nWrite ){
9926       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
9927       return SQLITE_ERROR;
9928     }
9929     pTab->szCurrent += nWrite;
9930   }
9931   return SQLITE_OK;
9932 }
9933 
9934 /*
9935 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9936 */
zipfileGetU16(const u8 * aBuf)9937 static u16 zipfileGetU16(const u8 *aBuf){
9938   return (aBuf[1] << 8) + aBuf[0];
9939 }
9940 
9941 /*
9942 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9943 */
zipfileGetU32(const u8 * aBuf)9944 static u32 zipfileGetU32(const u8 *aBuf){
9945   if( aBuf==0 ) return 0;
9946   return ((u32)(aBuf[3]) << 24)
9947        + ((u32)(aBuf[2]) << 16)
9948        + ((u32)(aBuf[1]) <<  8)
9949        + ((u32)(aBuf[0]) <<  0);
9950 }
9951 
9952 /*
9953 ** Write a 16-bit little endiate integer into buffer aBuf.
9954 */
zipfilePutU16(u8 * aBuf,u16 val)9955 static void zipfilePutU16(u8 *aBuf, u16 val){
9956   aBuf[0] = val & 0xFF;
9957   aBuf[1] = (val>>8) & 0xFF;
9958 }
9959 
9960 /*
9961 ** Write a 32-bit little endiate integer into buffer aBuf.
9962 */
zipfilePutU32(u8 * aBuf,u32 val)9963 static void zipfilePutU32(u8 *aBuf, u32 val){
9964   aBuf[0] = val & 0xFF;
9965   aBuf[1] = (val>>8) & 0xFF;
9966   aBuf[2] = (val>>16) & 0xFF;
9967   aBuf[3] = (val>>24) & 0xFF;
9968 }
9969 
9970 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9971 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9972 
9973 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
9974 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
9975 
9976 /*
9977 ** Magic numbers used to read CDS records.
9978 */
9979 #define ZIPFILE_CDS_NFILE_OFF        28
9980 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
9981 
9982 /*
9983 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
9984 ** if the record is not well-formed, or SQLITE_OK otherwise.
9985 */
zipfileReadCDS(u8 * aBuf,ZipfileCDS * pCDS)9986 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
9987   u8 *aRead = aBuf;
9988   u32 sig = zipfileRead32(aRead);
9989   int rc = SQLITE_OK;
9990   if( sig!=ZIPFILE_SIGNATURE_CDS ){
9991     rc = SQLITE_ERROR;
9992   }else{
9993     pCDS->iVersionMadeBy = zipfileRead16(aRead);
9994     pCDS->iVersionExtract = zipfileRead16(aRead);
9995     pCDS->flags = zipfileRead16(aRead);
9996     pCDS->iCompression = zipfileRead16(aRead);
9997     pCDS->mTime = zipfileRead16(aRead);
9998     pCDS->mDate = zipfileRead16(aRead);
9999     pCDS->crc32 = zipfileRead32(aRead);
10000     pCDS->szCompressed = zipfileRead32(aRead);
10001     pCDS->szUncompressed = zipfileRead32(aRead);
10002     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
10003     pCDS->nFile = zipfileRead16(aRead);
10004     pCDS->nExtra = zipfileRead16(aRead);
10005     pCDS->nComment = zipfileRead16(aRead);
10006     pCDS->iDiskStart = zipfileRead16(aRead);
10007     pCDS->iInternalAttr = zipfileRead16(aRead);
10008     pCDS->iExternalAttr = zipfileRead32(aRead);
10009     pCDS->iOffset = zipfileRead32(aRead);
10010     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
10011   }
10012 
10013   return rc;
10014 }
10015 
10016 /*
10017 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
10018 ** if the record is not well-formed, or SQLITE_OK otherwise.
10019 */
zipfileReadLFH(u8 * aBuffer,ZipfileLFH * pLFH)10020 static int zipfileReadLFH(
10021   u8 *aBuffer,
10022   ZipfileLFH *pLFH
10023 ){
10024   u8 *aRead = aBuffer;
10025   int rc = SQLITE_OK;
10026 
10027   u32 sig = zipfileRead32(aRead);
10028   if( sig!=ZIPFILE_SIGNATURE_LFH ){
10029     rc = SQLITE_ERROR;
10030   }else{
10031     pLFH->iVersionExtract = zipfileRead16(aRead);
10032     pLFH->flags = zipfileRead16(aRead);
10033     pLFH->iCompression = zipfileRead16(aRead);
10034     pLFH->mTime = zipfileRead16(aRead);
10035     pLFH->mDate = zipfileRead16(aRead);
10036     pLFH->crc32 = zipfileRead32(aRead);
10037     pLFH->szCompressed = zipfileRead32(aRead);
10038     pLFH->szUncompressed = zipfileRead32(aRead);
10039     pLFH->nFile = zipfileRead16(aRead);
10040     pLFH->nExtra = zipfileRead16(aRead);
10041   }
10042   return rc;
10043 }
10044 
10045 
10046 /*
10047 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
10048 ** Scan through this buffer to find an "extra-timestamp" field. If one
10049 ** exists, extract the 32-bit modification-timestamp from it and store
10050 ** the value in output parameter *pmTime.
10051 **
10052 ** Zero is returned if no extra-timestamp record could be found (and so
10053 ** *pmTime is left unchanged), or non-zero otherwise.
10054 **
10055 ** The general format of an extra field is:
10056 **
10057 **   Header ID    2 bytes
10058 **   Data Size    2 bytes
10059 **   Data         N bytes
10060 */
zipfileScanExtra(u8 * aExtra,int nExtra,u32 * pmTime)10061 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
10062   int ret = 0;
10063   u8 *p = aExtra;
10064   u8 *pEnd = &aExtra[nExtra];
10065 
10066   while( p<pEnd ){
10067     u16 id = zipfileRead16(p);
10068     u16 nByte = zipfileRead16(p);
10069 
10070     switch( id ){
10071       case ZIPFILE_EXTRA_TIMESTAMP: {
10072         u8 b = p[0];
10073         if( b & 0x01 ){     /* 0x01 -> modtime is present */
10074           *pmTime = zipfileGetU32(&p[1]);
10075           ret = 1;
10076         }
10077         break;
10078       }
10079     }
10080 
10081     p += nByte;
10082   }
10083   return ret;
10084 }
10085 
10086 /*
10087 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10088 ** fields of the CDS structure passed as the only argument to a 32-bit
10089 ** UNIX seconds-since-the-epoch timestamp. Return the result.
10090 **
10091 ** "Standard" MS-DOS time format:
10092 **
10093 **   File modification time:
10094 **     Bits 00-04: seconds divided by 2
10095 **     Bits 05-10: minute
10096 **     Bits 11-15: hour
10097 **   File modification date:
10098 **     Bits 00-04: day
10099 **     Bits 05-08: month (1-12)
10100 **     Bits 09-15: years from 1980
10101 **
10102 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10103 */
zipfileMtime(ZipfileCDS * pCDS)10104 static u32 zipfileMtime(ZipfileCDS *pCDS){
10105   int Y,M,D,X1,X2,A,B,sec,min,hr;
10106   i64 JDsec;
10107   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
10108   M = ((pCDS->mDate >> 5) & 0x0F);
10109   D = (pCDS->mDate & 0x1F);
10110   sec = (pCDS->mTime & 0x1F)*2;
10111   min = (pCDS->mTime >> 5) & 0x3F;
10112   hr = (pCDS->mTime >> 11) & 0x1F;
10113   if( M<=2 ){
10114     Y--;
10115     M += 12;
10116   }
10117   X1 = 36525*(Y+4716)/100;
10118   X2 = 306001*(M+1)/10000;
10119   A = Y/100;
10120   B = 2 - A + (A/4);
10121   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
10122   return (u32)(JDsec - (i64)24405875*(i64)8640);
10123 }
10124 
10125 /*
10126 ** The opposite of zipfileMtime(). This function populates the mTime and
10127 ** mDate fields of the CDS structure passed as the first argument according
10128 ** to the UNIX timestamp value passed as the second.
10129 */
zipfileMtimeToDos(ZipfileCDS * pCds,u32 mUnixTime)10130 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
10131   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
10132   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
10133 
10134   int A, B, C, D, E;
10135   int yr, mon, day;
10136   int hr, min, sec;
10137 
10138   A = (int)((JD - 1867216.25)/36524.25);
10139   A = (int)(JD + 1 + A - (A/4));
10140   B = A + 1524;
10141   C = (int)((B - 122.1)/365.25);
10142   D = (36525*(C&32767))/100;
10143   E = (int)((B-D)/30.6001);
10144 
10145   day = B - D - (int)(30.6001*E);
10146   mon = (E<14 ? E-1 : E-13);
10147   yr = mon>2 ? C-4716 : C-4715;
10148 
10149   hr = (mUnixTime % (24*60*60)) / (60*60);
10150   min = (mUnixTime % (60*60)) / 60;
10151   sec = (mUnixTime % 60);
10152 
10153   if( yr>=1980 ){
10154     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
10155     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
10156   }else{
10157     pCds->mDate = pCds->mTime = 0;
10158   }
10159 
10160   assert( mUnixTime<315507600
10161        || mUnixTime==zipfileMtime(pCds)
10162        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
10163        /* || (mUnixTime % 2) */
10164   );
10165 }
10166 
10167 /*
10168 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
10169 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
10170 ** then pFile is a file-handle open on a zip file. In either case, this
10171 ** function creates a ZipfileEntry object based on the zip archive entry
10172 ** for which the CDS record is at offset iOff.
10173 **
10174 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
10175 ** the new object. Otherwise, an SQLite error code is returned and the
10176 ** final value of (*ppEntry) undefined.
10177 */
zipfileGetEntry(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,i64 iOff,ZipfileEntry ** ppEntry)10178 static int zipfileGetEntry(
10179   ZipfileTab *pTab,               /* Store any error message here */
10180   const u8 *aBlob,                /* Pointer to in-memory file image */
10181   int nBlob,                      /* Size of aBlob[] in bytes */
10182   FILE *pFile,                    /* If aBlob==0, read from this file */
10183   i64 iOff,                       /* Offset of CDS record */
10184   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
10185 ){
10186   u8 *aRead;
10187   char **pzErr = &pTab->base.zErrMsg;
10188   int rc = SQLITE_OK;
10189   (void)nBlob;
10190 
10191   if( aBlob==0 ){
10192     aRead = pTab->aBuffer;
10193     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
10194   }else{
10195     aRead = (u8*)&aBlob[iOff];
10196   }
10197 
10198   if( rc==SQLITE_OK ){
10199     sqlite3_int64 nAlloc;
10200     ZipfileEntry *pNew;
10201 
10202     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
10203     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
10204     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
10205 
10206     nAlloc = sizeof(ZipfileEntry) + nExtra;
10207     if( aBlob ){
10208       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
10209     }
10210 
10211     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
10212     if( pNew==0 ){
10213       rc = SQLITE_NOMEM;
10214     }else{
10215       memset(pNew, 0, sizeof(ZipfileEntry));
10216       rc = zipfileReadCDS(aRead, &pNew->cds);
10217       if( rc!=SQLITE_OK ){
10218         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
10219       }else if( aBlob==0 ){
10220         rc = zipfileReadData(
10221             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
10222         );
10223       }else{
10224         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
10225       }
10226     }
10227 
10228     if( rc==SQLITE_OK ){
10229       u32 *pt = &pNew->mUnixTime;
10230       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
10231       pNew->aExtra = (u8*)&pNew[1];
10232       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
10233       if( pNew->cds.zFile==0 ){
10234         rc = SQLITE_NOMEM;
10235       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
10236         pNew->mUnixTime = zipfileMtime(&pNew->cds);
10237       }
10238     }
10239 
10240     if( rc==SQLITE_OK ){
10241       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
10242       ZipfileLFH lfh;
10243       if( pFile ){
10244         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
10245       }else{
10246         aRead = (u8*)&aBlob[pNew->cds.iOffset];
10247       }
10248 
10249       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
10250       if( rc==SQLITE_OK ){
10251         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
10252         pNew->iDataOff += lfh.nFile + lfh.nExtra;
10253         if( aBlob && pNew->cds.szCompressed ){
10254           pNew->aData = &pNew->aExtra[nExtra];
10255           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
10256         }
10257       }else{
10258         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
10259             (int)pNew->cds.iOffset
10260         );
10261       }
10262     }
10263 
10264     if( rc!=SQLITE_OK ){
10265       zipfileEntryFree(pNew);
10266     }else{
10267       *ppEntry = pNew;
10268     }
10269   }
10270 
10271   return rc;
10272 }
10273 
10274 /*
10275 ** Advance an ZipfileCsr to its next row of output.
10276 */
zipfileNext(sqlite3_vtab_cursor * cur)10277 static int zipfileNext(sqlite3_vtab_cursor *cur){
10278   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10279   int rc = SQLITE_OK;
10280 
10281   if( pCsr->pFile ){
10282     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
10283     zipfileEntryFree(pCsr->pCurrent);
10284     pCsr->pCurrent = 0;
10285     if( pCsr->iNextOff>=iEof ){
10286       pCsr->bEof = 1;
10287     }else{
10288       ZipfileEntry *p = 0;
10289       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
10290       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
10291       if( rc==SQLITE_OK ){
10292         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
10293         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
10294       }
10295       pCsr->pCurrent = p;
10296     }
10297   }else{
10298     if( !pCsr->bNoop ){
10299       pCsr->pCurrent = pCsr->pCurrent->pNext;
10300     }
10301     if( pCsr->pCurrent==0 ){
10302       pCsr->bEof = 1;
10303     }
10304   }
10305 
10306   pCsr->bNoop = 0;
10307   return rc;
10308 }
10309 
zipfileFree(void * p)10310 static void zipfileFree(void *p) {
10311   sqlite3_free(p);
10312 }
10313 
10314 /*
10315 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
10316 ** size is nOut bytes. This function uncompresses the data and sets the
10317 ** return value in context pCtx to the result (a blob).
10318 **
10319 ** If an error occurs, an error code is left in pCtx instead.
10320 */
zipfileInflate(sqlite3_context * pCtx,const u8 * aIn,int nIn,int nOut)10321 static void zipfileInflate(
10322   sqlite3_context *pCtx,          /* Store result here */
10323   const u8 *aIn,                  /* Compressed data */
10324   int nIn,                        /* Size of buffer aIn[] in bytes */
10325   int nOut                        /* Expected output size */
10326 ){
10327   u8 *aRes = sqlite3_malloc(nOut);
10328   if( aRes==0 ){
10329     sqlite3_result_error_nomem(pCtx);
10330   }else{
10331     int err;
10332     z_stream str;
10333     memset(&str, 0, sizeof(str));
10334 
10335     str.next_in = (Byte*)aIn;
10336     str.avail_in = nIn;
10337     str.next_out = (Byte*)aRes;
10338     str.avail_out = nOut;
10339 
10340     err = inflateInit2(&str, -15);
10341     if( err!=Z_OK ){
10342       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
10343     }else{
10344       err = inflate(&str, Z_NO_FLUSH);
10345       if( err!=Z_STREAM_END ){
10346         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
10347       }else{
10348         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
10349         aRes = 0;
10350       }
10351     }
10352     sqlite3_free(aRes);
10353     inflateEnd(&str);
10354   }
10355 }
10356 
10357 /*
10358 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
10359 ** compresses it and sets (*ppOut) to point to a buffer containing the
10360 ** compressed data. The caller is responsible for eventually calling
10361 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
10362 ** is set to the size of buffer (*ppOut) in bytes.
10363 **
10364 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
10365 ** code is returned and an error message left in virtual-table handle
10366 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
10367 ** case.
10368 */
zipfileDeflate(const u8 * aIn,int nIn,u8 ** ppOut,int * pnOut,char ** pzErr)10369 static int zipfileDeflate(
10370   const u8 *aIn, int nIn,         /* Input */
10371   u8 **ppOut, int *pnOut,         /* Output */
10372   char **pzErr                    /* OUT: Error message */
10373 ){
10374   int rc = SQLITE_OK;
10375   sqlite3_int64 nAlloc;
10376   z_stream str;
10377   u8 *aOut;
10378 
10379   memset(&str, 0, sizeof(str));
10380   str.next_in = (Bytef*)aIn;
10381   str.avail_in = nIn;
10382   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
10383 
10384   nAlloc = deflateBound(&str, nIn);
10385   aOut = (u8*)sqlite3_malloc64(nAlloc);
10386   if( aOut==0 ){
10387     rc = SQLITE_NOMEM;
10388   }else{
10389     int res;
10390     str.next_out = aOut;
10391     str.avail_out = nAlloc;
10392     res = deflate(&str, Z_FINISH);
10393     if( res==Z_STREAM_END ){
10394       *ppOut = aOut;
10395       *pnOut = (int)str.total_out;
10396     }else{
10397       sqlite3_free(aOut);
10398       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
10399       rc = SQLITE_ERROR;
10400     }
10401     deflateEnd(&str);
10402   }
10403 
10404   return rc;
10405 }
10406 
10407 
10408 /*
10409 ** Return values of columns for the row at which the series_cursor
10410 ** is currently pointing.
10411 */
zipfileColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)10412 static int zipfileColumn(
10413   sqlite3_vtab_cursor *cur,   /* The cursor */
10414   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
10415   int i                       /* Which column to return */
10416 ){
10417   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10418   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
10419   int rc = SQLITE_OK;
10420   switch( i ){
10421     case 0:   /* name */
10422       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
10423       break;
10424     case 1:   /* mode */
10425       /* TODO: Whether or not the following is correct surely depends on
10426       ** the platform on which the archive was created.  */
10427       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
10428       break;
10429     case 2: { /* mtime */
10430       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
10431       break;
10432     }
10433     case 3: { /* sz */
10434       if( sqlite3_vtab_nochange(ctx)==0 ){
10435         sqlite3_result_int64(ctx, pCDS->szUncompressed);
10436       }
10437       break;
10438     }
10439     case 4:   /* rawdata */
10440       if( sqlite3_vtab_nochange(ctx) ) break;
10441     case 5: { /* data */
10442       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
10443         int sz = pCDS->szCompressed;
10444         int szFinal = pCDS->szUncompressed;
10445         if( szFinal>0 ){
10446           u8 *aBuf;
10447           u8 *aFree = 0;
10448           if( pCsr->pCurrent->aData ){
10449             aBuf = pCsr->pCurrent->aData;
10450           }else{
10451             aBuf = aFree = sqlite3_malloc64(sz);
10452             if( aBuf==0 ){
10453               rc = SQLITE_NOMEM;
10454             }else{
10455               FILE *pFile = pCsr->pFile;
10456               if( pFile==0 ){
10457                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
10458               }
10459               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
10460                   &pCsr->base.pVtab->zErrMsg
10461               );
10462             }
10463           }
10464           if( rc==SQLITE_OK ){
10465             if( i==5 && pCDS->iCompression ){
10466               zipfileInflate(ctx, aBuf, sz, szFinal);
10467             }else{
10468               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
10469             }
10470           }
10471           sqlite3_free(aFree);
10472         }else{
10473           /* Figure out if this is a directory or a zero-sized file. Consider
10474           ** it to be a directory either if the mode suggests so, or if
10475           ** the final character in the name is '/'.  */
10476           u32 mode = pCDS->iExternalAttr >> 16;
10477           if( !(mode & S_IFDIR)
10478            && pCDS->nFile>=1
10479            && pCDS->zFile[pCDS->nFile-1]!='/'
10480           ){
10481             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
10482           }
10483         }
10484       }
10485       break;
10486     }
10487     case 6:   /* method */
10488       sqlite3_result_int(ctx, pCDS->iCompression);
10489       break;
10490     default:  /* z */
10491       assert( i==7 );
10492       sqlite3_result_int64(ctx, pCsr->iId);
10493       break;
10494   }
10495 
10496   return rc;
10497 }
10498 
10499 /*
10500 ** Return TRUE if the cursor is at EOF.
10501 */
zipfileEof(sqlite3_vtab_cursor * cur)10502 static int zipfileEof(sqlite3_vtab_cursor *cur){
10503   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10504   return pCsr->bEof;
10505 }
10506 
10507 /*
10508 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
10509 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
10510 ** is guaranteed to be a file-handle open on a zip file.
10511 **
10512 ** This function attempts to locate the EOCD record within the zip archive
10513 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
10514 ** returned if successful. Otherwise, an SQLite error code is returned and
10515 ** an English language error message may be left in virtual-table pTab.
10516 */
zipfileReadEOCD(ZipfileTab * pTab,const u8 * aBlob,int nBlob,FILE * pFile,ZipfileEOCD * pEOCD)10517 static int zipfileReadEOCD(
10518   ZipfileTab *pTab,               /* Return errors here */
10519   const u8 *aBlob,                /* Pointer to in-memory file image */
10520   int nBlob,                      /* Size of aBlob[] in bytes */
10521   FILE *pFile,                    /* Read from this file if aBlob==0 */
10522   ZipfileEOCD *pEOCD              /* Object to populate */
10523 ){
10524   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
10525   int nRead;                      /* Bytes to read from file */
10526   int rc = SQLITE_OK;
10527 
10528   memset(pEOCD, 0, sizeof(ZipfileEOCD));
10529   if( aBlob==0 ){
10530     i64 iOff;                     /* Offset to read from */
10531     i64 szFile;                   /* Total size of file in bytes */
10532     fseek(pFile, 0, SEEK_END);
10533     szFile = (i64)ftell(pFile);
10534     if( szFile==0 ){
10535       return SQLITE_OK;
10536     }
10537     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
10538     iOff = szFile - nRead;
10539     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
10540   }else{
10541     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
10542     aRead = (u8*)&aBlob[nBlob-nRead];
10543   }
10544 
10545   if( rc==SQLITE_OK ){
10546     int i;
10547 
10548     /* Scan backwards looking for the signature bytes */
10549     for(i=nRead-20; i>=0; i--){
10550       if( aRead[i]==0x50 && aRead[i+1]==0x4b
10551        && aRead[i+2]==0x05 && aRead[i+3]==0x06
10552       ){
10553         break;
10554       }
10555     }
10556     if( i<0 ){
10557       pTab->base.zErrMsg = sqlite3_mprintf(
10558           "cannot find end of central directory record"
10559       );
10560       return SQLITE_ERROR;
10561     }
10562 
10563     aRead += i+4;
10564     pEOCD->iDisk = zipfileRead16(aRead);
10565     pEOCD->iFirstDisk = zipfileRead16(aRead);
10566     pEOCD->nEntry = zipfileRead16(aRead);
10567     pEOCD->nEntryTotal = zipfileRead16(aRead);
10568     pEOCD->nSize = zipfileRead32(aRead);
10569     pEOCD->iOffset = zipfileRead32(aRead);
10570   }
10571 
10572   return rc;
10573 }
10574 
10575 /*
10576 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
10577 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
10578 ** to the end of the list. Otherwise, it is added to the list immediately
10579 ** before pBefore (which is guaranteed to be a part of said list).
10580 */
zipfileAddEntry(ZipfileTab * pTab,ZipfileEntry * pBefore,ZipfileEntry * pNew)10581 static void zipfileAddEntry(
10582   ZipfileTab *pTab,
10583   ZipfileEntry *pBefore,
10584   ZipfileEntry *pNew
10585 ){
10586   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
10587   assert( pNew->pNext==0 );
10588   if( pBefore==0 ){
10589     if( pTab->pFirstEntry==0 ){
10590       pTab->pFirstEntry = pTab->pLastEntry = pNew;
10591     }else{
10592       assert( pTab->pLastEntry->pNext==0 );
10593       pTab->pLastEntry->pNext = pNew;
10594       pTab->pLastEntry = pNew;
10595     }
10596   }else{
10597     ZipfileEntry **pp;
10598     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
10599     pNew->pNext = pBefore;
10600     *pp = pNew;
10601   }
10602 }
10603 
zipfileLoadDirectory(ZipfileTab * pTab,const u8 * aBlob,int nBlob)10604 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
10605   ZipfileEOCD eocd;
10606   int rc;
10607   int i;
10608   i64 iOff;
10609 
10610   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
10611   iOff = eocd.iOffset;
10612   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
10613     ZipfileEntry *pNew = 0;
10614     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
10615 
10616     if( rc==SQLITE_OK ){
10617       zipfileAddEntry(pTab, 0, pNew);
10618       iOff += ZIPFILE_CDS_FIXED_SZ;
10619       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
10620     }
10621   }
10622   return rc;
10623 }
10624 
10625 /*
10626 ** xFilter callback.
10627 */
zipfileFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)10628 static int zipfileFilter(
10629   sqlite3_vtab_cursor *cur,
10630   int idxNum, const char *idxStr,
10631   int argc, sqlite3_value **argv
10632 ){
10633   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
10634   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10635   const char *zFile = 0;          /* Zip file to scan */
10636   int rc = SQLITE_OK;             /* Return Code */
10637   int bInMemory = 0;              /* True for an in-memory zipfile */
10638 
10639   (void)idxStr;
10640   (void)argc;
10641 
10642   zipfileResetCursor(pCsr);
10643 
10644   if( pTab->zFile ){
10645     zFile = pTab->zFile;
10646   }else if( idxNum==0 ){
10647     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
10648     return SQLITE_ERROR;
10649   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
10650     static const u8 aEmptyBlob = 0;
10651     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
10652     int nBlob = sqlite3_value_bytes(argv[0]);
10653     assert( pTab->pFirstEntry==0 );
10654     if( aBlob==0 ){
10655       aBlob = &aEmptyBlob;
10656       nBlob = 0;
10657     }
10658     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
10659     pCsr->pFreeEntry = pTab->pFirstEntry;
10660     pTab->pFirstEntry = pTab->pLastEntry = 0;
10661     if( rc!=SQLITE_OK ) return rc;
10662     bInMemory = 1;
10663   }else{
10664     zFile = (const char*)sqlite3_value_text(argv[0]);
10665   }
10666 
10667   if( 0==pTab->pWriteFd && 0==bInMemory ){
10668     pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
10669     if( pCsr->pFile==0 ){
10670       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
10671       rc = SQLITE_ERROR;
10672     }else{
10673       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
10674       if( rc==SQLITE_OK ){
10675         if( pCsr->eocd.nEntry==0 ){
10676           pCsr->bEof = 1;
10677         }else{
10678           pCsr->iNextOff = pCsr->eocd.iOffset;
10679           rc = zipfileNext(cur);
10680         }
10681       }
10682     }
10683   }else{
10684     pCsr->bNoop = 1;
10685     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
10686     rc = zipfileNext(cur);
10687   }
10688 
10689   return rc;
10690 }
10691 
10692 /*
10693 ** xBestIndex callback.
10694 */
zipfileBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)10695 static int zipfileBestIndex(
10696   sqlite3_vtab *tab,
10697   sqlite3_index_info *pIdxInfo
10698 ){
10699   int i;
10700   int idx = -1;
10701   int unusable = 0;
10702   (void)tab;
10703 
10704   for(i=0; i<pIdxInfo->nConstraint; i++){
10705     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
10706     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
10707     if( pCons->usable==0 ){
10708       unusable = 1;
10709     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10710       idx = i;
10711     }
10712   }
10713   pIdxInfo->estimatedCost = 1000.0;
10714   if( idx>=0 ){
10715     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
10716     pIdxInfo->aConstraintUsage[idx].omit = 1;
10717     pIdxInfo->idxNum = 1;
10718   }else if( unusable ){
10719     return SQLITE_CONSTRAINT;
10720   }
10721   return SQLITE_OK;
10722 }
10723 
zipfileNewEntry(const char * zPath)10724 static ZipfileEntry *zipfileNewEntry(const char *zPath){
10725   ZipfileEntry *pNew;
10726   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
10727   if( pNew ){
10728     memset(pNew, 0, sizeof(ZipfileEntry));
10729     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
10730     if( pNew->cds.zFile==0 ){
10731       sqlite3_free(pNew);
10732       pNew = 0;
10733     }
10734   }
10735   return pNew;
10736 }
10737 
zipfileSerializeLFH(ZipfileEntry * pEntry,u8 * aBuf)10738 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
10739   ZipfileCDS *pCds = &pEntry->cds;
10740   u8 *a = aBuf;
10741 
10742   pCds->nExtra = 9;
10743 
10744   /* Write the LFH itself */
10745   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
10746   zipfileWrite16(a, pCds->iVersionExtract);
10747   zipfileWrite16(a, pCds->flags);
10748   zipfileWrite16(a, pCds->iCompression);
10749   zipfileWrite16(a, pCds->mTime);
10750   zipfileWrite16(a, pCds->mDate);
10751   zipfileWrite32(a, pCds->crc32);
10752   zipfileWrite32(a, pCds->szCompressed);
10753   zipfileWrite32(a, pCds->szUncompressed);
10754   zipfileWrite16(a, (u16)pCds->nFile);
10755   zipfileWrite16(a, pCds->nExtra);
10756   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
10757 
10758   /* Add the file name */
10759   memcpy(a, pCds->zFile, (int)pCds->nFile);
10760   a += (int)pCds->nFile;
10761 
10762   /* The "extra" data */
10763   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
10764   zipfileWrite16(a, 5);
10765   *a++ = 0x01;
10766   zipfileWrite32(a, pEntry->mUnixTime);
10767 
10768   return a-aBuf;
10769 }
10770 
zipfileAppendEntry(ZipfileTab * pTab,ZipfileEntry * pEntry,const u8 * pData,int nData)10771 static int zipfileAppendEntry(
10772   ZipfileTab *pTab,
10773   ZipfileEntry *pEntry,
10774   const u8 *pData,
10775   int nData
10776 ){
10777   u8 *aBuf = pTab->aBuffer;
10778   int nBuf;
10779   int rc;
10780 
10781   nBuf = zipfileSerializeLFH(pEntry, aBuf);
10782   rc = zipfileAppendData(pTab, aBuf, nBuf);
10783   if( rc==SQLITE_OK ){
10784     pEntry->iDataOff = pTab->szCurrent;
10785     rc = zipfileAppendData(pTab, pData, nData);
10786   }
10787 
10788   return rc;
10789 }
10790 
zipfileGetMode(sqlite3_value * pVal,int bIsDir,u32 * pMode,char ** pzErr)10791 static int zipfileGetMode(
10792   sqlite3_value *pVal,
10793   int bIsDir,                     /* If true, default to directory */
10794   u32 *pMode,                     /* OUT: Mode value */
10795   char **pzErr                    /* OUT: Error message */
10796 ){
10797   const char *z = (const char*)sqlite3_value_text(pVal);
10798   u32 mode = 0;
10799   if( z==0 ){
10800     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
10801   }else if( z[0]>='0' && z[0]<='9' ){
10802     mode = (unsigned int)sqlite3_value_int(pVal);
10803   }else{
10804     const char zTemplate[11] = "-rwxrwxrwx";
10805     int i;
10806     if( strlen(z)!=10 ) goto parse_error;
10807     switch( z[0] ){
10808       case '-': mode |= S_IFREG; break;
10809       case 'd': mode |= S_IFDIR; break;
10810       case 'l': mode |= S_IFLNK; break;
10811       default: goto parse_error;
10812     }
10813     for(i=1; i<10; i++){
10814       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
10815       else if( z[i]!='-' ) goto parse_error;
10816     }
10817   }
10818   if( ((mode & S_IFDIR)==0)==bIsDir ){
10819     /* The "mode" attribute is a directory, but data has been specified.
10820     ** Or vice-versa - no data but "mode" is a file or symlink.  */
10821     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
10822     return SQLITE_CONSTRAINT;
10823   }
10824   *pMode = mode;
10825   return SQLITE_OK;
10826 
10827  parse_error:
10828   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
10829   return SQLITE_ERROR;
10830 }
10831 
10832 /*
10833 ** Both (const char*) arguments point to nul-terminated strings. Argument
10834 ** nB is the value of strlen(zB). This function returns 0 if the strings are
10835 ** identical, ignoring any trailing '/' character in either path.  */
zipfileComparePath(const char * zA,const char * zB,int nB)10836 static int zipfileComparePath(const char *zA, const char *zB, int nB){
10837   int nA = (int)strlen(zA);
10838   if( nA>0 && zA[nA-1]=='/' ) nA--;
10839   if( nB>0 && zB[nB-1]=='/' ) nB--;
10840   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
10841   return 1;
10842 }
10843 
zipfileBegin(sqlite3_vtab * pVtab)10844 static int zipfileBegin(sqlite3_vtab *pVtab){
10845   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10846   int rc = SQLITE_OK;
10847 
10848   assert( pTab->pWriteFd==0 );
10849   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
10850     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
10851     return SQLITE_ERROR;
10852   }
10853 
10854   /* Open a write fd on the file. Also load the entire central directory
10855   ** structure into memory. During the transaction any new file data is
10856   ** appended to the archive file, but the central directory is accumulated
10857   ** in main-memory until the transaction is committed.  */
10858   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
10859   if( pTab->pWriteFd==0 ){
10860     pTab->base.zErrMsg = sqlite3_mprintf(
10861         "zipfile: failed to open file %s for writing", pTab->zFile
10862         );
10863     rc = SQLITE_ERROR;
10864   }else{
10865     fseek(pTab->pWriteFd, 0, SEEK_END);
10866     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
10867     rc = zipfileLoadDirectory(pTab, 0, 0);
10868   }
10869 
10870   if( rc!=SQLITE_OK ){
10871     zipfileCleanupTransaction(pTab);
10872   }
10873 
10874   return rc;
10875 }
10876 
10877 /*
10878 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10879 ** time(2)).
10880 */
zipfileTime(void)10881 static u32 zipfileTime(void){
10882   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
10883   u32 ret;
10884   if( pVfs==0 ) return 0;
10885   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
10886     i64 ms;
10887     pVfs->xCurrentTimeInt64(pVfs, &ms);
10888     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
10889   }else{
10890     double day;
10891     pVfs->xCurrentTime(pVfs, &day);
10892     ret = (u32)((day - 2440587.5) * 86400);
10893   }
10894   return ret;
10895 }
10896 
10897 /*
10898 ** Return a 32-bit timestamp in UNIX epoch format.
10899 **
10900 ** If the value passed as the only argument is either NULL or an SQL NULL,
10901 ** return the current time. Otherwise, return the value stored in (*pVal)
10902 ** cast to a 32-bit unsigned integer.
10903 */
zipfileGetTime(sqlite3_value * pVal)10904 static u32 zipfileGetTime(sqlite3_value *pVal){
10905   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
10906     return zipfileTime();
10907   }
10908   return (u32)sqlite3_value_int64(pVal);
10909 }
10910 
10911 /*
10912 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10913 ** linked list.  Remove it from the list and free the object.
10914 */
zipfileRemoveEntryFromList(ZipfileTab * pTab,ZipfileEntry * pOld)10915 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
10916   if( pOld ){
10917     if( pTab->pFirstEntry==pOld ){
10918       pTab->pFirstEntry = pOld->pNext;
10919       if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
10920     }else{
10921       ZipfileEntry *p;
10922       for(p=pTab->pFirstEntry; p; p=p->pNext){
10923         if( p->pNext==pOld ){
10924           p->pNext = pOld->pNext;
10925           if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
10926           break;
10927         }
10928       }
10929     }
10930     zipfileEntryFree(pOld);
10931   }
10932 }
10933 
10934 /*
10935 ** xUpdate method.
10936 */
zipfileUpdate(sqlite3_vtab * pVtab,int nVal,sqlite3_value ** apVal,sqlite_int64 * pRowid)10937 static int zipfileUpdate(
10938   sqlite3_vtab *pVtab,
10939   int nVal,
10940   sqlite3_value **apVal,
10941   sqlite_int64 *pRowid
10942 ){
10943   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10944   int rc = SQLITE_OK;             /* Return Code */
10945   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
10946 
10947   u32 mode = 0;                   /* Mode for new entry */
10948   u32 mTime = 0;                  /* Modification time for new entry */
10949   i64 sz = 0;                     /* Uncompressed size */
10950   const char *zPath = 0;          /* Path for new entry */
10951   int nPath = 0;                  /* strlen(zPath) */
10952   const u8 *pData = 0;            /* Pointer to buffer containing content */
10953   int nData = 0;                  /* Size of pData buffer in bytes */
10954   int iMethod = 0;                /* Compression method for new entry */
10955   u8 *pFree = 0;                  /* Free this */
10956   char *zFree = 0;                /* Also free this */
10957   ZipfileEntry *pOld = 0;
10958   ZipfileEntry *pOld2 = 0;
10959   int bUpdate = 0;                /* True for an update that modifies "name" */
10960   int bIsDir = 0;
10961   u32 iCrc32 = 0;
10962 
10963   (void)pRowid;
10964 
10965   if( pTab->pWriteFd==0 ){
10966     rc = zipfileBegin(pVtab);
10967     if( rc!=SQLITE_OK ) return rc;
10968   }
10969 
10970   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
10971   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
10972     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
10973     int nDelete = (int)strlen(zDelete);
10974     if( nVal>1 ){
10975       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
10976       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
10977         bUpdate = 1;
10978       }
10979     }
10980     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
10981       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
10982         break;
10983       }
10984       assert( pOld->pNext );
10985     }
10986   }
10987 
10988   if( nVal>1 ){
10989     /* Check that "sz" and "rawdata" are both NULL: */
10990     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
10991       zipfileTableErr(pTab, "sz must be NULL");
10992       rc = SQLITE_CONSTRAINT;
10993     }
10994     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
10995       zipfileTableErr(pTab, "rawdata must be NULL");
10996       rc = SQLITE_CONSTRAINT;
10997     }
10998 
10999     if( rc==SQLITE_OK ){
11000       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
11001         /* data=NULL. A directory */
11002         bIsDir = 1;
11003       }else{
11004         /* Value specified for "data", and possibly "method". This must be
11005         ** a regular file or a symlink. */
11006         const u8 *aIn = sqlite3_value_blob(apVal[7]);
11007         int nIn = sqlite3_value_bytes(apVal[7]);
11008         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
11009 
11010         iMethod = sqlite3_value_int(apVal[8]);
11011         sz = nIn;
11012         pData = aIn;
11013         nData = nIn;
11014         if( iMethod!=0 && iMethod!=8 ){
11015           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
11016           rc = SQLITE_CONSTRAINT;
11017         }else{
11018           if( bAuto || iMethod ){
11019             int nCmp;
11020             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
11021             if( rc==SQLITE_OK ){
11022               if( iMethod || nCmp<nIn ){
11023                 iMethod = 8;
11024                 pData = pFree;
11025                 nData = nCmp;
11026               }
11027             }
11028           }
11029           iCrc32 = crc32(0, aIn, nIn);
11030         }
11031       }
11032     }
11033 
11034     if( rc==SQLITE_OK ){
11035       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
11036     }
11037 
11038     if( rc==SQLITE_OK ){
11039       zPath = (const char*)sqlite3_value_text(apVal[2]);
11040       if( zPath==0 ) zPath = "";
11041       nPath = (int)strlen(zPath);
11042       mTime = zipfileGetTime(apVal[4]);
11043     }
11044 
11045     if( rc==SQLITE_OK && bIsDir ){
11046       /* For a directory, check that the last character in the path is a
11047       ** '/'. This appears to be required for compatibility with info-zip
11048       ** (the unzip command on unix). It does not create directories
11049       ** otherwise.  */
11050       if( nPath<=0 || zPath[nPath-1]!='/' ){
11051         zFree = sqlite3_mprintf("%s/", zPath);
11052         zPath = (const char*)zFree;
11053         if( zFree==0 ){
11054           rc = SQLITE_NOMEM;
11055           nPath = 0;
11056         }else{
11057           nPath = (int)strlen(zPath);
11058         }
11059       }
11060     }
11061 
11062     /* Check that we're not inserting a duplicate entry -OR- updating an
11063     ** entry with a path, thereby making it into a duplicate. */
11064     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
11065       ZipfileEntry *p;
11066       for(p=pTab->pFirstEntry; p; p=p->pNext){
11067         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
11068           switch( sqlite3_vtab_on_conflict(pTab->db) ){
11069             case SQLITE_IGNORE: {
11070               goto zipfile_update_done;
11071             }
11072             case SQLITE_REPLACE: {
11073               pOld2 = p;
11074               break;
11075             }
11076             default: {
11077               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
11078               rc = SQLITE_CONSTRAINT;
11079               break;
11080             }
11081           }
11082           break;
11083         }
11084       }
11085     }
11086 
11087     if( rc==SQLITE_OK ){
11088       /* Create the new CDS record. */
11089       pNew = zipfileNewEntry(zPath);
11090       if( pNew==0 ){
11091         rc = SQLITE_NOMEM;
11092       }else{
11093         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11094         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11095         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11096         pNew->cds.iCompression = (u16)iMethod;
11097         zipfileMtimeToDos(&pNew->cds, mTime);
11098         pNew->cds.crc32 = iCrc32;
11099         pNew->cds.szCompressed = nData;
11100         pNew->cds.szUncompressed = (u32)sz;
11101         pNew->cds.iExternalAttr = (mode<<16);
11102         pNew->cds.iOffset = (u32)pTab->szCurrent;
11103         pNew->cds.nFile = (u16)nPath;
11104         pNew->mUnixTime = (u32)mTime;
11105         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
11106         zipfileAddEntry(pTab, pOld, pNew);
11107       }
11108     }
11109   }
11110 
11111   if( rc==SQLITE_OK && (pOld || pOld2) ){
11112     ZipfileCsr *pCsr;
11113     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11114       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
11115         pCsr->pCurrent = pCsr->pCurrent->pNext;
11116         pCsr->bNoop = 1;
11117       }
11118     }
11119 
11120     zipfileRemoveEntryFromList(pTab, pOld);
11121     zipfileRemoveEntryFromList(pTab, pOld2);
11122   }
11123 
11124 zipfile_update_done:
11125   sqlite3_free(pFree);
11126   sqlite3_free(zFree);
11127   return rc;
11128 }
11129 
zipfileSerializeEOCD(ZipfileEOCD * p,u8 * aBuf)11130 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
11131   u8 *a = aBuf;
11132   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
11133   zipfileWrite16(a, p->iDisk);
11134   zipfileWrite16(a, p->iFirstDisk);
11135   zipfileWrite16(a, p->nEntry);
11136   zipfileWrite16(a, p->nEntryTotal);
11137   zipfileWrite32(a, p->nSize);
11138   zipfileWrite32(a, p->iOffset);
11139   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
11140 
11141   return a-aBuf;
11142 }
11143 
zipfileAppendEOCD(ZipfileTab * pTab,ZipfileEOCD * p)11144 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
11145   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
11146   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
11147   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
11148 }
11149 
11150 /*
11151 ** Serialize the CDS structure into buffer aBuf[]. Return the number
11152 ** of bytes written.
11153 */
zipfileSerializeCDS(ZipfileEntry * pEntry,u8 * aBuf)11154 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
11155   u8 *a = aBuf;
11156   ZipfileCDS *pCDS = &pEntry->cds;
11157 
11158   if( pEntry->aExtra==0 ){
11159     pCDS->nExtra = 9;
11160   }
11161 
11162   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
11163   zipfileWrite16(a, pCDS->iVersionMadeBy);
11164   zipfileWrite16(a, pCDS->iVersionExtract);
11165   zipfileWrite16(a, pCDS->flags);
11166   zipfileWrite16(a, pCDS->iCompression);
11167   zipfileWrite16(a, pCDS->mTime);
11168   zipfileWrite16(a, pCDS->mDate);
11169   zipfileWrite32(a, pCDS->crc32);
11170   zipfileWrite32(a, pCDS->szCompressed);
11171   zipfileWrite32(a, pCDS->szUncompressed);
11172   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
11173   zipfileWrite16(a, pCDS->nFile);
11174   zipfileWrite16(a, pCDS->nExtra);
11175   zipfileWrite16(a, pCDS->nComment);
11176   zipfileWrite16(a, pCDS->iDiskStart);
11177   zipfileWrite16(a, pCDS->iInternalAttr);
11178   zipfileWrite32(a, pCDS->iExternalAttr);
11179   zipfileWrite32(a, pCDS->iOffset);
11180 
11181   memcpy(a, pCDS->zFile, pCDS->nFile);
11182   a += pCDS->nFile;
11183 
11184   if( pEntry->aExtra ){
11185     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
11186     memcpy(a, pEntry->aExtra, n);
11187     a += n;
11188   }else{
11189     assert( pCDS->nExtra==9 );
11190     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
11191     zipfileWrite16(a, 5);
11192     *a++ = 0x01;
11193     zipfileWrite32(a, pEntry->mUnixTime);
11194   }
11195 
11196   return a-aBuf;
11197 }
11198 
zipfileCommit(sqlite3_vtab * pVtab)11199 static int zipfileCommit(sqlite3_vtab *pVtab){
11200   ZipfileTab *pTab = (ZipfileTab*)pVtab;
11201   int rc = SQLITE_OK;
11202   if( pTab->pWriteFd ){
11203     i64 iOffset = pTab->szCurrent;
11204     ZipfileEntry *p;
11205     ZipfileEOCD eocd;
11206     int nEntry = 0;
11207 
11208     /* Write out all entries */
11209     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
11210       int n = zipfileSerializeCDS(p, pTab->aBuffer);
11211       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
11212       nEntry++;
11213     }
11214 
11215     /* Write out the EOCD record */
11216     eocd.iDisk = 0;
11217     eocd.iFirstDisk = 0;
11218     eocd.nEntry = (u16)nEntry;
11219     eocd.nEntryTotal = (u16)nEntry;
11220     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
11221     eocd.iOffset = (u32)iOffset;
11222     rc = zipfileAppendEOCD(pTab, &eocd);
11223 
11224     zipfileCleanupTransaction(pTab);
11225   }
11226   return rc;
11227 }
11228 
zipfileRollback(sqlite3_vtab * pVtab)11229 static int zipfileRollback(sqlite3_vtab *pVtab){
11230   return zipfileCommit(pVtab);
11231 }
11232 
zipfileFindCursor(ZipfileTab * pTab,i64 iId)11233 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
11234   ZipfileCsr *pCsr;
11235   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11236     if( iId==pCsr->iId ) break;
11237   }
11238   return pCsr;
11239 }
11240 
zipfileFunctionCds(sqlite3_context * context,int argc,sqlite3_value ** argv)11241 static void zipfileFunctionCds(
11242   sqlite3_context *context,
11243   int argc,
11244   sqlite3_value **argv
11245 ){
11246   ZipfileCsr *pCsr;
11247   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
11248   assert( argc>0 );
11249 
11250   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
11251   if( pCsr ){
11252     ZipfileCDS *p = &pCsr->pCurrent->cds;
11253     char *zRes = sqlite3_mprintf("{"
11254         "\"version-made-by\" : %u, "
11255         "\"version-to-extract\" : %u, "
11256         "\"flags\" : %u, "
11257         "\"compression\" : %u, "
11258         "\"time\" : %u, "
11259         "\"date\" : %u, "
11260         "\"crc32\" : %u, "
11261         "\"compressed-size\" : %u, "
11262         "\"uncompressed-size\" : %u, "
11263         "\"file-name-length\" : %u, "
11264         "\"extra-field-length\" : %u, "
11265         "\"file-comment-length\" : %u, "
11266         "\"disk-number-start\" : %u, "
11267         "\"internal-attr\" : %u, "
11268         "\"external-attr\" : %u, "
11269         "\"offset\" : %u }",
11270         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
11271         (u32)p->flags, (u32)p->iCompression,
11272         (u32)p->mTime, (u32)p->mDate,
11273         (u32)p->crc32, (u32)p->szCompressed,
11274         (u32)p->szUncompressed, (u32)p->nFile,
11275         (u32)p->nExtra, (u32)p->nComment,
11276         (u32)p->iDiskStart, (u32)p->iInternalAttr,
11277         (u32)p->iExternalAttr, (u32)p->iOffset
11278     );
11279 
11280     if( zRes==0 ){
11281       sqlite3_result_error_nomem(context);
11282     }else{
11283       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
11284       sqlite3_free(zRes);
11285     }
11286   }
11287 }
11288 
11289 /*
11290 ** xFindFunction method.
11291 */
zipfileFindFunction(sqlite3_vtab * pVtab,int nArg,const char * zName,void (** pxFunc)(sqlite3_context *,int,sqlite3_value **),void ** ppArg)11292 static int zipfileFindFunction(
11293   sqlite3_vtab *pVtab,            /* Virtual table handle */
11294   int nArg,                       /* Number of SQL function arguments */
11295   const char *zName,              /* Name of SQL function */
11296   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
11297   void **ppArg                    /* OUT: User data for *pxFunc */
11298 ){
11299   (void)nArg;
11300   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
11301     *pxFunc = zipfileFunctionCds;
11302     *ppArg = (void*)pVtab;
11303     return 1;
11304   }
11305   return 0;
11306 }
11307 
11308 typedef struct ZipfileBuffer ZipfileBuffer;
11309 struct ZipfileBuffer {
11310   u8 *a;                          /* Pointer to buffer */
11311   int n;                          /* Size of buffer in bytes */
11312   int nAlloc;                     /* Byte allocated at a[] */
11313 };
11314 
11315 typedef struct ZipfileCtx ZipfileCtx;
11316 struct ZipfileCtx {
11317   int nEntry;
11318   ZipfileBuffer body;
11319   ZipfileBuffer cds;
11320 };
11321 
zipfileBufferGrow(ZipfileBuffer * pBuf,int nByte)11322 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
11323   if( pBuf->n+nByte>pBuf->nAlloc ){
11324     u8 *aNew;
11325     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
11326     int nReq = pBuf->n + nByte;
11327 
11328     while( nNew<nReq ) nNew = nNew*2;
11329     aNew = sqlite3_realloc64(pBuf->a, nNew);
11330     if( aNew==0 ) return SQLITE_NOMEM;
11331     pBuf->a = aNew;
11332     pBuf->nAlloc = (int)nNew;
11333   }
11334   return SQLITE_OK;
11335 }
11336 
11337 /*
11338 ** xStep() callback for the zipfile() aggregate. This can be called in
11339 ** any of the following ways:
11340 **
11341 **   SELECT zipfile(name,data) ...
11342 **   SELECT zipfile(name,mode,mtime,data) ...
11343 **   SELECT zipfile(name,mode,mtime,data,method) ...
11344 */
zipfileStep(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)11345 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
11346   ZipfileCtx *p;                  /* Aggregate function context */
11347   ZipfileEntry e;                 /* New entry to add to zip archive */
11348 
11349   sqlite3_value *pName = 0;
11350   sqlite3_value *pMode = 0;
11351   sqlite3_value *pMtime = 0;
11352   sqlite3_value *pData = 0;
11353   sqlite3_value *pMethod = 0;
11354 
11355   int bIsDir = 0;
11356   u32 mode;
11357   int rc = SQLITE_OK;
11358   char *zErr = 0;
11359 
11360   int iMethod = -1;               /* Compression method to use (0 or 8) */
11361 
11362   const u8 *aData = 0;            /* Possibly compressed data for new entry */
11363   int nData = 0;                  /* Size of aData[] in bytes */
11364   int szUncompressed = 0;         /* Size of data before compression */
11365   u8 *aFree = 0;                  /* Free this before returning */
11366   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
11367 
11368   char *zName = 0;                /* Path (name) of new entry */
11369   int nName = 0;                  /* Size of zName in bytes */
11370   char *zFree = 0;                /* Free this before returning */
11371   int nByte;
11372 
11373   memset(&e, 0, sizeof(e));
11374   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11375   if( p==0 ) return;
11376 
11377   /* Martial the arguments into stack variables */
11378   if( nVal!=2 && nVal!=4 && nVal!=5 ){
11379     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
11380     rc = SQLITE_ERROR;
11381     goto zipfile_step_out;
11382   }
11383   pName = apVal[0];
11384   if( nVal==2 ){
11385     pData = apVal[1];
11386   }else{
11387     pMode = apVal[1];
11388     pMtime = apVal[2];
11389     pData = apVal[3];
11390     if( nVal==5 ){
11391       pMethod = apVal[4];
11392     }
11393   }
11394 
11395   /* Check that the 'name' parameter looks ok. */
11396   zName = (char*)sqlite3_value_text(pName);
11397   nName = sqlite3_value_bytes(pName);
11398   if( zName==0 ){
11399     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
11400     rc = SQLITE_ERROR;
11401     goto zipfile_step_out;
11402   }
11403 
11404   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
11405   ** deflate compression) or NULL (choose automatically).  */
11406   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
11407     iMethod = (int)sqlite3_value_int64(pMethod);
11408     if( iMethod!=0 && iMethod!=8 ){
11409       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
11410       rc = SQLITE_ERROR;
11411       goto zipfile_step_out;
11412     }
11413   }
11414 
11415   /* Now inspect the data. If this is NULL, then the new entry must be a
11416   ** directory.  Otherwise, figure out whether or not the data should
11417   ** be deflated or simply stored in the zip archive. */
11418   if( sqlite3_value_type(pData)==SQLITE_NULL ){
11419     bIsDir = 1;
11420     iMethod = 0;
11421   }else{
11422     aData = sqlite3_value_blob(pData);
11423     szUncompressed = nData = sqlite3_value_bytes(pData);
11424     iCrc32 = crc32(0, aData, nData);
11425     if( iMethod<0 || iMethod==8 ){
11426       int nOut = 0;
11427       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
11428       if( rc!=SQLITE_OK ){
11429         goto zipfile_step_out;
11430       }
11431       if( iMethod==8 || nOut<nData ){
11432         aData = aFree;
11433         nData = nOut;
11434         iMethod = 8;
11435       }else{
11436         iMethod = 0;
11437       }
11438     }
11439   }
11440 
11441   /* Decode the "mode" argument. */
11442   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
11443   if( rc ) goto zipfile_step_out;
11444 
11445   /* Decode the "mtime" argument. */
11446   e.mUnixTime = zipfileGetTime(pMtime);
11447 
11448   /* If this is a directory entry, ensure that there is exactly one '/'
11449   ** at the end of the path. Or, if this is not a directory and the path
11450   ** ends in '/' it is an error. */
11451   if( bIsDir==0 ){
11452     if( nName>0 && zName[nName-1]=='/' ){
11453       zErr = sqlite3_mprintf("non-directory name must not end with /");
11454       rc = SQLITE_ERROR;
11455       goto zipfile_step_out;
11456     }
11457   }else{
11458     if( nName==0 || zName[nName-1]!='/' ){
11459       zName = zFree = sqlite3_mprintf("%s/", zName);
11460       if( zName==0 ){
11461         rc = SQLITE_NOMEM;
11462         goto zipfile_step_out;
11463       }
11464       nName = (int)strlen(zName);
11465     }else{
11466       while( nName>1 && zName[nName-2]=='/' ) nName--;
11467     }
11468   }
11469 
11470   /* Assemble the ZipfileEntry object for the new zip archive entry */
11471   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11472   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11473   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11474   e.cds.iCompression = (u16)iMethod;
11475   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
11476   e.cds.crc32 = iCrc32;
11477   e.cds.szCompressed = nData;
11478   e.cds.szUncompressed = szUncompressed;
11479   e.cds.iExternalAttr = (mode<<16);
11480   e.cds.iOffset = p->body.n;
11481   e.cds.nFile = (u16)nName;
11482   e.cds.zFile = zName;
11483 
11484   /* Append the LFH to the body of the new archive */
11485   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
11486   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
11487   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
11488 
11489   /* Append the data to the body of the new archive */
11490   if( nData>0 ){
11491     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
11492     memcpy(&p->body.a[p->body.n], aData, nData);
11493     p->body.n += nData;
11494   }
11495 
11496   /* Append the CDS record to the directory of the new archive */
11497   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
11498   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
11499   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
11500 
11501   /* Increment the count of entries in the archive */
11502   p->nEntry++;
11503 
11504  zipfile_step_out:
11505   sqlite3_free(aFree);
11506   sqlite3_free(zFree);
11507   if( rc ){
11508     if( zErr ){
11509       sqlite3_result_error(pCtx, zErr, -1);
11510     }else{
11511       sqlite3_result_error_code(pCtx, rc);
11512     }
11513   }
11514   sqlite3_free(zErr);
11515 }
11516 
11517 /*
11518 ** xFinalize() callback for zipfile aggregate function.
11519 */
zipfileFinal(sqlite3_context * pCtx)11520 static void zipfileFinal(sqlite3_context *pCtx){
11521   ZipfileCtx *p;
11522   ZipfileEOCD eocd;
11523   sqlite3_int64 nZip;
11524   u8 *aZip;
11525 
11526   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11527   if( p==0 ) return;
11528   if( p->nEntry>0 ){
11529     memset(&eocd, 0, sizeof(eocd));
11530     eocd.nEntry = (u16)p->nEntry;
11531     eocd.nEntryTotal = (u16)p->nEntry;
11532     eocd.nSize = p->cds.n;
11533     eocd.iOffset = p->body.n;
11534 
11535     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
11536     aZip = (u8*)sqlite3_malloc64(nZip);
11537     if( aZip==0 ){
11538       sqlite3_result_error_nomem(pCtx);
11539     }else{
11540       memcpy(aZip, p->body.a, p->body.n);
11541       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
11542       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
11543       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
11544     }
11545   }
11546 
11547   sqlite3_free(p->body.a);
11548   sqlite3_free(p->cds.a);
11549 }
11550 
11551 
11552 /*
11553 ** Register the "zipfile" virtual table.
11554 */
zipfileRegister(sqlite3 * db)11555 static int zipfileRegister(sqlite3 *db){
11556   static sqlite3_module zipfileModule = {
11557     1,                         /* iVersion */
11558     zipfileConnect,            /* xCreate */
11559     zipfileConnect,            /* xConnect */
11560     zipfileBestIndex,          /* xBestIndex */
11561     zipfileDisconnect,         /* xDisconnect */
11562     zipfileDisconnect,         /* xDestroy */
11563     zipfileOpen,               /* xOpen - open a cursor */
11564     zipfileClose,              /* xClose - close a cursor */
11565     zipfileFilter,             /* xFilter - configure scan constraints */
11566     zipfileNext,               /* xNext - advance a cursor */
11567     zipfileEof,                /* xEof - check for end of scan */
11568     zipfileColumn,             /* xColumn - read data */
11569     0,                         /* xRowid - read data */
11570     zipfileUpdate,             /* xUpdate */
11571     zipfileBegin,              /* xBegin */
11572     0,                         /* xSync */
11573     zipfileCommit,             /* xCommit */
11574     zipfileRollback,           /* xRollback */
11575     zipfileFindFunction,       /* xFindMethod */
11576     0,                         /* xRename */
11577     0,                         /* xSavepoint */
11578     0,                         /* xRelease */
11579     0,                         /* xRollback */
11580     0,                         /* xShadowName */
11581     0                          /* xIntegrity */
11582   };
11583 
11584   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
11585   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
11586   if( rc==SQLITE_OK ){
11587     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
11588         zipfileStep, zipfileFinal
11589     );
11590   }
11591   assert( sizeof(i64)==8 );
11592   assert( sizeof(u32)==4 );
11593   assert( sizeof(u16)==2 );
11594   assert( sizeof(u8)==1 );
11595   return rc;
11596 }
11597 #else         /* SQLITE_OMIT_VIRTUALTABLE */
11598 # define zipfileRegister(x) SQLITE_OK
11599 #endif
11600 
11601 #ifdef _WIN32
11602 
11603 #endif
sqlite3_zipfile_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)11604 int sqlite3_zipfile_init(
11605   sqlite3 *db,
11606   char **pzErrMsg,
11607   const sqlite3_api_routines *pApi
11608 ){
11609   SQLITE_EXTENSION_INIT2(pApi);
11610   (void)pzErrMsg;  /* Unused parameter */
11611   return zipfileRegister(db);
11612 }
11613 
11614 /************************* End ../ext/misc/zipfile.c ********************/
11615 /************************* Begin ../ext/misc/sqlar.c ******************/
11616 /*
11617 ** 2017-12-17
11618 **
11619 ** The author disclaims copyright to this source code.  In place of
11620 ** a legal notice, here is a blessing:
11621 **
11622 **    May you do good and not evil.
11623 **    May you find forgiveness for yourself and forgive others.
11624 **    May you share freely, never taking more than you give.
11625 **
11626 ******************************************************************************
11627 **
11628 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
11629 ** for working with sqlar archives and used by the shell tool's built-in
11630 ** sqlar support.
11631 */
11632 /* #include "sqlite3ext.h" */
11633 SQLITE_EXTENSION_INIT1
11634 #include <zlib.h>
11635 #include <assert.h>
11636 
11637 /*
11638 ** Implementation of the "sqlar_compress(X)" SQL function.
11639 **
11640 ** If the type of X is SQLITE_BLOB, and compressing that blob using
11641 ** zlib utility function compress() yields a smaller blob, return the
11642 ** compressed blob. Otherwise, return a copy of X.
11643 **
11644 ** SQLar uses the "zlib format" for compressed content.  The zlib format
11645 ** contains a two-byte identification header and a four-byte checksum at
11646 ** the end.  This is different from ZIP which uses the raw deflate format.
11647 **
11648 ** Future enhancements to SQLar might add support for new compression formats.
11649 ** If so, those new formats will be identified by alternative headers in the
11650 ** compressed data.
11651 */
sqlarCompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)11652 static void sqlarCompressFunc(
11653   sqlite3_context *context,
11654   int argc,
11655   sqlite3_value **argv
11656 ){
11657   assert( argc==1 );
11658   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
11659     const Bytef *pData = sqlite3_value_blob(argv[0]);
11660     uLong nData = sqlite3_value_bytes(argv[0]);
11661     uLongf nOut = compressBound(nData);
11662     Bytef *pOut;
11663 
11664     pOut = (Bytef*)sqlite3_malloc(nOut);
11665     if( pOut==0 ){
11666       sqlite3_result_error_nomem(context);
11667       return;
11668     }else{
11669       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
11670         sqlite3_result_error(context, "error in compress()", -1);
11671       }else if( nOut<nData ){
11672         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
11673       }else{
11674         sqlite3_result_value(context, argv[0]);
11675       }
11676       sqlite3_free(pOut);
11677     }
11678   }else{
11679     sqlite3_result_value(context, argv[0]);
11680   }
11681 }
11682 
11683 /*
11684 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
11685 **
11686 ** Parameter SZ is interpreted as an integer. If it is less than or
11687 ** equal to zero, then this function returns a copy of X. Or, if
11688 ** SZ is equal to the size of X when interpreted as a blob, also
11689 ** return a copy of X. Otherwise, decompress blob X using zlib
11690 ** utility function uncompress() and return the results (another
11691 ** blob).
11692 */
sqlarUncompressFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)11693 static void sqlarUncompressFunc(
11694   sqlite3_context *context,
11695   int argc,
11696   sqlite3_value **argv
11697 ){
11698   uLong nData;
11699   sqlite3_int64 sz;
11700 
11701   assert( argc==2 );
11702   sz = sqlite3_value_int(argv[1]);
11703 
11704   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
11705     sqlite3_result_value(context, argv[0]);
11706   }else{
11707     uLongf szf = sz;
11708     const Bytef *pData= sqlite3_value_blob(argv[0]);
11709     Bytef *pOut = sqlite3_malloc(sz);
11710     if( pOut==0 ){
11711       sqlite3_result_error_nomem(context);
11712     }else if( Z_OK!=uncompress(pOut, &szf, pData, nData) ){
11713       sqlite3_result_error(context, "error in uncompress()", -1);
11714     }else{
11715       sqlite3_result_blob(context, pOut, szf, SQLITE_TRANSIENT);
11716     }
11717     sqlite3_free(pOut);
11718   }
11719 }
11720 
11721 #ifdef _WIN32
11722 
11723 #endif
sqlite3_sqlar_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)11724 int sqlite3_sqlar_init(
11725   sqlite3 *db,
11726   char **pzErrMsg,
11727   const sqlite3_api_routines *pApi
11728 ){
11729   int rc = SQLITE_OK;
11730   SQLITE_EXTENSION_INIT2(pApi);
11731   (void)pzErrMsg;  /* Unused parameter */
11732   rc = sqlite3_create_function(db, "sqlar_compress", 1,
11733                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11734                                sqlarCompressFunc, 0, 0);
11735   if( rc==SQLITE_OK ){
11736     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
11737                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11738                                  sqlarUncompressFunc, 0, 0);
11739   }
11740   return rc;
11741 }
11742 
11743 /************************* End ../ext/misc/sqlar.c ********************/
11744 #endif
11745 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
11746 /*
11747 ** 2017 April 07
11748 **
11749 ** The author disclaims copyright to this source code.  In place of
11750 ** a legal notice, here is a blessing:
11751 **
11752 **    May you do good and not evil.
11753 **    May you find forgiveness for yourself and forgive others.
11754 **    May you share freely, never taking more than you give.
11755 **
11756 *************************************************************************
11757 */
11758 #if !defined(SQLITEEXPERT_H)
11759 #define SQLITEEXPERT_H 1
11760 /* #include "sqlite3.h" */
11761 
11762 typedef struct sqlite3expert sqlite3expert;
11763 
11764 /*
11765 ** Create a new sqlite3expert object.
11766 **
11767 ** If successful, a pointer to the new object is returned and (*pzErr) set
11768 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
11769 ** an English-language error message. In this case it is the responsibility
11770 ** of the caller to eventually free the error message buffer using
11771 ** sqlite3_free().
11772 */
11773 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
11774 
11775 /*
11776 ** Configure an sqlite3expert object.
11777 **
11778 ** EXPERT_CONFIG_SAMPLE:
11779 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
11780 **   each candidate index. This involves scanning and sorting the entire
11781 **   contents of each user database table once for each candidate index
11782 **   associated with the table. For large databases, this can be
11783 **   prohibitively slow. This option allows the sqlite3expert object to
11784 **   be configured so that sqlite_stat1 data is instead generated based on a
11785 **   subset of each table, or so that no sqlite_stat1 data is used at all.
11786 **
11787 **   A single integer argument is passed to this option. If the value is less
11788 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
11789 **   the analysis - indexes are recommended based on the database schema only.
11790 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
11791 **   generated for each candidate index (this is the default). Finally, if the
11792 **   value falls between 0 and 100, then it represents the percentage of user
11793 **   table rows that should be considered when generating sqlite_stat1 data.
11794 **
11795 **   Examples:
11796 **
11797 **     // Do not generate any sqlite_stat1 data
11798 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
11799 **
11800 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
11801 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
11802 */
11803 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
11804 
11805 #define EXPERT_CONFIG_SAMPLE 1    /* int */
11806 
11807 /*
11808 ** Specify zero or more SQL statements to be included in the analysis.
11809 **
11810 ** Buffer zSql must contain zero or more complete SQL statements. This
11811 ** function parses all statements contained in the buffer and adds them
11812 ** to the internal list of statements to analyze. If successful, SQLITE_OK
11813 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11814 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11815 ** may be set to point to an English language error message. In this case
11816 ** the caller is responsible for eventually freeing the error message buffer
11817 ** using sqlite3_free().
11818 **
11819 ** If an error does occur while processing one of the statements in the
11820 ** buffer passed as the second argument, none of the statements in the
11821 ** buffer are added to the analysis.
11822 **
11823 ** This function must be called before sqlite3_expert_analyze(). If a call
11824 ** to this function is made on an sqlite3expert object that has already
11825 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
11826 ** immediately and no statements are added to the analysis.
11827 */
11828 int sqlite3_expert_sql(
11829   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
11830   const char *zSql,               /* SQL statement(s) to add */
11831   char **pzErr                    /* OUT: Error message (if any) */
11832 );
11833 
11834 
11835 /*
11836 ** This function is called after the sqlite3expert object has been configured
11837 ** with all SQL statements using sqlite3_expert_sql() to actually perform
11838 ** the analysis. Once this function has been called, it is not possible to
11839 ** add further SQL statements to the analysis.
11840 **
11841 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
11842 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
11843 ** point to a buffer containing an English language error message. In this
11844 ** case it is the responsibility of the caller to eventually free the buffer
11845 ** using sqlite3_free().
11846 **
11847 ** If an error does occur within this function, the sqlite3expert object
11848 ** is no longer useful for any purpose. At that point it is no longer
11849 ** possible to add further SQL statements to the object or to re-attempt
11850 ** the analysis. The sqlite3expert object must still be freed using a call
11851 ** sqlite3_expert_destroy().
11852 */
11853 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
11854 
11855 /*
11856 ** Return the total number of statements loaded using sqlite3_expert_sql().
11857 ** The total number of SQL statements may be different from the total number
11858 ** to calls to sqlite3_expert_sql().
11859 */
11860 int sqlite3_expert_count(sqlite3expert*);
11861 
11862 /*
11863 ** Return a component of the report.
11864 **
11865 ** This function is called after sqlite3_expert_analyze() to extract the
11866 ** results of the analysis. Each call to this function returns either a
11867 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11868 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
11869 ** #define constants defined below.
11870 **
11871 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
11872 ** information relating to a specific SQL statement. In these cases that
11873 ** SQL statement is identified by the value passed as the second argument.
11874 ** SQL statements are numbered from 0 in the order in which they are parsed.
11875 ** If an out-of-range value (less than zero or equal to or greater than the
11876 ** value returned by sqlite3_expert_count()) is passed as the second argument
11877 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
11878 **
11879 ** EXPERT_REPORT_SQL:
11880 **   Return the text of SQL statement iStmt.
11881 **
11882 ** EXPERT_REPORT_INDEXES:
11883 **   Return a buffer containing the CREATE INDEX statements for all recommended
11884 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
11885 **   is returned.
11886 **
11887 ** EXPERT_REPORT_PLAN:
11888 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
11889 **   iStmt after the proposed indexes have been added to the database schema.
11890 **
11891 ** EXPERT_REPORT_CANDIDATES:
11892 **   Return a pointer to a buffer containing the CREATE INDEX statements
11893 **   for all indexes that were tested (for all SQL statements). The iStmt
11894 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
11895 */
11896 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
11897 
11898 /*
11899 ** Values for the third argument passed to sqlite3_expert_report().
11900 */
11901 #define EXPERT_REPORT_SQL        1
11902 #define EXPERT_REPORT_INDEXES    2
11903 #define EXPERT_REPORT_PLAN       3
11904 #define EXPERT_REPORT_CANDIDATES 4
11905 
11906 /*
11907 ** Free an (sqlite3expert*) handle and all associated resources. There
11908 ** should be one call to this function for each successful call to
11909 ** sqlite3-expert_new().
11910 */
11911 void sqlite3_expert_destroy(sqlite3expert*);
11912 
11913 #endif  /* !defined(SQLITEEXPERT_H) */
11914 
11915 /************************* End ../ext/expert/sqlite3expert.h ********************/
11916 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
11917 /*
11918 ** 2017 April 09
11919 **
11920 ** The author disclaims copyright to this source code.  In place of
11921 ** a legal notice, here is a blessing:
11922 **
11923 **    May you do good and not evil.
11924 **    May you find forgiveness for yourself and forgive others.
11925 **    May you share freely, never taking more than you give.
11926 **
11927 *************************************************************************
11928 */
11929 /* #include "sqlite3expert.h" */
11930 #include <assert.h>
11931 #include <string.h>
11932 #include <stdio.h>
11933 
11934 #if !defined(SQLITE_AMALGAMATION)
11935 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11936 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
11937 #endif
11938 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
11939 # define ALWAYS(X)      (1)
11940 # define NEVER(X)       (0)
11941 #elif !defined(NDEBUG)
11942 # define ALWAYS(X)      ((X)?1:(assert(0),0))
11943 # define NEVER(X)       ((X)?(assert(0),1):0)
11944 #else
11945 # define ALWAYS(X)      (X)
11946 # define NEVER(X)       (X)
11947 #endif
11948 #endif /* !defined(SQLITE_AMALGAMATION) */
11949 
11950 
11951 #ifndef SQLITE_OMIT_VIRTUALTABLE
11952 
11953 /* typedef sqlite3_int64 i64; */
11954 /* typedef sqlite3_uint64 u64; */
11955 
11956 typedef struct IdxColumn IdxColumn;
11957 typedef struct IdxConstraint IdxConstraint;
11958 typedef struct IdxScan IdxScan;
11959 typedef struct IdxStatement IdxStatement;
11960 typedef struct IdxTable IdxTable;
11961 typedef struct IdxWrite IdxWrite;
11962 
11963 #define STRLEN  (int)strlen
11964 
11965 /*
11966 ** A temp table name that we assume no user database will actually use.
11967 ** If this assumption proves incorrect triggers on the table with the
11968 ** conflicting name will be ignored.
11969 */
11970 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
11971 
11972 /*
11973 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
11974 ** any other type of single-ended range constraint on a column).
11975 **
11976 ** pLink:
11977 **   Used to temporarily link IdxConstraint objects into lists while
11978 **   creating candidate indexes.
11979 */
11980 struct IdxConstraint {
11981   char *zColl;                    /* Collation sequence */
11982   int bRange;                     /* True for range, false for eq */
11983   int iCol;                       /* Constrained table column */
11984   int bFlag;                      /* Used by idxFindCompatible() */
11985   int bDesc;                      /* True if ORDER BY <expr> DESC */
11986   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
11987   IdxConstraint *pLink;           /* See above */
11988 };
11989 
11990 /*
11991 ** A single scan of a single table.
11992 */
11993 struct IdxScan {
11994   IdxTable *pTab;                 /* Associated table object */
11995   int iDb;                        /* Database containing table zTable */
11996   i64 covering;                   /* Mask of columns required for cov. index */
11997   IdxConstraint *pOrder;          /* ORDER BY columns */
11998   IdxConstraint *pEq;             /* List of == constraints */
11999   IdxConstraint *pRange;          /* List of < constraints */
12000   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
12001 };
12002 
12003 /*
12004 ** Information regarding a single database table. Extracted from
12005 ** "PRAGMA table_info" by function idxGetTableInfo().
12006 */
12007 struct IdxColumn {
12008   char *zName;
12009   char *zColl;
12010   int iPk;
12011 };
12012 struct IdxTable {
12013   int nCol;
12014   char *zName;                    /* Table name */
12015   IdxColumn *aCol;
12016   IdxTable *pNext;                /* Next table in linked list of all tables */
12017 };
12018 
12019 /*
12020 ** An object of the following type is created for each unique table/write-op
12021 ** seen. The objects are stored in a singly-linked list beginning at
12022 ** sqlite3expert.pWrite.
12023 */
12024 struct IdxWrite {
12025   IdxTable *pTab;
12026   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
12027   IdxWrite *pNext;
12028 };
12029 
12030 /*
12031 ** Each statement being analyzed is represented by an instance of this
12032 ** structure.
12033 */
12034 struct IdxStatement {
12035   int iId;                        /* Statement number */
12036   char *zSql;                     /* SQL statement */
12037   char *zIdx;                     /* Indexes */
12038   char *zEQP;                     /* Plan */
12039   IdxStatement *pNext;
12040 };
12041 
12042 
12043 /*
12044 ** A hash table for storing strings. With space for a payload string
12045 ** with each entry. Methods are:
12046 **
12047 **   idxHashInit()
12048 **   idxHashClear()
12049 **   idxHashAdd()
12050 **   idxHashSearch()
12051 */
12052 #define IDX_HASH_SIZE 1023
12053 typedef struct IdxHashEntry IdxHashEntry;
12054 typedef struct IdxHash IdxHash;
12055 struct IdxHashEntry {
12056   char *zKey;                     /* nul-terminated key */
12057   char *zVal;                     /* nul-terminated value string */
12058   char *zVal2;                    /* nul-terminated value string 2 */
12059   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
12060   IdxHashEntry *pNext;            /* Next entry in hash */
12061 };
12062 struct IdxHash {
12063   IdxHashEntry *pFirst;
12064   IdxHashEntry *aHash[IDX_HASH_SIZE];
12065 };
12066 
12067 /*
12068 ** sqlite3expert object.
12069 */
12070 struct sqlite3expert {
12071   int iSample;                    /* Percentage of tables to sample for stat1 */
12072   sqlite3 *db;                    /* User database */
12073   sqlite3 *dbm;                   /* In-memory db for this analysis */
12074   sqlite3 *dbv;                   /* Vtab schema for this analysis */
12075   IdxTable *pTable;               /* List of all IdxTable objects */
12076   IdxScan *pScan;                 /* List of scan objects */
12077   IdxWrite *pWrite;               /* List of write objects */
12078   IdxStatement *pStatement;       /* List of IdxStatement objects */
12079   int bRun;                       /* True once analysis has run */
12080   char **pzErrmsg;
12081   int rc;                         /* Error code from whereinfo hook */
12082   IdxHash hIdx;                   /* Hash containing all candidate indexes */
12083   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
12084 };
12085 
12086 
12087 /*
12088 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
12089 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
12090 */
idxMalloc(int * pRc,int nByte)12091 static void *idxMalloc(int *pRc, int nByte){
12092   void *pRet;
12093   assert( *pRc==SQLITE_OK );
12094   assert( nByte>0 );
12095   pRet = sqlite3_malloc(nByte);
12096   if( pRet ){
12097     memset(pRet, 0, nByte);
12098   }else{
12099     *pRc = SQLITE_NOMEM;
12100   }
12101   return pRet;
12102 }
12103 
12104 /*
12105 ** Initialize an IdxHash hash table.
12106 */
idxHashInit(IdxHash * pHash)12107 static void idxHashInit(IdxHash *pHash){
12108   memset(pHash, 0, sizeof(IdxHash));
12109 }
12110 
12111 /*
12112 ** Reset an IdxHash hash table.
12113 */
idxHashClear(IdxHash * pHash)12114 static void idxHashClear(IdxHash *pHash){
12115   int i;
12116   for(i=0; i<IDX_HASH_SIZE; i++){
12117     IdxHashEntry *pEntry;
12118     IdxHashEntry *pNext;
12119     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
12120       pNext = pEntry->pHashNext;
12121       sqlite3_free(pEntry->zVal2);
12122       sqlite3_free(pEntry);
12123     }
12124   }
12125   memset(pHash, 0, sizeof(IdxHash));
12126 }
12127 
12128 /*
12129 ** Return the index of the hash bucket that the string specified by the
12130 ** arguments to this function belongs.
12131 */
idxHashString(const char * z,int n)12132 static int idxHashString(const char *z, int n){
12133   unsigned int ret = 0;
12134   int i;
12135   for(i=0; i<n; i++){
12136     ret += (ret<<3) + (unsigned char)(z[i]);
12137   }
12138   return (int)(ret % IDX_HASH_SIZE);
12139 }
12140 
12141 /*
12142 ** If zKey is already present in the hash table, return non-zero and do
12143 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
12144 ** the hash table passed as the second argument.
12145 */
idxHashAdd(int * pRc,IdxHash * pHash,const char * zKey,const char * zVal)12146 static int idxHashAdd(
12147   int *pRc,
12148   IdxHash *pHash,
12149   const char *zKey,
12150   const char *zVal
12151 ){
12152   int nKey = STRLEN(zKey);
12153   int iHash = idxHashString(zKey, nKey);
12154   int nVal = (zVal ? STRLEN(zVal) : 0);
12155   IdxHashEntry *pEntry;
12156   assert( iHash>=0 );
12157   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12158     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12159       return 1;
12160     }
12161   }
12162   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
12163   if( pEntry ){
12164     pEntry->zKey = (char*)&pEntry[1];
12165     memcpy(pEntry->zKey, zKey, nKey);
12166     if( zVal ){
12167       pEntry->zVal = &pEntry->zKey[nKey+1];
12168       memcpy(pEntry->zVal, zVal, nVal);
12169     }
12170     pEntry->pHashNext = pHash->aHash[iHash];
12171     pHash->aHash[iHash] = pEntry;
12172 
12173     pEntry->pNext = pHash->pFirst;
12174     pHash->pFirst = pEntry;
12175   }
12176   return 0;
12177 }
12178 
12179 /*
12180 ** If zKey/nKey is present in the hash table, return a pointer to the
12181 ** hash-entry object.
12182 */
idxHashFind(IdxHash * pHash,const char * zKey,int nKey)12183 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
12184   int iHash;
12185   IdxHashEntry *pEntry;
12186   if( nKey<0 ) nKey = STRLEN(zKey);
12187   iHash = idxHashString(zKey, nKey);
12188   assert( iHash>=0 );
12189   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12190     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12191       return pEntry;
12192     }
12193   }
12194   return 0;
12195 }
12196 
12197 /*
12198 ** If the hash table contains an entry with a key equal to the string
12199 ** passed as the final two arguments to this function, return a pointer
12200 ** to the payload string. Otherwise, if zKey/nKey is not present in the
12201 ** hash table, return NULL.
12202 */
idxHashSearch(IdxHash * pHash,const char * zKey,int nKey)12203 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
12204   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
12205   if( pEntry ) return pEntry->zVal;
12206   return 0;
12207 }
12208 
12209 /*
12210 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
12211 ** variable to point to a copy of nul-terminated string zColl.
12212 */
idxNewConstraint(int * pRc,const char * zColl)12213 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
12214   IdxConstraint *pNew;
12215   int nColl = STRLEN(zColl);
12216 
12217   assert( *pRc==SQLITE_OK );
12218   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
12219   if( pNew ){
12220     pNew->zColl = (char*)&pNew[1];
12221     memcpy(pNew->zColl, zColl, nColl+1);
12222   }
12223   return pNew;
12224 }
12225 
12226 /*
12227 ** An error associated with database handle db has just occurred. Pass
12228 ** the error message to callback function xOut.
12229 */
idxDatabaseError(sqlite3 * db,char ** pzErrmsg)12230 static void idxDatabaseError(
12231   sqlite3 *db,                    /* Database handle */
12232   char **pzErrmsg                 /* Write error here */
12233 ){
12234   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
12235 }
12236 
12237 /*
12238 ** Prepare an SQL statement.
12239 */
idxPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zSql)12240 static int idxPrepareStmt(
12241   sqlite3 *db,                    /* Database handle to compile against */
12242   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12243   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12244   const char *zSql                /* SQL statement to compile */
12245 ){
12246   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12247   if( rc!=SQLITE_OK ){
12248     *ppStmt = 0;
12249     idxDatabaseError(db, pzErrmsg);
12250   }
12251   return rc;
12252 }
12253 
12254 /*
12255 ** Prepare an SQL statement using the results of a printf() formatting.
12256 */
idxPrintfPrepareStmt(sqlite3 * db,sqlite3_stmt ** ppStmt,char ** pzErrmsg,const char * zFmt,...)12257 static int idxPrintfPrepareStmt(
12258   sqlite3 *db,                    /* Database handle to compile against */
12259   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12260   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12261   const char *zFmt,               /* printf() format of SQL statement */
12262   ...                             /* Trailing printf() arguments */
12263 ){
12264   va_list ap;
12265   int rc;
12266   char *zSql;
12267   va_start(ap, zFmt);
12268   zSql = sqlite3_vmprintf(zFmt, ap);
12269   if( zSql==0 ){
12270     rc = SQLITE_NOMEM;
12271   }else{
12272     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
12273     sqlite3_free(zSql);
12274   }
12275   va_end(ap);
12276   return rc;
12277 }
12278 
12279 
12280 /*************************************************************************
12281 ** Beginning of virtual table implementation.
12282 */
12283 typedef struct ExpertVtab ExpertVtab;
12284 struct ExpertVtab {
12285   sqlite3_vtab base;
12286   IdxTable *pTab;
12287   sqlite3expert *pExpert;
12288 };
12289 
12290 typedef struct ExpertCsr ExpertCsr;
12291 struct ExpertCsr {
12292   sqlite3_vtab_cursor base;
12293   sqlite3_stmt *pData;
12294 };
12295 
expertDequote(const char * zIn)12296 static char *expertDequote(const char *zIn){
12297   int n = STRLEN(zIn);
12298   char *zRet = sqlite3_malloc(n);
12299 
12300   assert( zIn[0]=='\'' );
12301   assert( zIn[n-1]=='\'' );
12302 
12303   if( zRet ){
12304     int iOut = 0;
12305     int iIn = 0;
12306     for(iIn=1; iIn<(n-1); iIn++){
12307       if( zIn[iIn]=='\'' ){
12308         assert( zIn[iIn+1]=='\'' );
12309         iIn++;
12310       }
12311       zRet[iOut++] = zIn[iIn];
12312     }
12313     zRet[iOut] = '\0';
12314   }
12315 
12316   return zRet;
12317 }
12318 
12319 /*
12320 ** This function is the implementation of both the xConnect and xCreate
12321 ** methods of the r-tree virtual table.
12322 **
12323 **   argv[0]   -> module name
12324 **   argv[1]   -> database name
12325 **   argv[2]   -> table name
12326 **   argv[...] -> column names...
12327 */
expertConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)12328 static int expertConnect(
12329   sqlite3 *db,
12330   void *pAux,
12331   int argc, const char *const*argv,
12332   sqlite3_vtab **ppVtab,
12333   char **pzErr
12334 ){
12335   sqlite3expert *pExpert = (sqlite3expert*)pAux;
12336   ExpertVtab *p = 0;
12337   int rc;
12338 
12339   if( argc!=4 ){
12340     *pzErr = sqlite3_mprintf("internal error!");
12341     rc = SQLITE_ERROR;
12342   }else{
12343     char *zCreateTable = expertDequote(argv[3]);
12344     if( zCreateTable ){
12345       rc = sqlite3_declare_vtab(db, zCreateTable);
12346       if( rc==SQLITE_OK ){
12347         p = idxMalloc(&rc, sizeof(ExpertVtab));
12348       }
12349       if( rc==SQLITE_OK ){
12350         p->pExpert = pExpert;
12351         p->pTab = pExpert->pTable;
12352         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
12353       }
12354       sqlite3_free(zCreateTable);
12355     }else{
12356       rc = SQLITE_NOMEM;
12357     }
12358   }
12359 
12360   *ppVtab = (sqlite3_vtab*)p;
12361   return rc;
12362 }
12363 
expertDisconnect(sqlite3_vtab * pVtab)12364 static int expertDisconnect(sqlite3_vtab *pVtab){
12365   ExpertVtab *p = (ExpertVtab*)pVtab;
12366   sqlite3_free(p);
12367   return SQLITE_OK;
12368 }
12369 
expertBestIndex(sqlite3_vtab * pVtab,sqlite3_index_info * pIdxInfo)12370 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
12371   ExpertVtab *p = (ExpertVtab*)pVtab;
12372   int rc = SQLITE_OK;
12373   int n = 0;
12374   IdxScan *pScan;
12375   const int opmask =
12376     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
12377     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
12378     SQLITE_INDEX_CONSTRAINT_LE;
12379 
12380   pScan = idxMalloc(&rc, sizeof(IdxScan));
12381   if( pScan ){
12382     int i;
12383 
12384     /* Link the new scan object into the list */
12385     pScan->pTab = p->pTab;
12386     pScan->pNextScan = p->pExpert->pScan;
12387     p->pExpert->pScan = pScan;
12388 
12389     /* Add the constraints to the IdxScan object */
12390     for(i=0; i<pIdxInfo->nConstraint; i++){
12391       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
12392       if( pCons->usable
12393        && pCons->iColumn>=0
12394        && p->pTab->aCol[pCons->iColumn].iPk==0
12395        && (pCons->op & opmask)
12396       ){
12397         IdxConstraint *pNew;
12398         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
12399         pNew = idxNewConstraint(&rc, zColl);
12400         if( pNew ){
12401           pNew->iCol = pCons->iColumn;
12402           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
12403             pNew->pNext = pScan->pEq;
12404             pScan->pEq = pNew;
12405           }else{
12406             pNew->bRange = 1;
12407             pNew->pNext = pScan->pRange;
12408             pScan->pRange = pNew;
12409           }
12410         }
12411         n++;
12412         pIdxInfo->aConstraintUsage[i].argvIndex = n;
12413       }
12414     }
12415 
12416     /* Add the ORDER BY to the IdxScan object */
12417     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
12418       int iCol = pIdxInfo->aOrderBy[i].iColumn;
12419       if( iCol>=0 ){
12420         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
12421         if( pNew ){
12422           pNew->iCol = iCol;
12423           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
12424           pNew->pNext = pScan->pOrder;
12425           pNew->pLink = pScan->pOrder;
12426           pScan->pOrder = pNew;
12427           n++;
12428         }
12429       }
12430     }
12431   }
12432 
12433   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
12434   return rc;
12435 }
12436 
expertUpdate(sqlite3_vtab * pVtab,int nData,sqlite3_value ** azData,sqlite_int64 * pRowid)12437 static int expertUpdate(
12438   sqlite3_vtab *pVtab,
12439   int nData,
12440   sqlite3_value **azData,
12441   sqlite_int64 *pRowid
12442 ){
12443   (void)pVtab;
12444   (void)nData;
12445   (void)azData;
12446   (void)pRowid;
12447   return SQLITE_OK;
12448 }
12449 
12450 /*
12451 ** Virtual table module xOpen method.
12452 */
expertOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)12453 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
12454   int rc = SQLITE_OK;
12455   ExpertCsr *pCsr;
12456   (void)pVTab;
12457   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
12458   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
12459   return rc;
12460 }
12461 
12462 /*
12463 ** Virtual table module xClose method.
12464 */
expertClose(sqlite3_vtab_cursor * cur)12465 static int expertClose(sqlite3_vtab_cursor *cur){
12466   ExpertCsr *pCsr = (ExpertCsr*)cur;
12467   sqlite3_finalize(pCsr->pData);
12468   sqlite3_free(pCsr);
12469   return SQLITE_OK;
12470 }
12471 
12472 /*
12473 ** Virtual table module xEof method.
12474 **
12475 ** Return non-zero if the cursor does not currently point to a valid
12476 ** record (i.e if the scan has finished), or zero otherwise.
12477 */
expertEof(sqlite3_vtab_cursor * cur)12478 static int expertEof(sqlite3_vtab_cursor *cur){
12479   ExpertCsr *pCsr = (ExpertCsr*)cur;
12480   return pCsr->pData==0;
12481 }
12482 
12483 /*
12484 ** Virtual table module xNext method.
12485 */
expertNext(sqlite3_vtab_cursor * cur)12486 static int expertNext(sqlite3_vtab_cursor *cur){
12487   ExpertCsr *pCsr = (ExpertCsr*)cur;
12488   int rc = SQLITE_OK;
12489 
12490   assert( pCsr->pData );
12491   rc = sqlite3_step(pCsr->pData);
12492   if( rc!=SQLITE_ROW ){
12493     rc = sqlite3_finalize(pCsr->pData);
12494     pCsr->pData = 0;
12495   }else{
12496     rc = SQLITE_OK;
12497   }
12498 
12499   return rc;
12500 }
12501 
12502 /*
12503 ** Virtual table module xRowid method.
12504 */
expertRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)12505 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
12506   (void)cur;
12507   *pRowid = 0;
12508   return SQLITE_OK;
12509 }
12510 
12511 /*
12512 ** Virtual table module xColumn method.
12513 */
expertColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)12514 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
12515   ExpertCsr *pCsr = (ExpertCsr*)cur;
12516   sqlite3_value *pVal;
12517   pVal = sqlite3_column_value(pCsr->pData, i);
12518   if( pVal ){
12519     sqlite3_result_value(ctx, pVal);
12520   }
12521   return SQLITE_OK;
12522 }
12523 
12524 /*
12525 ** Virtual table module xFilter method.
12526 */
expertFilter(sqlite3_vtab_cursor * cur,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)12527 static int expertFilter(
12528   sqlite3_vtab_cursor *cur,
12529   int idxNum, const char *idxStr,
12530   int argc, sqlite3_value **argv
12531 ){
12532   ExpertCsr *pCsr = (ExpertCsr*)cur;
12533   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
12534   sqlite3expert *pExpert = pVtab->pExpert;
12535   int rc;
12536 
12537   (void)idxNum;
12538   (void)idxStr;
12539   (void)argc;
12540   (void)argv;
12541   rc = sqlite3_finalize(pCsr->pData);
12542   pCsr->pData = 0;
12543   if( rc==SQLITE_OK ){
12544     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
12545         "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName
12546     );
12547   }
12548 
12549   if( rc==SQLITE_OK ){
12550     rc = expertNext(cur);
12551   }
12552   return rc;
12553 }
12554 
idxRegisterVtab(sqlite3expert * p)12555 static int idxRegisterVtab(sqlite3expert *p){
12556   static sqlite3_module expertModule = {
12557     2,                            /* iVersion */
12558     expertConnect,                /* xCreate - create a table */
12559     expertConnect,                /* xConnect - connect to an existing table */
12560     expertBestIndex,              /* xBestIndex - Determine search strategy */
12561     expertDisconnect,             /* xDisconnect - Disconnect from a table */
12562     expertDisconnect,             /* xDestroy - Drop a table */
12563     expertOpen,                   /* xOpen - open a cursor */
12564     expertClose,                  /* xClose - close a cursor */
12565     expertFilter,                 /* xFilter - configure scan constraints */
12566     expertNext,                   /* xNext - advance a cursor */
12567     expertEof,                    /* xEof */
12568     expertColumn,                 /* xColumn - read data */
12569     expertRowid,                  /* xRowid - read data */
12570     expertUpdate,                 /* xUpdate - write data */
12571     0,                            /* xBegin - begin transaction */
12572     0,                            /* xSync - sync transaction */
12573     0,                            /* xCommit - commit transaction */
12574     0,                            /* xRollback - rollback transaction */
12575     0,                            /* xFindFunction - function overloading */
12576     0,                            /* xRename - rename the table */
12577     0,                            /* xSavepoint */
12578     0,                            /* xRelease */
12579     0,                            /* xRollbackTo */
12580     0,                            /* xShadowName */
12581     0,                            /* xIntegrity */
12582   };
12583 
12584   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
12585 }
12586 /*
12587 ** End of virtual table implementation.
12588 *************************************************************************/
12589 /*
12590 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
12591 ** is called, set it to the return value of sqlite3_finalize() before
12592 ** returning. Otherwise, discard the sqlite3_finalize() return value.
12593 */
idxFinalize(int * pRc,sqlite3_stmt * pStmt)12594 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
12595   int rc = sqlite3_finalize(pStmt);
12596   if( *pRc==SQLITE_OK ) *pRc = rc;
12597 }
12598 
12599 /*
12600 ** Attempt to allocate an IdxTable structure corresponding to table zTab
12601 ** in the main database of connection db. If successful, set (*ppOut) to
12602 ** point to the new object and return SQLITE_OK. Otherwise, return an
12603 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
12604 ** set to point to an error string.
12605 **
12606 ** It is the responsibility of the caller to eventually free either the
12607 ** IdxTable object or error message using sqlite3_free().
12608 */
idxGetTableInfo(sqlite3 * db,const char * zTab,IdxTable ** ppOut,char ** pzErrmsg)12609 static int idxGetTableInfo(
12610   sqlite3 *db,                    /* Database connection to read details from */
12611   const char *zTab,               /* Table name */
12612   IdxTable **ppOut,               /* OUT: New object (if successful) */
12613   char **pzErrmsg                 /* OUT: Error message (if not) */
12614 ){
12615   sqlite3_stmt *p1 = 0;
12616   int nCol = 0;
12617   int nTab;
12618   int nByte;
12619   IdxTable *pNew = 0;
12620   int rc, rc2;
12621   char *pCsr = 0;
12622   int nPk = 0;
12623 
12624   *ppOut = 0;
12625   if( zTab==0 ) return SQLITE_ERROR;
12626   nTab = STRLEN(zTab);
12627   nByte = sizeof(IdxTable) + nTab + 1;
12628   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
12629   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12630     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12631     const char *zColSeq = 0;
12632     if( zCol==0 ){
12633       rc = SQLITE_ERROR;
12634       break;
12635     }
12636     nByte += 1 + STRLEN(zCol);
12637     rc = sqlite3_table_column_metadata(
12638         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12639     );
12640     if( zColSeq==0 ) zColSeq = "binary";
12641     nByte += 1 + STRLEN(zColSeq);
12642     nCol++;
12643     nPk += (sqlite3_column_int(p1, 5)>0);
12644   }
12645   rc2 = sqlite3_reset(p1);
12646   if( rc==SQLITE_OK ) rc = rc2;
12647 
12648   nByte += sizeof(IdxColumn) * nCol;
12649   if( rc==SQLITE_OK ){
12650     pNew = idxMalloc(&rc, nByte);
12651   }
12652   if( rc==SQLITE_OK ){
12653     pNew->aCol = (IdxColumn*)&pNew[1];
12654     pNew->nCol = nCol;
12655     pCsr = (char*)&pNew->aCol[nCol];
12656   }
12657 
12658   nCol = 0;
12659   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12660     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12661     const char *zColSeq = 0;
12662     int nCopy;
12663     if( zCol==0 ) continue;
12664     nCopy = STRLEN(zCol) + 1;
12665     pNew->aCol[nCol].zName = pCsr;
12666     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
12667     memcpy(pCsr, zCol, nCopy);
12668     pCsr += nCopy;
12669 
12670     rc = sqlite3_table_column_metadata(
12671         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12672     );
12673     if( rc==SQLITE_OK ){
12674       if( zColSeq==0 ) zColSeq = "binary";
12675       nCopy = STRLEN(zColSeq) + 1;
12676       pNew->aCol[nCol].zColl = pCsr;
12677       memcpy(pCsr, zColSeq, nCopy);
12678       pCsr += nCopy;
12679     }
12680 
12681     nCol++;
12682   }
12683   idxFinalize(&rc, p1);
12684 
12685   if( rc!=SQLITE_OK ){
12686     sqlite3_free(pNew);
12687     pNew = 0;
12688   }else if( ALWAYS(pNew!=0) ){
12689     pNew->zName = pCsr;
12690     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
12691   }
12692 
12693   *ppOut = pNew;
12694   return rc;
12695 }
12696 
12697 /*
12698 ** This function is a no-op if *pRc is set to anything other than
12699 ** SQLITE_OK when it is called.
12700 **
12701 ** If *pRc is initially set to SQLITE_OK, then the text specified by
12702 ** the printf() style arguments is appended to zIn and the result returned
12703 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
12704 ** zIn before returning.
12705 */
idxAppendText(int * pRc,char * zIn,const char * zFmt,...)12706 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
12707   va_list ap;
12708   char *zAppend = 0;
12709   char *zRet = 0;
12710   int nIn = zIn ? STRLEN(zIn) : 0;
12711   int nAppend = 0;
12712   va_start(ap, zFmt);
12713   if( *pRc==SQLITE_OK ){
12714     zAppend = sqlite3_vmprintf(zFmt, ap);
12715     if( zAppend ){
12716       nAppend = STRLEN(zAppend);
12717       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
12718     }
12719     if( zAppend && zRet ){
12720       if( nIn ) memcpy(zRet, zIn, nIn);
12721       memcpy(&zRet[nIn], zAppend, nAppend+1);
12722     }else{
12723       sqlite3_free(zRet);
12724       zRet = 0;
12725       *pRc = SQLITE_NOMEM;
12726     }
12727     sqlite3_free(zAppend);
12728     sqlite3_free(zIn);
12729   }
12730   va_end(ap);
12731   return zRet;
12732 }
12733 
12734 /*
12735 ** Return true if zId must be quoted in order to use it as an SQL
12736 ** identifier, or false otherwise.
12737 */
idxIdentifierRequiresQuotes(const char * zId)12738 static int idxIdentifierRequiresQuotes(const char *zId){
12739   int i;
12740   int nId = STRLEN(zId);
12741 
12742   if( sqlite3_keyword_check(zId, nId) ) return 1;
12743 
12744   for(i=0; zId[i]; i++){
12745     if( !(zId[i]=='_')
12746      && !(zId[i]>='0' && zId[i]<='9')
12747      && !(zId[i]>='a' && zId[i]<='z')
12748      && !(zId[i]>='A' && zId[i]<='Z')
12749     ){
12750       return 1;
12751     }
12752   }
12753   return 0;
12754 }
12755 
12756 /*
12757 ** This function appends an index column definition suitable for constraint
12758 ** pCons to the string passed as zIn and returns the result.
12759 */
idxAppendColDefn(int * pRc,char * zIn,IdxTable * pTab,IdxConstraint * pCons)12760 static char *idxAppendColDefn(
12761   int *pRc,                       /* IN/OUT: Error code */
12762   char *zIn,                      /* Column defn accumulated so far */
12763   IdxTable *pTab,                 /* Table index will be created on */
12764   IdxConstraint *pCons
12765 ){
12766   char *zRet = zIn;
12767   IdxColumn *p = &pTab->aCol[pCons->iCol];
12768   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
12769 
12770   if( idxIdentifierRequiresQuotes(p->zName) ){
12771     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
12772   }else{
12773     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
12774   }
12775 
12776   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
12777     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
12778       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
12779     }else{
12780       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
12781     }
12782   }
12783 
12784   if( pCons->bDesc ){
12785     zRet = idxAppendText(pRc, zRet, " DESC");
12786   }
12787   return zRet;
12788 }
12789 
12790 /*
12791 ** Search database dbm for an index compatible with the one idxCreateFromCons()
12792 ** would create from arguments pScan, pEq and pTail. If no error occurs and
12793 ** such an index is found, return non-zero. Or, if no such index is found,
12794 ** return zero.
12795 **
12796 ** If an error occurs, set *pRc to an SQLite error code and return zero.
12797 */
idxFindCompatible(int * pRc,sqlite3 * dbm,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)12798 static int idxFindCompatible(
12799   int *pRc,                       /* OUT: Error code */
12800   sqlite3* dbm,                   /* Database to search */
12801   IdxScan *pScan,                 /* Scan for table to search for index on */
12802   IdxConstraint *pEq,             /* List of == constraints */
12803   IdxConstraint *pTail            /* List of range constraints */
12804 ){
12805   const char *zTbl = pScan->pTab->zName;
12806   sqlite3_stmt *pIdxList = 0;
12807   IdxConstraint *pIter;
12808   int nEq = 0;                    /* Number of elements in pEq */
12809   int rc;
12810 
12811   /* Count the elements in list pEq */
12812   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
12813 
12814   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
12815   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
12816     int bMatch = 1;
12817     IdxConstraint *pT = pTail;
12818     sqlite3_stmt *pInfo = 0;
12819     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
12820     if( zIdx==0 ) continue;
12821 
12822     /* Zero the IdxConstraint.bFlag values in the pEq list */
12823     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
12824 
12825     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
12826     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
12827       int iIdx = sqlite3_column_int(pInfo, 0);
12828       int iCol = sqlite3_column_int(pInfo, 1);
12829       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
12830 
12831       if( iIdx<nEq ){
12832         for(pIter=pEq; pIter; pIter=pIter->pLink){
12833           if( pIter->bFlag ) continue;
12834           if( pIter->iCol!=iCol ) continue;
12835           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
12836           pIter->bFlag = 1;
12837           break;
12838         }
12839         if( pIter==0 ){
12840           bMatch = 0;
12841           break;
12842         }
12843       }else{
12844         if( pT ){
12845           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
12846             bMatch = 0;
12847             break;
12848           }
12849           pT = pT->pLink;
12850         }
12851       }
12852     }
12853     idxFinalize(&rc, pInfo);
12854 
12855     if( rc==SQLITE_OK && bMatch ){
12856       sqlite3_finalize(pIdxList);
12857       return 1;
12858     }
12859   }
12860   idxFinalize(&rc, pIdxList);
12861 
12862   *pRc = rc;
12863   return 0;
12864 }
12865 
12866 /* Callback for sqlite3_exec() with query with leading count(*) column.
12867  * The first argument is expected to be an int*, referent to be incremented
12868  * if that leading column is not exactly '0'.
12869  */
countNonzeros(void * pCount,int nc,char * azResults[],char * azColumns[])12870 static int countNonzeros(void* pCount, int nc,
12871                          char* azResults[], char* azColumns[]){
12872   (void)azColumns;  /* Suppress unused parameter warning */
12873   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
12874     *((int *)pCount) += 1;
12875   }
12876   return 0;
12877 }
12878 
idxCreateFromCons(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pEq,IdxConstraint * pTail)12879 static int idxCreateFromCons(
12880   sqlite3expert *p,
12881   IdxScan *pScan,
12882   IdxConstraint *pEq,
12883   IdxConstraint *pTail
12884 ){
12885   sqlite3 *dbm = p->dbm;
12886   int rc = SQLITE_OK;
12887   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
12888     IdxTable *pTab = pScan->pTab;
12889     char *zCols = 0;
12890     char *zIdx = 0;
12891     IdxConstraint *pCons;
12892     unsigned int h = 0;
12893     const char *zFmt;
12894 
12895     for(pCons=pEq; pCons; pCons=pCons->pLink){
12896       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12897     }
12898     for(pCons=pTail; pCons; pCons=pCons->pLink){
12899       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12900     }
12901 
12902     if( rc==SQLITE_OK ){
12903       /* Hash the list of columns to come up with a name for the index */
12904       const char *zTable = pScan->pTab->zName;
12905       int quoteTable = idxIdentifierRequiresQuotes(zTable);
12906       char *zName = 0;          /* Index name */
12907       int collisions = 0;
12908       do{
12909         int i;
12910         char *zFind;
12911         for(i=0; zCols[i]; i++){
12912           h += ((h<<3) + zCols[i]);
12913         }
12914         sqlite3_free(zName);
12915         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
12916         if( zName==0 ) break;
12917         /* Is is unique among table, view and index names? */
12918         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
12919           " AND type in ('index','table','view')";
12920         zFind = sqlite3_mprintf(zFmt, zName);
12921         i = 0;
12922         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
12923         assert(rc==SQLITE_OK);
12924         sqlite3_free(zFind);
12925         if( i==0 ){
12926           collisions = 0;
12927           break;
12928         }
12929         ++collisions;
12930       }while( collisions<50 && zName!=0 );
12931       if( collisions ){
12932         /* This return means "Gave up trying to find a unique index name." */
12933         rc = SQLITE_BUSY_TIMEOUT;
12934       }else if( zName==0 ){
12935         rc = SQLITE_NOMEM;
12936       }else{
12937         if( quoteTable ){
12938           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
12939         }else{
12940           zFmt = "CREATE INDEX %s ON %s(%s)";
12941         }
12942         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
12943         if( !zIdx ){
12944           rc = SQLITE_NOMEM;
12945         }else{
12946           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
12947           if( rc!=SQLITE_OK ){
12948             rc = SQLITE_BUSY_TIMEOUT;
12949           }else{
12950             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
12951           }
12952         }
12953         sqlite3_free(zName);
12954         sqlite3_free(zIdx);
12955       }
12956     }
12957 
12958     sqlite3_free(zCols);
12959   }
12960   return rc;
12961 }
12962 
12963 /*
12964 ** Return true if list pList (linked by IdxConstraint.pLink) contains
12965 ** a constraint compatible with *p. Otherwise return false.
12966 */
idxFindConstraint(IdxConstraint * pList,IdxConstraint * p)12967 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
12968   IdxConstraint *pCmp;
12969   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
12970     if( p->iCol==pCmp->iCol ) return 1;
12971   }
12972   return 0;
12973 }
12974 
idxCreateFromWhere(sqlite3expert * p,IdxScan * pScan,IdxConstraint * pTail)12975 static int idxCreateFromWhere(
12976   sqlite3expert *p,
12977   IdxScan *pScan,                 /* Create indexes for this scan */
12978   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
12979 ){
12980   IdxConstraint *p1 = 0;
12981   IdxConstraint *pCon;
12982   int rc;
12983 
12984   /* Gather up all the == constraints. */
12985   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
12986     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12987       pCon->pLink = p1;
12988       p1 = pCon;
12989     }
12990   }
12991 
12992   /* Create an index using the == constraints collected above. And the
12993   ** range constraint/ORDER BY terms passed in by the caller, if any. */
12994   rc = idxCreateFromCons(p, pScan, p1, pTail);
12995 
12996   /* If no range/ORDER BY passed by the caller, create a version of the
12997   ** index for each range constraint.  */
12998   if( pTail==0 ){
12999     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
13000       assert( pCon->pLink==0 );
13001       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
13002         rc = idxCreateFromCons(p, pScan, p1, pCon);
13003       }
13004     }
13005   }
13006 
13007   return rc;
13008 }
13009 
13010 /*
13011 ** Create candidate indexes in database [dbm] based on the data in
13012 ** linked-list pScan.
13013 */
idxCreateCandidates(sqlite3expert * p)13014 static int idxCreateCandidates(sqlite3expert *p){
13015   int rc = SQLITE_OK;
13016   IdxScan *pIter;
13017 
13018   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
13019     rc = idxCreateFromWhere(p, pIter, 0);
13020     if( rc==SQLITE_OK && pIter->pOrder ){
13021       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
13022     }
13023   }
13024 
13025   return rc;
13026 }
13027 
13028 /*
13029 ** Free all elements of the linked list starting at pConstraint.
13030 */
idxConstraintFree(IdxConstraint * pConstraint)13031 static void idxConstraintFree(IdxConstraint *pConstraint){
13032   IdxConstraint *pNext;
13033   IdxConstraint *p;
13034 
13035   for(p=pConstraint; p; p=pNext){
13036     pNext = p->pNext;
13037     sqlite3_free(p);
13038   }
13039 }
13040 
13041 /*
13042 ** Free all elements of the linked list starting from pScan up until pLast
13043 ** (pLast is not freed).
13044 */
idxScanFree(IdxScan * pScan,IdxScan * pLast)13045 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
13046   IdxScan *p;
13047   IdxScan *pNext;
13048   for(p=pScan; p!=pLast; p=pNext){
13049     pNext = p->pNextScan;
13050     idxConstraintFree(p->pOrder);
13051     idxConstraintFree(p->pEq);
13052     idxConstraintFree(p->pRange);
13053     sqlite3_free(p);
13054   }
13055 }
13056 
13057 /*
13058 ** Free all elements of the linked list starting from pStatement up
13059 ** until pLast (pLast is not freed).
13060 */
idxStatementFree(IdxStatement * pStatement,IdxStatement * pLast)13061 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
13062   IdxStatement *p;
13063   IdxStatement *pNext;
13064   for(p=pStatement; p!=pLast; p=pNext){
13065     pNext = p->pNext;
13066     sqlite3_free(p->zEQP);
13067     sqlite3_free(p->zIdx);
13068     sqlite3_free(p);
13069   }
13070 }
13071 
13072 /*
13073 ** Free the linked list of IdxTable objects starting at pTab.
13074 */
idxTableFree(IdxTable * pTab)13075 static void idxTableFree(IdxTable *pTab){
13076   IdxTable *pIter;
13077   IdxTable *pNext;
13078   for(pIter=pTab; pIter; pIter=pNext){
13079     pNext = pIter->pNext;
13080     sqlite3_free(pIter);
13081   }
13082 }
13083 
13084 /*
13085 ** Free the linked list of IdxWrite objects starting at pTab.
13086 */
idxWriteFree(IdxWrite * pTab)13087 static void idxWriteFree(IdxWrite *pTab){
13088   IdxWrite *pIter;
13089   IdxWrite *pNext;
13090   for(pIter=pTab; pIter; pIter=pNext){
13091     pNext = pIter->pNext;
13092     sqlite3_free(pIter);
13093   }
13094 }
13095 
13096 
13097 
13098 /*
13099 ** This function is called after candidate indexes have been created. It
13100 ** runs all the queries to see which indexes they prefer, and populates
13101 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
13102 */
idxFindIndexes(sqlite3expert * p,char ** pzErr)13103 static int idxFindIndexes(
13104   sqlite3expert *p,
13105   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
13106 ){
13107   IdxStatement *pStmt;
13108   sqlite3 *dbm = p->dbm;
13109   int rc = SQLITE_OK;
13110 
13111   IdxHash hIdx;
13112   idxHashInit(&hIdx);
13113 
13114   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
13115     IdxHashEntry *pEntry;
13116     sqlite3_stmt *pExplain = 0;
13117     idxHashClear(&hIdx);
13118     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
13119         "EXPLAIN QUERY PLAN %s", pStmt->zSql
13120     );
13121     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
13122       /* int iId = sqlite3_column_int(pExplain, 0); */
13123       /* int iParent = sqlite3_column_int(pExplain, 1); */
13124       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
13125       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
13126       int nDetail;
13127       int i;
13128 
13129       if( !zDetail ) continue;
13130       nDetail = STRLEN(zDetail);
13131 
13132       for(i=0; i<nDetail; i++){
13133         const char *zIdx = 0;
13134         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
13135           zIdx = &zDetail[i+13];
13136         }else if( i+22<nDetail
13137             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
13138         ){
13139           zIdx = &zDetail[i+22];
13140         }
13141         if( zIdx ){
13142           const char *zSql;
13143           int nIdx = 0;
13144           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
13145             nIdx++;
13146           }
13147           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
13148           if( zSql ){
13149             idxHashAdd(&rc, &hIdx, zSql, 0);
13150             if( rc ) goto find_indexes_out;
13151           }
13152           break;
13153         }
13154       }
13155 
13156       if( zDetail[0]!='-' ){
13157         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
13158       }
13159     }
13160 
13161     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13162       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
13163     }
13164 
13165     idxFinalize(&rc, pExplain);
13166   }
13167 
13168  find_indexes_out:
13169   idxHashClear(&hIdx);
13170   return rc;
13171 }
13172 
idxAuthCallback(void * pCtx,int eOp,const char * z3,const char * z4,const char * zDb,const char * zTrigger)13173 static int idxAuthCallback(
13174   void *pCtx,
13175   int eOp,
13176   const char *z3,
13177   const char *z4,
13178   const char *zDb,
13179   const char *zTrigger
13180 ){
13181   int rc = SQLITE_OK;
13182   (void)z4;
13183   (void)zTrigger;
13184   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
13185     if( sqlite3_stricmp(zDb, "main")==0 ){
13186       sqlite3expert *p = (sqlite3expert*)pCtx;
13187       IdxTable *pTab;
13188       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
13189         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
13190       }
13191       if( pTab ){
13192         IdxWrite *pWrite;
13193         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
13194           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
13195         }
13196         if( pWrite==0 ){
13197           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
13198           if( rc==SQLITE_OK ){
13199             pWrite->pTab = pTab;
13200             pWrite->eOp = eOp;
13201             pWrite->pNext = p->pWrite;
13202             p->pWrite = pWrite;
13203           }
13204         }
13205       }
13206     }
13207   }
13208   return rc;
13209 }
13210 
idxProcessOneTrigger(sqlite3expert * p,IdxWrite * pWrite,char ** pzErr)13211 static int idxProcessOneTrigger(
13212   sqlite3expert *p,
13213   IdxWrite *pWrite,
13214   char **pzErr
13215 ){
13216   static const char *zInt = UNIQUE_TABLE_NAME;
13217   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
13218   IdxTable *pTab = pWrite->pTab;
13219   const char *zTab = pTab->zName;
13220   const char *zSql =
13221     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
13222     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
13223     "ORDER BY type;";
13224   sqlite3_stmt *pSelect = 0;
13225   int rc = SQLITE_OK;
13226   char *zWrite = 0;
13227 
13228   /* Create the table and its triggers in the temp schema */
13229   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
13230   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
13231     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
13232     if( zCreate==0 ) continue;
13233     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
13234   }
13235   idxFinalize(&rc, pSelect);
13236 
13237   /* Rename the table in the temp schema to zInt */
13238   if( rc==SQLITE_OK ){
13239     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
13240     if( z==0 ){
13241       rc = SQLITE_NOMEM;
13242     }else{
13243       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
13244       sqlite3_free(z);
13245     }
13246   }
13247 
13248   switch( pWrite->eOp ){
13249     case SQLITE_INSERT: {
13250       int i;
13251       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
13252       for(i=0; i<pTab->nCol; i++){
13253         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
13254       }
13255       zWrite = idxAppendText(&rc, zWrite, ")");
13256       break;
13257     }
13258     case SQLITE_UPDATE: {
13259       int i;
13260       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
13261       for(i=0; i<pTab->nCol; i++){
13262         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
13263             pTab->aCol[i].zName
13264         );
13265       }
13266       break;
13267     }
13268     default: {
13269       assert( pWrite->eOp==SQLITE_DELETE );
13270       if( rc==SQLITE_OK ){
13271         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
13272         if( zWrite==0 ) rc = SQLITE_NOMEM;
13273       }
13274     }
13275   }
13276 
13277   if( rc==SQLITE_OK ){
13278     sqlite3_stmt *pX = 0;
13279     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
13280     idxFinalize(&rc, pX);
13281     if( rc!=SQLITE_OK ){
13282       idxDatabaseError(p->dbv, pzErr);
13283     }
13284   }
13285   sqlite3_free(zWrite);
13286 
13287   if( rc==SQLITE_OK ){
13288     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
13289   }
13290 
13291   return rc;
13292 }
13293 
idxProcessTriggers(sqlite3expert * p,char ** pzErr)13294 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
13295   int rc = SQLITE_OK;
13296   IdxWrite *pEnd = 0;
13297   IdxWrite *pFirst = p->pWrite;
13298 
13299   while( rc==SQLITE_OK && pFirst!=pEnd ){
13300     IdxWrite *pIter;
13301     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
13302       rc = idxProcessOneTrigger(p, pIter, pzErr);
13303     }
13304     pEnd = pFirst;
13305     pFirst = p->pWrite;
13306   }
13307 
13308   return rc;
13309 }
13310 
13311 
idxCreateVtabSchema(sqlite3expert * p,char ** pzErrmsg)13312 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
13313   int rc = idxRegisterVtab(p);
13314   sqlite3_stmt *pSchema = 0;
13315 
13316   /* For each table in the main db schema:
13317   **
13318   **   1) Add an entry to the p->pTable list, and
13319   **   2) Create the equivalent virtual table in dbv.
13320   */
13321   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
13322       "SELECT type, name, sql, 1 FROM sqlite_schema "
13323       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
13324       " UNION ALL "
13325       "SELECT type, name, sql, 2 FROM sqlite_schema "
13326       "WHERE type = 'trigger'"
13327       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
13328       "ORDER BY 4, 1"
13329   );
13330   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
13331     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
13332     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
13333     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
13334 
13335     if( zType==0 || zName==0 ) continue;
13336     if( zType[0]=='v' || zType[1]=='r' ){
13337       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
13338     }else{
13339       IdxTable *pTab;
13340       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
13341       if( rc==SQLITE_OK ){
13342         int i;
13343         char *zInner = 0;
13344         char *zOuter = 0;
13345         pTab->pNext = p->pTable;
13346         p->pTable = pTab;
13347 
13348         /* The statement the vtab will pass to sqlite3_declare_vtab() */
13349         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
13350         for(i=0; i<pTab->nCol; i++){
13351           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
13352               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
13353           );
13354         }
13355         zInner = idxAppendText(&rc, zInner, ")");
13356 
13357         /* The CVT statement to create the vtab */
13358         zOuter = idxAppendText(&rc, 0,
13359             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
13360         );
13361         if( rc==SQLITE_OK ){
13362           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
13363         }
13364         sqlite3_free(zInner);
13365         sqlite3_free(zOuter);
13366       }
13367     }
13368   }
13369   idxFinalize(&rc, pSchema);
13370   return rc;
13371 }
13372 
13373 struct IdxSampleCtx {
13374   int iTarget;
13375   double target;                  /* Target nRet/nRow value */
13376   double nRow;                    /* Number of rows seen */
13377   double nRet;                    /* Number of rows returned */
13378 };
13379 
idxSampleFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)13380 static void idxSampleFunc(
13381   sqlite3_context *pCtx,
13382   int argc,
13383   sqlite3_value **argv
13384 ){
13385   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
13386   int bRet;
13387 
13388   (void)argv;
13389   assert( argc==0 );
13390   if( p->nRow==0.0 ){
13391     bRet = 1;
13392   }else{
13393     bRet = (p->nRet / p->nRow) <= p->target;
13394     if( bRet==0 ){
13395       unsigned short rnd;
13396       sqlite3_randomness(2, (void*)&rnd);
13397       bRet = ((int)rnd % 100) <= p->iTarget;
13398     }
13399   }
13400 
13401   sqlite3_result_int(pCtx, bRet);
13402   p->nRow += 1.0;
13403   p->nRet += (double)bRet;
13404 }
13405 
13406 struct IdxRemCtx {
13407   int nSlot;
13408   struct IdxRemSlot {
13409     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
13410     i64 iVal;                     /* SQLITE_INTEGER value */
13411     double rVal;                  /* SQLITE_FLOAT value */
13412     int nByte;                    /* Bytes of space allocated at z */
13413     int n;                        /* Size of buffer z */
13414     char *z;                      /* SQLITE_TEXT/BLOB value */
13415   } aSlot[1];
13416 };
13417 
13418 /*
13419 ** Implementation of scalar function sqlite_expert_rem().
13420 */
idxRemFunc(sqlite3_context * pCtx,int argc,sqlite3_value ** argv)13421 static void idxRemFunc(
13422   sqlite3_context *pCtx,
13423   int argc,
13424   sqlite3_value **argv
13425 ){
13426   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
13427   struct IdxRemSlot *pSlot;
13428   int iSlot;
13429   assert( argc==2 );
13430 
13431   iSlot = sqlite3_value_int(argv[0]);
13432   assert( iSlot<p->nSlot );
13433   pSlot = &p->aSlot[iSlot];
13434 
13435   switch( pSlot->eType ){
13436     case SQLITE_NULL:
13437       /* no-op */
13438       break;
13439 
13440     case SQLITE_INTEGER:
13441       sqlite3_result_int64(pCtx, pSlot->iVal);
13442       break;
13443 
13444     case SQLITE_FLOAT:
13445       sqlite3_result_double(pCtx, pSlot->rVal);
13446       break;
13447 
13448     case SQLITE_BLOB:
13449       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13450       break;
13451 
13452     case SQLITE_TEXT:
13453       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13454       break;
13455   }
13456 
13457   pSlot->eType = sqlite3_value_type(argv[1]);
13458   switch( pSlot->eType ){
13459     case SQLITE_NULL:
13460       /* no-op */
13461       break;
13462 
13463     case SQLITE_INTEGER:
13464       pSlot->iVal = sqlite3_value_int64(argv[1]);
13465       break;
13466 
13467     case SQLITE_FLOAT:
13468       pSlot->rVal = sqlite3_value_double(argv[1]);
13469       break;
13470 
13471     case SQLITE_BLOB:
13472     case SQLITE_TEXT: {
13473       int nByte = sqlite3_value_bytes(argv[1]);
13474       const void *pData = 0;
13475       if( nByte>pSlot->nByte ){
13476         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
13477         if( zNew==0 ){
13478           sqlite3_result_error_nomem(pCtx);
13479           return;
13480         }
13481         pSlot->nByte = nByte*2;
13482         pSlot->z = zNew;
13483       }
13484       pSlot->n = nByte;
13485       if( pSlot->eType==SQLITE_BLOB ){
13486         pData = sqlite3_value_blob(argv[1]);
13487         if( pData ) memcpy(pSlot->z, pData, nByte);
13488       }else{
13489         pData = sqlite3_value_text(argv[1]);
13490         memcpy(pSlot->z, pData, nByte);
13491       }
13492       break;
13493     }
13494   }
13495 }
13496 
idxLargestIndex(sqlite3 * db,int * pnMax,char ** pzErr)13497 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
13498   int rc = SQLITE_OK;
13499   const char *zMax =
13500     "SELECT max(i.seqno) FROM "
13501     "  sqlite_schema AS s, "
13502     "  pragma_index_list(s.name) AS l, "
13503     "  pragma_index_info(l.name) AS i "
13504     "WHERE s.type = 'table'";
13505   sqlite3_stmt *pMax = 0;
13506 
13507   *pnMax = 0;
13508   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
13509   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
13510     *pnMax = sqlite3_column_int(pMax, 0) + 1;
13511   }
13512   idxFinalize(&rc, pMax);
13513 
13514   return rc;
13515 }
13516 
idxPopulateOneStat1(sqlite3expert * p,sqlite3_stmt * pIndexXInfo,sqlite3_stmt * pWriteStat,const char * zTab,const char * zIdx,char ** pzErr)13517 static int idxPopulateOneStat1(
13518   sqlite3expert *p,
13519   sqlite3_stmt *pIndexXInfo,
13520   sqlite3_stmt *pWriteStat,
13521   const char *zTab,
13522   const char *zIdx,
13523   char **pzErr
13524 ){
13525   char *zCols = 0;
13526   char *zOrder = 0;
13527   char *zQuery = 0;
13528   int nCol = 0;
13529   int i;
13530   sqlite3_stmt *pQuery = 0;
13531   int *aStat = 0;
13532   int rc = SQLITE_OK;
13533 
13534   assert( p->iSample>0 );
13535 
13536   /* Formulate the query text */
13537   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
13538   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
13539     const char *zComma = zCols==0 ? "" : ", ";
13540     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
13541     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
13542     zCols = idxAppendText(&rc, zCols,
13543         "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s",
13544         zComma, zName, nCol, zName, zColl
13545     );
13546     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
13547   }
13548   sqlite3_reset(pIndexXInfo);
13549   if( rc==SQLITE_OK ){
13550     if( p->iSample==100 ){
13551       zQuery = sqlite3_mprintf(
13552           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
13553       );
13554     }else{
13555       zQuery = sqlite3_mprintf(
13556           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
13557       );
13558     }
13559   }
13560   sqlite3_free(zCols);
13561   sqlite3_free(zOrder);
13562 
13563   /* Formulate the query text */
13564   if( rc==SQLITE_OK ){
13565     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13566     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
13567   }
13568   sqlite3_free(zQuery);
13569 
13570   if( rc==SQLITE_OK ){
13571     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
13572   }
13573   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13574     IdxHashEntry *pEntry;
13575     char *zStat = 0;
13576     for(i=0; i<=nCol; i++) aStat[i] = 1;
13577     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13578       aStat[0]++;
13579       for(i=0; i<nCol; i++){
13580         if( sqlite3_column_int(pQuery, i)==0 ) break;
13581       }
13582       for(/*no-op*/; i<nCol; i++){
13583         aStat[i+1]++;
13584       }
13585     }
13586 
13587     if( rc==SQLITE_OK ){
13588       int s0 = aStat[0];
13589       zStat = sqlite3_mprintf("%d", s0);
13590       if( zStat==0 ) rc = SQLITE_NOMEM;
13591       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
13592         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
13593       }
13594     }
13595 
13596     if( rc==SQLITE_OK ){
13597       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
13598       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
13599       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
13600       sqlite3_step(pWriteStat);
13601       rc = sqlite3_reset(pWriteStat);
13602     }
13603 
13604     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
13605     if( pEntry ){
13606       assert( pEntry->zVal2==0 );
13607       pEntry->zVal2 = zStat;
13608     }else{
13609       sqlite3_free(zStat);
13610     }
13611   }
13612   sqlite3_free(aStat);
13613   idxFinalize(&rc, pQuery);
13614 
13615   return rc;
13616 }
13617 
idxBuildSampleTable(sqlite3expert * p,const char * zTab)13618 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
13619   int rc;
13620   char *zSql;
13621 
13622   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13623   if( rc!=SQLITE_OK ) return rc;
13624 
13625   zSql = sqlite3_mprintf(
13626       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
13627   );
13628   if( zSql==0 ) return SQLITE_NOMEM;
13629   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
13630   sqlite3_free(zSql);
13631 
13632   return rc;
13633 }
13634 
13635 /*
13636 ** This function is called as part of sqlite3_expert_analyze(). Candidate
13637 ** indexes have already been created in database sqlite3expert.dbm, this
13638 ** function populates sqlite_stat1 table in the same database.
13639 **
13640 ** The stat1 data is generated by querying the
13641 */
idxPopulateStat1(sqlite3expert * p,char ** pzErr)13642 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
13643   int rc = SQLITE_OK;
13644   int nMax =0;
13645   struct IdxRemCtx *pCtx = 0;
13646   struct IdxSampleCtx samplectx;
13647   int i;
13648   i64 iPrev = -100000;
13649   sqlite3_stmt *pAllIndex = 0;
13650   sqlite3_stmt *pIndexXInfo = 0;
13651   sqlite3_stmt *pWrite = 0;
13652 
13653   const char *zAllIndex =
13654     "SELECT s.rowid, s.name, l.name FROM "
13655     "  sqlite_schema AS s, "
13656     "  pragma_index_list(s.name) AS l "
13657     "WHERE s.type = 'table'";
13658   const char *zIndexXInfo =
13659     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
13660   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
13661 
13662   /* If iSample==0, no sqlite_stat1 data is required. */
13663   if( p->iSample==0 ) return SQLITE_OK;
13664 
13665   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
13666   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
13667 
13668   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
13669 
13670   if( rc==SQLITE_OK ){
13671     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
13672     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
13673   }
13674 
13675   if( rc==SQLITE_OK ){
13676     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13677     rc = sqlite3_create_function(dbrem, "sqlite_expert_rem",
13678         2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
13679     );
13680   }
13681   if( rc==SQLITE_OK ){
13682     rc = sqlite3_create_function(p->db, "sqlite_expert_sample",
13683         0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
13684     );
13685   }
13686 
13687   if( rc==SQLITE_OK ){
13688     pCtx->nSlot = nMax+1;
13689     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
13690   }
13691   if( rc==SQLITE_OK ){
13692     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
13693   }
13694   if( rc==SQLITE_OK ){
13695     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
13696   }
13697 
13698   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
13699     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
13700     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
13701     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
13702     if( zTab==0 || zIdx==0 ) continue;
13703     if( p->iSample<100 && iPrev!=iRowid ){
13704       samplectx.target = (double)p->iSample / 100.0;
13705       samplectx.iTarget = p->iSample;
13706       samplectx.nRow = 0.0;
13707       samplectx.nRet = 0.0;
13708       rc = idxBuildSampleTable(p, zTab);
13709       if( rc!=SQLITE_OK ) break;
13710     }
13711     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
13712     iPrev = iRowid;
13713   }
13714   if( rc==SQLITE_OK && p->iSample<100 ){
13715     rc = sqlite3_exec(p->dbv,
13716         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
13717     );
13718   }
13719 
13720   idxFinalize(&rc, pAllIndex);
13721   idxFinalize(&rc, pIndexXInfo);
13722   idxFinalize(&rc, pWrite);
13723 
13724   if( pCtx ){
13725     for(i=0; i<pCtx->nSlot; i++){
13726       sqlite3_free(pCtx->aSlot[i].z);
13727     }
13728     sqlite3_free(pCtx);
13729   }
13730 
13731   if( rc==SQLITE_OK ){
13732     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
13733   }
13734 
13735   sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0);
13736   sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0);
13737 
13738   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13739   return rc;
13740 }
13741 
13742 /*
13743 ** Define and possibly pretend to use a useless collation sequence.
13744 ** This pretense allows expert to accept SQL using custom collations.
13745 */
dummyCompare(void * up1,int up2,const void * up3,int up4,const void * up5)13746 int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
13747   (void)up1;
13748   (void)up2;
13749   (void)up3;
13750   (void)up4;
13751   (void)up5;
13752   assert(0); /* VDBE should never be run. */
13753   return 0;
13754 }
13755 /* And a callback to register above upon actual need */
useDummyCS(void * up1,sqlite3 * db,int etr,const char * zName)13756 void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
13757   (void)up1;
13758   sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
13759 }
13760 
13761 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13762   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13763 /*
13764 ** dummy functions for no-op implementation of UDFs during expert's work
13765 */
dummyUDF(sqlite3_context * up1,int up2,sqlite3_value ** up3)13766 void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
13767   (void)up1;
13768   (void)up2;
13769   (void)up3;
13770   assert(0); /* VDBE should never be run. */
13771 }
dummyUDFvalue(sqlite3_context * up1)13772 void dummyUDFvalue(sqlite3_context *up1){
13773   (void)up1;
13774   assert(0); /* VDBE should never be run. */
13775 }
13776 
13777 /*
13778 ** Register UDFs from user database with another.
13779 */
registerUDFs(sqlite3 * dbSrc,sqlite3 * dbDst)13780 int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
13781   sqlite3_stmt *pStmt;
13782   int rc = sqlite3_prepare_v2(dbSrc,
13783             "SELECT name,type,enc,narg,flags "
13784             "FROM pragma_function_list() "
13785             "WHERE builtin==0", -1, &pStmt, 0);
13786   if( rc==SQLITE_OK ){
13787     while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
13788       int nargs = sqlite3_column_int(pStmt,3);
13789       int flags = sqlite3_column_int(pStmt,4);
13790       const char *name = (char*)sqlite3_column_text(pStmt,0);
13791       const char *type = (char*)sqlite3_column_text(pStmt,1);
13792       const char *enc = (char*)sqlite3_column_text(pStmt,2);
13793       if( name==0 || type==0 || enc==0 ){
13794         /* no-op.  Only happens on OOM */
13795       }else{
13796         int ienc = SQLITE_UTF8;
13797         int rcf = SQLITE_ERROR;
13798         if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
13799         else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
13800         ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
13801         if( strcmp(type,"w")==0 ){
13802           rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
13803                                                dummyUDF,dummyUDFvalue,0,0,0);
13804         }else if( strcmp(type,"a")==0 ){
13805           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13806                                         0,dummyUDF,dummyUDFvalue);
13807         }else if( strcmp(type,"s")==0 ){
13808           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13809                                         dummyUDF,0,0);
13810         }
13811         if( rcf!=SQLITE_OK ){
13812           rc = rcf;
13813           break;
13814         }
13815       }
13816     }
13817     sqlite3_finalize(pStmt);
13818     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
13819   }
13820   return rc;
13821 }
13822 #endif
13823 
13824 /*
13825 ** Allocate a new sqlite3expert object.
13826 */
sqlite3_expert_new(sqlite3 * db,char ** pzErrmsg)13827 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
13828   int rc = SQLITE_OK;
13829   sqlite3expert *pNew;
13830 
13831   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
13832 
13833   /* Open two in-memory databases to work with. The "vtab database" (dbv)
13834   ** will contain a virtual table corresponding to each real table in
13835   ** the user database schema, and a copy of each view. It is used to
13836   ** collect information regarding the WHERE, ORDER BY and other clauses
13837   ** of the user's query.
13838   */
13839   if( rc==SQLITE_OK ){
13840     pNew->db = db;
13841     pNew->iSample = 100;
13842     rc = sqlite3_open(":memory:", &pNew->dbv);
13843   }
13844   if( rc==SQLITE_OK ){
13845     rc = sqlite3_open(":memory:", &pNew->dbm);
13846     if( rc==SQLITE_OK ){
13847       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
13848     }
13849   }
13850 
13851   /* Allow custom collations to be dealt with through prepare. */
13852   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
13853   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
13854 
13855 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13856   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13857   /* Register UDFs from database [db] with [dbm] and [dbv]. */
13858   if( rc==SQLITE_OK ){
13859     rc = registerUDFs(pNew->db, pNew->dbm);
13860   }
13861   if( rc==SQLITE_OK ){
13862     rc = registerUDFs(pNew->db, pNew->dbv);
13863   }
13864 #endif
13865 
13866   /* Copy the entire schema of database [db] into [dbm]. */
13867   if( rc==SQLITE_OK ){
13868     sqlite3_stmt *pSql = 0;
13869     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
13870         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
13871         " AND sql NOT LIKE 'CREATE VIRTUAL %%' ORDER BY rowid"
13872     );
13873     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
13874       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
13875       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
13876     }
13877     idxFinalize(&rc, pSql);
13878   }
13879 
13880   /* Create the vtab schema */
13881   if( rc==SQLITE_OK ){
13882     rc = idxCreateVtabSchema(pNew, pzErrmsg);
13883   }
13884 
13885   /* Register the auth callback with dbv */
13886   if( rc==SQLITE_OK ){
13887     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
13888   }
13889 
13890   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
13891   ** return the new sqlite3expert handle.  */
13892   if( rc!=SQLITE_OK ){
13893     sqlite3_expert_destroy(pNew);
13894     pNew = 0;
13895   }
13896   return pNew;
13897 }
13898 
13899 /*
13900 ** Configure an sqlite3expert object.
13901 */
sqlite3_expert_config(sqlite3expert * p,int op,...)13902 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
13903   int rc = SQLITE_OK;
13904   va_list ap;
13905   va_start(ap, op);
13906   switch( op ){
13907     case EXPERT_CONFIG_SAMPLE: {
13908       int iVal = va_arg(ap, int);
13909       if( iVal<0 ) iVal = 0;
13910       if( iVal>100 ) iVal = 100;
13911       p->iSample = iVal;
13912       break;
13913     }
13914     default:
13915       rc = SQLITE_NOTFOUND;
13916       break;
13917   }
13918 
13919   va_end(ap);
13920   return rc;
13921 }
13922 
13923 /*
13924 ** Add an SQL statement to the analysis.
13925 */
sqlite3_expert_sql(sqlite3expert * p,const char * zSql,char ** pzErr)13926 int sqlite3_expert_sql(
13927   sqlite3expert *p,               /* From sqlite3_expert_new() */
13928   const char *zSql,               /* SQL statement to add */
13929   char **pzErr                    /* OUT: Error message (if any) */
13930 ){
13931   IdxScan *pScanOrig = p->pScan;
13932   IdxStatement *pStmtOrig = p->pStatement;
13933   int rc = SQLITE_OK;
13934   const char *zStmt = zSql;
13935 
13936   if( p->bRun ) return SQLITE_MISUSE;
13937 
13938   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
13939     sqlite3_stmt *pStmt = 0;
13940     /* Ensure that the provided statement compiles against user's DB. */
13941     rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
13942     if( rc!=SQLITE_OK ) break;
13943     sqlite3_finalize(pStmt);
13944     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
13945     if( rc==SQLITE_OK ){
13946       if( pStmt ){
13947         IdxStatement *pNew;
13948         const char *z = sqlite3_sql(pStmt);
13949         int n = STRLEN(z);
13950         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
13951         if( rc==SQLITE_OK ){
13952           pNew->zSql = (char*)&pNew[1];
13953           memcpy(pNew->zSql, z, n+1);
13954           pNew->pNext = p->pStatement;
13955           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
13956           p->pStatement = pNew;
13957         }
13958         sqlite3_finalize(pStmt);
13959       }
13960     }else{
13961       idxDatabaseError(p->dbv, pzErr);
13962     }
13963   }
13964 
13965   if( rc!=SQLITE_OK ){
13966     idxScanFree(p->pScan, pScanOrig);
13967     idxStatementFree(p->pStatement, pStmtOrig);
13968     p->pScan = pScanOrig;
13969     p->pStatement = pStmtOrig;
13970   }
13971 
13972   return rc;
13973 }
13974 
sqlite3_expert_analyze(sqlite3expert * p,char ** pzErr)13975 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
13976   int rc;
13977   IdxHashEntry *pEntry;
13978 
13979   /* Do trigger processing to collect any extra IdxScan structures */
13980   rc = idxProcessTriggers(p, pzErr);
13981 
13982   /* Create candidate indexes within the in-memory database file */
13983   if( rc==SQLITE_OK ){
13984     rc = idxCreateCandidates(p);
13985   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
13986     if( pzErr )
13987       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
13988     return rc;
13989   }
13990 
13991   /* Generate the stat1 data */
13992   if( rc==SQLITE_OK ){
13993     rc = idxPopulateStat1(p, pzErr);
13994   }
13995 
13996   /* Formulate the EXPERT_REPORT_CANDIDATES text */
13997   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13998     p->zCandidates = idxAppendText(&rc, p->zCandidates,
13999         "%s;%s%s\n", pEntry->zVal,
14000         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
14001     );
14002   }
14003 
14004   /* Figure out which of the candidate indexes are preferred by the query
14005   ** planner and report the results to the user.  */
14006   if( rc==SQLITE_OK ){
14007     rc = idxFindIndexes(p, pzErr);
14008   }
14009 
14010   if( rc==SQLITE_OK ){
14011     p->bRun = 1;
14012   }
14013   return rc;
14014 }
14015 
14016 /*
14017 ** Return the total number of statements that have been added to this
14018 ** sqlite3expert using sqlite3_expert_sql().
14019 */
sqlite3_expert_count(sqlite3expert * p)14020 int sqlite3_expert_count(sqlite3expert *p){
14021   int nRet = 0;
14022   if( p->pStatement ) nRet = p->pStatement->iId+1;
14023   return nRet;
14024 }
14025 
14026 /*
14027 ** Return a component of the report.
14028 */
sqlite3_expert_report(sqlite3expert * p,int iStmt,int eReport)14029 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
14030   const char *zRet = 0;
14031   IdxStatement *pStmt;
14032 
14033   if( p->bRun==0 ) return 0;
14034   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
14035   switch( eReport ){
14036     case EXPERT_REPORT_SQL:
14037       if( pStmt ) zRet = pStmt->zSql;
14038       break;
14039     case EXPERT_REPORT_INDEXES:
14040       if( pStmt ) zRet = pStmt->zIdx;
14041       break;
14042     case EXPERT_REPORT_PLAN:
14043       if( pStmt ) zRet = pStmt->zEQP;
14044       break;
14045     case EXPERT_REPORT_CANDIDATES:
14046       zRet = p->zCandidates;
14047       break;
14048   }
14049   return zRet;
14050 }
14051 
14052 /*
14053 ** Free an sqlite3expert object.
14054 */
sqlite3_expert_destroy(sqlite3expert * p)14055 void sqlite3_expert_destroy(sqlite3expert *p){
14056   if( p ){
14057     sqlite3_close(p->dbm);
14058     sqlite3_close(p->dbv);
14059     idxScanFree(p->pScan, 0);
14060     idxStatementFree(p->pStatement, 0);
14061     idxTableFree(p->pTable);
14062     idxWriteFree(p->pWrite);
14063     idxHashClear(&p->hIdx);
14064     sqlite3_free(p->zCandidates);
14065     sqlite3_free(p);
14066   }
14067 }
14068 
14069 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
14070 
14071 /************************* End ../ext/expert/sqlite3expert.c ********************/
14072 
14073 /************************* Begin ../ext/intck/sqlite3intck.h ******************/
14074 /*
14075 ** 2024-02-08
14076 **
14077 ** The author disclaims copyright to this source code.  In place of
14078 ** a legal notice, here is a blessing:
14079 **
14080 **    May you do good and not evil.
14081 **    May you find forgiveness for yourself and forgive others.
14082 **    May you share freely, never taking more than you give.
14083 **
14084 *************************************************************************
14085 */
14086 
14087 /*
14088 ** Incremental Integrity-Check Extension
14089 ** -------------------------------------
14090 **
14091 ** This module contains code to check whether or not an SQLite database
14092 ** is well-formed or corrupt. This is the same task as performed by SQLite's
14093 ** built-in "PRAGMA integrity_check" command. This module differs from
14094 ** "PRAGMA integrity_check" in that:
14095 **
14096 **   +  It is less thorough - this module does not detect certain types
14097 **      of corruption that are detected by the PRAGMA command. However,
14098 **      it does detect all kinds of corruption that are likely to cause
14099 **      errors in SQLite applications.
14100 **
14101 **   +  It is slower. Sometimes up to three times slower.
14102 **
14103 **   +  It allows integrity-check operations to be split into multiple
14104 **      transactions, so that the database does not need to be read-locked
14105 **      for the duration of the integrity-check.
14106 **
14107 ** One way to use the API to run integrity-check on the "main" database
14108 ** of handle db is:
14109 **
14110 **   int rc = SQLITE_OK;
14111 **   sqlite3_intck *p = 0;
14112 **
14113 **   sqlite3_intck_open(db, "main", &p);
14114 **   while( SQLITE_OK==sqlite3_intck_step(p) ){
14115 **     const char *zMsg = sqlite3_intck_message(p);
14116 **     if( zMsg ) printf("corruption: %s\n", zMsg);
14117 **   }
14118 **   rc = sqlite3_intck_error(p, &zErr);
14119 **   if( rc!=SQLITE_OK ){
14120 **     printf("error occured (rc=%d), (errmsg=%s)\n", rc, zErr);
14121 **   }
14122 **   sqlite3_intck_close(p);
14123 **
14124 ** Usually, the sqlite3_intck object opens a read transaction within the
14125 ** first call to sqlite3_intck_step() and holds it open until the
14126 ** integrity-check is complete. However, if sqlite3_intck_unlock() is
14127 ** called, the read transaction is ended and a new read transaction opened
14128 ** by the subsequent call to sqlite3_intck_step().
14129 */
14130 
14131 #ifndef _SQLITE_INTCK_H
14132 #define _SQLITE_INTCK_H
14133 
14134 /* #include "sqlite3.h" */
14135 
14136 #ifdef __cplusplus
14137 extern "C" {
14138 #endif
14139 
14140 /*
14141 ** An ongoing incremental integrity-check operation is represented by an
14142 ** opaque pointer of the following type.
14143 */
14144 typedef struct sqlite3_intck sqlite3_intck;
14145 
14146 /*
14147 ** Open a new incremental integrity-check object. If successful, populate
14148 ** output variable (*ppOut) with the new object handle and return SQLITE_OK.
14149 ** Or, if an error occurs, set (*ppOut) to NULL and return an SQLite error
14150 ** code (e.g. SQLITE_NOMEM).
14151 **
14152 ** The integrity-check will be conducted on database zDb (which must be "main",
14153 ** "temp", or the name of an attached database) of database handle db. Once
14154 ** this function has been called successfully, the caller should not use
14155 ** database handle db until the integrity-check object has been destroyed
14156 ** using sqlite3_intck_close().
14157 */
14158 int sqlite3_intck_open(
14159   sqlite3 *db,                    /* Database handle */
14160   const char *zDb,                /* Database name ("main", "temp" etc.) */
14161   sqlite3_intck **ppOut           /* OUT: New sqlite3_intck handle */
14162 );
14163 
14164 /*
14165 ** Close and release all resources associated with a handle opened by an
14166 ** earlier call to sqlite3_intck_open(). The results of using an
14167 ** integrity-check handle after it has been passed to this function are
14168 ** undefined.
14169 */
14170 void sqlite3_intck_close(sqlite3_intck *pCk);
14171 
14172 /*
14173 ** Do the next step of the integrity-check operation specified by the handle
14174 ** passed as the only argument. This function returns SQLITE_DONE if the
14175 ** integrity-check operation is finished, or an SQLite error code if
14176 ** an error occurs, or SQLITE_OK if no error occurs but the integrity-check
14177 ** is not finished. It is not considered an error if database corruption
14178 ** is encountered.
14179 **
14180 ** Following a successful call to sqlite3_intck_step() (one that returns
14181 ** SQLITE_OK), sqlite3_intck_message() returns a non-NULL value if
14182 ** corruption was detected in the db.
14183 **
14184 ** If an error occurs and a value other than SQLITE_OK or SQLITE_DONE is
14185 ** returned, then the integrity-check handle is placed in an error state.
14186 ** In this state all subsequent calls to sqlite3_intck_step() or
14187 ** sqlite3_intck_unlock() will immediately return the same error. The
14188 ** sqlite3_intck_error() method may be used to obtain an English language
14189 ** error message in this case.
14190 */
14191 int sqlite3_intck_step(sqlite3_intck *pCk);
14192 
14193 /*
14194 ** If the previous call to sqlite3_intck_step() encountered corruption
14195 ** within the database, then this function returns a pointer to a buffer
14196 ** containing a nul-terminated string describing the corruption in
14197 ** English. If the previous call to sqlite3_intck_step() did not encounter
14198 ** corruption, or if there was no previous call, this function returns
14199 ** NULL.
14200 */
14201 const char *sqlite3_intck_message(sqlite3_intck *pCk);
14202 
14203 /*
14204 ** Close any read-transaction opened by an earlier call to
14205 ** sqlite3_intck_step(). Any subsequent call to sqlite3_intck_step() will
14206 ** open a new transaction. Return SQLITE_OK if successful, or an SQLite error
14207 ** code otherwise.
14208 **
14209 ** If an error occurs, then the integrity-check handle is placed in an error
14210 ** state. In this state all subsequent calls to sqlite3_intck_step() or
14211 ** sqlite3_intck_unlock() will immediately return the same error. The
14212 ** sqlite3_intck_error() method may be used to obtain an English language
14213 ** error message in this case.
14214 */
14215 int sqlite3_intck_unlock(sqlite3_intck *pCk);
14216 
14217 /*
14218 ** If an error has occurred in an earlier call to sqlite3_intck_step()
14219 ** or sqlite3_intck_unlock(), then this method returns the associated
14220 ** SQLite error code. Additionally, if pzErr is not NULL, then (*pzErr)
14221 ** may be set to point to a nul-terminated string containing an English
14222 ** language error message. Or, if no error message is available, to
14223 ** NULL.
14224 **
14225 ** If no error has occurred within sqlite3_intck_step() or
14226 ** sqlite_intck_unlock() calls on the handle passed as the first argument,
14227 ** then SQLITE_OK is returned and (*pzErr) set to NULL.
14228 */
14229 int sqlite3_intck_error(sqlite3_intck *pCk, const char **pzErr);
14230 
14231 /*
14232 ** This API is used for testing only. It returns the full-text of an SQL
14233 ** statement used to test object zObj, which may be a table or index.
14234 ** The returned buffer is valid until the next call to either this function
14235 ** or sqlite3_intck_close() on the same sqlite3_intck handle.
14236 */
14237 const char *sqlite3_intck_test_sql(sqlite3_intck *pCk, const char *zObj);
14238 
14239 
14240 #ifdef __cplusplus
14241 }  /* end of the 'extern "C"' block */
14242 #endif
14243 
14244 #endif /* ifndef _SQLITE_INTCK_H */
14245 
14246 /************************* End ../ext/intck/sqlite3intck.h ********************/
14247 /************************* Begin ../ext/intck/sqlite3intck.c ******************/
14248 /*
14249 ** 2024-02-08
14250 **
14251 ** The author disclaims copyright to this source code.  In place of
14252 ** a legal notice, here is a blessing:
14253 **
14254 **    May you do good and not evil.
14255 **    May you find forgiveness for yourself and forgive others.
14256 **    May you share freely, never taking more than you give.
14257 **
14258 *************************************************************************
14259 */
14260 
14261 /* #include "sqlite3intck.h" */
14262 #include <string.h>
14263 #include <assert.h>
14264 
14265 #include <stdio.h>
14266 #include <stdlib.h>
14267 
14268 /*
14269 ** nKeyVal:
14270 **   The number of values that make up the 'key' for the current pCheck
14271 **   statement.
14272 **
14273 ** rc:
14274 **   Error code returned by most recent sqlite3_intck_step() or
14275 **   sqlite3_intck_unlock() call. This is set to SQLITE_DONE when
14276 **   the integrity-check operation is finished.
14277 **
14278 ** zErr:
14279 **   If the object has entered the error state, this is the error message.
14280 **   Is freed using sqlite3_free() when the object is deleted.
14281 **
14282 ** zTestSql:
14283 **   The value returned by the most recent call to sqlite3_intck_testsql().
14284 **   Each call to testsql() frees the previous zTestSql value (using
14285 **   sqlite3_free()) and replaces it with the new value it will return.
14286 */
14287 struct sqlite3_intck {
14288   sqlite3 *db;
14289   const char *zDb;                /* Copy of zDb parameter to _open() */
14290   char *zObj;                     /* Current object. Or NULL. */
14291 
14292   sqlite3_stmt *pCheck;           /* Current check statement */
14293   char *zKey;
14294   int nKeyVal;
14295 
14296   char *zMessage;
14297   int bCorruptSchema;
14298 
14299   int rc;                         /* Error code */
14300   char *zErr;                     /* Error message */
14301   char *zTestSql;                 /* Returned by sqlite3_intck_test_sql() */
14302 };
14303 
14304 
14305 /*
14306 ** Some error has occurred while using database p->db. Save the error message
14307 ** and error code currently held by the database handle in p->rc and p->zErr.
14308 */
intckSaveErrmsg(sqlite3_intck * p)14309 static void intckSaveErrmsg(sqlite3_intck *p){
14310   p->rc = sqlite3_errcode(p->db);
14311   sqlite3_free(p->zErr);
14312   p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
14313 }
14314 
14315 /*
14316 ** If the handle passed as the first argument is already in the error state,
14317 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
14318 ** error occurs within this function, it leaves an error in said handle.
14319 **
14320 ** Otherwise, this function attempts to prepare SQL statement zSql and
14321 ** return the resulting statement handle to the user.
14322 */
intckPrepare(sqlite3_intck * p,const char * zSql)14323 static sqlite3_stmt *intckPrepare(sqlite3_intck *p, const char *zSql){
14324   sqlite3_stmt *pRet = 0;
14325   if( p->rc==SQLITE_OK ){
14326     p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0);
14327     if( p->rc!=SQLITE_OK ){
14328       intckSaveErrmsg(p);
14329       assert( pRet==0 );
14330     }
14331   }
14332   return pRet;
14333 }
14334 
14335 /*
14336 ** If the handle passed as the first argument is already in the error state,
14337 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
14338 ** error occurs within this function, it leaves an error in said handle.
14339 **
14340 ** Otherwise, this function treats argument zFmt as a printf() style format
14341 ** string. It formats it according to the trailing arguments and then
14342 ** attempts to prepare the results and return the resulting prepared
14343 ** statement.
14344 */
intckPrepareFmt(sqlite3_intck * p,const char * zFmt,...)14345 static sqlite3_stmt *intckPrepareFmt(sqlite3_intck *p, const char *zFmt, ...){
14346   sqlite3_stmt *pRet = 0;
14347   va_list ap;
14348   char *zSql = 0;
14349   va_start(ap, zFmt);
14350   zSql = sqlite3_vmprintf(zFmt, ap);
14351   if( p->rc==SQLITE_OK && zSql==0 ){
14352     p->rc = SQLITE_NOMEM;
14353   }
14354   pRet = intckPrepare(p, zSql);
14355   sqlite3_free(zSql);
14356   va_end(ap);
14357   return pRet;
14358 }
14359 
14360 /*
14361 ** Finalize SQL statement pStmt. If an error occurs and the handle passed
14362 ** as the first argument does not already contain an error, store the
14363 ** error in the handle.
14364 */
intckFinalize(sqlite3_intck * p,sqlite3_stmt * pStmt)14365 static void intckFinalize(sqlite3_intck *p, sqlite3_stmt *pStmt){
14366   int rc = sqlite3_finalize(pStmt);
14367   if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
14368     intckSaveErrmsg(p);
14369   }
14370 }
14371 
14372 /*
14373 ** If there is already an error in handle p, return it. Otherwise, call
14374 ** sqlite3_step() on the statement handle and return that value.
14375 */
intckStep(sqlite3_intck * p,sqlite3_stmt * pStmt)14376 static int intckStep(sqlite3_intck *p, sqlite3_stmt *pStmt){
14377   if( p->rc ) return p->rc;
14378   return sqlite3_step(pStmt);
14379 }
14380 
14381 /*
14382 ** Execute SQL statement zSql. There is no way to obtain any results
14383 ** returned by the statement. This function uses the sqlite3_intck error
14384 ** code convention.
14385 */
intckExec(sqlite3_intck * p,const char * zSql)14386 static void intckExec(sqlite3_intck *p, const char *zSql){
14387   sqlite3_stmt *pStmt = 0;
14388   pStmt = intckPrepare(p, zSql);
14389   intckStep(p, pStmt);
14390   intckFinalize(p, pStmt);
14391 }
14392 
14393 /*
14394 ** A wrapper around sqlite3_mprintf() that uses the sqlite3_intck error
14395 ** code convention.
14396 */
intckMprintf(sqlite3_intck * p,const char * zFmt,...)14397 static char *intckMprintf(sqlite3_intck *p, const char *zFmt, ...){
14398   va_list ap;
14399   char *zRet = 0;
14400   va_start(ap, zFmt);
14401   zRet = sqlite3_vmprintf(zFmt, ap);
14402   if( p->rc==SQLITE_OK ){
14403     if( zRet==0 ){
14404       p->rc = SQLITE_NOMEM;
14405     }
14406   }else{
14407     sqlite3_free(zRet);
14408     zRet = 0;
14409   }
14410   return zRet;
14411 }
14412 
14413 /*
14414 ** This is used by sqlite3_intck_unlock() to save the vector key value
14415 ** required to restart the current pCheck query as a nul-terminated string
14416 ** in p->zKey.
14417 */
intckSaveKey(sqlite3_intck * p)14418 static void intckSaveKey(sqlite3_intck *p){
14419   int ii;
14420   char *zSql = 0;
14421   sqlite3_stmt *pStmt = 0;
14422   sqlite3_stmt *pXinfo = 0;
14423   const char *zDir = 0;
14424 
14425   assert( p->pCheck );
14426   assert( p->zKey==0 );
14427 
14428   pXinfo = intckPrepareFmt(p,
14429       "SELECT group_concat(desc, '') FROM %Q.sqlite_schema s, "
14430       "pragma_index_xinfo(%Q, %Q) "
14431       "WHERE s.type='index' AND s.name=%Q",
14432       p->zDb, p->zObj, p->zDb, p->zObj
14433   );
14434   if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){
14435     zDir = (const char*)sqlite3_column_text(pXinfo, 0);
14436   }
14437 
14438   if( zDir==0 ){
14439     /* Object is a table, not an index. This is the easy case,as there are
14440     ** no DESC columns or NULL values in a primary key.  */
14441     const char *zSep = "SELECT '(' || ";
14442     for(ii=0; ii<p->nKeyVal; ii++){
14443       zSql = intckMprintf(p, "%z%squote(?)", zSql, zSep);
14444       zSep = " || ', ' || ";
14445     }
14446     zSql = intckMprintf(p, "%z || ')'", zSql);
14447   }else{
14448 
14449     /* Object is an index. */
14450     assert( p->nKeyVal>1 );
14451     for(ii=p->nKeyVal; ii>0; ii--){
14452       int bLastIsDesc = zDir[ii-1]=='1';
14453       int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL;
14454       const char *zLast = sqlite3_column_name(p->pCheck, ii);
14455       char *zLhs = 0;
14456       char *zRhs = 0;
14457       char *zWhere = 0;
14458 
14459       if( bLastIsNull ){
14460         if( bLastIsDesc ) continue;
14461         zWhere = intckMprintf(p, "'%s IS NOT NULL'", zLast);
14462       }else{
14463         const char *zOp = bLastIsDesc ? "<" : ">";
14464         zWhere = intckMprintf(p, "'%s %s ' || quote(?%d)", zLast, zOp, ii);
14465       }
14466 
14467       if( ii>1 ){
14468         const char *zLhsSep = "";
14469         const char *zRhsSep = "";
14470         int jj;
14471         for(jj=0; jj<ii-1; jj++){
14472           const char *zAlias = (const char*)sqlite3_column_name(p->pCheck,jj+1);
14473           zLhs = intckMprintf(p, "%z%s%s", zLhs, zLhsSep, zAlias);
14474           zRhs = intckMprintf(p, "%z%squote(?%d)", zRhs, zRhsSep, jj+1);
14475           zLhsSep = ",";
14476           zRhsSep = " || ',' || ";
14477         }
14478 
14479         zWhere = intckMprintf(p,
14480             "'(%z) IS (' || %z || ') AND ' || %z",
14481             zLhs, zRhs, zWhere);
14482       }
14483       zWhere = intckMprintf(p, "'WHERE ' || %z", zWhere);
14484 
14485       zSql = intckMprintf(p, "%z%s(quote( %z ) )",
14486           zSql,
14487           (zSql==0 ? "VALUES" : ",\n      "),
14488           zWhere
14489       );
14490     }
14491     zSql = intckMprintf(p,
14492         "WITH wc(q) AS (\n%z\n)"
14493         "SELECT 'VALUES' || group_concat('(' || q || ')', ',\n      ') FROM wc"
14494         , zSql
14495     );
14496   }
14497 
14498   pStmt = intckPrepare(p, zSql);
14499   if( p->rc==SQLITE_OK ){
14500     for(ii=0; ii<p->nKeyVal; ii++){
14501       sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1));
14502     }
14503     if( SQLITE_ROW==sqlite3_step(pStmt) ){
14504       p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
14505     }
14506     intckFinalize(p, pStmt);
14507   }
14508 
14509   sqlite3_free(zSql);
14510   intckFinalize(p, pXinfo);
14511 }
14512 
14513 /*
14514 ** Find the next database object (table or index) to check. If successful,
14515 ** set sqlite3_intck.zObj to point to a nul-terminated buffer containing
14516 ** the object's name before returning.
14517 */
intckFindObject(sqlite3_intck * p)14518 static void intckFindObject(sqlite3_intck *p){
14519   sqlite3_stmt *pStmt = 0;
14520   char *zPrev = p->zObj;
14521   p->zObj = 0;
14522 
14523   assert( p->rc==SQLITE_OK );
14524   assert( p->pCheck==0 );
14525 
14526   pStmt = intckPrepareFmt(p,
14527     "WITH tables(table_name) AS ("
14528     "  SELECT name"
14529     "  FROM %Q.sqlite_schema WHERE (type='table' OR type='index') AND rootpage"
14530     "  UNION ALL "
14531     "  SELECT 'sqlite_schema'"
14532     ")"
14533     "SELECT table_name FROM tables "
14534     "WHERE ?1 IS NULL OR table_name%s?1 "
14535     "ORDER BY 1"
14536     , p->zDb, (p->zKey ? ">=" : ">")
14537   );
14538 
14539   if( p->rc==SQLITE_OK ){
14540     sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT);
14541     if( sqlite3_step(pStmt)==SQLITE_ROW ){
14542       p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
14543     }
14544   }
14545   intckFinalize(p, pStmt);
14546 
14547   /* If this is a new object, ensure the previous key value is cleared. */
14548   if( sqlite3_stricmp(p->zObj, zPrev) ){
14549     sqlite3_free(p->zKey);
14550     p->zKey = 0;
14551   }
14552 
14553   sqlite3_free(zPrev);
14554 }
14555 
14556 /*
14557 ** Return the size in bytes of the first token in nul-terminated buffer z.
14558 ** For the purposes of this call, a token is either:
14559 **
14560 **   *  a quoted SQL string,
14561 *    *  a contiguous series of ascii alphabet characters, or
14562 *    *  any other single byte.
14563 */
intckGetToken(const char * z)14564 static int intckGetToken(const char *z){
14565   char c = z[0];
14566   int iRet = 1;
14567   if( c=='\'' || c=='"' || c=='`' ){
14568     while( 1 ){
14569       if( z[iRet]==c ){
14570         iRet++;
14571         if( z[iRet]!=c ) break;
14572       }
14573       iRet++;
14574     }
14575   }
14576   else if( c=='[' ){
14577     while( z[iRet++]!=']' && z[iRet] );
14578   }
14579   else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
14580     while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){
14581       iRet++;
14582     }
14583   }
14584 
14585   return iRet;
14586 }
14587 
14588 /*
14589 ** Return true if argument c is an ascii whitespace character.
14590 */
intckIsSpace(char c)14591 static int intckIsSpace(char c){
14592   return (c==' ' || c=='\t' || c=='\n' || c=='\r');
14593 }
14594 
14595 /*
14596 ** Argument z points to the text of a CREATE INDEX statement. This function
14597 ** identifies the part of the text that contains either the index WHERE
14598 ** clause (if iCol<0) or the iCol'th column of the index.
14599 **
14600 ** If (iCol<0), the identified fragment does not include the "WHERE" keyword,
14601 ** only the expression that follows it. If (iCol>=0) then the identified
14602 ** fragment does not include any trailing sort-order keywords - "ASC" or
14603 ** "DESC".
14604 **
14605 ** If the CREATE INDEX statement does not contain the requested field or
14606 ** clause, NULL is returned and (*pnByte) is set to 0. Otherwise, a pointer to
14607 ** the identified fragment is returned and output parameter (*pnByte) set
14608 ** to its size in bytes.
14609 */
intckParseCreateIndex(const char * z,int iCol,int * pnByte)14610 static const char *intckParseCreateIndex(const char *z, int iCol, int *pnByte){
14611   int iOff = 0;
14612   int iThisCol = 0;
14613   int iStart = 0;
14614   int nOpen = 0;
14615 
14616   const char *zRet = 0;
14617   int nRet = 0;
14618 
14619   int iEndOfCol = 0;
14620 
14621   /* Skip forward until the first "(" token */
14622   while( z[iOff]!='(' ){
14623     iOff += intckGetToken(&z[iOff]);
14624     if( z[iOff]=='\0' ) return 0;
14625   }
14626   assert( z[iOff]=='(' );
14627 
14628   nOpen = 1;
14629   iOff++;
14630   iStart = iOff;
14631   while( z[iOff] ){
14632     const char *zToken = &z[iOff];
14633     int nToken = 0;
14634 
14635     /* Check if this is the end of the current column - either a "," or ")"
14636     ** when nOpen==1.  */
14637     if( nOpen==1 ){
14638       if( z[iOff]==',' || z[iOff]==')' ){
14639         if( iCol==iThisCol ){
14640           int iEnd = iEndOfCol ? iEndOfCol : iOff;
14641           nRet = (iEnd - iStart);
14642           zRet = &z[iStart];
14643           break;
14644         }
14645         iStart = iOff+1;
14646         while( intckIsSpace(z[iStart]) ) iStart++;
14647         iThisCol++;
14648       }
14649       if( z[iOff]==')' ) break;
14650     }
14651     if( z[iOff]=='(' ) nOpen++;
14652     if( z[iOff]==')' ) nOpen--;
14653     nToken = intckGetToken(zToken);
14654 
14655     if( (nToken==3 && 0==sqlite3_strnicmp(zToken, "ASC", nToken))
14656      || (nToken==4 && 0==sqlite3_strnicmp(zToken, "DESC", nToken))
14657     ){
14658       iEndOfCol = iOff;
14659     }else if( 0==intckIsSpace(zToken[0]) ){
14660       iEndOfCol = 0;
14661     }
14662 
14663     iOff += nToken;
14664   }
14665 
14666   /* iStart is now the byte offset of 1 byte passed the final ')' in the
14667   ** CREATE INDEX statement. Try to find a WHERE clause to return.  */
14668   while( zRet==0 && z[iOff] ){
14669     int n = intckGetToken(&z[iOff]);
14670     if( n==5 && 0==sqlite3_strnicmp(&z[iOff], "where", 5) ){
14671       zRet = &z[iOff+5];
14672       nRet = (int)strlen(zRet);
14673     }
14674     iOff += n;
14675   }
14676 
14677   /* Trim any whitespace from the start and end of the returned string. */
14678   if( zRet ){
14679     while( intckIsSpace(zRet[0]) ){
14680       nRet--;
14681       zRet++;
14682     }
14683     while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--;
14684   }
14685 
14686   *pnByte = nRet;
14687   return zRet;
14688 }
14689 
14690 /*
14691 ** User-defined SQL function wrapper for intckParseCreateIndex():
14692 **
14693 **     SELECT parse_create_index(<sql>, <icol>);
14694 */
intckParseCreateIndexFunc(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)14695 static void intckParseCreateIndexFunc(
14696   sqlite3_context *pCtx,
14697   int nVal,
14698   sqlite3_value **apVal
14699 ){
14700   const char *zSql = (const char*)sqlite3_value_text(apVal[0]);
14701   int idx = sqlite3_value_int(apVal[1]);
14702   const char *zRes = 0;
14703   int nRes = 0;
14704 
14705   assert( nVal==2 );
14706   if( zSql ){
14707     zRes = intckParseCreateIndex(zSql, idx, &nRes);
14708   }
14709   sqlite3_result_text(pCtx, zRes, nRes, SQLITE_TRANSIENT);
14710 }
14711 
14712 /*
14713 ** Return true if sqlite3_intck.db has automatic indexes enabled, false
14714 ** otherwise.
14715 */
intckGetAutoIndex(sqlite3_intck * p)14716 static int intckGetAutoIndex(sqlite3_intck *p){
14717   int bRet = 0;
14718   sqlite3_stmt *pStmt = 0;
14719   pStmt = intckPrepare(p, "PRAGMA automatic_index");
14720   if( SQLITE_ROW==intckStep(p, pStmt) ){
14721     bRet = sqlite3_column_int(pStmt, 0);
14722   }
14723   intckFinalize(p, pStmt);
14724   return bRet;
14725 }
14726 
14727 /*
14728 ** Return true if zObj is an index, or false otherwise.
14729 */
intckIsIndex(sqlite3_intck * p,const char * zObj)14730 static int intckIsIndex(sqlite3_intck *p, const char *zObj){
14731   int bRet = 0;
14732   sqlite3_stmt *pStmt = 0;
14733   pStmt = intckPrepareFmt(p,
14734       "SELECT 1 FROM %Q.sqlite_schema WHERE name=%Q AND type='index'",
14735       p->zDb, zObj
14736   );
14737   if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
14738     bRet = 1;
14739   }
14740   intckFinalize(p, pStmt);
14741   return bRet;
14742 }
14743 
14744 /*
14745 ** Return a pointer to a nul-terminated buffer containing the SQL statement
14746 ** used to check database object zObj (a table or index) for corruption.
14747 ** If parameter zPrev is not NULL, then it must be a string containing the
14748 ** vector key required to restart the check where it left off last time.
14749 ** If pnKeyVal is not NULL, then (*pnKeyVal) is set to the number of
14750 ** columns in the vector key value for the specified object.
14751 **
14752 ** This function uses the sqlite3_intck error code convention.
14753 */
intckCheckObjectSql(sqlite3_intck * p,const char * zObj,const char * zPrev,int * pnKeyVal)14754 static char *intckCheckObjectSql(
14755   sqlite3_intck *p,               /* Integrity check object */
14756   const char *zObj,               /* Object (table or index) to scan */
14757   const char *zPrev,              /* Restart key vector, if any */
14758   int *pnKeyVal                   /* OUT: Number of key-values for this scan */
14759 ){
14760   char *zRet = 0;
14761   sqlite3_stmt *pStmt = 0;
14762   int bAutoIndex = 0;
14763   int bIsIndex = 0;
14764 
14765   const char *zCommon =
14766       /* Relation without_rowid also contains just one row. Column "b" is
14767       ** set to true if the table being examined is a WITHOUT ROWID table,
14768       ** or false otherwise.  */
14769       ", without_rowid(b) AS ("
14770       "  SELECT EXISTS ("
14771       "    SELECT 1 FROM tabname, pragma_index_list(tab, db) AS l"
14772       "      WHERE origin='pk' "
14773       "      AND NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name=l.name)"
14774       "  )"
14775       ")"
14776       ""
14777       /* Table idx_cols contains 1 row for each column in each index on the
14778       ** table being checked. Columns are:
14779       **
14780       **   idx_name: Name of the index.
14781       **   idx_ispk: True if this index is the PK of a WITHOUT ROWID table.
14782       **   col_name: Name of indexed column, or NULL for index on expression.
14783       **   col_expr: Indexed expression, including COLLATE clause.
14784       **   col_alias: Alias used for column in 'intck_wrapper' table.
14785       */
14786       ", idx_cols(idx_name, idx_ispk, col_name, col_expr, col_alias) AS ("
14787       "  SELECT l.name, (l.origin=='pk' AND w.b), i.name, COALESCE(("
14788       "    SELECT parse_create_index(sql, i.seqno) FROM "
14789       "    sqlite_schema WHERE name = l.name"
14790       "  ), format('\"%w\"', i.name) || ' COLLATE ' || quote(i.coll)),"
14791       "  'c' || row_number() OVER ()"
14792       "  FROM "
14793       "      tabname t,"
14794       "      without_rowid w,"
14795       "      pragma_index_list(t.tab, t.db) l,"
14796       "      pragma_index_xinfo(l.name) i"
14797       "      WHERE i.key"
14798       "  UNION ALL"
14799       "  SELECT '', 1, '_rowid_', '_rowid_', 'r1' FROM without_rowid WHERE b=0"
14800       ")"
14801       ""
14802       ""
14803       /*
14804       ** For a PK declared as "PRIMARY KEY(a, b) ... WITHOUT ROWID", where
14805       ** the intck_wrapper aliases of "a" and "b" are "c1" and "c2":
14806       **
14807       **   o_pk:   "o.c1, o.c2"
14808       **   i_pk:   "i.'a', i.'b'"
14809       **   ...
14810       **   n_pk:   2
14811       */
14812       ", tabpk(db, tab, idx, o_pk, i_pk, q_pk, eq_pk, ps_pk, pk_pk, n_pk) AS ("
14813       "    WITH pkfields(f, a) AS ("
14814       "      SELECT i.col_name, i.col_alias FROM idx_cols i WHERE i.idx_ispk"
14815       "    )"
14816       "    SELECT t.db, t.tab, t.idx, "
14817       "           group_concat(a, ', '), "
14818       "           group_concat('i.'||quote(f), ', '), "
14819       "           group_concat('quote(o.'||a||')', ' || '','' || '),  "
14820       "           format('(%s)==(%s)',"
14821       "               group_concat('o.'||a, ', '), "
14822       "               group_concat(format('\"%w\"', f), ', ')"
14823       "           ),"
14824       "           group_concat('%s', ','),"
14825       "           group_concat('quote('||a||')', ', '),  "
14826       "           count(*)"
14827       "    FROM tabname t, pkfields"
14828       ")"
14829       ""
14830       ", idx(name, match_expr, partial, partial_alias, idx_ps, idx_idx) AS ("
14831       "  SELECT idx_name,"
14832       "    format('(%s,%s) IS (%s,%s)', "
14833       "           group_concat(i.col_expr, ', '), i_pk,"
14834       "           group_concat('o.'||i.col_alias, ', '), o_pk"
14835       "    ), "
14836       "    parse_create_index("
14837       "        (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1"
14838       "    ),"
14839       "    'cond' || row_number() OVER ()"
14840       "    , group_concat('%s', ',')"
14841       "    , group_concat('quote('||i.col_alias||')', ', ')"
14842       "  FROM tabpk t, "
14843       "       without_rowid w,"
14844       "       idx_cols i"
14845       "  WHERE i.idx_ispk==0 "
14846       "  GROUP BY idx_name"
14847       ")"
14848       ""
14849       ", wrapper_with(s) AS ("
14850       "  SELECT 'intck_wrapper AS (\n  SELECT\n    ' || ("
14851       "      WITH f(a, b) AS ("
14852       "        SELECT col_expr, col_alias FROM idx_cols"
14853       "          UNION ALL "
14854       "        SELECT partial, partial_alias FROM idx WHERE partial IS NOT NULL"
14855       "      )"
14856       "      SELECT group_concat(format('%s AS %s', a, b), ',\n    ') FROM f"
14857       "    )"
14858       "    || format('\n  FROM %Q.%Q ', t.db, t.tab)"
14859            /* If the object being checked is a table, append "NOT INDEXED".
14860            ** Otherwise, append "INDEXED BY <index>", and then, if the index
14861            ** is a partial index " WHERE <condition>".  */
14862       "    || CASE WHEN t.idx IS NULL THEN "
14863       "        'NOT INDEXED'"
14864       "       ELSE"
14865       "        format('INDEXED BY %Q%s', t.idx, ' WHERE '||i.partial)"
14866       "       END"
14867       "    || '\n)'"
14868       "    FROM tabname t LEFT JOIN idx i ON (i.name=t.idx)"
14869       ")"
14870       ""
14871   ;
14872 
14873   bAutoIndex = intckGetAutoIndex(p);
14874   if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 0");
14875 
14876   bIsIndex = intckIsIndex(p, zObj);
14877   if( bIsIndex ){
14878     pStmt = intckPrepareFmt(p,
14879       /* Table idxname contains a single row. The first column, "db", contains
14880       ** the name of the db containing the table (e.g. "main") and the second,
14881       ** "tab", the name of the table itself.  */
14882       "WITH tabname(db, tab, idx) AS ("
14883       "  SELECT %Q, (SELECT tbl_name FROM %Q.sqlite_schema WHERE name=%Q), %Q "
14884       ")"
14885       ""
14886       ", whereclause(w_c) AS (%s)"
14887       ""
14888       "%s" /* zCommon */
14889       ""
14890       ", case_statement(c) AS ("
14891       "  SELECT "
14892       "    'CASE WHEN (' || group_concat(col_alias, ', ') || ', 1) IS (\n' "
14893       "    || '      SELECT ' || group_concat(col_expr, ', ') || ', 1 FROM '"
14894       "    || format('%%Q.%%Q NOT INDEXED WHERE %%s\n', t.db, t.tab, p.eq_pk)"
14895       "    || '    )\n  THEN NULL\n    '"
14896       "    || 'ELSE format(''surplus entry ('"
14897       "    ||   group_concat('%%s', ',') || ',' || p.ps_pk"
14898       "    || ') in index ' || t.idx || ''', ' "
14899       "    ||   group_concat('quote('||i.col_alias||')', ', ') || ', ' || p.pk_pk"
14900       "    || ')'"
14901       "    || '\n  END AS error_message'"
14902       "  FROM tabname t, tabpk p, idx_cols i WHERE i.idx_name=t.idx"
14903       ")"
14904       ""
14905       ", thiskey(k, n) AS ("
14906       "    SELECT group_concat(i.col_alias, ', ') || ', ' || p.o_pk, "
14907       "           count(*) + p.n_pk "
14908       "    FROM tabpk p, idx_cols i WHERE i.idx_name=p.idx"
14909       ")"
14910       ""
14911       ", main_select(m, n) AS ("
14912       "  SELECT format("
14913       "      'WITH %%s\n' ||"
14914       "      ', idx_checker AS (\n' ||"
14915       "      '  SELECT %%s,\n' ||"
14916       "      '  %%s\n' || "
14917       "      '  FROM intck_wrapper AS o\n' ||"
14918       "      ')\n',"
14919       "      ww.s, c, t.k"
14920       "  ), t.n"
14921       "  FROM case_statement, wrapper_with ww, thiskey t"
14922       ")"
14923 
14924       "SELECT m || "
14925       "    group_concat('SELECT * FROM idx_checker ' || w_c, ' UNION ALL '), n"
14926       " FROM "
14927       "main_select, whereclause "
14928       , p->zDb, p->zDb, zObj, zObj
14929       , zPrev ? zPrev : "VALUES('')", zCommon
14930       );
14931   }else{
14932     pStmt = intckPrepareFmt(p,
14933       /* Table tabname contains a single row. The first column, "db", contains
14934       ** the name of the db containing the table (e.g. "main") and the second,
14935       ** "tab", the name of the table itself.  */
14936       "WITH tabname(db, tab, idx, prev) AS (SELECT %Q, %Q, NULL, %Q)"
14937       ""
14938       "%s" /* zCommon */
14939 
14940       /* expr(e) contains one row for each index on table zObj. Value e
14941       ** is set to an expression that evaluates to NULL if the required
14942       ** entry is present in the index, or an error message otherwise.  */
14943       ", expr(e, p) AS ("
14944       "  SELECT format('CASE WHEN EXISTS \n"
14945       "    (SELECT 1 FROM %%Q.%%Q AS i INDEXED BY %%Q WHERE %%s%%s)\n"
14946       "    THEN NULL\n"
14947       "    ELSE format(''entry (%%s,%%s) missing from index %%s'', %%s, %%s)\n"
14948       "  END\n'"
14949       "    , t.db, t.tab, i.name, i.match_expr, ' AND (' || partial || ')',"
14950       "      i.idx_ps, t.ps_pk, i.name, i.idx_idx, t.pk_pk),"
14951       "    CASE WHEN partial IS NULL THEN NULL ELSE i.partial_alias END"
14952       "  FROM tabpk t, idx i"
14953       ")"
14954 
14955       ", numbered(ii, cond, e) AS ("
14956       "  SELECT 0, 'n.ii=0', 'NULL'"
14957       "    UNION ALL "
14958       "  SELECT row_number() OVER (),"
14959       "      '(n.ii='||row_number() OVER ()||COALESCE(' AND '||p||')', ')'), e"
14960       "  FROM expr"
14961       ")"
14962 
14963       ", counter_with(w) AS ("
14964       "    SELECT 'WITH intck_counter(ii) AS (\n  ' || "
14965       "       group_concat('SELECT '||ii, ' UNION ALL\n  ') "
14966       "    || '\n)' FROM numbered"
14967       ")"
14968       ""
14969       ", case_statement(c) AS ("
14970       "    SELECT 'CASE ' || "
14971       "    group_concat(format('\n  WHEN %%s THEN (%%s)', cond, e), '') ||"
14972       "    '\nEND AS error_message'"
14973       "    FROM numbered"
14974       ")"
14975       ""
14976 
14977       /* This table contains a single row consisting of a single value -
14978       ** the text of an SQL expression that may be used by the main SQL
14979       ** statement to output an SQL literal that can be used to resume
14980       ** the scan if it is suspended. e.g. for a rowid table, an expression
14981       ** like:
14982       **
14983       **     format('(%d,%d)', _rowid_, n.ii)
14984       */
14985       ", thiskey(k, n) AS ("
14986       "    SELECT o_pk || ', ii', n_pk+1 FROM tabpk"
14987       ")"
14988       ""
14989       ", whereclause(w_c) AS ("
14990       "    SELECT CASE WHEN prev!='' THEN "
14991       "    '\nWHERE (' || o_pk ||', n.ii) > ' || prev"
14992       "    ELSE ''"
14993       "    END"
14994       "    FROM tabpk, tabname"
14995       ")"
14996       ""
14997       ", main_select(m, n) AS ("
14998       "  SELECT format("
14999       "      '%%s, %%s\nSELECT %%s,\n%%s\nFROM intck_wrapper AS o"
15000                ", intck_counter AS n%%s\nORDER BY %%s', "
15001       "      w, ww.s, c, thiskey.k, whereclause.w_c, t.o_pk"
15002       "  ), thiskey.n"
15003       "  FROM case_statement, tabpk t, counter_with, "
15004       "       wrapper_with ww, thiskey, whereclause"
15005       ")"
15006 
15007       "SELECT m, n FROM main_select",
15008       p->zDb, zObj, zPrev, zCommon
15009     );
15010   }
15011 
15012   while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15013     zRet = intckMprintf(p, "%s", (const char*)sqlite3_column_text(pStmt, 0));
15014     if( pnKeyVal ){
15015       *pnKeyVal = sqlite3_column_int(pStmt, 1);
15016     }
15017   }
15018   intckFinalize(p, pStmt);
15019 
15020   if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1");
15021   return zRet;
15022 }
15023 
15024 /*
15025 ** Open a new integrity-check object.
15026 */
sqlite3_intck_open(sqlite3 * db,const char * zDbArg,sqlite3_intck ** ppOut)15027 int sqlite3_intck_open(
15028   sqlite3 *db,                    /* Database handle to operate on */
15029   const char *zDbArg,             /* "main", "temp" etc. */
15030   sqlite3_intck **ppOut           /* OUT: New integrity-check handle */
15031 ){
15032   sqlite3_intck *pNew = 0;
15033   int rc = SQLITE_OK;
15034   const char *zDb = zDbArg ? zDbArg : "main";
15035   int nDb = (int)strlen(zDb);
15036 
15037   pNew = (sqlite3_intck*)sqlite3_malloc(sizeof(*pNew) + nDb + 1);
15038   if( pNew==0 ){
15039     rc = SQLITE_NOMEM;
15040   }else{
15041     memset(pNew, 0, sizeof(*pNew));
15042     pNew->db = db;
15043     pNew->zDb = (const char*)&pNew[1];
15044     memcpy(&pNew[1], zDb, nDb+1);
15045     rc = sqlite3_create_function(db, "parse_create_index",
15046         2, SQLITE_UTF8, 0, intckParseCreateIndexFunc, 0, 0
15047     );
15048     if( rc!=SQLITE_OK ){
15049       sqlite3_intck_close(pNew);
15050       pNew = 0;
15051     }
15052   }
15053 
15054   *ppOut = pNew;
15055   return rc;
15056 }
15057 
15058 /*
15059 ** Free the integrity-check object.
15060 */
sqlite3_intck_close(sqlite3_intck * p)15061 void sqlite3_intck_close(sqlite3_intck *p){
15062   if( p ){
15063     sqlite3_finalize(p->pCheck);
15064     sqlite3_create_function(
15065         p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0
15066     );
15067     sqlite3_free(p->zObj);
15068     sqlite3_free(p->zKey);
15069     sqlite3_free(p->zTestSql);
15070     sqlite3_free(p->zErr);
15071     sqlite3_free(p->zMessage);
15072     sqlite3_free(p);
15073   }
15074 }
15075 
15076 /*
15077 ** Step the integrity-check object.
15078 */
sqlite3_intck_step(sqlite3_intck * p)15079 int sqlite3_intck_step(sqlite3_intck *p){
15080   if( p->rc==SQLITE_OK ){
15081 
15082     if( p->zMessage ){
15083       sqlite3_free(p->zMessage);
15084       p->zMessage = 0;
15085     }
15086 
15087     if( p->bCorruptSchema ){
15088       p->rc = SQLITE_DONE;
15089     }else
15090     if( p->pCheck==0 ){
15091       intckFindObject(p);
15092       if( p->rc==SQLITE_OK ){
15093         if( p->zObj ){
15094           char *zSql = 0;
15095           zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal);
15096           p->pCheck = intckPrepare(p, zSql);
15097           sqlite3_free(zSql);
15098           sqlite3_free(p->zKey);
15099           p->zKey = 0;
15100         }else{
15101           p->rc = SQLITE_DONE;
15102         }
15103       }else if( p->rc==SQLITE_CORRUPT ){
15104         p->rc = SQLITE_OK;
15105         p->zMessage = intckMprintf(p, "%s",
15106             "corruption found while reading database schema"
15107         );
15108         p->bCorruptSchema = 1;
15109       }
15110     }
15111 
15112     if( p->pCheck ){
15113       assert( p->rc==SQLITE_OK );
15114       if( sqlite3_step(p->pCheck)==SQLITE_ROW ){
15115         /* Normal case, do nothing. */
15116       }else{
15117         intckFinalize(p, p->pCheck);
15118         p->pCheck = 0;
15119         p->nKeyVal = 0;
15120         if( p->rc==SQLITE_CORRUPT ){
15121           p->rc = SQLITE_OK;
15122           p->zMessage = intckMprintf(p,
15123               "corruption found while scanning database object %s", p->zObj
15124           );
15125         }
15126       }
15127     }
15128   }
15129 
15130   return p->rc;
15131 }
15132 
15133 /*
15134 ** Return a message describing the corruption encountered by the most recent
15135 ** call to sqlite3_intck_step(), or NULL if no corruption was encountered.
15136 */
sqlite3_intck_message(sqlite3_intck * p)15137 const char *sqlite3_intck_message(sqlite3_intck *p){
15138   assert( p->pCheck==0 || p->zMessage==0 );
15139   if( p->zMessage ){
15140     return p->zMessage;
15141   }
15142   if( p->pCheck ){
15143     return (const char*)sqlite3_column_text(p->pCheck, 0);
15144   }
15145   return 0;
15146 }
15147 
15148 /*
15149 ** Return the error code and message.
15150 */
sqlite3_intck_error(sqlite3_intck * p,const char ** pzErr)15151 int sqlite3_intck_error(sqlite3_intck *p, const char **pzErr){
15152   if( pzErr ) *pzErr = p->zErr;
15153   return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc);
15154 }
15155 
15156 /*
15157 ** Close any read transaction the integrity-check object is holding open
15158 ** on the database.
15159 */
sqlite3_intck_unlock(sqlite3_intck * p)15160 int sqlite3_intck_unlock(sqlite3_intck *p){
15161   if( p->rc==SQLITE_OK && p->pCheck ){
15162     assert( p->zKey==0 && p->nKeyVal>0 );
15163     intckSaveKey(p);
15164     intckFinalize(p, p->pCheck);
15165     p->pCheck = 0;
15166   }
15167   return p->rc;
15168 }
15169 
15170 /*
15171 ** Return the SQL statement used to check object zObj. Or, if zObj is
15172 ** NULL, the current SQL statement.
15173 */
sqlite3_intck_test_sql(sqlite3_intck * p,const char * zObj)15174 const char *sqlite3_intck_test_sql(sqlite3_intck *p, const char *zObj){
15175   sqlite3_free(p->zTestSql);
15176   if( zObj ){
15177     p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0);
15178   }else{
15179     if( p->zObj ){
15180       p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0);
15181     }else{
15182       sqlite3_free(p->zTestSql);
15183       p->zTestSql = 0;
15184     }
15185   }
15186   return p->zTestSql;
15187 }
15188 
15189 /************************* End ../ext/intck/sqlite3intck.c ********************/
15190 
15191 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15192 #define SQLITE_SHELL_HAVE_RECOVER 1
15193 #else
15194 #define SQLITE_SHELL_HAVE_RECOVER 0
15195 #endif
15196 #if SQLITE_SHELL_HAVE_RECOVER
15197 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
15198 /*
15199 ** 2022-08-27
15200 **
15201 ** The author disclaims copyright to this source code.  In place of
15202 ** a legal notice, here is a blessing:
15203 **
15204 **    May you do good and not evil.
15205 **    May you find forgiveness for yourself and forgive others.
15206 **    May you share freely, never taking more than you give.
15207 **
15208 *************************************************************************
15209 **
15210 ** This file contains the public interface to the "recover" extension -
15211 ** an SQLite extension designed to recover data from corrupted database
15212 ** files.
15213 */
15214 
15215 /*
15216 ** OVERVIEW:
15217 **
15218 ** To use the API to recover data from a corrupted database, an
15219 ** application:
15220 **
15221 **   1) Creates an sqlite3_recover handle by calling either
15222 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
15223 **
15224 **   2) Configures the new handle using one or more calls to
15225 **      sqlite3_recover_config().
15226 **
15227 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
15228 **      the handle until it returns something other than SQLITE_OK. If it
15229 **      returns SQLITE_DONE, then the recovery operation completed without
15230 **      error. If it returns some other non-SQLITE_OK value, then an error
15231 **      has occurred.
15232 **
15233 **   4) Retrieves any error code and English language error message using the
15234 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
15235 **      respectively.
15236 **
15237 **   5) Destroys the sqlite3_recover handle and frees all resources
15238 **      using sqlite3_recover_finish().
15239 **
15240 ** The application may abandon the recovery operation at any point
15241 ** before it is finished by passing the sqlite3_recover handle to
15242 ** sqlite3_recover_finish(). This is not an error, but the final state
15243 ** of the output database, or the results of running the partial script
15244 ** delivered to the SQL callback, are undefined.
15245 */
15246 
15247 #ifndef _SQLITE_RECOVER_H
15248 #define _SQLITE_RECOVER_H
15249 
15250 /* #include "sqlite3.h" */
15251 
15252 #ifdef __cplusplus
15253 extern "C" {
15254 #endif
15255 
15256 /*
15257 ** An instance of the sqlite3_recover object represents a recovery
15258 ** operation in progress.
15259 **
15260 ** Constructors:
15261 **
15262 **    sqlite3_recover_init()
15263 **    sqlite3_recover_init_sql()
15264 **
15265 ** Destructor:
15266 **
15267 **    sqlite3_recover_finish()
15268 **
15269 ** Methods:
15270 **
15271 **    sqlite3_recover_config()
15272 **    sqlite3_recover_errcode()
15273 **    sqlite3_recover_errmsg()
15274 **    sqlite3_recover_run()
15275 **    sqlite3_recover_step()
15276 */
15277 typedef struct sqlite3_recover sqlite3_recover;
15278 
15279 /*
15280 ** These two APIs attempt to create and return a new sqlite3_recover object.
15281 ** In both cases the first two arguments identify the (possibly
15282 ** corrupt) database to recover data from. The first argument is an open
15283 ** database handle and the second the name of a database attached to that
15284 ** handle (i.e. "main", "temp" or the name of an attached database).
15285 **
15286 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
15287 ** handle, then data is recovered into a new database, identified by
15288 ** string parameter zUri. zUri may be an absolute or relative file path,
15289 ** or may be an SQLite URI. If the identified database file already exists,
15290 ** it is overwritten.
15291 **
15292 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
15293 ** be returned to the user as a series of SQL statements. Executing these
15294 ** SQL statements results in the same database as would have been created
15295 ** had sqlite3_recover_init() been used. For each SQL statement in the
15296 ** output, the callback function passed as the third argument (xSql) is
15297 ** invoked once. The first parameter is a passed a copy of the fourth argument
15298 ** to this function (pCtx) as its first parameter, and a pointer to a
15299 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
15300 ** the second. If the xSql callback returns any value other than SQLITE_OK,
15301 ** then processing is immediately abandoned and the value returned used as
15302 ** the recover handle error code (see below).
15303 **
15304 ** If an out-of-memory error occurs, NULL may be returned instead of
15305 ** a valid handle. In all other cases, it is the responsibility of the
15306 ** application to avoid resource leaks by ensuring that
15307 ** sqlite3_recover_finish() is called on all allocated handles.
15308 */
15309 sqlite3_recover *sqlite3_recover_init(
15310   sqlite3* db,
15311   const char *zDb,
15312   const char *zUri
15313 );
15314 sqlite3_recover *sqlite3_recover_init_sql(
15315   sqlite3* db,
15316   const char *zDb,
15317   int (*xSql)(void*, const char*),
15318   void *pCtx
15319 );
15320 
15321 /*
15322 ** Configure an sqlite3_recover object that has just been created using
15323 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
15324 ** may only be called before the first call to sqlite3_recover_step()
15325 ** or sqlite3_recover_run() on the object.
15326 **
15327 ** The second argument passed to this function must be one of the
15328 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
15329 ** depend on the specific SQLITE_RECOVER_* symbol in use.
15330 **
15331 ** SQLITE_OK is returned if the configuration operation was successful,
15332 ** or an SQLite error code otherwise.
15333 */
15334 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
15335 
15336 /*
15337 ** SQLITE_RECOVER_LOST_AND_FOUND:
15338 **   The pArg argument points to a string buffer containing the name
15339 **   of a "lost-and-found" table in the output database, or NULL. If
15340 **   the argument is non-NULL and the database contains seemingly
15341 **   valid pages that cannot be associated with any table in the
15342 **   recovered part of the schema, data is extracted from these
15343 **   pages to add to the lost-and-found table.
15344 **
15345 ** SQLITE_RECOVER_FREELIST_CORRUPT:
15346 **   The pArg value must actually be a pointer to a value of type
15347 **   int containing value 0 or 1 cast as a (void*). If this option is set
15348 **   (argument is 1) and a lost-and-found table has been configured using
15349 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
15350 **   corrupt and an attempt is made to recover records from pages that
15351 **   appear to be linked into the freelist. Otherwise, pages on the freelist
15352 **   are ignored. Setting this option can recover more data from the
15353 **   database, but often ends up "recovering" deleted records. The default
15354 **   value is 0 (clear).
15355 **
15356 ** SQLITE_RECOVER_ROWIDS:
15357 **   The pArg value must actually be a pointer to a value of type
15358 **   int containing value 0 or 1 cast as a (void*). If this option is set
15359 **   (argument is 1), then an attempt is made to recover rowid values
15360 **   that are not also INTEGER PRIMARY KEY values. If this option is
15361 **   clear, then new rowids are assigned to all recovered rows. The
15362 **   default value is 1 (set).
15363 **
15364 ** SQLITE_RECOVER_SLOWINDEXES:
15365 **   The pArg value must actually be a pointer to a value of type
15366 **   int containing value 0 or 1 cast as a (void*). If this option is clear
15367 **   (argument is 0), then when creating an output database, the recover
15368 **   module creates and populates non-UNIQUE indexes right at the end of the
15369 **   recovery operation - after all recoverable data has been inserted
15370 **   into the new database. This is faster overall, but means that the
15371 **   final call to sqlite3_recover_step() for a recovery operation may
15372 **   be need to create a large number of indexes, which may be very slow.
15373 **
15374 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
15375 **   are created in the output database before it is populated with
15376 **   recovered data. This is slower overall, but avoids the slow call
15377 **   to sqlite3_recover_step() at the end of the recovery operation.
15378 **
15379 **   The default option value is 0.
15380 */
15381 #define SQLITE_RECOVER_LOST_AND_FOUND   1
15382 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
15383 #define SQLITE_RECOVER_ROWIDS           3
15384 #define SQLITE_RECOVER_SLOWINDEXES      4
15385 
15386 /*
15387 ** Perform a unit of work towards the recovery operation. This function
15388 ** must normally be called multiple times to complete database recovery.
15389 **
15390 ** If no error occurs but the recovery operation is not completed, this
15391 ** function returns SQLITE_OK. If recovery has been completed successfully
15392 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
15393 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
15394 ** considered an error if some or all of the data cannot be recovered
15395 ** due to database corruption.
15396 **
15397 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
15398 ** all further such calls on the same recover handle are no-ops that return
15399 ** the same non-SQLITE_OK value.
15400 */
15401 int sqlite3_recover_step(sqlite3_recover*);
15402 
15403 /*
15404 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
15405 ** or an SQLite error code otherwise. Calling this function is the same
15406 ** as executing:
15407 **
15408 **     while( SQLITE_OK==sqlite3_recover_step(p) );
15409 **     return sqlite3_recover_errcode(p);
15410 */
15411 int sqlite3_recover_run(sqlite3_recover*);
15412 
15413 /*
15414 ** If an error has been encountered during a prior call to
15415 ** sqlite3_recover_step(), then this function attempts to return a
15416 ** pointer to a buffer containing an English language explanation of
15417 ** the error. If no error message is available, or if an out-of memory
15418 ** error occurs while attempting to allocate a buffer in which to format
15419 ** the error message, NULL is returned.
15420 **
15421 ** The returned buffer remains valid until the sqlite3_recover handle is
15422 ** destroyed using sqlite3_recover_finish().
15423 */
15424 const char *sqlite3_recover_errmsg(sqlite3_recover*);
15425 
15426 /*
15427 ** If this function is called on an sqlite3_recover handle after
15428 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
15429 */
15430 int sqlite3_recover_errcode(sqlite3_recover*);
15431 
15432 /*
15433 ** Clean up a recovery object created by a call to sqlite3_recover_init().
15434 ** The results of using a recovery object with any API after it has been
15435 ** passed to this function are undefined.
15436 **
15437 ** This function returns the same value as sqlite3_recover_errcode().
15438 */
15439 int sqlite3_recover_finish(sqlite3_recover*);
15440 
15441 
15442 #ifdef __cplusplus
15443 }  /* end of the 'extern "C"' block */
15444 #endif
15445 
15446 #endif /* ifndef _SQLITE_RECOVER_H */
15447 
15448 /************************* End ../ext/recover/sqlite3recover.h ********************/
15449 # ifndef SQLITE_HAVE_SQLITE3R
15450 /************************* Begin ../ext/recover/dbdata.c ******************/
15451 /*
15452 ** 2019-04-17
15453 **
15454 ** The author disclaims copyright to this source code.  In place of
15455 ** a legal notice, here is a blessing:
15456 **
15457 **    May you do good and not evil.
15458 **    May you find forgiveness for yourself and forgive others.
15459 **    May you share freely, never taking more than you give.
15460 **
15461 ******************************************************************************
15462 **
15463 ** This file contains an implementation of two eponymous virtual tables,
15464 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
15465 ** "sqlite_dbpage" eponymous virtual table be available.
15466 **
15467 ** SQLITE_DBDATA:
15468 **   sqlite_dbdata is used to extract data directly from a database b-tree
15469 **   page and its associated overflow pages, bypassing the b-tree layer.
15470 **   The table schema is equivalent to:
15471 **
15472 **     CREATE TABLE sqlite_dbdata(
15473 **       pgno INTEGER,
15474 **       cell INTEGER,
15475 **       field INTEGER,
15476 **       value ANY,
15477 **       schema TEXT HIDDEN
15478 **     );
15479 **
15480 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
15481 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
15482 **   "schema".
15483 **
15484 **   Each page of the database is inspected. If it cannot be interpreted as
15485 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
15486 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
15487 **   table contains one row for each field in the record associated with
15488 **   each cell on the page. For intkey b-trees, the key value is stored in
15489 **   field -1.
15490 **
15491 **   For example, for the database:
15492 **
15493 **     CREATE TABLE t1(a, b);     -- root page is page 2
15494 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
15495 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
15496 **
15497 **   the sqlite_dbdata table contains, as well as from entries related to
15498 **   page 1, content equivalent to:
15499 **
15500 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
15501 **         (2, 0, -1, 5     ),
15502 **         (2, 0,  0, 'v'   ),
15503 **         (2, 0,  1, 'five'),
15504 **         (2, 1, -1, 10    ),
15505 **         (2, 1,  0, 'x'   ),
15506 **         (2, 1,  1, 'ten' );
15507 **
15508 **   If database corruption is encountered, this module does not report an
15509 **   error. Instead, it attempts to extract as much data as possible and
15510 **   ignores the corruption.
15511 **
15512 ** SQLITE_DBPTR:
15513 **   The sqlite_dbptr table has the following schema:
15514 **
15515 **     CREATE TABLE sqlite_dbptr(
15516 **       pgno INTEGER,
15517 **       child INTEGER,
15518 **       schema TEXT HIDDEN
15519 **     );
15520 **
15521 **   It contains one entry for each b-tree pointer between a parent and
15522 **   child page in the database.
15523 */
15524 
15525 #if !defined(SQLITEINT_H)
15526 /* #include "sqlite3.h" */
15527 
15528 /* typedef unsigned char u8; */
15529 /* typedef unsigned int u32; */
15530 
15531 #endif
15532 #include <string.h>
15533 #include <assert.h>
15534 
15535 #ifndef SQLITE_OMIT_VIRTUALTABLE
15536 
15537 #define DBDATA_PADDING_BYTES 100
15538 
15539 typedef struct DbdataTable DbdataTable;
15540 typedef struct DbdataCursor DbdataCursor;
15541 typedef struct DbdataBuffer DbdataBuffer;
15542 
15543 /*
15544 ** Buffer type.
15545 */
15546 struct DbdataBuffer {
15547   u8 *aBuf;
15548   sqlite3_int64 nBuf;
15549 };
15550 
15551 /* Cursor object */
15552 struct DbdataCursor {
15553   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
15554   sqlite3_stmt *pStmt;            /* For fetching database pages */
15555 
15556   int iPgno;                      /* Current page number */
15557   u8 *aPage;                      /* Buffer containing page */
15558   int nPage;                      /* Size of aPage[] in bytes */
15559   int nCell;                      /* Number of cells on aPage[] */
15560   int iCell;                      /* Current cell number */
15561   int bOnePage;                   /* True to stop after one page */
15562   int szDb;
15563   sqlite3_int64 iRowid;
15564 
15565   /* Only for the sqlite_dbdata table */
15566   DbdataBuffer rec;
15567   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
15568   sqlite3_int64 nHdr;             /* Size of header in bytes */
15569   int iField;                     /* Current field number */
15570   u8 *pHdrPtr;
15571   u8 *pPtr;
15572   u32 enc;                        /* Text encoding */
15573 
15574   sqlite3_int64 iIntkey;          /* Integer key value */
15575 };
15576 
15577 /* Table object */
15578 struct DbdataTable {
15579   sqlite3_vtab base;              /* Base class.  Must be first */
15580   sqlite3 *db;                    /* The database connection */
15581   sqlite3_stmt *pStmt;            /* For fetching database pages */
15582   int bPtr;                       /* True for sqlite3_dbptr table */
15583 };
15584 
15585 /* Column and schema definitions for sqlite_dbdata */
15586 #define DBDATA_COLUMN_PGNO        0
15587 #define DBDATA_COLUMN_CELL        1
15588 #define DBDATA_COLUMN_FIELD       2
15589 #define DBDATA_COLUMN_VALUE       3
15590 #define DBDATA_COLUMN_SCHEMA      4
15591 #define DBDATA_SCHEMA             \
15592       "CREATE TABLE x("           \
15593       "  pgno INTEGER,"           \
15594       "  cell INTEGER,"           \
15595       "  field INTEGER,"          \
15596       "  value ANY,"              \
15597       "  schema TEXT HIDDEN"      \
15598       ")"
15599 
15600 /* Column and schema definitions for sqlite_dbptr */
15601 #define DBPTR_COLUMN_PGNO         0
15602 #define DBPTR_COLUMN_CHILD        1
15603 #define DBPTR_COLUMN_SCHEMA       2
15604 #define DBPTR_SCHEMA              \
15605       "CREATE TABLE x("           \
15606       "  pgno INTEGER,"           \
15607       "  child INTEGER,"          \
15608       "  schema TEXT HIDDEN"      \
15609       ")"
15610 
15611 /*
15612 ** Ensure the buffer passed as the first argument is at least nMin bytes
15613 ** in size. If an error occurs while attempting to resize the buffer,
15614 ** SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
15615 */
dbdataBufferSize(DbdataBuffer * pBuf,sqlite3_int64 nMin)15616 static int dbdataBufferSize(DbdataBuffer *pBuf, sqlite3_int64 nMin){
15617   if( nMin>pBuf->nBuf ){
15618     sqlite3_int64 nNew = nMin+16384;
15619     u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew);
15620 
15621     if( aNew==0 ) return SQLITE_NOMEM;
15622     pBuf->aBuf = aNew;
15623     pBuf->nBuf = nNew;
15624   }
15625   return SQLITE_OK;
15626 }
15627 
15628 /*
15629 ** Release the allocation managed by buffer pBuf.
15630 */
dbdataBufferFree(DbdataBuffer * pBuf)15631 static void dbdataBufferFree(DbdataBuffer *pBuf){
15632   sqlite3_free(pBuf->aBuf);
15633   memset(pBuf, 0, sizeof(*pBuf));
15634 }
15635 
15636 /*
15637 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
15638 ** table.
15639 */
dbdataConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)15640 static int dbdataConnect(
15641   sqlite3 *db,
15642   void *pAux,
15643   int argc, const char *const*argv,
15644   sqlite3_vtab **ppVtab,
15645   char **pzErr
15646 ){
15647   DbdataTable *pTab = 0;
15648   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
15649 
15650   (void)argc;
15651   (void)argv;
15652   (void)pzErr;
15653   sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
15654   if( rc==SQLITE_OK ){
15655     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
15656     if( pTab==0 ){
15657       rc = SQLITE_NOMEM;
15658     }else{
15659       memset(pTab, 0, sizeof(DbdataTable));
15660       pTab->db = db;
15661       pTab->bPtr = (pAux!=0);
15662     }
15663   }
15664 
15665   *ppVtab = (sqlite3_vtab*)pTab;
15666   return rc;
15667 }
15668 
15669 /*
15670 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
15671 */
dbdataDisconnect(sqlite3_vtab * pVtab)15672 static int dbdataDisconnect(sqlite3_vtab *pVtab){
15673   DbdataTable *pTab = (DbdataTable*)pVtab;
15674   if( pTab ){
15675     sqlite3_finalize(pTab->pStmt);
15676     sqlite3_free(pVtab);
15677   }
15678   return SQLITE_OK;
15679 }
15680 
15681 /*
15682 ** This function interprets two types of constraints:
15683 **
15684 **       schema=?
15685 **       pgno=?
15686 **
15687 ** If neither are present, idxNum is set to 0. If schema=? is present,
15688 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
15689 ** in idxNum is set.
15690 **
15691 ** If both parameters are present, schema is in position 0 and pgno in
15692 ** position 1.
15693 */
dbdataBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdx)15694 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
15695   DbdataTable *pTab = (DbdataTable*)tab;
15696   int i;
15697   int iSchema = -1;
15698   int iPgno = -1;
15699   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
15700 
15701   for(i=0; i<pIdx->nConstraint; i++){
15702     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
15703     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
15704       if( p->iColumn==colSchema ){
15705         if( p->usable==0 ) return SQLITE_CONSTRAINT;
15706         iSchema = i;
15707       }
15708       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
15709         iPgno = i;
15710       }
15711     }
15712   }
15713 
15714   if( iSchema>=0 ){
15715     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
15716     pIdx->aConstraintUsage[iSchema].omit = 1;
15717   }
15718   if( iPgno>=0 ){
15719     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
15720     pIdx->aConstraintUsage[iPgno].omit = 1;
15721     pIdx->estimatedCost = 100;
15722     pIdx->estimatedRows =  50;
15723 
15724     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
15725       int iCol = pIdx->aOrderBy[0].iColumn;
15726       if( pIdx->nOrderBy==1 ){
15727         pIdx->orderByConsumed = (iCol==0 || iCol==1);
15728       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
15729         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
15730       }
15731     }
15732 
15733   }else{
15734     pIdx->estimatedCost = 100000000;
15735     pIdx->estimatedRows = 1000000000;
15736   }
15737   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
15738   return SQLITE_OK;
15739 }
15740 
15741 /*
15742 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
15743 */
dbdataOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)15744 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
15745   DbdataCursor *pCsr;
15746 
15747   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
15748   if( pCsr==0 ){
15749     return SQLITE_NOMEM;
15750   }else{
15751     memset(pCsr, 0, sizeof(DbdataCursor));
15752     pCsr->base.pVtab = pVTab;
15753   }
15754 
15755   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
15756   return SQLITE_OK;
15757 }
15758 
15759 /*
15760 ** Restore a cursor object to the state it was in when first allocated
15761 ** by dbdataOpen().
15762 */
dbdataResetCursor(DbdataCursor * pCsr)15763 static void dbdataResetCursor(DbdataCursor *pCsr){
15764   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
15765   if( pTab->pStmt==0 ){
15766     pTab->pStmt = pCsr->pStmt;
15767   }else{
15768     sqlite3_finalize(pCsr->pStmt);
15769   }
15770   pCsr->pStmt = 0;
15771   pCsr->iPgno = 1;
15772   pCsr->iCell = 0;
15773   pCsr->iField = 0;
15774   pCsr->bOnePage = 0;
15775   sqlite3_free(pCsr->aPage);
15776   dbdataBufferFree(&pCsr->rec);
15777   pCsr->aPage = 0;
15778   pCsr->nRec = 0;
15779 }
15780 
15781 /*
15782 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
15783 */
dbdataClose(sqlite3_vtab_cursor * pCursor)15784 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
15785   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15786   dbdataResetCursor(pCsr);
15787   sqlite3_free(pCsr);
15788   return SQLITE_OK;
15789 }
15790 
15791 /*
15792 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
15793 */
get_uint16(unsigned char * a)15794 static u32 get_uint16(unsigned char *a){
15795   return (a[0]<<8)|a[1];
15796 }
get_uint32(unsigned char * a)15797 static u32 get_uint32(unsigned char *a){
15798   return ((u32)a[0]<<24)
15799        | ((u32)a[1]<<16)
15800        | ((u32)a[2]<<8)
15801        | ((u32)a[3]);
15802 }
15803 
15804 /*
15805 ** Load page pgno from the database via the sqlite_dbpage virtual table.
15806 ** If successful, set (*ppPage) to point to a buffer containing the page
15807 ** data, (*pnPage) to the size of that buffer in bytes and return
15808 ** SQLITE_OK. In this case it is the responsibility of the caller to
15809 ** eventually free the buffer using sqlite3_free().
15810 **
15811 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
15812 ** return an SQLite error code.
15813 */
dbdataLoadPage(DbdataCursor * pCsr,u32 pgno,u8 ** ppPage,int * pnPage)15814 static int dbdataLoadPage(
15815   DbdataCursor *pCsr,             /* Cursor object */
15816   u32 pgno,                       /* Page number of page to load */
15817   u8 **ppPage,                    /* OUT: pointer to page buffer */
15818   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
15819 ){
15820   int rc2;
15821   int rc = SQLITE_OK;
15822   sqlite3_stmt *pStmt = pCsr->pStmt;
15823 
15824   *ppPage = 0;
15825   *pnPage = 0;
15826   if( pgno>0 ){
15827     sqlite3_bind_int64(pStmt, 2, pgno);
15828     if( SQLITE_ROW==sqlite3_step(pStmt) ){
15829       int nCopy = sqlite3_column_bytes(pStmt, 0);
15830       if( nCopy>0 ){
15831         u8 *pPage;
15832         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
15833         if( pPage==0 ){
15834           rc = SQLITE_NOMEM;
15835         }else{
15836           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
15837           memcpy(pPage, pCopy, nCopy);
15838           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
15839         }
15840         *ppPage = pPage;
15841         *pnPage = nCopy;
15842       }
15843     }
15844     rc2 = sqlite3_reset(pStmt);
15845     if( rc==SQLITE_OK ) rc = rc2;
15846   }
15847 
15848   return rc;
15849 }
15850 
15851 /*
15852 ** Read a varint.  Put the value in *pVal and return the number of bytes.
15853 */
dbdataGetVarint(const u8 * z,sqlite3_int64 * pVal)15854 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
15855   sqlite3_uint64 u = 0;
15856   int i;
15857   for(i=0; i<8; i++){
15858     u = (u<<7) + (z[i]&0x7f);
15859     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
15860   }
15861   u = (u<<8) + (z[i]&0xff);
15862   *pVal = (sqlite3_int64)u;
15863   return 9;
15864 }
15865 
15866 /*
15867 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
15868 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
15869 ** SQLite database except for key values in intkey tables.
15870 */
dbdataGetVarintU32(const u8 * z,sqlite3_int64 * pVal)15871 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
15872   sqlite3_int64 val;
15873   int nRet = dbdataGetVarint(z, &val);
15874   if( val<0 || val>0xFFFFFFFF ) val = 0;
15875   *pVal = val;
15876   return nRet;
15877 }
15878 
15879 /*
15880 ** Return the number of bytes of space used by an SQLite value of type
15881 ** eType.
15882 */
dbdataValueBytes(int eType)15883 static int dbdataValueBytes(int eType){
15884   switch( eType ){
15885     case 0: case 8: case 9:
15886     case 10: case 11:
15887       return 0;
15888     case 1:
15889       return 1;
15890     case 2:
15891       return 2;
15892     case 3:
15893       return 3;
15894     case 4:
15895       return 4;
15896     case 5:
15897       return 6;
15898     case 6:
15899     case 7:
15900       return 8;
15901     default:
15902       if( eType>0 ){
15903         return ((eType-12) / 2);
15904       }
15905       return 0;
15906   }
15907 }
15908 
15909 /*
15910 ** Load a value of type eType from buffer pData and use it to set the
15911 ** result of context object pCtx.
15912 */
dbdataValue(sqlite3_context * pCtx,u32 enc,int eType,u8 * pData,sqlite3_int64 nData)15913 static void dbdataValue(
15914   sqlite3_context *pCtx,
15915   u32 enc,
15916   int eType,
15917   u8 *pData,
15918   sqlite3_int64 nData
15919 ){
15920   if( eType>=0 ){
15921     if( dbdataValueBytes(eType)<=nData ){
15922       switch( eType ){
15923         case 0:
15924         case 10:
15925         case 11:
15926           sqlite3_result_null(pCtx);
15927           break;
15928 
15929         case 8:
15930           sqlite3_result_int(pCtx, 0);
15931           break;
15932         case 9:
15933           sqlite3_result_int(pCtx, 1);
15934           break;
15935 
15936         case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
15937           sqlite3_uint64 v = (signed char)pData[0];
15938           pData++;
15939           switch( eType ){
15940             case 7:
15941             case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
15942             case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
15943             case 4:  v = (v<<8) + pData[0];  pData++;
15944             case 3:  v = (v<<8) + pData[0];  pData++;
15945             case 2:  v = (v<<8) + pData[0];  pData++;
15946           }
15947 
15948           if( eType==7 ){
15949             double r;
15950             memcpy(&r, &v, sizeof(r));
15951             sqlite3_result_double(pCtx, r);
15952           }else{
15953             sqlite3_result_int64(pCtx, (sqlite3_int64)v);
15954           }
15955           break;
15956         }
15957 
15958         default: {
15959           int n = ((eType-12) / 2);
15960           if( eType % 2 ){
15961             switch( enc ){
15962   #ifndef SQLITE_OMIT_UTF16
15963               case SQLITE_UTF16BE:
15964                 sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
15965                 break;
15966               case SQLITE_UTF16LE:
15967                 sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
15968                 break;
15969   #endif
15970               default:
15971                 sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
15972                 break;
15973             }
15974           }else{
15975             sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
15976           }
15977         }
15978       }
15979     }else{
15980       if( eType==7 ){
15981         sqlite3_result_double(pCtx, 0.0);
15982       }else if( eType<7 ){
15983         sqlite3_result_int(pCtx, 0);
15984       }else if( eType%2 ){
15985         sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
15986       }else{
15987         sqlite3_result_blob(pCtx, "", 0, SQLITE_STATIC);
15988       }
15989     }
15990   }
15991 }
15992 
15993 /* This macro is a copy of the MX_CELL() macro in the SQLite core. Given
15994 ** a page-size, it returns the maximum number of cells that may be present
15995 ** on the page.  */
15996 #define DBDATA_MX_CELL(pgsz) ((pgsz-8)/6)
15997 
15998 /* Maximum number of fields that may appear in a single record. This is
15999 ** the "hard-limit", according to comments in sqliteLimit.h. */
16000 #define DBDATA_MX_FIELD 32676
16001 
16002 /*
16003 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
16004 */
dbdataNext(sqlite3_vtab_cursor * pCursor)16005 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
16006   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16007   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
16008 
16009   pCsr->iRowid++;
16010   while( 1 ){
16011     int rc;
16012     int iOff = (pCsr->iPgno==1 ? 100 : 0);
16013     int bNextPage = 0;
16014 
16015     if( pCsr->aPage==0 ){
16016       while( 1 ){
16017         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
16018         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
16019         if( rc!=SQLITE_OK ) return rc;
16020         if( pCsr->aPage && pCsr->nPage>=256 ) break;
16021         sqlite3_free(pCsr->aPage);
16022         pCsr->aPage = 0;
16023         if( pCsr->bOnePage ) return SQLITE_OK;
16024         pCsr->iPgno++;
16025       }
16026 
16027       assert( iOff+3+2<=pCsr->nPage );
16028       pCsr->iCell = pTab->bPtr ? -2 : 0;
16029       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
16030       if( pCsr->nCell>DBDATA_MX_CELL(pCsr->nPage) ){
16031         pCsr->nCell = DBDATA_MX_CELL(pCsr->nPage);
16032       }
16033     }
16034 
16035     if( pTab->bPtr ){
16036       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
16037         pCsr->iCell = pCsr->nCell;
16038       }
16039       pCsr->iCell++;
16040       if( pCsr->iCell>=pCsr->nCell ){
16041         sqlite3_free(pCsr->aPage);
16042         pCsr->aPage = 0;
16043         if( pCsr->bOnePage ) return SQLITE_OK;
16044         pCsr->iPgno++;
16045       }else{
16046         return SQLITE_OK;
16047       }
16048     }else{
16049       /* If there is no record loaded, load it now. */
16050       assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 );
16051       if( pCsr->nRec==0 ){
16052         int bHasRowid = 0;
16053         int nPointer = 0;
16054         sqlite3_int64 nPayload = 0;
16055         sqlite3_int64 nHdr = 0;
16056         int iHdr;
16057         int U, X;
16058         int nLocal;
16059 
16060         switch( pCsr->aPage[iOff] ){
16061           case 0x02:
16062             nPointer = 4;
16063             break;
16064           case 0x0a:
16065             break;
16066           case 0x0d:
16067             bHasRowid = 1;
16068             break;
16069           default:
16070             /* This is not a b-tree page with records on it. Continue. */
16071             pCsr->iCell = pCsr->nCell;
16072             break;
16073         }
16074 
16075         if( pCsr->iCell>=pCsr->nCell ){
16076           bNextPage = 1;
16077         }else{
16078           int iCellPtr = iOff + 8 + nPointer + pCsr->iCell*2;
16079 
16080           if( iCellPtr>pCsr->nPage ){
16081             bNextPage = 1;
16082           }else{
16083             iOff = get_uint16(&pCsr->aPage[iCellPtr]);
16084           }
16085 
16086           /* For an interior node cell, skip past the child-page number */
16087           iOff += nPointer;
16088 
16089           /* Load the "byte of payload including overflow" field */
16090           if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){
16091             bNextPage = 1;
16092           }else{
16093             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
16094             if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
16095             if( nPayload==0 ) nPayload = 1;
16096           }
16097 
16098           /* If this is a leaf intkey cell, load the rowid */
16099           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
16100             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
16101           }
16102 
16103           /* Figure out how much data to read from the local page */
16104           U = pCsr->nPage;
16105           if( bHasRowid ){
16106             X = U-35;
16107           }else{
16108             X = ((U-12)*64/255)-23;
16109           }
16110           if( nPayload<=X ){
16111             nLocal = nPayload;
16112           }else{
16113             int M, K;
16114             M = ((U-12)*32/255)-23;
16115             K = M+((nPayload-M)%(U-4));
16116             if( K<=X ){
16117               nLocal = K;
16118             }else{
16119               nLocal = M;
16120             }
16121           }
16122 
16123           if( bNextPage || nLocal+iOff>pCsr->nPage ){
16124             bNextPage = 1;
16125           }else{
16126 
16127             /* Allocate space for payload. And a bit more to catch small buffer
16128             ** overruns caused by attempting to read a varint or similar from
16129             ** near the end of a corrupt record.  */
16130             rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES);
16131             if( rc!=SQLITE_OK ) return rc;
16132             assert( nPayload!=0 );
16133 
16134             /* Load the nLocal bytes of payload */
16135             memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal);
16136             iOff += nLocal;
16137 
16138             /* Load content from overflow pages */
16139             if( nPayload>nLocal ){
16140               sqlite3_int64 nRem = nPayload - nLocal;
16141               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
16142               while( nRem>0 ){
16143                 u8 *aOvfl = 0;
16144                 int nOvfl = 0;
16145                 int nCopy;
16146                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
16147                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
16148                 if( rc!=SQLITE_OK ) return rc;
16149                 if( aOvfl==0 ) break;
16150 
16151                 nCopy = U-4;
16152                 if( nCopy>nRem ) nCopy = nRem;
16153                 memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy);
16154                 nRem -= nCopy;
16155 
16156                 pgnoOvfl = get_uint32(aOvfl);
16157                 sqlite3_free(aOvfl);
16158               }
16159               nPayload -= nRem;
16160             }
16161             memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES);
16162             pCsr->nRec = nPayload;
16163 
16164             iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr);
16165             if( nHdr>nPayload ) nHdr = 0;
16166             pCsr->nHdr = nHdr;
16167             pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr];
16168             pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr];
16169             pCsr->iField = (bHasRowid ? -1 : 0);
16170           }
16171         }
16172       }else{
16173         pCsr->iField++;
16174         if( pCsr->iField>0 ){
16175           sqlite3_int64 iType;
16176           if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec]
16177            || pCsr->iField>=DBDATA_MX_FIELD
16178           ){
16179             bNextPage = 1;
16180           }else{
16181             int szField = 0;
16182             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
16183             szField = dbdataValueBytes(iType);
16184             if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))<szField ){
16185               pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nRec];
16186             }else{
16187               pCsr->pPtr += szField;
16188             }
16189           }
16190         }
16191       }
16192 
16193       if( bNextPage ){
16194         sqlite3_free(pCsr->aPage);
16195         pCsr->aPage = 0;
16196         pCsr->nRec = 0;
16197         if( pCsr->bOnePage ) return SQLITE_OK;
16198         pCsr->iPgno++;
16199       }else{
16200         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){
16201           return SQLITE_OK;
16202         }
16203 
16204         /* Advance to the next cell. The next iteration of the loop will load
16205         ** the record and so on. */
16206         pCsr->nRec = 0;
16207         pCsr->iCell++;
16208       }
16209     }
16210   }
16211 
16212   assert( !"can't get here" );
16213   return SQLITE_OK;
16214 }
16215 
16216 /*
16217 ** Return true if the cursor is at EOF.
16218 */
dbdataEof(sqlite3_vtab_cursor * pCursor)16219 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
16220   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16221   return pCsr->aPage==0;
16222 }
16223 
16224 /*
16225 ** Return true if nul-terminated string zSchema ends in "()". Or false
16226 ** otherwise.
16227 */
dbdataIsFunction(const char * zSchema)16228 static int dbdataIsFunction(const char *zSchema){
16229   size_t n = strlen(zSchema);
16230   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
16231     return (int)n-2;
16232   }
16233   return 0;
16234 }
16235 
16236 /*
16237 ** Determine the size in pages of database zSchema (where zSchema is
16238 ** "main", "temp" or the name of an attached database) and set
16239 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
16240 ** an SQLite error code.
16241 */
dbdataDbsize(DbdataCursor * pCsr,const char * zSchema)16242 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
16243   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
16244   char *zSql = 0;
16245   int rc, rc2;
16246   int nFunc = 0;
16247   sqlite3_stmt *pStmt = 0;
16248 
16249   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
16250     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
16251   }else{
16252     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
16253   }
16254   if( zSql==0 ) return SQLITE_NOMEM;
16255 
16256   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
16257   sqlite3_free(zSql);
16258   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
16259     pCsr->szDb = sqlite3_column_int(pStmt, 0);
16260   }
16261   rc2 = sqlite3_finalize(pStmt);
16262   if( rc==SQLITE_OK ) rc = rc2;
16263   return rc;
16264 }
16265 
16266 /*
16267 ** Attempt to figure out the encoding of the database by retrieving page 1
16268 ** and inspecting the header field. If successful, set the pCsr->enc variable
16269 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
16270 */
dbdataGetEncoding(DbdataCursor * pCsr)16271 static int dbdataGetEncoding(DbdataCursor *pCsr){
16272   int rc = SQLITE_OK;
16273   int nPg1 = 0;
16274   u8 *aPg1 = 0;
16275   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
16276   if( rc==SQLITE_OK && nPg1>=(56+4) ){
16277     pCsr->enc = get_uint32(&aPg1[56]);
16278   }
16279   sqlite3_free(aPg1);
16280   return rc;
16281 }
16282 
16283 
16284 /*
16285 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
16286 */
dbdataFilter(sqlite3_vtab_cursor * pCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)16287 static int dbdataFilter(
16288   sqlite3_vtab_cursor *pCursor,
16289   int idxNum, const char *idxStr,
16290   int argc, sqlite3_value **argv
16291 ){
16292   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16293   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
16294   int rc = SQLITE_OK;
16295   const char *zSchema = "main";
16296   (void)idxStr;
16297   (void)argc;
16298 
16299   dbdataResetCursor(pCsr);
16300   assert( pCsr->iPgno==1 );
16301   if( idxNum & 0x01 ){
16302     zSchema = (const char*)sqlite3_value_text(argv[0]);
16303     if( zSchema==0 ) zSchema = "";
16304   }
16305   if( idxNum & 0x02 ){
16306     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
16307     pCsr->bOnePage = 1;
16308   }else{
16309     rc = dbdataDbsize(pCsr, zSchema);
16310   }
16311 
16312   if( rc==SQLITE_OK ){
16313     int nFunc = 0;
16314     if( pTab->pStmt ){
16315       pCsr->pStmt = pTab->pStmt;
16316       pTab->pStmt = 0;
16317     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
16318       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
16319       if( zSql==0 ){
16320         rc = SQLITE_NOMEM;
16321       }else{
16322         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
16323         sqlite3_free(zSql);
16324       }
16325     }else{
16326       rc = sqlite3_prepare_v2(pTab->db,
16327           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
16328           &pCsr->pStmt, 0
16329       );
16330     }
16331   }
16332   if( rc==SQLITE_OK ){
16333     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
16334   }
16335 
16336   /* Try to determine the encoding of the db by inspecting the header
16337   ** field on page 1. */
16338   if( rc==SQLITE_OK ){
16339     rc = dbdataGetEncoding(pCsr);
16340   }
16341 
16342   if( rc!=SQLITE_OK ){
16343     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
16344   }
16345 
16346   if( rc==SQLITE_OK ){
16347     rc = dbdataNext(pCursor);
16348   }
16349   return rc;
16350 }
16351 
16352 /*
16353 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
16354 */
dbdataColumn(sqlite3_vtab_cursor * pCursor,sqlite3_context * ctx,int i)16355 static int dbdataColumn(
16356   sqlite3_vtab_cursor *pCursor,
16357   sqlite3_context *ctx,
16358   int i
16359 ){
16360   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16361   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
16362   if( pTab->bPtr ){
16363     switch( i ){
16364       case DBPTR_COLUMN_PGNO:
16365         sqlite3_result_int64(ctx, pCsr->iPgno);
16366         break;
16367       case DBPTR_COLUMN_CHILD: {
16368         int iOff = pCsr->iPgno==1 ? 100 : 0;
16369         if( pCsr->iCell<0 ){
16370           iOff += 8;
16371         }else{
16372           iOff += 12 + pCsr->iCell*2;
16373           if( iOff>pCsr->nPage ) return SQLITE_OK;
16374           iOff = get_uint16(&pCsr->aPage[iOff]);
16375         }
16376         if( iOff<=pCsr->nPage ){
16377           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
16378         }
16379         break;
16380       }
16381     }
16382   }else{
16383     switch( i ){
16384       case DBDATA_COLUMN_PGNO:
16385         sqlite3_result_int64(ctx, pCsr->iPgno);
16386         break;
16387       case DBDATA_COLUMN_CELL:
16388         sqlite3_result_int(ctx, pCsr->iCell);
16389         break;
16390       case DBDATA_COLUMN_FIELD:
16391         sqlite3_result_int(ctx, pCsr->iField);
16392         break;
16393       case DBDATA_COLUMN_VALUE: {
16394         if( pCsr->iField<0 ){
16395           sqlite3_result_int64(ctx, pCsr->iIntkey);
16396         }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){
16397           sqlite3_int64 iType;
16398           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
16399           dbdataValue(
16400               ctx, pCsr->enc, iType, pCsr->pPtr,
16401               &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr
16402           );
16403         }
16404         break;
16405       }
16406     }
16407   }
16408   return SQLITE_OK;
16409 }
16410 
16411 /*
16412 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
16413 */
dbdataRowid(sqlite3_vtab_cursor * pCursor,sqlite_int64 * pRowid)16414 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
16415   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16416   *pRowid = pCsr->iRowid;
16417   return SQLITE_OK;
16418 }
16419 
16420 
16421 /*
16422 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
16423 */
sqlite3DbdataRegister(sqlite3 * db)16424 static int sqlite3DbdataRegister(sqlite3 *db){
16425   static sqlite3_module dbdata_module = {
16426     0,                            /* iVersion */
16427     0,                            /* xCreate */
16428     dbdataConnect,                /* xConnect */
16429     dbdataBestIndex,              /* xBestIndex */
16430     dbdataDisconnect,             /* xDisconnect */
16431     0,                            /* xDestroy */
16432     dbdataOpen,                   /* xOpen - open a cursor */
16433     dbdataClose,                  /* xClose - close a cursor */
16434     dbdataFilter,                 /* xFilter - configure scan constraints */
16435     dbdataNext,                   /* xNext - advance a cursor */
16436     dbdataEof,                    /* xEof - check for end of scan */
16437     dbdataColumn,                 /* xColumn - read data */
16438     dbdataRowid,                  /* xRowid - read data */
16439     0,                            /* xUpdate */
16440     0,                            /* xBegin */
16441     0,                            /* xSync */
16442     0,                            /* xCommit */
16443     0,                            /* xRollback */
16444     0,                            /* xFindMethod */
16445     0,                            /* xRename */
16446     0,                            /* xSavepoint */
16447     0,                            /* xRelease */
16448     0,                            /* xRollbackTo */
16449     0,                            /* xShadowName */
16450     0                             /* xIntegrity */
16451   };
16452 
16453   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
16454   if( rc==SQLITE_OK ){
16455     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
16456   }
16457   return rc;
16458 }
16459 
sqlite3_dbdata_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)16460 int sqlite3_dbdata_init(
16461   sqlite3 *db,
16462   char **pzErrMsg,
16463   const sqlite3_api_routines *pApi
16464 ){
16465   (void)pzErrMsg;
16466   return sqlite3DbdataRegister(db);
16467 }
16468 
16469 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
16470 
16471 /************************* End ../ext/recover/dbdata.c ********************/
16472 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
16473 /*
16474 ** 2022-08-27
16475 **
16476 ** The author disclaims copyright to this source code.  In place of
16477 ** a legal notice, here is a blessing:
16478 **
16479 **    May you do good and not evil.
16480 **    May you find forgiveness for yourself and forgive others.
16481 **    May you share freely, never taking more than you give.
16482 **
16483 *************************************************************************
16484 **
16485 */
16486 
16487 
16488 /* #include "sqlite3recover.h" */
16489 #include <assert.h>
16490 #include <string.h>
16491 
16492 #ifndef SQLITE_OMIT_VIRTUALTABLE
16493 
16494 /*
16495 ** Declaration for public API function in file dbdata.c. This may be called
16496 ** with NULL as the final two arguments to register the sqlite_dbptr and
16497 ** sqlite_dbdata virtual tables with a database handle.
16498 */
16499 #ifdef _WIN32
16500 
16501 #endif
16502 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
16503 
16504 /* typedef unsigned int u32; */
16505 /* typedef unsigned char u8; */
16506 /* typedef sqlite3_int64 i64; */
16507 
16508 typedef struct RecoverTable RecoverTable;
16509 typedef struct RecoverColumn RecoverColumn;
16510 
16511 /*
16512 ** When recovering rows of data that can be associated with table
16513 ** definitions recovered from the sqlite_schema table, each table is
16514 ** represented by an instance of the following object.
16515 **
16516 ** iRoot:
16517 **   The root page in the original database. Not necessarily (and usually
16518 **   not) the same in the recovered database.
16519 **
16520 ** zTab:
16521 **   Name of the table.
16522 **
16523 ** nCol/aCol[]:
16524 **   aCol[] is an array of nCol columns. In the order in which they appear
16525 **   in the table.
16526 **
16527 ** bIntkey:
16528 **   Set to true for intkey tables, false for WITHOUT ROWID.
16529 **
16530 ** iRowidBind:
16531 **   Each column in the aCol[] array has associated with it the index of
16532 **   the bind parameter its values will be bound to in the INSERT statement
16533 **   used to construct the output database. If the table does has a rowid
16534 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
16535 **   index of the bind paramater to which the rowid value should be bound.
16536 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
16537 **   KEY column, then the rowid value should be bound to the index associated
16538 **   with the column.
16539 **
16540 ** pNext:
16541 **   All RecoverTable objects used by the recovery operation are allocated
16542 **   and populated as part of creating the recovered database schema in
16543 **   the output database, before any non-schema data are recovered. They
16544 **   are then stored in a singly-linked list linked by this variable beginning
16545 **   at sqlite3_recover.pTblList.
16546 */
16547 struct RecoverTable {
16548   u32 iRoot;                      /* Root page in original database */
16549   char *zTab;                     /* Name of table */
16550   int nCol;                       /* Number of columns in table */
16551   RecoverColumn *aCol;            /* Array of columns */
16552   int bIntkey;                    /* True for intkey, false for without rowid */
16553   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
16554   RecoverTable *pNext;
16555 };
16556 
16557 /*
16558 ** Each database column is represented by an instance of the following object
16559 ** stored in the RecoverTable.aCol[] array of the associated table.
16560 **
16561 ** iField:
16562 **   The index of the associated field within database records. Or -1 if
16563 **   there is no associated field (e.g. for virtual generated columns).
16564 **
16565 ** iBind:
16566 **   The bind index of the INSERT statement to bind this columns values
16567 **   to. Or 0 if there is no such index (iff (iField<0)).
16568 **
16569 ** bIPK:
16570 **   True if this is the INTEGER PRIMARY KEY column.
16571 **
16572 ** zCol:
16573 **   Name of column.
16574 **
16575 ** eHidden:
16576 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
16577 */
16578 struct RecoverColumn {
16579   int iField;                     /* Field in record on disk */
16580   int iBind;                      /* Binding to use in INSERT */
16581   int bIPK;                       /* True for IPK column */
16582   char *zCol;
16583   int eHidden;
16584 };
16585 
16586 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
16587 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
16588 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
16589 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
16590 
16591 /*
16592 ** Bitmap object used to track pages in the input database. Allocated
16593 ** and manipulated only by the following functions:
16594 **
16595 **     recoverBitmapAlloc()
16596 **     recoverBitmapFree()
16597 **     recoverBitmapSet()
16598 **     recoverBitmapQuery()
16599 **
16600 ** nPg:
16601 **   Largest page number that may be stored in the bitmap. The range
16602 **   of valid keys is 1 to nPg, inclusive.
16603 **
16604 ** aElem[]:
16605 **   Array large enough to contain a bit for each key. For key value
16606 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
16607 **   In other words, the following is true if bit iKey is set, or
16608 **   false if it is clear:
16609 **
16610 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
16611 */
16612 typedef struct RecoverBitmap RecoverBitmap;
16613 struct RecoverBitmap {
16614   i64 nPg;                        /* Size of bitmap */
16615   u32 aElem[1];                   /* Array of 32-bit bitmasks */
16616 };
16617 
16618 /*
16619 ** State variables (part of the sqlite3_recover structure) used while
16620 ** recovering data for tables identified in the recovered schema (state
16621 ** RECOVER_STATE_WRITING).
16622 */
16623 typedef struct RecoverStateW1 RecoverStateW1;
16624 struct RecoverStateW1 {
16625   sqlite3_stmt *pTbls;
16626   sqlite3_stmt *pSel;
16627   sqlite3_stmt *pInsert;
16628   int nInsert;
16629 
16630   RecoverTable *pTab;             /* Table currently being written */
16631   int nMax;                       /* Max column count in any schema table */
16632   sqlite3_value **apVal;          /* Array of nMax values */
16633   int nVal;                       /* Number of valid entries in apVal[] */
16634   int bHaveRowid;
16635   i64 iRowid;
16636   i64 iPrevPage;
16637   int iPrevCell;
16638 };
16639 
16640 /*
16641 ** State variables (part of the sqlite3_recover structure) used while
16642 ** recovering data destined for the lost and found table (states
16643 ** RECOVER_STATE_LOSTANDFOUND[123]).
16644 */
16645 typedef struct RecoverStateLAF RecoverStateLAF;
16646 struct RecoverStateLAF {
16647   RecoverBitmap *pUsed;
16648   i64 nPg;                        /* Size of db in pages */
16649   sqlite3_stmt *pAllAndParent;
16650   sqlite3_stmt *pMapInsert;
16651   sqlite3_stmt *pMaxField;
16652   sqlite3_stmt *pUsedPages;
16653   sqlite3_stmt *pFindRoot;
16654   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
16655   sqlite3_stmt *pAllPage;
16656   sqlite3_stmt *pPageData;
16657   sqlite3_value **apVal;
16658   int nMaxField;
16659 };
16660 
16661 /*
16662 ** Main recover handle structure.
16663 */
16664 struct sqlite3_recover {
16665   /* Copies of sqlite3_recover_init[_sql]() parameters */
16666   sqlite3 *dbIn;                  /* Input database */
16667   char *zDb;                      /* Name of input db ("main" etc.) */
16668   char *zUri;                     /* URI for output database */
16669   void *pSqlCtx;                  /* SQL callback context */
16670   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
16671 
16672   /* Values configured by sqlite3_recover_config() */
16673   char *zStateDb;                 /* State database to use (or NULL) */
16674   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
16675   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
16676   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
16677   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
16678 
16679   int pgsz;
16680   int detected_pgsz;
16681   int nReserve;
16682   u8 *pPage1Disk;
16683   u8 *pPage1Cache;
16684 
16685   /* Error code and error message */
16686   int errCode;                    /* For sqlite3_recover_errcode() */
16687   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
16688 
16689   int eState;
16690   int bCloseTransaction;
16691 
16692   /* Variables used with eState==RECOVER_STATE_WRITING */
16693   RecoverStateW1 w1;
16694 
16695   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
16696   RecoverStateLAF laf;
16697 
16698   /* Fields used within sqlite3_recover_run() */
16699   sqlite3 *dbOut;                 /* Output database */
16700   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
16701   RecoverTable *pTblList;         /* List of tables recovered from schema */
16702 };
16703 
16704 /*
16705 ** The various states in which an sqlite3_recover object may exist:
16706 **
16707 **   RECOVER_STATE_INIT:
16708 **    The object is initially created in this state. sqlite3_recover_step()
16709 **    has yet to be called. This is the only state in which it is permitted
16710 **    to call sqlite3_recover_config().
16711 **
16712 **   RECOVER_STATE_WRITING:
16713 **
16714 **   RECOVER_STATE_LOSTANDFOUND1:
16715 **    State to populate the bitmap of pages used by other tables or the
16716 **    database freelist.
16717 **
16718 **   RECOVER_STATE_LOSTANDFOUND2:
16719 **    Populate the recovery.map table - used to figure out a "root" page
16720 **    for each lost page from in the database from which records are
16721 **    extracted.
16722 **
16723 **   RECOVER_STATE_LOSTANDFOUND3:
16724 **    Populate the lost-and-found table itself.
16725 */
16726 #define RECOVER_STATE_INIT           0
16727 #define RECOVER_STATE_WRITING        1
16728 #define RECOVER_STATE_LOSTANDFOUND1  2
16729 #define RECOVER_STATE_LOSTANDFOUND2  3
16730 #define RECOVER_STATE_LOSTANDFOUND3  4
16731 #define RECOVER_STATE_SCHEMA2        5
16732 #define RECOVER_STATE_DONE           6
16733 
16734 
16735 /*
16736 ** Global variables used by this extension.
16737 */
16738 typedef struct RecoverGlobal RecoverGlobal;
16739 struct RecoverGlobal {
16740   const sqlite3_io_methods *pMethods;
16741   sqlite3_recover *p;
16742 };
16743 static RecoverGlobal recover_g;
16744 
16745 /*
16746 ** Use this static SQLite mutex to protect the globals during the
16747 ** first call to sqlite3_recover_step().
16748 */
16749 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
16750 
16751 
16752 /*
16753 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
16754 */
16755 #define RECOVER_ROWID_DEFAULT 1
16756 
16757 /*
16758 ** Mutex handling:
16759 **
16760 **    recoverEnterMutex()       -   Enter the recovery mutex
16761 **    recoverLeaveMutex()       -   Leave the recovery mutex
16762 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
16763 */
16764 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
16765 # define recoverEnterMutex()
16766 # define recoverLeaveMutex()
16767 #else
recoverEnterMutex(void)16768 static void recoverEnterMutex(void){
16769   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
16770 }
recoverLeaveMutex(void)16771 static void recoverLeaveMutex(void){
16772   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
16773 }
16774 #endif
16775 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
recoverAssertMutexHeld(void)16776 static void recoverAssertMutexHeld(void){
16777   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
16778 }
16779 #else
16780 # define recoverAssertMutexHeld()
16781 #endif
16782 
16783 
16784 /*
16785 ** Like strlen(). But handles NULL pointer arguments.
16786 */
recoverStrlen(const char * zStr)16787 static int recoverStrlen(const char *zStr){
16788   if( zStr==0 ) return 0;
16789   return (int)(strlen(zStr)&0x7fffffff);
16790 }
16791 
16792 /*
16793 ** This function is a no-op if the recover handle passed as the first
16794 ** argument already contains an error (if p->errCode!=SQLITE_OK).
16795 **
16796 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
16797 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
16798 ** if an OOM error occurs, NULL is returned and the handle error code
16799 ** (p->errCode) set to SQLITE_NOMEM.
16800 */
recoverMalloc(sqlite3_recover * p,i64 nByte)16801 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
16802   void *pRet = 0;
16803   assert( nByte>0 );
16804   if( p->errCode==SQLITE_OK ){
16805     pRet = sqlite3_malloc64(nByte);
16806     if( pRet ){
16807       memset(pRet, 0, nByte);
16808     }else{
16809       p->errCode = SQLITE_NOMEM;
16810     }
16811   }
16812   return pRet;
16813 }
16814 
16815 /*
16816 ** Set the error code and error message for the recover handle passed as
16817 ** the first argument. The error code is set to the value of parameter
16818 ** errCode.
16819 **
16820 ** Parameter zFmt must be a printf() style formatting string. The handle
16821 ** error message is set to the result of using any trailing arguments for
16822 ** parameter substitutions in the formatting string.
16823 **
16824 ** For example:
16825 **
16826 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
16827 */
recoverError(sqlite3_recover * p,int errCode,const char * zFmt,...)16828 static int recoverError(
16829   sqlite3_recover *p,
16830   int errCode,
16831   const char *zFmt, ...
16832 ){
16833   char *z = 0;
16834   va_list ap;
16835   va_start(ap, zFmt);
16836   if( zFmt ){
16837     z = sqlite3_vmprintf(zFmt, ap);
16838   }
16839   va_end(ap);
16840   sqlite3_free(p->zErrMsg);
16841   p->zErrMsg = z;
16842   p->errCode = errCode;
16843   return errCode;
16844 }
16845 
16846 
16847 /*
16848 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
16849 ** In this case it returns NULL.
16850 **
16851 ** Otherwise, an attempt is made to allocate and return a bitmap object
16852 ** large enough to store a bit for all page numbers between 1 and nPg,
16853 ** inclusive. The bitmap is initially zeroed.
16854 */
recoverBitmapAlloc(sqlite3_recover * p,i64 nPg)16855 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
16856   int nElem = (nPg+1+31) / 32;
16857   int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
16858   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
16859 
16860   if( pRet ){
16861     pRet->nPg = nPg;
16862   }
16863   return pRet;
16864 }
16865 
16866 /*
16867 ** Free a bitmap object allocated by recoverBitmapAlloc().
16868 */
recoverBitmapFree(RecoverBitmap * pMap)16869 static void recoverBitmapFree(RecoverBitmap *pMap){
16870   sqlite3_free(pMap);
16871 }
16872 
16873 /*
16874 ** Set the bit associated with page iPg in bitvec pMap.
16875 */
recoverBitmapSet(RecoverBitmap * pMap,i64 iPg)16876 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
16877   if( iPg<=pMap->nPg ){
16878     int iElem = (iPg / 32);
16879     int iBit = (iPg % 32);
16880     pMap->aElem[iElem] |= (((u32)1) << iBit);
16881   }
16882 }
16883 
16884 /*
16885 ** Query bitmap object pMap for the state of the bit associated with page
16886 ** iPg. Return 1 if it is set, or 0 otherwise.
16887 */
recoverBitmapQuery(RecoverBitmap * pMap,i64 iPg)16888 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
16889   int ret = 1;
16890   if( iPg<=pMap->nPg && iPg>0 ){
16891     int iElem = (iPg / 32);
16892     int iBit = (iPg % 32);
16893     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
16894   }
16895   return ret;
16896 }
16897 
16898 /*
16899 ** Set the recover handle error to the error code and message returned by
16900 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
16901 ** handle db.
16902 */
recoverDbError(sqlite3_recover * p,sqlite3 * db)16903 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
16904   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
16905 }
16906 
16907 /*
16908 ** This function is a no-op if recover handle p already contains an error
16909 ** (if p->errCode!=SQLITE_OK).
16910 **
16911 ** Otherwise, it attempts to prepare the SQL statement in zSql against
16912 ** database handle db. If successful, the statement handle is returned.
16913 ** Or, if an error occurs, NULL is returned and an error left in the
16914 ** recover handle.
16915 */
recoverPrepare(sqlite3_recover * p,sqlite3 * db,const char * zSql)16916 static sqlite3_stmt *recoverPrepare(
16917   sqlite3_recover *p,
16918   sqlite3 *db,
16919   const char *zSql
16920 ){
16921   sqlite3_stmt *pStmt = 0;
16922   if( p->errCode==SQLITE_OK ){
16923     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
16924       recoverDbError(p, db);
16925     }
16926   }
16927   return pStmt;
16928 }
16929 
16930 /*
16931 ** This function is a no-op if recover handle p already contains an error
16932 ** (if p->errCode!=SQLITE_OK).
16933 **
16934 ** Otherwise, argument zFmt is used as a printf() style format string,
16935 ** along with any trailing arguments, to create an SQL statement. This
16936 ** SQL statement is prepared against database handle db and, if successful,
16937 ** the statment handle returned. Or, if an error occurs - either during
16938 ** the printf() formatting or when preparing the resulting SQL - an
16939 ** error code and message are left in the recover handle.
16940 */
recoverPreparePrintf(sqlite3_recover * p,sqlite3 * db,const char * zFmt,...)16941 static sqlite3_stmt *recoverPreparePrintf(
16942   sqlite3_recover *p,
16943   sqlite3 *db,
16944   const char *zFmt, ...
16945 ){
16946   sqlite3_stmt *pStmt = 0;
16947   if( p->errCode==SQLITE_OK ){
16948     va_list ap;
16949     char *z;
16950     va_start(ap, zFmt);
16951     z = sqlite3_vmprintf(zFmt, ap);
16952     va_end(ap);
16953     if( z==0 ){
16954       p->errCode = SQLITE_NOMEM;
16955     }else{
16956       pStmt = recoverPrepare(p, db, z);
16957       sqlite3_free(z);
16958     }
16959   }
16960   return pStmt;
16961 }
16962 
16963 /*
16964 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
16965 ** indicates that an error occurred, and there is not already an error
16966 ** in the recover handle passed as the first argument, set the error
16967 ** code and error message appropriately.
16968 **
16969 ** This function returns a copy of the statement handle pointer passed
16970 ** as the second argument.
16971 */
recoverReset(sqlite3_recover * p,sqlite3_stmt * pStmt)16972 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
16973   int rc = sqlite3_reset(pStmt);
16974   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
16975     recoverDbError(p, sqlite3_db_handle(pStmt));
16976   }
16977   return pStmt;
16978 }
16979 
16980 /*
16981 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
16982 ** indicates that an error occurred, and there is not already an error
16983 ** in the recover handle passed as the first argument, set the error
16984 ** code and error message appropriately.
16985 */
recoverFinalize(sqlite3_recover * p,sqlite3_stmt * pStmt)16986 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
16987   sqlite3 *db = sqlite3_db_handle(pStmt);
16988   int rc = sqlite3_finalize(pStmt);
16989   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
16990     recoverDbError(p, db);
16991   }
16992 }
16993 
16994 /*
16995 ** This function is a no-op if recover handle p already contains an error
16996 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
16997 ** case.
16998 **
16999 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
17000 ** Or, if an error occurs, leave an error code and message in the recover
17001 ** handle and return a copy of the error code.
17002 */
recoverExec(sqlite3_recover * p,sqlite3 * db,const char * zSql)17003 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
17004   if( p->errCode==SQLITE_OK ){
17005     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
17006     if( rc ){
17007       recoverDbError(p, db);
17008     }
17009   }
17010   return p->errCode;
17011 }
17012 
17013 /*
17014 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
17015 ** error in the recover handle passed as the first argument if an error
17016 ** (e.g. an OOM) occurs.
17017 */
recoverBindValue(sqlite3_recover * p,sqlite3_stmt * pStmt,int iBind,sqlite3_value * pVal)17018 static void recoverBindValue(
17019   sqlite3_recover *p,
17020   sqlite3_stmt *pStmt,
17021   int iBind,
17022   sqlite3_value *pVal
17023 ){
17024   if( p->errCode==SQLITE_OK ){
17025     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
17026     if( rc ) recoverError(p, rc, 0);
17027   }
17028 }
17029 
17030 /*
17031 ** This function is a no-op if recover handle p already contains an error
17032 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
17033 **
17034 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
17035 ** formatting string and the result of using the trailing arguments for
17036 ** parameter substitution with it written into a buffer obtained from
17037 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
17038 ** It is the responsibility of the caller to eventually free the buffer
17039 ** using sqlite3_free().
17040 **
17041 ** Or, if an error occurs, an error code and message is left in the recover
17042 ** handle and NULL returned.
17043 */
recoverMPrintf(sqlite3_recover * p,const char * zFmt,...)17044 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
17045   va_list ap;
17046   char *z;
17047   va_start(ap, zFmt);
17048   z = sqlite3_vmprintf(zFmt, ap);
17049   va_end(ap);
17050   if( p->errCode==SQLITE_OK ){
17051     if( z==0 ) p->errCode = SQLITE_NOMEM;
17052   }else{
17053     sqlite3_free(z);
17054     z = 0;
17055   }
17056   return z;
17057 }
17058 
17059 /*
17060 ** This function is a no-op if recover handle p already contains an error
17061 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
17062 **
17063 ** Otherwise, execute "PRAGMA page_count" against the input database. If
17064 ** successful, return the integer result. Or, if an error occurs, leave an
17065 ** error code and error message in the sqlite3_recover handle and return
17066 ** zero.
17067 */
recoverPageCount(sqlite3_recover * p)17068 static i64 recoverPageCount(sqlite3_recover *p){
17069   i64 nPg = 0;
17070   if( p->errCode==SQLITE_OK ){
17071     sqlite3_stmt *pStmt = 0;
17072     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
17073     if( pStmt ){
17074       sqlite3_step(pStmt);
17075       nPg = sqlite3_column_int64(pStmt, 0);
17076     }
17077     recoverFinalize(p, pStmt);
17078   }
17079   return nPg;
17080 }
17081 
17082 /*
17083 ** Implementation of SQL scalar function "read_i32". The first argument to
17084 ** this function must be a blob. The second a non-negative integer. This
17085 ** function reads and returns a 32-bit big-endian integer from byte
17086 ** offset (4*<arg2>) of the blob.
17087 **
17088 **     SELECT read_i32(<blob>, <idx>)
17089 */
recoverReadI32(sqlite3_context * context,int argc,sqlite3_value ** argv)17090 static void recoverReadI32(
17091   sqlite3_context *context,
17092   int argc,
17093   sqlite3_value **argv
17094 ){
17095   const unsigned char *pBlob;
17096   int nBlob;
17097   int iInt;
17098 
17099   assert( argc==2 );
17100   nBlob = sqlite3_value_bytes(argv[0]);
17101   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
17102   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
17103 
17104   if( (iInt+1)*4<=nBlob ){
17105     const unsigned char *a = &pBlob[iInt*4];
17106     i64 iVal = ((i64)a[0]<<24)
17107              + ((i64)a[1]<<16)
17108              + ((i64)a[2]<< 8)
17109              + ((i64)a[3]<< 0);
17110     sqlite3_result_int64(context, iVal);
17111   }
17112 }
17113 
17114 /*
17115 ** Implementation of SQL scalar function "page_is_used". This function
17116 ** is used as part of the procedure for locating orphan rows for the
17117 ** lost-and-found table, and it depends on those routines having populated
17118 ** the sqlite3_recover.laf.pUsed variable.
17119 **
17120 ** The only argument to this function is a page-number. It returns true
17121 ** if the page has already been used somehow during data recovery, or false
17122 ** otherwise.
17123 **
17124 **     SELECT page_is_used(<pgno>);
17125 */
recoverPageIsUsed(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)17126 static void recoverPageIsUsed(
17127   sqlite3_context *pCtx,
17128   int nArg,
17129   sqlite3_value **apArg
17130 ){
17131   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
17132   i64 pgno = sqlite3_value_int64(apArg[0]);
17133   assert( nArg==1 );
17134   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
17135 }
17136 
17137 /*
17138 ** The implementation of a user-defined SQL function invoked by the
17139 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
17140 ** of the database being recovered.
17141 **
17142 ** This function always takes a single integer argument. If the argument
17143 ** is zero, then the value returned is the number of pages in the db being
17144 ** recovered. If the argument is greater than zero, it is a page number.
17145 ** The value returned in this case is an SQL blob containing the data for
17146 ** the identified page of the db being recovered. e.g.
17147 **
17148 **     SELECT getpage(0);       -- return number of pages in db
17149 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
17150 */
recoverGetPage(sqlite3_context * pCtx,int nArg,sqlite3_value ** apArg)17151 static void recoverGetPage(
17152   sqlite3_context *pCtx,
17153   int nArg,
17154   sqlite3_value **apArg
17155 ){
17156   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
17157   i64 pgno = sqlite3_value_int64(apArg[0]);
17158   sqlite3_stmt *pStmt = 0;
17159 
17160   assert( nArg==1 );
17161   if( pgno==0 ){
17162     i64 nPg = recoverPageCount(p);
17163     sqlite3_result_int64(pCtx, nPg);
17164     return;
17165   }else{
17166     if( p->pGetPage==0 ){
17167       pStmt = p->pGetPage = recoverPreparePrintf(
17168           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
17169       );
17170     }else if( p->errCode==SQLITE_OK ){
17171       pStmt = p->pGetPage;
17172     }
17173 
17174     if( pStmt ){
17175       sqlite3_bind_int64(pStmt, 1, pgno);
17176       if( SQLITE_ROW==sqlite3_step(pStmt) ){
17177         const u8 *aPg;
17178         int nPg;
17179         assert( p->errCode==SQLITE_OK );
17180         aPg = sqlite3_column_blob(pStmt, 0);
17181         nPg = sqlite3_column_bytes(pStmt, 0);
17182         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
17183           aPg = p->pPage1Disk;
17184         }
17185         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
17186       }
17187       recoverReset(p, pStmt);
17188     }
17189   }
17190 
17191   if( p->errCode ){
17192     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
17193     sqlite3_result_error_code(pCtx, p->errCode);
17194   }
17195 }
17196 
17197 /*
17198 ** Find a string that is not found anywhere in z[].  Return a pointer
17199 ** to that string.
17200 **
17201 ** Try to use zA and zB first.  If both of those are already found in z[]
17202 ** then make up some string and store it in the buffer zBuf.
17203 */
recoverUnusedString(const char * z,const char * zA,const char * zB,char * zBuf)17204 static const char *recoverUnusedString(
17205   const char *z,                    /* Result must not appear anywhere in z */
17206   const char *zA, const char *zB,   /* Try these first */
17207   char *zBuf                        /* Space to store a generated string */
17208 ){
17209   unsigned i = 0;
17210   if( strstr(z, zA)==0 ) return zA;
17211   if( strstr(z, zB)==0 ) return zB;
17212   do{
17213     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
17214   }while( strstr(z,zBuf)!=0 );
17215   return zBuf;
17216 }
17217 
17218 /*
17219 ** Implementation of scalar SQL function "escape_crnl".  The argument passed to
17220 ** this function is the output of built-in function quote(). If the first
17221 ** character of the input is "'", indicating that the value passed to quote()
17222 ** was a text value, then this function searches the input for "\n" and "\r"
17223 ** characters and adds a wrapper similar to the following:
17224 **
17225 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
17226 **
17227 ** Or, if the first character of the input is not "'", then a copy of the input
17228 ** is returned.
17229 */
recoverEscapeCrnl(sqlite3_context * context,int argc,sqlite3_value ** argv)17230 static void recoverEscapeCrnl(
17231   sqlite3_context *context,
17232   int argc,
17233   sqlite3_value **argv
17234 ){
17235   const char *zText = (const char*)sqlite3_value_text(argv[0]);
17236   (void)argc;
17237   if( zText && zText[0]=='\'' ){
17238     int nText = sqlite3_value_bytes(argv[0]);
17239     int i;
17240     char zBuf1[20];
17241     char zBuf2[20];
17242     const char *zNL = 0;
17243     const char *zCR = 0;
17244     int nCR = 0;
17245     int nNL = 0;
17246 
17247     for(i=0; zText[i]; i++){
17248       if( zNL==0 && zText[i]=='\n' ){
17249         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
17250         nNL = (int)strlen(zNL);
17251       }
17252       if( zCR==0 && zText[i]=='\r' ){
17253         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
17254         nCR = (int)strlen(zCR);
17255       }
17256     }
17257 
17258     if( zNL || zCR ){
17259       int iOut = 0;
17260       i64 nMax = (nNL > nCR) ? nNL : nCR;
17261       i64 nAlloc = nMax * nText + (nMax+64)*2;
17262       char *zOut = (char*)sqlite3_malloc64(nAlloc);
17263       if( zOut==0 ){
17264         sqlite3_result_error_nomem(context);
17265         return;
17266       }
17267 
17268       if( zNL && zCR ){
17269         memcpy(&zOut[iOut], "replace(replace(", 16);
17270         iOut += 16;
17271       }else{
17272         memcpy(&zOut[iOut], "replace(", 8);
17273         iOut += 8;
17274       }
17275       for(i=0; zText[i]; i++){
17276         if( zText[i]=='\n' ){
17277           memcpy(&zOut[iOut], zNL, nNL);
17278           iOut += nNL;
17279         }else if( zText[i]=='\r' ){
17280           memcpy(&zOut[iOut], zCR, nCR);
17281           iOut += nCR;
17282         }else{
17283           zOut[iOut] = zText[i];
17284           iOut++;
17285         }
17286       }
17287 
17288       if( zNL ){
17289         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
17290         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
17291         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
17292       }
17293       if( zCR ){
17294         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
17295         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
17296         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
17297       }
17298 
17299       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
17300       sqlite3_free(zOut);
17301       return;
17302     }
17303   }
17304 
17305   sqlite3_result_value(context, argv[0]);
17306 }
17307 
17308 /*
17309 ** This function is a no-op if recover handle p already contains an error
17310 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
17311 ** this case.
17312 **
17313 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
17314 ** parts of the database schema that can be extracted from the input database.
17315 **
17316 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
17317 ** and error message are left in the recover handle and a copy of the
17318 ** error code returned. It is not considered an error if part of all of
17319 ** the database schema cannot be recovered due to corruption.
17320 */
recoverCacheSchema(sqlite3_recover * p)17321 static int recoverCacheSchema(sqlite3_recover *p){
17322   return recoverExec(p, p->dbOut,
17323     "WITH RECURSIVE pages(p) AS ("
17324     "  SELECT 1"
17325     "    UNION"
17326     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
17327     ")"
17328     "INSERT INTO recovery.schema SELECT"
17329     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
17330     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
17331     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
17332     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
17333     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
17334     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
17335     "  SELECT p FROM pages"
17336     ") GROUP BY pgno, cell"
17337   );
17338 }
17339 
17340 /*
17341 ** If this recover handle is not in SQL callback mode (i.e. was not created
17342 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
17343 ** this function is a no-op. Otherwise, issue a callback with SQL statement
17344 ** zSql as the parameter.
17345 **
17346 ** If the callback returns non-zero, set the recover handle error code to
17347 ** the value returned (so that the caller will abandon processing).
17348 */
recoverSqlCallback(sqlite3_recover * p,const char * zSql)17349 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
17350   if( p->errCode==SQLITE_OK && p->xSql ){
17351     int res = p->xSql(p->pSqlCtx, zSql);
17352     if( res ){
17353       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
17354     }
17355   }
17356 }
17357 
17358 /*
17359 ** Transfer the following settings from the input database to the output
17360 ** database:
17361 **
17362 **   + page-size,
17363 **   + auto-vacuum settings,
17364 **   + database encoding,
17365 **   + user-version (PRAGMA user_version), and
17366 **   + application-id (PRAGMA application_id), and
17367 */
recoverTransferSettings(sqlite3_recover * p)17368 static void recoverTransferSettings(sqlite3_recover *p){
17369   const char *aPragma[] = {
17370     "encoding",
17371     "page_size",
17372     "auto_vacuum",
17373     "user_version",
17374     "application_id"
17375   };
17376   int ii;
17377 
17378   /* Truncate the output database to 0 pages in size. This is done by
17379   ** opening a new, empty, temp db, then using the backup API to clobber
17380   ** any existing output db with a copy of it. */
17381   if( p->errCode==SQLITE_OK ){
17382     sqlite3 *db2 = 0;
17383     int rc = sqlite3_open("", &db2);
17384     if( rc!=SQLITE_OK ){
17385       recoverDbError(p, db2);
17386       return;
17387     }
17388 
17389     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
17390       const char *zPrag = aPragma[ii];
17391       sqlite3_stmt *p1 = 0;
17392       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
17393       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
17394         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
17395         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
17396         recoverSqlCallback(p, z2);
17397         recoverExec(p, db2, z2);
17398         sqlite3_free(z2);
17399         if( zArg==0 ){
17400           recoverError(p, SQLITE_NOMEM, 0);
17401         }
17402       }
17403       recoverFinalize(p, p1);
17404     }
17405     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
17406 
17407     if( p->errCode==SQLITE_OK ){
17408       sqlite3 *db = p->dbOut;
17409       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
17410       if( pBackup ){
17411         sqlite3_backup_step(pBackup, -1);
17412         p->errCode = sqlite3_backup_finish(pBackup);
17413       }else{
17414         recoverDbError(p, db);
17415       }
17416     }
17417 
17418     sqlite3_close(db2);
17419   }
17420 }
17421 
17422 /*
17423 ** This function is a no-op if recover handle p already contains an error
17424 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
17425 ** this case.
17426 **
17427 ** Otherwise, an attempt is made to open the output database, attach
17428 ** and create the schema of the temporary database used to store
17429 ** intermediate data, and to register all required user functions and
17430 ** virtual table modules with the output handle.
17431 **
17432 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
17433 ** and error message are left in the recover handle and a copy of the
17434 ** error code returned.
17435 */
recoverOpenOutput(sqlite3_recover * p)17436 static int recoverOpenOutput(sqlite3_recover *p){
17437   struct Func {
17438     const char *zName;
17439     int nArg;
17440     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
17441   } aFunc[] = {
17442     { "getpage", 1, recoverGetPage },
17443     { "page_is_used", 1, recoverPageIsUsed },
17444     { "read_i32", 2, recoverReadI32 },
17445     { "escape_crnl", 1, recoverEscapeCrnl },
17446   };
17447 
17448   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
17449   sqlite3 *db = 0;                /* New database handle */
17450   int ii;                         /* For iterating through aFunc[] */
17451 
17452   assert( p->dbOut==0 );
17453 
17454   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
17455     recoverDbError(p, db);
17456   }
17457 
17458   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
17459   ** These two are registered with the output database handle - this
17460   ** module depends on the input handle supporting the sqlite_dbpage
17461   ** virtual table only.  */
17462   if( p->errCode==SQLITE_OK ){
17463     p->errCode = sqlite3_dbdata_init(db, 0, 0);
17464   }
17465 
17466   /* Register the custom user-functions with the output handle. */
17467   for(ii=0;
17468       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
17469       ii++){
17470     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
17471         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
17472     );
17473   }
17474 
17475   p->dbOut = db;
17476   return p->errCode;
17477 }
17478 
17479 /*
17480 ** Attach the auxiliary database 'recovery' to the output database handle.
17481 ** This temporary database is used during the recovery process and then
17482 ** discarded.
17483 */
recoverOpenRecovery(sqlite3_recover * p)17484 static void recoverOpenRecovery(sqlite3_recover *p){
17485   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
17486   recoverExec(p, p->dbOut, zSql);
17487   recoverExec(p, p->dbOut,
17488       "PRAGMA writable_schema = 1;"
17489       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
17490       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
17491   );
17492   sqlite3_free(zSql);
17493 }
17494 
17495 
17496 /*
17497 ** This function is a no-op if recover handle p already contains an error
17498 ** (if p->errCode!=SQLITE_OK).
17499 **
17500 ** Otherwise, argument zName must be the name of a table that has just been
17501 ** created in the output database. This function queries the output db
17502 ** for the schema of said table, and creates a RecoverTable object to
17503 ** store the schema in memory. The new RecoverTable object is linked into
17504 ** the list at sqlite3_recover.pTblList.
17505 **
17506 ** Parameter iRoot must be the root page of table zName in the INPUT
17507 ** database.
17508 */
recoverAddTable(sqlite3_recover * p,const char * zName,i64 iRoot)17509 static void recoverAddTable(
17510   sqlite3_recover *p,
17511   const char *zName,              /* Name of table created in output db */
17512   i64 iRoot                       /* Root page of same table in INPUT db */
17513 ){
17514   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
17515       "PRAGMA table_xinfo(%Q)", zName
17516   );
17517 
17518   if( pStmt ){
17519     int iPk = -1;
17520     int iBind = 1;
17521     RecoverTable *pNew = 0;
17522     int nCol = 0;
17523     int nName = recoverStrlen(zName);
17524     int nByte = 0;
17525     while( sqlite3_step(pStmt)==SQLITE_ROW ){
17526       nCol++;
17527       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
17528     }
17529     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
17530     recoverReset(p, pStmt);
17531 
17532     pNew = recoverMalloc(p, nByte);
17533     if( pNew ){
17534       int i = 0;
17535       int iField = 0;
17536       char *csr = 0;
17537       pNew->aCol = (RecoverColumn*)&pNew[1];
17538       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
17539       pNew->nCol = nCol;
17540       pNew->iRoot = iRoot;
17541       memcpy(csr, zName, nName);
17542       csr += nName+1;
17543 
17544       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
17545         int iPKF = sqlite3_column_int(pStmt, 5);
17546         int n = sqlite3_column_bytes(pStmt, 1);
17547         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
17548         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
17549         int eHidden = sqlite3_column_int(pStmt, 6);
17550 
17551         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
17552         if( iPKF>1 ) iPk = -2;
17553         pNew->aCol[i].zCol = csr;
17554         pNew->aCol[i].eHidden = eHidden;
17555         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
17556           pNew->aCol[i].iField = -1;
17557         }else{
17558           pNew->aCol[i].iField = iField++;
17559         }
17560         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
17561          && eHidden!=RECOVER_EHIDDEN_STORED
17562         ){
17563           pNew->aCol[i].iBind = iBind++;
17564         }
17565         memcpy(csr, z, n);
17566         csr += (n+1);
17567       }
17568 
17569       pNew->pNext = p->pTblList;
17570       p->pTblList = pNew;
17571       pNew->bIntkey = 1;
17572     }
17573 
17574     recoverFinalize(p, pStmt);
17575 
17576     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
17577     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
17578       int iField = sqlite3_column_int(pStmt, 0);
17579       int iCol = sqlite3_column_int(pStmt, 1);
17580 
17581       assert( iCol<pNew->nCol );
17582       pNew->aCol[iCol].iField = iField;
17583 
17584       pNew->bIntkey = 0;
17585       iPk = -2;
17586     }
17587     recoverFinalize(p, pStmt);
17588 
17589     if( p->errCode==SQLITE_OK ){
17590       if( iPk>=0 ){
17591         pNew->aCol[iPk].bIPK = 1;
17592       }else if( pNew->bIntkey ){
17593         pNew->iRowidBind = iBind++;
17594       }
17595     }
17596   }
17597 }
17598 
17599 /*
17600 ** This function is called after recoverCacheSchema() has cached those parts
17601 ** of the input database schema that could be recovered in temporary table
17602 ** "recovery.schema". This function creates in the output database copies
17603 ** of all parts of that schema that must be created before the tables can
17604 ** be populated. Specifically, this means:
17605 **
17606 **     * all tables that are not VIRTUAL, and
17607 **     * UNIQUE indexes.
17608 **
17609 ** If the recovery handle uses SQL callbacks, then callbacks containing
17610 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
17611 **
17612 ** Additionally, records are added to the sqlite_schema table of the
17613 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
17614 ** records are written directly to sqlite_schema, not actually executed.
17615 ** If the handle is in SQL callback mode, then callbacks are invoked
17616 ** with equivalent SQL statements.
17617 */
recoverWriteSchema1(sqlite3_recover * p)17618 static int recoverWriteSchema1(sqlite3_recover *p){
17619   sqlite3_stmt *pSelect = 0;
17620   sqlite3_stmt *pTblname = 0;
17621 
17622   pSelect = recoverPrepare(p, p->dbOut,
17623       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
17624       "  SELECT rootpage, name, sql, "
17625       "    type='table', "
17626       "    sql LIKE 'create virtual%',"
17627       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
17628       "  FROM recovery.schema"
17629       ")"
17630       "SELECT rootpage, tbl, isVirtual, name, sql"
17631       " FROM dbschema "
17632       "  WHERE tbl OR isIndex"
17633       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
17634   );
17635 
17636   pTblname = recoverPrepare(p, p->dbOut,
17637       "SELECT name FROM sqlite_schema "
17638       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
17639   );
17640 
17641   if( pSelect ){
17642     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
17643     while( sqlite3_step(pSelect)==SQLITE_ROW ){
17644       i64 iRoot = sqlite3_column_int64(pSelect, 0);
17645       int bTable = sqlite3_column_int(pSelect, 1);
17646       int bVirtual = sqlite3_column_int(pSelect, 2);
17647       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
17648       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
17649       char *zFree = 0;
17650       int rc = SQLITE_OK;
17651 
17652       if( bVirtual ){
17653         zSql = (const char*)(zFree = recoverMPrintf(p,
17654             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
17655             zName, zName, zSql
17656         ));
17657       }
17658       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
17659       if( rc==SQLITE_OK ){
17660         recoverSqlCallback(p, zSql);
17661         if( bTable && !bVirtual ){
17662           if( SQLITE_ROW==sqlite3_step(pTblname) ){
17663             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
17664             if( zTbl ) recoverAddTable(p, zTbl, iRoot);
17665           }
17666           recoverReset(p, pTblname);
17667         }
17668       }else if( rc!=SQLITE_ERROR ){
17669         recoverDbError(p, p->dbOut);
17670       }
17671       sqlite3_free(zFree);
17672     }
17673   }
17674   recoverFinalize(p, pSelect);
17675   recoverFinalize(p, pTblname);
17676 
17677   return p->errCode;
17678 }
17679 
17680 /*
17681 ** This function is called after the output database has been populated. It
17682 ** adds all recovered schema elements that were not created in the output
17683 ** database by recoverWriteSchema1() - everything except for tables and
17684 ** UNIQUE indexes. Specifically:
17685 **
17686 **     * views,
17687 **     * triggers,
17688 **     * non-UNIQUE indexes.
17689 **
17690 ** If the recover handle is in SQL callback mode, then equivalent callbacks
17691 ** are issued to create the schema elements.
17692 */
recoverWriteSchema2(sqlite3_recover * p)17693 static int recoverWriteSchema2(sqlite3_recover *p){
17694   sqlite3_stmt *pSelect = 0;
17695 
17696   pSelect = recoverPrepare(p, p->dbOut,
17697       p->bSlowIndexes ?
17698       "SELECT rootpage, sql FROM recovery.schema "
17699       "  WHERE type!='table' AND type!='index'"
17700       :
17701       "SELECT rootpage, sql FROM recovery.schema "
17702       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
17703   );
17704 
17705   if( pSelect ){
17706     while( sqlite3_step(pSelect)==SQLITE_ROW ){
17707       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
17708       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
17709       if( rc==SQLITE_OK ){
17710         recoverSqlCallback(p, zSql);
17711       }else if( rc!=SQLITE_ERROR ){
17712         recoverDbError(p, p->dbOut);
17713       }
17714     }
17715   }
17716   recoverFinalize(p, pSelect);
17717 
17718   return p->errCode;
17719 }
17720 
17721 /*
17722 ** This function is a no-op if recover handle p already contains an error
17723 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
17724 **
17725 ** Otherwise, if the recover handle is configured to create an output
17726 ** database (was created by sqlite3_recover_init()), then this function
17727 ** prepares and returns an SQL statement to INSERT a new record into table
17728 ** pTab, assuming the first nField fields of a record extracted from disk
17729 ** are valid.
17730 **
17731 ** For example, if table pTab is:
17732 **
17733 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
17734 **
17735 ** And nField is 4, then the SQL statement prepared and returned is:
17736 **
17737 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
17738 **
17739 ** In this case even though 4 values were extracted from the input db,
17740 ** only 3 are written to the output, as the generated STORED column
17741 ** cannot be written.
17742 **
17743 ** If the recover handle is in SQL callback mode, then the SQL statement
17744 ** prepared is such that evaluating it returns a single row containing
17745 ** a single text value - itself an SQL statement similar to the above,
17746 ** except with SQL literals in place of the variables. For example:
17747 **
17748 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
17749 **          || quote(?1) || ', '
17750 **          || quote(?2) || ', '
17751 **          || quote(?3) || ')';
17752 **
17753 ** In either case, it is the responsibility of the caller to eventually
17754 ** free the statement handle using sqlite3_finalize().
17755 */
recoverInsertStmt(sqlite3_recover * p,RecoverTable * pTab,int nField)17756 static sqlite3_stmt *recoverInsertStmt(
17757   sqlite3_recover *p,
17758   RecoverTable *pTab,
17759   int nField
17760 ){
17761   sqlite3_stmt *pRet = 0;
17762   const char *zSep = "";
17763   const char *zSqlSep = "";
17764   char *zSql = 0;
17765   char *zFinal = 0;
17766   char *zBind = 0;
17767   int ii;
17768   int bSql = p->xSql ? 1 : 0;
17769 
17770   if( nField<=0 ) return 0;
17771 
17772   assert( nField<=pTab->nCol );
17773 
17774   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
17775 
17776   if( pTab->iRowidBind ){
17777     assert( pTab->bIntkey );
17778     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
17779     if( bSql ){
17780       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
17781     }else{
17782       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
17783     }
17784     zSqlSep = "||', '||";
17785     zSep = ", ";
17786   }
17787 
17788   for(ii=0; ii<nField; ii++){
17789     int eHidden = pTab->aCol[ii].eHidden;
17790     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
17791      && eHidden!=RECOVER_EHIDDEN_STORED
17792     ){
17793       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
17794       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
17795 
17796       if( bSql ){
17797         zBind = recoverMPrintf(p,
17798             "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
17799         );
17800         zSqlSep = "||', '||";
17801       }else{
17802         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
17803       }
17804       zSep = ", ";
17805     }
17806   }
17807 
17808   if( bSql ){
17809     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
17810         zSql, zBind
17811     );
17812   }else{
17813     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
17814   }
17815 
17816   pRet = recoverPrepare(p, p->dbOut, zFinal);
17817   sqlite3_free(zSql);
17818   sqlite3_free(zBind);
17819   sqlite3_free(zFinal);
17820 
17821   return pRet;
17822 }
17823 
17824 
17825 /*
17826 ** Search the list of RecoverTable objects at p->pTblList for one that
17827 ** has root page iRoot in the input database. If such an object is found,
17828 ** return a pointer to it. Otherwise, return NULL.
17829 */
recoverFindTable(sqlite3_recover * p,u32 iRoot)17830 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
17831   RecoverTable *pRet = 0;
17832   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
17833   return pRet;
17834 }
17835 
17836 /*
17837 ** This function attempts to create a lost and found table within the
17838 ** output db. If successful, it returns a pointer to a buffer containing
17839 ** the name of the new table. It is the responsibility of the caller to
17840 ** eventually free this buffer using sqlite3_free().
17841 **
17842 ** If an error occurs, NULL is returned and an error code and error
17843 ** message left in the recover handle.
17844 */
recoverLostAndFoundCreate(sqlite3_recover * p,int nField)17845 static char *recoverLostAndFoundCreate(
17846   sqlite3_recover *p,             /* Recover object */
17847   int nField                      /* Number of column fields in new table */
17848 ){
17849   char *zTbl = 0;
17850   sqlite3_stmt *pProbe = 0;
17851   int ii = 0;
17852 
17853   pProbe = recoverPrepare(p, p->dbOut,
17854     "SELECT 1 FROM sqlite_schema WHERE name=?"
17855   );
17856   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
17857     int bFail = 0;
17858     if( ii<0 ){
17859       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
17860     }else{
17861       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
17862     }
17863 
17864     if( p->errCode==SQLITE_OK ){
17865       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
17866       if( SQLITE_ROW==sqlite3_step(pProbe) ){
17867         bFail = 1;
17868       }
17869       recoverReset(p, pProbe);
17870     }
17871 
17872     if( bFail ){
17873       sqlite3_clear_bindings(pProbe);
17874       sqlite3_free(zTbl);
17875       zTbl = 0;
17876     }
17877   }
17878   recoverFinalize(p, pProbe);
17879 
17880   if( zTbl ){
17881     const char *zSep = 0;
17882     char *zField = 0;
17883     char *zSql = 0;
17884 
17885     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
17886     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
17887       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
17888       zSep = ", ";
17889     }
17890 
17891     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
17892     sqlite3_free(zField);
17893 
17894     recoverExec(p, p->dbOut, zSql);
17895     recoverSqlCallback(p, zSql);
17896     sqlite3_free(zSql);
17897   }else if( p->errCode==SQLITE_OK ){
17898     recoverError(
17899         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
17900     );
17901   }
17902 
17903   return zTbl;
17904 }
17905 
17906 /*
17907 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
17908 ** table in the output database. The name of the table is zTab, and it has
17909 ** nField c* fields.
17910 */
recoverLostAndFoundInsert(sqlite3_recover * p,const char * zTab,int nField)17911 static sqlite3_stmt *recoverLostAndFoundInsert(
17912   sqlite3_recover *p,
17913   const char *zTab,
17914   int nField
17915 ){
17916   int nTotal = nField + 4;
17917   int ii;
17918   char *zBind = 0;
17919   sqlite3_stmt *pRet = 0;
17920 
17921   if( p->xSql==0 ){
17922     for(ii=0; ii<nTotal; ii++){
17923       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
17924     }
17925     pRet = recoverPreparePrintf(
17926         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
17927     );
17928   }else{
17929     const char *zSep = "";
17930     for(ii=0; ii<nTotal; ii++){
17931       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
17932       zSep = "|| ', ' ||";
17933     }
17934     pRet = recoverPreparePrintf(
17935         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
17936     );
17937   }
17938 
17939   sqlite3_free(zBind);
17940   return pRet;
17941 }
17942 
17943 /*
17944 ** Input database page iPg contains data that will be written to the
17945 ** lost-and-found table of the output database. This function attempts
17946 ** to identify the root page of the tree that page iPg belonged to.
17947 ** If successful, it sets output variable (*piRoot) to the page number
17948 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
17949 ** an SQLite error code is returned and the final value of *piRoot
17950 ** undefined.
17951 */
recoverLostAndFoundFindRoot(sqlite3_recover * p,i64 iPg,i64 * piRoot)17952 static int recoverLostAndFoundFindRoot(
17953   sqlite3_recover *p,
17954   i64 iPg,
17955   i64 *piRoot
17956 ){
17957   RecoverStateLAF *pLaf = &p->laf;
17958 
17959   if( pLaf->pFindRoot==0 ){
17960     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
17961         "WITH RECURSIVE p(pgno) AS ("
17962         "  SELECT ?"
17963         "    UNION"
17964         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
17965         ") "
17966         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
17967         "    AND m.parent IS NULL"
17968     );
17969   }
17970   if( p->errCode==SQLITE_OK ){
17971     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
17972     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
17973       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
17974     }else{
17975       *piRoot = iPg;
17976     }
17977     recoverReset(p, pLaf->pFindRoot);
17978   }
17979   return p->errCode;
17980 }
17981 
17982 /*
17983 ** Recover data from page iPage of the input database and write it to
17984 ** the lost-and-found table in the output database.
17985 */
recoverLostAndFoundOnePage(sqlite3_recover * p,i64 iPage)17986 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
17987   RecoverStateLAF *pLaf = &p->laf;
17988   sqlite3_value **apVal = pLaf->apVal;
17989   sqlite3_stmt *pPageData = pLaf->pPageData;
17990   sqlite3_stmt *pInsert = pLaf->pInsert;
17991 
17992   int nVal = -1;
17993   int iPrevCell = 0;
17994   i64 iRoot = 0;
17995   int bHaveRowid = 0;
17996   i64 iRowid = 0;
17997   int ii = 0;
17998 
17999   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
18000   sqlite3_bind_int64(pPageData, 1, iPage);
18001   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
18002     int iCell = sqlite3_column_int64(pPageData, 0);
18003     int iField = sqlite3_column_int64(pPageData, 1);
18004 
18005     if( iPrevCell!=iCell && nVal>=0 ){
18006       /* Insert the new row */
18007       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
18008       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
18009       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
18010       if( bHaveRowid ){
18011         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
18012       }
18013       for(ii=0; ii<nVal; ii++){
18014         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
18015       }
18016       if( sqlite3_step(pInsert)==SQLITE_ROW ){
18017         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
18018       }
18019       recoverReset(p, pInsert);
18020 
18021       /* Discard the accumulated row data */
18022       for(ii=0; ii<nVal; ii++){
18023         sqlite3_value_free(apVal[ii]);
18024         apVal[ii] = 0;
18025       }
18026       sqlite3_clear_bindings(pInsert);
18027       bHaveRowid = 0;
18028       nVal = -1;
18029     }
18030 
18031     if( iCell<0 ) break;
18032 
18033     if( iField<0 ){
18034       assert( nVal==-1 );
18035       iRowid = sqlite3_column_int64(pPageData, 2);
18036       bHaveRowid = 1;
18037       nVal = 0;
18038     }else if( iField<pLaf->nMaxField ){
18039       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
18040       apVal[iField] = sqlite3_value_dup(pVal);
18041       assert( iField==nVal || (nVal==-1 && iField==0) );
18042       nVal = iField+1;
18043       if( apVal[iField]==0 ){
18044         recoverError(p, SQLITE_NOMEM, 0);
18045       }
18046     }
18047 
18048     iPrevCell = iCell;
18049   }
18050   recoverReset(p, pPageData);
18051 
18052   for(ii=0; ii<nVal; ii++){
18053     sqlite3_value_free(apVal[ii]);
18054     apVal[ii] = 0;
18055   }
18056 }
18057 
18058 /*
18059 ** Perform one step (sqlite3_recover_step()) of work for the connection
18060 ** passed as the only argument, which is guaranteed to be in
18061 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
18062 ** table of the output database is populated with recovered data that can
18063 ** not be assigned to any recovered schema object.
18064 */
recoverLostAndFound3Step(sqlite3_recover * p)18065 static int recoverLostAndFound3Step(sqlite3_recover *p){
18066   RecoverStateLAF *pLaf = &p->laf;
18067   if( p->errCode==SQLITE_OK ){
18068     if( pLaf->pInsert==0 ){
18069       return SQLITE_DONE;
18070     }else{
18071       if( p->errCode==SQLITE_OK ){
18072         int res = sqlite3_step(pLaf->pAllPage);
18073         if( res==SQLITE_ROW ){
18074           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
18075           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
18076             recoverLostAndFoundOnePage(p, iPage);
18077           }
18078         }else{
18079           recoverReset(p, pLaf->pAllPage);
18080           return SQLITE_DONE;
18081         }
18082       }
18083     }
18084   }
18085   return SQLITE_OK;
18086 }
18087 
18088 /*
18089 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
18090 ** state - during which the lost-and-found table of the output database
18091 ** is populated with recovered data that can not be assigned to any
18092 ** recovered schema object.
18093 */
recoverLostAndFound3Init(sqlite3_recover * p)18094 static void recoverLostAndFound3Init(sqlite3_recover *p){
18095   RecoverStateLAF *pLaf = &p->laf;
18096 
18097   if( pLaf->nMaxField>0 ){
18098     char *zTab = 0;               /* Name of lost_and_found table */
18099 
18100     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
18101     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
18102     sqlite3_free(zTab);
18103 
18104     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
18105         "WITH RECURSIVE seq(ii) AS ("
18106         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
18107         ")"
18108         "SELECT ii FROM seq" , p->laf.nPg
18109     );
18110     pLaf->pPageData = recoverPrepare(p, p->dbOut,
18111         "SELECT cell, field, value "
18112         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
18113         "UNION ALL "
18114         "SELECT -1, -1, -1"
18115     );
18116 
18117     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
18118         pLaf->nMaxField*sizeof(sqlite3_value*)
18119     );
18120   }
18121 }
18122 
18123 /*
18124 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
18125 ** tables recovered from the schema of the input database are populated with
18126 ** recovered data.
18127 */
recoverWriteDataInit(sqlite3_recover * p)18128 static int recoverWriteDataInit(sqlite3_recover *p){
18129   RecoverStateW1 *p1 = &p->w1;
18130   RecoverTable *pTbl = 0;
18131   int nByte = 0;
18132 
18133   /* Figure out the maximum number of columns for any table in the schema */
18134   assert( p1->nMax==0 );
18135   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
18136     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
18137   }
18138 
18139   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
18140   ** that will be written to the output database in a single row. */
18141   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
18142   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
18143   if( p1->apVal==0 ) return p->errCode;
18144 
18145   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
18146   ** to loop through cells that appear to belong to a single table (pSel). */
18147   p1->pTbls = recoverPrepare(p, p->dbOut,
18148       "SELECT rootpage FROM recovery.schema "
18149       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
18150       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
18151   );
18152   p1->pSel = recoverPrepare(p, p->dbOut,
18153       "WITH RECURSIVE pages(page) AS ("
18154       "  SELECT ?1"
18155       "    UNION"
18156       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
18157       "    WHERE pgno=page"
18158       ") "
18159       "SELECT page, cell, field, value "
18160       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
18161       "UNION ALL "
18162       "SELECT 0, 0, 0, 0"
18163   );
18164 
18165   return p->errCode;
18166 }
18167 
18168 /*
18169 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
18170 ** sqlite3_recover.w1).
18171 */
recoverWriteDataCleanup(sqlite3_recover * p)18172 static void recoverWriteDataCleanup(sqlite3_recover *p){
18173   RecoverStateW1 *p1 = &p->w1;
18174   int ii;
18175   for(ii=0; ii<p1->nVal; ii++){
18176     sqlite3_value_free(p1->apVal[ii]);
18177   }
18178   sqlite3_free(p1->apVal);
18179   recoverFinalize(p, p1->pInsert);
18180   recoverFinalize(p, p1->pTbls);
18181   recoverFinalize(p, p1->pSel);
18182   memset(p1, 0, sizeof(*p1));
18183 }
18184 
18185 /*
18186 ** Perform one step (sqlite3_recover_step()) of work for the connection
18187 ** passed as the only argument, which is guaranteed to be in
18188 ** RECOVER_STATE_WRITING state - during which tables recovered from the
18189 ** schema of the input database are populated with recovered data.
18190 */
recoverWriteDataStep(sqlite3_recover * p)18191 static int recoverWriteDataStep(sqlite3_recover *p){
18192   RecoverStateW1 *p1 = &p->w1;
18193   sqlite3_stmt *pSel = p1->pSel;
18194   sqlite3_value **apVal = p1->apVal;
18195 
18196   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
18197     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
18198       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
18199       p1->pTab = recoverFindTable(p, iRoot);
18200 
18201       recoverFinalize(p, p1->pInsert);
18202       p1->pInsert = 0;
18203 
18204       /* If this table is unknown, return early. The caller will invoke this
18205       ** function again and it will move on to the next table.  */
18206       if( p1->pTab==0 ) return p->errCode;
18207 
18208       /* If this is the sqlite_sequence table, delete any rows added by
18209       ** earlier INSERT statements on tables with AUTOINCREMENT primary
18210       ** keys before recovering its contents. The p1->pTbls SELECT statement
18211       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
18212       ** worry about it being modified after it is recovered. */
18213       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
18214         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
18215         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
18216       }
18217 
18218       /* Bind the root page of this table within the original database to
18219       ** SELECT statement p1->pSel. The SELECT statement will then iterate
18220       ** through cells that look like they belong to table pTab.  */
18221       sqlite3_bind_int64(pSel, 1, iRoot);
18222 
18223       p1->nVal = 0;
18224       p1->bHaveRowid = 0;
18225       p1->iPrevPage = -1;
18226       p1->iPrevCell = -1;
18227     }else{
18228       return SQLITE_DONE;
18229     }
18230   }
18231   assert( p->errCode!=SQLITE_OK || p1->pTab );
18232 
18233   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
18234     RecoverTable *pTab = p1->pTab;
18235 
18236     i64 iPage = sqlite3_column_int64(pSel, 0);
18237     int iCell = sqlite3_column_int(pSel, 1);
18238     int iField = sqlite3_column_int(pSel, 2);
18239     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
18240     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
18241 
18242     assert( bNewCell==0 || (iField==-1 || iField==0) );
18243     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
18244 
18245     if( bNewCell ){
18246       int ii = 0;
18247       if( p1->nVal>=0 ){
18248         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
18249           recoverFinalize(p, p1->pInsert);
18250           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
18251           p1->nInsert = p1->nVal;
18252         }
18253         if( p1->nVal>0 ){
18254           sqlite3_stmt *pInsert = p1->pInsert;
18255           for(ii=0; ii<pTab->nCol; ii++){
18256             RecoverColumn *pCol = &pTab->aCol[ii];
18257             int iBind = pCol->iBind;
18258             if( iBind>0 ){
18259               if( pCol->bIPK ){
18260                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
18261               }else if( pCol->iField<p1->nVal ){
18262                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
18263               }
18264             }
18265           }
18266           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
18267             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
18268           }
18269           if( SQLITE_ROW==sqlite3_step(pInsert) ){
18270             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
18271             recoverSqlCallback(p, z);
18272           }
18273           recoverReset(p, pInsert);
18274           assert( p->errCode || pInsert );
18275           if( pInsert ) sqlite3_clear_bindings(pInsert);
18276         }
18277       }
18278 
18279       for(ii=0; ii<p1->nVal; ii++){
18280         sqlite3_value_free(apVal[ii]);
18281         apVal[ii] = 0;
18282       }
18283       p1->nVal = -1;
18284       p1->bHaveRowid = 0;
18285     }
18286 
18287     if( iPage!=0 ){
18288       if( iField<0 ){
18289         p1->iRowid = sqlite3_column_int64(pSel, 3);
18290         assert( p1->nVal==-1 );
18291         p1->nVal = 0;
18292         p1->bHaveRowid = 1;
18293       }else if( iField<pTab->nCol ){
18294         assert( apVal[iField]==0 );
18295         apVal[iField] = sqlite3_value_dup( pVal );
18296         if( apVal[iField]==0 ){
18297           recoverError(p, SQLITE_NOMEM, 0);
18298         }
18299         p1->nVal = iField+1;
18300       }
18301       p1->iPrevCell = iCell;
18302       p1->iPrevPage = iPage;
18303     }
18304   }else{
18305     recoverReset(p, pSel);
18306     p1->pTab = 0;
18307   }
18308 
18309   return p->errCode;
18310 }
18311 
18312 /*
18313 ** Initialize resources required by sqlite3_recover_step() in
18314 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
18315 ** already allocated to a recovered schema element is determined.
18316 */
recoverLostAndFound1Init(sqlite3_recover * p)18317 static void recoverLostAndFound1Init(sqlite3_recover *p){
18318   RecoverStateLAF *pLaf = &p->laf;
18319   sqlite3_stmt *pStmt = 0;
18320 
18321   assert( p->laf.pUsed==0 );
18322   pLaf->nPg = recoverPageCount(p);
18323   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
18324 
18325   /* Prepare a statement to iterate through all pages that are part of any tree
18326   ** in the recoverable part of the input database schema to the bitmap. And,
18327   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
18328   ** freelist.  */
18329   pStmt = recoverPrepare(
18330       p, p->dbOut,
18331       "WITH trunk(pgno) AS ("
18332       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
18333       "    UNION"
18334       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
18335       "),"
18336       "trunkdata(pgno, data) AS ("
18337       "  SELECT pgno, getpage(pgno) FROM trunk"
18338       "),"
18339       "freelist(data, n, freepgno) AS ("
18340       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
18341       "    UNION ALL"
18342       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
18343       "),"
18344       ""
18345       "roots(r) AS ("
18346       "  SELECT 1 UNION ALL"
18347       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
18348       "),"
18349       "used(page) AS ("
18350       "  SELECT r FROM roots"
18351       "    UNION"
18352       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
18353       "    WHERE pgno=page"
18354       ") "
18355       "SELECT page FROM used"
18356       " UNION ALL "
18357       "SELECT freepgno FROM freelist WHERE NOT ?"
18358   );
18359   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
18360   pLaf->pUsedPages = pStmt;
18361 }
18362 
18363 /*
18364 ** Perform one step (sqlite3_recover_step()) of work for the connection
18365 ** passed as the only argument, which is guaranteed to be in
18366 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
18367 ** already allocated to a recovered schema element is determined.
18368 */
recoverLostAndFound1Step(sqlite3_recover * p)18369 static int recoverLostAndFound1Step(sqlite3_recover *p){
18370   RecoverStateLAF *pLaf = &p->laf;
18371   int rc = p->errCode;
18372   if( rc==SQLITE_OK ){
18373     rc = sqlite3_step(pLaf->pUsedPages);
18374     if( rc==SQLITE_ROW ){
18375       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
18376       recoverBitmapSet(pLaf->pUsed, iPg);
18377       rc = SQLITE_OK;
18378     }else{
18379       recoverFinalize(p, pLaf->pUsedPages);
18380       pLaf->pUsedPages = 0;
18381     }
18382   }
18383   return rc;
18384 }
18385 
18386 /*
18387 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
18388 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
18389 ** are sorted into sets that likely belonged to the same database tree.
18390 */
recoverLostAndFound2Init(sqlite3_recover * p)18391 static void recoverLostAndFound2Init(sqlite3_recover *p){
18392   RecoverStateLAF *pLaf = &p->laf;
18393 
18394   assert( p->laf.pAllAndParent==0 );
18395   assert( p->laf.pMapInsert==0 );
18396   assert( p->laf.pMaxField==0 );
18397   assert( p->laf.nMaxField==0 );
18398 
18399   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
18400       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
18401   );
18402   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
18403       "WITH RECURSIVE seq(ii) AS ("
18404       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
18405       ")"
18406       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
18407       " UNION ALL "
18408       "SELECT NULL, ii FROM seq", p->laf.nPg
18409   );
18410   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
18411       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
18412   );
18413 }
18414 
18415 /*
18416 ** Perform one step (sqlite3_recover_step()) of work for the connection
18417 ** passed as the only argument, which is guaranteed to be in
18418 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
18419 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
18420 ** to the same database tree.
18421 */
recoverLostAndFound2Step(sqlite3_recover * p)18422 static int recoverLostAndFound2Step(sqlite3_recover *p){
18423   RecoverStateLAF *pLaf = &p->laf;
18424   if( p->errCode==SQLITE_OK ){
18425     int res = sqlite3_step(pLaf->pAllAndParent);
18426     if( res==SQLITE_ROW ){
18427       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
18428       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
18429         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
18430         sqlite3_bind_value(pLaf->pMapInsert, 2,
18431             sqlite3_column_value(pLaf->pAllAndParent, 0)
18432         );
18433         sqlite3_step(pLaf->pMapInsert);
18434         recoverReset(p, pLaf->pMapInsert);
18435         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
18436         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
18437           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
18438           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
18439         }
18440         recoverReset(p, pLaf->pMaxField);
18441       }
18442     }else{
18443       recoverFinalize(p, pLaf->pAllAndParent);
18444       pLaf->pAllAndParent =0;
18445       return SQLITE_DONE;
18446     }
18447   }
18448   return p->errCode;
18449 }
18450 
18451 /*
18452 ** Free all resources allocated as part of sqlite3_recover_step() calls
18453 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
18454 */
recoverLostAndFoundCleanup(sqlite3_recover * p)18455 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
18456   recoverBitmapFree(p->laf.pUsed);
18457   p->laf.pUsed = 0;
18458   sqlite3_finalize(p->laf.pUsedPages);
18459   sqlite3_finalize(p->laf.pAllAndParent);
18460   sqlite3_finalize(p->laf.pMapInsert);
18461   sqlite3_finalize(p->laf.pMaxField);
18462   sqlite3_finalize(p->laf.pFindRoot);
18463   sqlite3_finalize(p->laf.pInsert);
18464   sqlite3_finalize(p->laf.pAllPage);
18465   sqlite3_finalize(p->laf.pPageData);
18466   p->laf.pUsedPages = 0;
18467   p->laf.pAllAndParent = 0;
18468   p->laf.pMapInsert = 0;
18469   p->laf.pMaxField = 0;
18470   p->laf.pFindRoot = 0;
18471   p->laf.pInsert = 0;
18472   p->laf.pAllPage = 0;
18473   p->laf.pPageData = 0;
18474   sqlite3_free(p->laf.apVal);
18475   p->laf.apVal = 0;
18476 }
18477 
18478 /*
18479 ** Free all resources allocated as part of sqlite3_recover_step() calls.
18480 */
recoverFinalCleanup(sqlite3_recover * p)18481 static void recoverFinalCleanup(sqlite3_recover *p){
18482   RecoverTable *pTab = 0;
18483   RecoverTable *pNext = 0;
18484 
18485   recoverWriteDataCleanup(p);
18486   recoverLostAndFoundCleanup(p);
18487 
18488   for(pTab=p->pTblList; pTab; pTab=pNext){
18489     pNext = pTab->pNext;
18490     sqlite3_free(pTab);
18491   }
18492   p->pTblList = 0;
18493   sqlite3_finalize(p->pGetPage);
18494   p->pGetPage = 0;
18495   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
18496 
18497   {
18498 #ifndef NDEBUG
18499     int res =
18500 #endif
18501        sqlite3_close(p->dbOut);
18502     assert( res==SQLITE_OK );
18503   }
18504   p->dbOut = 0;
18505 }
18506 
18507 /*
18508 ** Decode and return an unsigned 16-bit big-endian integer value from
18509 ** buffer a[].
18510 */
recoverGetU16(const u8 * a)18511 static u32 recoverGetU16(const u8 *a){
18512   return (((u32)a[0])<<8) + ((u32)a[1]);
18513 }
18514 
18515 /*
18516 ** Decode and return an unsigned 32-bit big-endian integer value from
18517 ** buffer a[].
18518 */
recoverGetU32(const u8 * a)18519 static u32 recoverGetU32(const u8 *a){
18520   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
18521 }
18522 
18523 /*
18524 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
18525 ** and return the number of bytes consumed.
18526 */
recoverGetVarint(const u8 * a,i64 * pVal)18527 static int recoverGetVarint(const u8 *a, i64 *pVal){
18528   sqlite3_uint64 u = 0;
18529   int i;
18530   for(i=0; i<8; i++){
18531     u = (u<<7) + (a[i]&0x7f);
18532     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
18533   }
18534   u = (u<<8) + (a[i]&0xff);
18535   *pVal = (sqlite3_int64)u;
18536   return 9;
18537 }
18538 
18539 /*
18540 ** The second argument points to a buffer n bytes in size. If this buffer
18541 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
18542 ** return the page-size in bytes. Otherwise, if the buffer does not
18543 ** appear to contain a well-formed b-tree page, return 0.
18544 */
recoverIsValidPage(u8 * aTmp,const u8 * a,int n)18545 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
18546   u8 *aUsed = aTmp;
18547   int nFrag = 0;
18548   int nActual = 0;
18549   int iFree = 0;
18550   int nCell = 0;                  /* Number of cells on page */
18551   int iCellOff = 0;               /* Offset of cell array in page */
18552   int iContent = 0;
18553   int eType = 0;
18554   int ii = 0;
18555 
18556   eType = (int)a[0];
18557   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
18558 
18559   iFree = (int)recoverGetU16(&a[1]);
18560   nCell = (int)recoverGetU16(&a[3]);
18561   iContent = (int)recoverGetU16(&a[5]);
18562   if( iContent==0 ) iContent = 65536;
18563   nFrag = (int)a[7];
18564 
18565   if( iContent>n ) return 0;
18566 
18567   memset(aUsed, 0, n);
18568   memset(aUsed, 0xFF, iContent);
18569 
18570   /* Follow the free-list. This is the same format for all b-tree pages. */
18571   if( iFree && iFree<=iContent ) return 0;
18572   while( iFree ){
18573     int iNext = 0;
18574     int nByte = 0;
18575     if( iFree>(n-4) ) return 0;
18576     iNext = recoverGetU16(&a[iFree]);
18577     nByte = recoverGetU16(&a[iFree+2]);
18578     if( iFree+nByte>n || nByte<4 ) return 0;
18579     if( iNext && iNext<iFree+nByte ) return 0;
18580     memset(&aUsed[iFree], 0xFF, nByte);
18581     iFree = iNext;
18582   }
18583 
18584   /* Run through the cells */
18585   if( eType==0x02 || eType==0x05 ){
18586     iCellOff = 12;
18587   }else{
18588     iCellOff = 8;
18589   }
18590   if( (iCellOff + 2*nCell)>iContent ) return 0;
18591   for(ii=0; ii<nCell; ii++){
18592     int iByte;
18593     i64 nPayload = 0;
18594     int nByte = 0;
18595     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
18596     if( iOff<iContent || iOff>n ){
18597       return 0;
18598     }
18599     if( eType==0x05 || eType==0x02 ) nByte += 4;
18600     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
18601     if( eType==0x0D ){
18602       i64 dummy = 0;
18603       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
18604     }
18605     if( eType!=0x05 ){
18606       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
18607       int M = ((n-12)*32/255)-23;
18608       int K = M+((nPayload-M)%(n-4));
18609 
18610       if( nPayload<X ){
18611         nByte += nPayload;
18612       }else if( K<=X ){
18613         nByte += K+4;
18614       }else{
18615         nByte += M+4;
18616       }
18617     }
18618 
18619     if( iOff+nByte>n ){
18620       return 0;
18621     }
18622     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
18623       if( aUsed[iByte]!=0 ){
18624         return 0;
18625       }
18626       aUsed[iByte] = 0xFF;
18627     }
18628   }
18629 
18630   nActual = 0;
18631   for(ii=0; ii<n; ii++){
18632     if( aUsed[ii]==0 ) nActual++;
18633   }
18634   return (nActual==nFrag);
18635 }
18636 
18637 
18638 static int recoverVfsClose(sqlite3_file*);
18639 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
18640 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
18641 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
18642 static int recoverVfsSync(sqlite3_file*, int flags);
18643 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
18644 static int recoverVfsLock(sqlite3_file*, int);
18645 static int recoverVfsUnlock(sqlite3_file*, int);
18646 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
18647 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
18648 static int recoverVfsSectorSize(sqlite3_file*);
18649 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
18650 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
18651 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
18652 static void recoverVfsShmBarrier(sqlite3_file*);
18653 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
18654 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
18655 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
18656 
18657 static sqlite3_io_methods recover_methods = {
18658   2, /* iVersion */
18659   recoverVfsClose,
18660   recoverVfsRead,
18661   recoverVfsWrite,
18662   recoverVfsTruncate,
18663   recoverVfsSync,
18664   recoverVfsFileSize,
18665   recoverVfsLock,
18666   recoverVfsUnlock,
18667   recoverVfsCheckReservedLock,
18668   recoverVfsFileControl,
18669   recoverVfsSectorSize,
18670   recoverVfsDeviceCharacteristics,
18671   recoverVfsShmMap,
18672   recoverVfsShmLock,
18673   recoverVfsShmBarrier,
18674   recoverVfsShmUnmap,
18675   recoverVfsFetch,
18676   recoverVfsUnfetch
18677 };
18678 
recoverVfsClose(sqlite3_file * pFd)18679 static int recoverVfsClose(sqlite3_file *pFd){
18680   assert( pFd->pMethods!=&recover_methods );
18681   return pFd->pMethods->xClose(pFd);
18682 }
18683 
18684 /*
18685 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
18686 */
recoverPutU16(u8 * a,u32 v)18687 static void recoverPutU16(u8 *a, u32 v){
18688   a[0] = (v>>8) & 0x00FF;
18689   a[1] = (v>>0) & 0x00FF;
18690 }
18691 
18692 /*
18693 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
18694 */
recoverPutU32(u8 * a,u32 v)18695 static void recoverPutU32(u8 *a, u32 v){
18696   a[0] = (v>>24) & 0x00FF;
18697   a[1] = (v>>16) & 0x00FF;
18698   a[2] = (v>>8) & 0x00FF;
18699   a[3] = (v>>0) & 0x00FF;
18700 }
18701 
18702 /*
18703 ** Detect the page-size of the database opened by file-handle pFd by
18704 ** searching the first part of the file for a well-formed SQLite b-tree
18705 ** page. If parameter nReserve is non-zero, then as well as searching for
18706 ** a b-tree page with zero reserved bytes, this function searches for one
18707 ** with nReserve reserved bytes at the end of it.
18708 **
18709 ** If successful, set variable p->detected_pgsz to the detected page-size
18710 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
18711 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
18712 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
18713 ** is returned. The final value of p->detected_pgsz is undefined in this
18714 ** case.
18715 */
recoverVfsDetectPagesize(sqlite3_recover * p,sqlite3_file * pFd,u32 nReserve,i64 nSz)18716 static int recoverVfsDetectPagesize(
18717   sqlite3_recover *p,             /* Recover handle */
18718   sqlite3_file *pFd,              /* File-handle open on input database */
18719   u32 nReserve,                   /* Possible nReserve value */
18720   i64 nSz                         /* Size of database file in bytes */
18721 ){
18722   int rc = SQLITE_OK;
18723   const int nMin = 512;
18724   const int nMax = 65536;
18725   const int nMaxBlk = 4;
18726   u32 pgsz = 0;
18727   int iBlk = 0;
18728   u8 *aPg = 0;
18729   u8 *aTmp = 0;
18730   int nBlk = 0;
18731 
18732   aPg = (u8*)sqlite3_malloc(2*nMax);
18733   if( aPg==0 ) return SQLITE_NOMEM;
18734   aTmp = &aPg[nMax];
18735 
18736   nBlk = (nSz+nMax-1)/nMax;
18737   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
18738 
18739   do {
18740     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
18741       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
18742       memset(aPg, 0, nMax);
18743       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
18744       if( rc==SQLITE_OK ){
18745         int pgsz2;
18746         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
18747           int iOff;
18748           for(iOff=0; iOff<nMax; iOff+=pgsz2){
18749             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
18750               pgsz = pgsz2;
18751               break;
18752             }
18753           }
18754         }
18755       }
18756     }
18757     if( pgsz>(u32)p->detected_pgsz ){
18758       p->detected_pgsz = pgsz;
18759       p->nReserve = nReserve;
18760     }
18761     if( nReserve==0 ) break;
18762     nReserve = 0;
18763   }while( 1 );
18764 
18765   p->detected_pgsz = pgsz;
18766   sqlite3_free(aPg);
18767   return rc;
18768 }
18769 
18770 /*
18771 ** The xRead() method of the wrapper VFS. This is used to intercept calls
18772 ** to read page 1 of the input database.
18773 */
recoverVfsRead(sqlite3_file * pFd,void * aBuf,int nByte,i64 iOff)18774 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
18775   int rc = SQLITE_OK;
18776   if( pFd->pMethods==&recover_methods ){
18777     pFd->pMethods = recover_g.pMethods;
18778     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
18779     if( nByte==16 ){
18780       sqlite3_randomness(16, aBuf);
18781     }else
18782     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
18783       /* Ensure that the database has a valid header file. The only fields
18784       ** that really matter to recovery are:
18785       **
18786       **   + Database page size (16-bits at offset 16)
18787       **   + Size of db in pages (32-bits at offset 28)
18788       **   + Database encoding (32-bits at offset 56)
18789       **
18790       ** Also preserved are:
18791       **
18792       **   + first freelist page (32-bits at offset 32)
18793       **   + size of freelist (32-bits at offset 36)
18794       **   + the wal-mode flags (16-bits at offset 18)
18795       **
18796       ** We also try to preserve the auto-vacuum, incr-value, user-version
18797       ** and application-id fields - all 32 bit quantities at offsets
18798       ** 52, 60, 64 and 68. All other fields are set to known good values.
18799       **
18800       ** Byte offset 105 should also contain the page-size as a 16-bit
18801       ** integer.
18802       */
18803       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
18804       u8 aHdr[108] = {
18805         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
18806         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
18807         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
18808         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
18809         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
18810         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
18811         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
18812         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
18813         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
18814         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
18815         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
18816         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
18817         0x00, 0x2e, 0x5b, 0x30,
18818 
18819         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
18820       };
18821       u8 *a = (u8*)aBuf;
18822 
18823       u32 pgsz = recoverGetU16(&a[16]);
18824       u32 nReserve = a[20];
18825       u32 enc = recoverGetU32(&a[56]);
18826       u32 dbsz = 0;
18827       i64 dbFileSize = 0;
18828       int ii;
18829       sqlite3_recover *p = recover_g.p;
18830 
18831       if( pgsz==0x01 ) pgsz = 65536;
18832       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
18833 
18834       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
18835         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
18836       }
18837       if( p->detected_pgsz ){
18838         pgsz = p->detected_pgsz;
18839         nReserve = p->nReserve;
18840       }
18841 
18842       if( pgsz ){
18843         dbsz = dbFileSize / pgsz;
18844       }
18845       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
18846         enc = SQLITE_UTF8;
18847       }
18848 
18849       sqlite3_free(p->pPage1Cache);
18850       p->pPage1Cache = 0;
18851       p->pPage1Disk = 0;
18852 
18853       p->pgsz = nByte;
18854       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
18855       if( p->pPage1Cache ){
18856         p->pPage1Disk = &p->pPage1Cache[nByte];
18857         memcpy(p->pPage1Disk, aBuf, nByte);
18858         aHdr[18] = a[18];
18859         aHdr[19] = a[19];
18860         recoverPutU32(&aHdr[28], dbsz);
18861         recoverPutU32(&aHdr[56], enc);
18862         recoverPutU16(&aHdr[105], pgsz-nReserve);
18863         if( pgsz==65536 ) pgsz = 1;
18864         recoverPutU16(&aHdr[16], pgsz);
18865         aHdr[20] = nReserve;
18866         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
18867           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
18868         }
18869         memcpy(aBuf, aHdr, sizeof(aHdr));
18870         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
18871 
18872         memcpy(p->pPage1Cache, aBuf, nByte);
18873       }else{
18874         rc = p->errCode;
18875       }
18876 
18877     }
18878     pFd->pMethods = &recover_methods;
18879   }else{
18880     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
18881   }
18882   return rc;
18883 }
18884 
18885 /*
18886 ** Used to make sqlite3_io_methods wrapper methods less verbose.
18887 */
18888 #define RECOVER_VFS_WRAPPER(code)                         \
18889   int rc = SQLITE_OK;                                     \
18890   if( pFd->pMethods==&recover_methods ){                  \
18891     pFd->pMethods = recover_g.pMethods;                   \
18892     rc = code;                                            \
18893     pFd->pMethods = &recover_methods;                     \
18894   }else{                                                  \
18895     rc = code;                                            \
18896   }                                                       \
18897   return rc;
18898 
18899 /*
18900 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
18901 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
18902 ** method on the lower level VFS, then reinstall the wrapper before returning.
18903 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
18904 */
recoverVfsWrite(sqlite3_file * pFd,const void * aBuf,int nByte,i64 iOff)18905 static int recoverVfsWrite(
18906   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
18907 ){
18908   RECOVER_VFS_WRAPPER (
18909       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
18910   );
18911 }
recoverVfsTruncate(sqlite3_file * pFd,sqlite3_int64 size)18912 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
18913   RECOVER_VFS_WRAPPER (
18914       pFd->pMethods->xTruncate(pFd, size)
18915   );
18916 }
recoverVfsSync(sqlite3_file * pFd,int flags)18917 static int recoverVfsSync(sqlite3_file *pFd, int flags){
18918   RECOVER_VFS_WRAPPER (
18919       pFd->pMethods->xSync(pFd, flags)
18920   );
18921 }
recoverVfsFileSize(sqlite3_file * pFd,sqlite3_int64 * pSize)18922 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
18923   RECOVER_VFS_WRAPPER (
18924       pFd->pMethods->xFileSize(pFd, pSize)
18925   );
18926 }
recoverVfsLock(sqlite3_file * pFd,int eLock)18927 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
18928   RECOVER_VFS_WRAPPER (
18929       pFd->pMethods->xLock(pFd, eLock)
18930   );
18931 }
recoverVfsUnlock(sqlite3_file * pFd,int eLock)18932 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
18933   RECOVER_VFS_WRAPPER (
18934       pFd->pMethods->xUnlock(pFd, eLock)
18935   );
18936 }
recoverVfsCheckReservedLock(sqlite3_file * pFd,int * pResOut)18937 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
18938   RECOVER_VFS_WRAPPER (
18939       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
18940   );
18941 }
recoverVfsFileControl(sqlite3_file * pFd,int op,void * pArg)18942 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
18943   RECOVER_VFS_WRAPPER (
18944     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
18945   );
18946 }
recoverVfsSectorSize(sqlite3_file * pFd)18947 static int recoverVfsSectorSize(sqlite3_file *pFd){
18948   RECOVER_VFS_WRAPPER (
18949       pFd->pMethods->xSectorSize(pFd)
18950   );
18951 }
recoverVfsDeviceCharacteristics(sqlite3_file * pFd)18952 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
18953   RECOVER_VFS_WRAPPER (
18954       pFd->pMethods->xDeviceCharacteristics(pFd)
18955   );
18956 }
recoverVfsShmMap(sqlite3_file * pFd,int iPg,int pgsz,int bExtend,void volatile ** pp)18957 static int recoverVfsShmMap(
18958   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
18959 ){
18960   RECOVER_VFS_WRAPPER (
18961       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
18962   );
18963 }
recoverVfsShmLock(sqlite3_file * pFd,int offset,int n,int flags)18964 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
18965   RECOVER_VFS_WRAPPER (
18966       pFd->pMethods->xShmLock(pFd, offset, n, flags)
18967   );
18968 }
recoverVfsShmBarrier(sqlite3_file * pFd)18969 static void recoverVfsShmBarrier(sqlite3_file *pFd){
18970   if( pFd->pMethods==&recover_methods ){
18971     pFd->pMethods = recover_g.pMethods;
18972     pFd->pMethods->xShmBarrier(pFd);
18973     pFd->pMethods = &recover_methods;
18974   }else{
18975     pFd->pMethods->xShmBarrier(pFd);
18976   }
18977 }
recoverVfsShmUnmap(sqlite3_file * pFd,int deleteFlag)18978 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
18979   RECOVER_VFS_WRAPPER (
18980       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
18981   );
18982 }
18983 
recoverVfsFetch(sqlite3_file * pFd,sqlite3_int64 iOff,int iAmt,void ** pp)18984 static int recoverVfsFetch(
18985   sqlite3_file *pFd,
18986   sqlite3_int64 iOff,
18987   int iAmt,
18988   void **pp
18989 ){
18990   (void)pFd;
18991   (void)iOff;
18992   (void)iAmt;
18993   *pp = 0;
18994   return SQLITE_OK;
18995 }
recoverVfsUnfetch(sqlite3_file * pFd,sqlite3_int64 iOff,void * p)18996 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
18997   (void)pFd;
18998   (void)iOff;
18999   (void)p;
19000   return SQLITE_OK;
19001 }
19002 
19003 /*
19004 ** Install the VFS wrapper around the file-descriptor open on the input
19005 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
19006 ** when this function is called.
19007 */
recoverInstallWrapper(sqlite3_recover * p)19008 static void recoverInstallWrapper(sqlite3_recover *p){
19009   sqlite3_file *pFd = 0;
19010   assert( recover_g.pMethods==0 );
19011   recoverAssertMutexHeld();
19012   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
19013   assert( pFd==0 || pFd->pMethods!=&recover_methods );
19014   if( pFd && pFd->pMethods ){
19015     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
19016     recover_g.pMethods = pFd->pMethods;
19017     recover_g.p = p;
19018     recover_methods.iVersion = iVersion;
19019     pFd->pMethods = &recover_methods;
19020   }
19021 }
19022 
19023 /*
19024 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
19025 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
19026 ** held when this function is called.
19027 */
recoverUninstallWrapper(sqlite3_recover * p)19028 static void recoverUninstallWrapper(sqlite3_recover *p){
19029   sqlite3_file *pFd = 0;
19030   recoverAssertMutexHeld();
19031   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
19032   if( pFd && pFd->pMethods ){
19033     pFd->pMethods = recover_g.pMethods;
19034     recover_g.pMethods = 0;
19035     recover_g.p = 0;
19036   }
19037 }
19038 
19039 /*
19040 ** This function does the work of a single sqlite3_recover_step() call. It
19041 ** is guaranteed that the handle is not in an error state when this
19042 ** function is called.
19043 */
recoverStep(sqlite3_recover * p)19044 static void recoverStep(sqlite3_recover *p){
19045   assert( p && p->errCode==SQLITE_OK );
19046   switch( p->eState ){
19047     case RECOVER_STATE_INIT:
19048       /* This is the very first call to sqlite3_recover_step() on this object.
19049       */
19050       recoverSqlCallback(p, "BEGIN");
19051       recoverSqlCallback(p, "PRAGMA writable_schema = on");
19052 
19053       recoverEnterMutex();
19054       recoverInstallWrapper(p);
19055 
19056       /* Open the output database. And register required virtual tables and
19057       ** user functions with the new handle. */
19058       recoverOpenOutput(p);
19059 
19060       /* Open transactions on both the input and output databases. */
19061       sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
19062       recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
19063       recoverExec(p, p->dbIn, "BEGIN");
19064       if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
19065       recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
19066       recoverTransferSettings(p);
19067       recoverOpenRecovery(p);
19068       recoverCacheSchema(p);
19069 
19070       recoverUninstallWrapper(p);
19071       recoverLeaveMutex();
19072 
19073       recoverExec(p, p->dbOut, "BEGIN");
19074 
19075       recoverWriteSchema1(p);
19076       p->eState = RECOVER_STATE_WRITING;
19077       break;
19078 
19079     case RECOVER_STATE_WRITING: {
19080       if( p->w1.pTbls==0 ){
19081         recoverWriteDataInit(p);
19082       }
19083       if( SQLITE_DONE==recoverWriteDataStep(p) ){
19084         recoverWriteDataCleanup(p);
19085         if( p->zLostAndFound ){
19086           p->eState = RECOVER_STATE_LOSTANDFOUND1;
19087         }else{
19088           p->eState = RECOVER_STATE_SCHEMA2;
19089         }
19090       }
19091       break;
19092     }
19093 
19094     case RECOVER_STATE_LOSTANDFOUND1: {
19095       if( p->laf.pUsed==0 ){
19096         recoverLostAndFound1Init(p);
19097       }
19098       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
19099         p->eState = RECOVER_STATE_LOSTANDFOUND2;
19100       }
19101       break;
19102     }
19103     case RECOVER_STATE_LOSTANDFOUND2: {
19104       if( p->laf.pAllAndParent==0 ){
19105         recoverLostAndFound2Init(p);
19106       }
19107       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
19108         p->eState = RECOVER_STATE_LOSTANDFOUND3;
19109       }
19110       break;
19111     }
19112 
19113     case RECOVER_STATE_LOSTANDFOUND3: {
19114       if( p->laf.pInsert==0 ){
19115         recoverLostAndFound3Init(p);
19116       }
19117       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
19118         p->eState = RECOVER_STATE_SCHEMA2;
19119       }
19120       break;
19121     }
19122 
19123     case RECOVER_STATE_SCHEMA2: {
19124       int rc = SQLITE_OK;
19125 
19126       recoverWriteSchema2(p);
19127       p->eState = RECOVER_STATE_DONE;
19128 
19129       /* If no error has occurred, commit the write transaction on the output
19130       ** database. Regardless of whether or not an error has occurred, make
19131       ** an attempt to end the read transaction on the input database.  */
19132       recoverExec(p, p->dbOut, "COMMIT");
19133       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
19134       if( p->errCode==SQLITE_OK ) p->errCode = rc;
19135 
19136       recoverSqlCallback(p, "PRAGMA writable_schema = off");
19137       recoverSqlCallback(p, "COMMIT");
19138       p->eState = RECOVER_STATE_DONE;
19139       recoverFinalCleanup(p);
19140       break;
19141     };
19142 
19143     case RECOVER_STATE_DONE: {
19144       /* no-op */
19145       break;
19146     };
19147   }
19148 }
19149 
19150 
19151 /*
19152 ** This is a worker function that does the heavy lifting for both init
19153 ** functions:
19154 **
19155 **     sqlite3_recover_init()
19156 **     sqlite3_recover_init_sql()
19157 **
19158 ** All this function does is allocate space for the recover handle and
19159 ** take copies of the input parameters. All the real work is done within
19160 ** sqlite3_recover_run().
19161 */
recoverInit(sqlite3 * db,const char * zDb,const char * zUri,int (* xSql)(void *,const char *),void * pSqlCtx)19162 sqlite3_recover *recoverInit(
19163   sqlite3* db,
19164   const char *zDb,
19165   const char *zUri,               /* Output URI for _recover_init() */
19166   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
19167   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
19168 ){
19169   sqlite3_recover *pRet = 0;
19170   int nDb = 0;
19171   int nUri = 0;
19172   int nByte = 0;
19173 
19174   if( zDb==0 ){ zDb = "main"; }
19175 
19176   nDb = recoverStrlen(zDb);
19177   nUri = recoverStrlen(zUri);
19178 
19179   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
19180   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
19181   if( pRet ){
19182     memset(pRet, 0, nByte);
19183     pRet->dbIn = db;
19184     pRet->zDb = (char*)&pRet[1];
19185     pRet->zUri = &pRet->zDb[nDb+1];
19186     memcpy(pRet->zDb, zDb, nDb);
19187     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
19188     pRet->xSql = xSql;
19189     pRet->pSqlCtx = pSqlCtx;
19190     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
19191   }
19192 
19193   return pRet;
19194 }
19195 
19196 /*
19197 ** Initialize a recovery handle that creates a new database containing
19198 ** the recovered data.
19199 */
sqlite3_recover_init(sqlite3 * db,const char * zDb,const char * zUri)19200 sqlite3_recover *sqlite3_recover_init(
19201   sqlite3* db,
19202   const char *zDb,
19203   const char *zUri
19204 ){
19205   return recoverInit(db, zDb, zUri, 0, 0);
19206 }
19207 
19208 /*
19209 ** Initialize a recovery handle that returns recovered data in the
19210 ** form of SQL statements via a callback.
19211 */
sqlite3_recover_init_sql(sqlite3 * db,const char * zDb,int (* xSql)(void *,const char *),void * pSqlCtx)19212 sqlite3_recover *sqlite3_recover_init_sql(
19213   sqlite3* db,
19214   const char *zDb,
19215   int (*xSql)(void*, const char*),
19216   void *pSqlCtx
19217 ){
19218   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
19219 }
19220 
19221 /*
19222 ** Return the handle error message, if any.
19223 */
sqlite3_recover_errmsg(sqlite3_recover * p)19224 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
19225   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
19226 }
19227 
19228 /*
19229 ** Return the handle error code.
19230 */
sqlite3_recover_errcode(sqlite3_recover * p)19231 int sqlite3_recover_errcode(sqlite3_recover *p){
19232   return p ? p->errCode : SQLITE_NOMEM;
19233 }
19234 
19235 /*
19236 ** Configure the handle.
19237 */
sqlite3_recover_config(sqlite3_recover * p,int op,void * pArg)19238 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
19239   int rc = SQLITE_OK;
19240   if( p==0 ){
19241     rc = SQLITE_NOMEM;
19242   }else if( p->eState!=RECOVER_STATE_INIT ){
19243     rc = SQLITE_MISUSE;
19244   }else{
19245     switch( op ){
19246       case 789:
19247         /* This undocumented magic configuration option is used to set the
19248         ** name of the auxiliary database that is ATTACH-ed to the database
19249         ** connection and used to hold state information during the
19250         ** recovery process.  This option is for debugging use only and
19251         ** is subject to change or removal at any time. */
19252         sqlite3_free(p->zStateDb);
19253         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
19254         break;
19255 
19256       case SQLITE_RECOVER_LOST_AND_FOUND: {
19257         const char *zArg = (const char*)pArg;
19258         sqlite3_free(p->zLostAndFound);
19259         if( zArg ){
19260           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
19261         }else{
19262           p->zLostAndFound = 0;
19263         }
19264         break;
19265       }
19266 
19267       case SQLITE_RECOVER_FREELIST_CORRUPT:
19268         p->bFreelistCorrupt = *(int*)pArg;
19269         break;
19270 
19271       case SQLITE_RECOVER_ROWIDS:
19272         p->bRecoverRowid = *(int*)pArg;
19273         break;
19274 
19275       case SQLITE_RECOVER_SLOWINDEXES:
19276         p->bSlowIndexes = *(int*)pArg;
19277         break;
19278 
19279       default:
19280         rc = SQLITE_NOTFOUND;
19281         break;
19282     }
19283   }
19284 
19285   return rc;
19286 }
19287 
19288 /*
19289 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
19290 ** no error has occurred but database recovery is not finished, SQLITE_DONE
19291 ** if database recovery has been successfully completed, or an SQLite
19292 ** error code if an error has occurred.
19293 */
sqlite3_recover_step(sqlite3_recover * p)19294 int sqlite3_recover_step(sqlite3_recover *p){
19295   if( p==0 ) return SQLITE_NOMEM;
19296   if( p->errCode==SQLITE_OK ) recoverStep(p);
19297   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
19298     return SQLITE_DONE;
19299   }
19300   return p->errCode;
19301 }
19302 
19303 /*
19304 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
19305 ** else an SQLite error code.
19306 */
sqlite3_recover_run(sqlite3_recover * p)19307 int sqlite3_recover_run(sqlite3_recover *p){
19308   while( SQLITE_OK==sqlite3_recover_step(p) );
19309   return sqlite3_recover_errcode(p);
19310 }
19311 
19312 
19313 /*
19314 ** Free all resources associated with the recover handle passed as the only
19315 ** argument. The results of using a handle with any sqlite3_recover_**
19316 ** API function after it has been passed to this function are undefined.
19317 **
19318 ** A copy of the value returned by the first call made to sqlite3_recover_run()
19319 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
19320 ** not been called on this handle.
19321 */
sqlite3_recover_finish(sqlite3_recover * p)19322 int sqlite3_recover_finish(sqlite3_recover *p){
19323   int rc;
19324   if( p==0 ){
19325     rc = SQLITE_NOMEM;
19326   }else{
19327     recoverFinalCleanup(p);
19328     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
19329       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
19330       if( p->errCode==SQLITE_OK ) p->errCode = rc;
19331     }
19332     rc = p->errCode;
19333     sqlite3_free(p->zErrMsg);
19334     sqlite3_free(p->zStateDb);
19335     sqlite3_free(p->zLostAndFound);
19336     sqlite3_free(p->pPage1Cache);
19337     sqlite3_free(p);
19338   }
19339   return rc;
19340 }
19341 
19342 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
19343 
19344 /************************* End ../ext/recover/sqlite3recover.c ********************/
19345 # endif /* SQLITE_HAVE_SQLITE3R */
19346 #endif
19347 #ifdef SQLITE_SHELL_EXTSRC
19348 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
19349 #endif
19350 
19351 #if defined(SQLITE_ENABLE_SESSION)
19352 /*
19353 ** State information for a single open session
19354 */
19355 typedef struct OpenSession OpenSession;
19356 struct OpenSession {
19357   char *zName;             /* Symbolic name for this session */
19358   int nFilter;             /* Number of xFilter rejection GLOB patterns */
19359   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
19360   sqlite3_session *p;      /* The open session */
19361 };
19362 #endif
19363 
19364 typedef struct ExpertInfo ExpertInfo;
19365 struct ExpertInfo {
19366   sqlite3expert *pExpert;
19367   int bVerbose;
19368 };
19369 
19370 /* A single line in the EQP output */
19371 typedef struct EQPGraphRow EQPGraphRow;
19372 struct EQPGraphRow {
19373   int iEqpId;           /* ID for this row */
19374   int iParentId;        /* ID of the parent row */
19375   EQPGraphRow *pNext;   /* Next row in sequence */
19376   char zText[1];        /* Text to display for this row */
19377 };
19378 
19379 /* All EQP output is collected into an instance of the following */
19380 typedef struct EQPGraph EQPGraph;
19381 struct EQPGraph {
19382   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
19383   EQPGraphRow *pLast;   /* Last element of the pRow list */
19384   char zPrefix[100];    /* Graph prefix */
19385 };
19386 
19387 /* Parameters affecting columnar mode result display (defaulting together) */
19388 typedef struct ColModeOpts {
19389   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
19390   u8 bQuote;            /* Quote results for .mode box and table */
19391   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
19392 } ColModeOpts;
19393 #define ColModeOpts_default { 60, 0, 0 }
19394 #define ColModeOpts_default_qbox { 60, 1, 0 }
19395 
19396 /*
19397 ** State information about the database connection is contained in an
19398 ** instance of the following structure.
19399 */
19400 typedef struct ShellState ShellState;
19401 struct ShellState {
19402   sqlite3 *db;           /* The database */
19403   u8 autoExplain;        /* Automatically turn on .explain mode */
19404   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
19405   u8 autoEQPtest;        /* autoEQP is in test mode */
19406   u8 autoEQPtrace;       /* autoEQP is in trace mode */
19407   u8 scanstatsOn;        /* True to display scan stats before each finalize */
19408   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
19409   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
19410   u8 nEqpLevel;          /* Depth of the EQP output graph */
19411   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
19412   u8 bSafeMode;          /* True to prohibit unsafe operations */
19413   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
19414   u8 eRestoreState;      /* See comments above doAutoDetectRestore() */
19415   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
19416   unsigned statsOn;      /* True to display memory stats before each finalize */
19417   unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
19418   int inputNesting;      /* Track nesting level of .read and other redirects */
19419   int outCount;          /* Revert to stdout when reaching zero */
19420   int cnt;               /* Number of records displayed so far */
19421   int lineno;            /* Line number of last line read from in */
19422   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
19423   FILE *in;              /* Read commands from this stream */
19424   FILE *out;             /* Write results here */
19425   FILE *traceOut;        /* Output for sqlite3_trace() */
19426   int nErr;              /* Number of errors seen */
19427   int mode;              /* An output mode setting */
19428   int modePrior;         /* Saved mode */
19429   int cMode;             /* temporary output mode for the current query */
19430   int normalMode;        /* Output mode before ".explain on" */
19431   int writableSchema;    /* True if PRAGMA writable_schema=ON */
19432   int showHeader;        /* True to show column names in List or Column mode */
19433   int nCheck;            /* Number of ".check" commands run */
19434   unsigned nProgress;    /* Number of progress callbacks encountered */
19435   unsigned mxProgress;   /* Maximum progress callbacks before failing */
19436   unsigned flgProgress;  /* Flags for the progress callback */
19437   unsigned shellFlgs;    /* Various flags */
19438   unsigned priorShFlgs;  /* Saved copy of flags */
19439   sqlite3_int64 szMax;   /* --maxsize argument to .open */
19440   char *zDestTable;      /* Name of destination table when MODE_Insert */
19441   char *zTempFile;       /* Temporary file that might need deleting */
19442   char zTestcase[30];    /* Name of current test case */
19443   char colSeparator[20]; /* Column separator character for several modes */
19444   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
19445   char colSepPrior[20];  /* Saved column separator */
19446   char rowSepPrior[20];  /* Saved row separator */
19447   int *colWidth;         /* Requested width of each column in columnar modes */
19448   int *actualWidth;      /* Actual width of each column */
19449   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
19450   char nullValue[20];    /* The text to print when a NULL comes back from
19451                          ** the database */
19452   char outfile[FILENAME_MAX]; /* Filename for *out */
19453   sqlite3_stmt *pStmt;   /* Current statement if any. */
19454   FILE *pLog;            /* Write log output here */
19455   struct AuxDb {         /* Storage space for auxiliary database connections */
19456     sqlite3 *db;               /* Connection pointer */
19457     const char *zDbFilename;   /* Filename used to open the connection */
19458     char *zFreeOnClose;        /* Free this memory allocation on close */
19459 #if defined(SQLITE_ENABLE_SESSION)
19460     int nSession;              /* Number of active sessions */
19461     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
19462 #endif
19463   } aAuxDb[5],           /* Array of all database connections */
19464     *pAuxDb;             /* Currently active database connection */
19465   int *aiIndent;         /* Array of indents used in MODE_Explain */
19466   int nIndent;           /* Size of array aiIndent[] */
19467   int iIndent;           /* Index of current op in aiIndent[] */
19468   char *zNonce;          /* Nonce for temporary safe-mode escapes */
19469   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
19470   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
19471 #ifdef SQLITE_SHELL_FIDDLE
19472   struct {
19473     const char * zInput; /* Input string from wasm/JS proxy */
19474     const char * zPos;   /* Cursor pos into zInput */
19475     const char * zDefaultDbName; /* Default name for db file */
19476   } wasm;
19477 #endif
19478 };
19479 
19480 #ifdef SQLITE_SHELL_FIDDLE
19481 static ShellState shellState;
19482 #endif
19483 
19484 
19485 /* Allowed values for ShellState.autoEQP
19486 */
19487 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
19488 #define AUTOEQP_on       1           /* Automatic EQP is on */
19489 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
19490 #define AUTOEQP_full     3           /* Show full EXPLAIN */
19491 
19492 /* Allowed values for ShellState.openMode
19493 */
19494 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
19495 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
19496 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
19497 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
19498 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
19499 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
19500 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
19501 
19502 /* Allowed values for ShellState.eTraceType
19503 */
19504 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
19505 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
19506 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
19507 
19508 /* Bits in the ShellState.flgProgress variable */
19509 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
19510 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
19511                                    ** callback limit is reached, and for each
19512                                    ** top-level SQL statement */
19513 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
19514 
19515 /*
19516 ** These are the allowed shellFlgs values
19517 */
19518 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
19519 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
19520 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
19521 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
19522 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
19523 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
19524 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
19525 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
19526 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
19527 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
19528 #define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
19529 
19530 /*
19531 ** Macros for testing and setting shellFlgs
19532 */
19533 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
19534 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
19535 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
19536 
19537 /*
19538 ** These are the allowed modes.
19539 */
19540 #define MODE_Line     0  /* One column per line.  Blank line between records */
19541 #define MODE_Column   1  /* One record per line in neat columns */
19542 #define MODE_List     2  /* One record per line with a separator */
19543 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
19544 #define MODE_Html     4  /* Generate an XHTML table */
19545 #define MODE_Insert   5  /* Generate SQL "insert" statements */
19546 #define MODE_Quote    6  /* Quote values as for SQL */
19547 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
19548 #define MODE_Csv      8  /* Quote strings, numbers are plain */
19549 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
19550 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
19551 #define MODE_Pretty  11  /* Pretty-print schemas */
19552 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
19553 #define MODE_Json    13  /* Output JSON */
19554 #define MODE_Markdown 14 /* Markdown formatting */
19555 #define MODE_Table   15  /* MySQL-style table formatting */
19556 #define MODE_Box     16  /* Unicode box-drawing characters */
19557 #define MODE_Count   17  /* Output only a count of the rows of output */
19558 #define MODE_Off     18  /* No query output shown */
19559 #define MODE_ScanExp 19  /* Like MODE_Explain, but for ".scanstats vm" */
19560 
19561 static const char *modeDescr[] = {
19562   "line",
19563   "column",
19564   "list",
19565   "semi",
19566   "html",
19567   "insert",
19568   "quote",
19569   "tcl",
19570   "csv",
19571   "explain",
19572   "ascii",
19573   "prettyprint",
19574   "eqp",
19575   "json",
19576   "markdown",
19577   "table",
19578   "box",
19579   "count",
19580   "off"
19581 };
19582 
19583 /*
19584 ** These are the column/row/line separators used by the various
19585 ** import/export modes.
19586 */
19587 #define SEP_Column    "|"
19588 #define SEP_Row       "\n"
19589 #define SEP_Tab       "\t"
19590 #define SEP_Space     " "
19591 #define SEP_Comma     ","
19592 #define SEP_CrLf      "\r\n"
19593 #define SEP_Unit      "\x1F"
19594 #define SEP_Record    "\x1E"
19595 
19596 /*
19597 ** Limit input nesting via .read or any other input redirect.
19598 ** It's not too expensive, so a generous allowance can be made.
19599 */
19600 #define MAX_INPUT_NESTING 25
19601 
19602 /*
19603 ** A callback for the sqlite3_log() interface.
19604 */
shellLog(void * pArg,int iErrCode,const char * zMsg)19605 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
19606   ShellState *p = (ShellState*)pArg;
19607   if( p->pLog==0 ) return;
19608   sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
19609   fflush(p->pLog);
19610 }
19611 
19612 /*
19613 ** SQL function:  shell_putsnl(X)
19614 **
19615 ** Write the text X to the screen (or whatever output is being directed)
19616 ** adding a newline at the end, and then return X.
19617 */
shellPutsFunc(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)19618 static void shellPutsFunc(
19619   sqlite3_context *pCtx,
19620   int nVal,
19621   sqlite3_value **apVal
19622 ){
19623   /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
19624   (void)nVal;
19625   oputf("%s\n", sqlite3_value_text(apVal[0]));
19626   sqlite3_result_value(pCtx, apVal[0]);
19627 }
19628 
19629 /*
19630 ** If in safe mode, print an error message described by the arguments
19631 ** and exit immediately.
19632 */
failIfSafeMode(ShellState * p,const char * zErrMsg,...)19633 static void failIfSafeMode(
19634   ShellState *p,
19635   const char *zErrMsg,
19636   ...
19637 ){
19638   if( p->bSafeMode ){
19639     va_list ap;
19640     char *zMsg;
19641     va_start(ap, zErrMsg);
19642     zMsg = sqlite3_vmprintf(zErrMsg, ap);
19643     va_end(ap);
19644     eputf("line %d: %s\n", p->lineno, zMsg);
19645     exit(1);
19646   }
19647 }
19648 
19649 /*
19650 ** SQL function:   edit(VALUE)
19651 **                 edit(VALUE,EDITOR)
19652 **
19653 ** These steps:
19654 **
19655 **     (1) Write VALUE into a temporary file.
19656 **     (2) Run program EDITOR on that temporary file.
19657 **     (3) Read the temporary file back and return its content as the result.
19658 **     (4) Delete the temporary file
19659 **
19660 ** If the EDITOR argument is omitted, use the value in the VISUAL
19661 ** environment variable.  If still there is no EDITOR, through an error.
19662 **
19663 ** Also throw an error if the EDITOR program returns a non-zero exit code.
19664 */
19665 #ifndef SQLITE_NOHAVE_SYSTEM
editFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)19666 static void editFunc(
19667   sqlite3_context *context,
19668   int argc,
19669   sqlite3_value **argv
19670 ){
19671   const char *zEditor;
19672   char *zTempFile = 0;
19673   sqlite3 *db;
19674   char *zCmd = 0;
19675   int bBin;
19676   int rc;
19677   int hasCRNL = 0;
19678   FILE *f = 0;
19679   sqlite3_int64 sz;
19680   sqlite3_int64 x;
19681   unsigned char *p = 0;
19682 
19683   if( argc==2 ){
19684     zEditor = (const char*)sqlite3_value_text(argv[1]);
19685   }else{
19686     zEditor = getenv("VISUAL");
19687   }
19688   if( zEditor==0 ){
19689     sqlite3_result_error(context, "no editor for edit()", -1);
19690     return;
19691   }
19692   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
19693     sqlite3_result_error(context, "NULL input to edit()", -1);
19694     return;
19695   }
19696   db = sqlite3_context_db_handle(context);
19697   zTempFile = 0;
19698   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
19699   if( zTempFile==0 ){
19700     sqlite3_uint64 r = 0;
19701     sqlite3_randomness(sizeof(r), &r);
19702     zTempFile = sqlite3_mprintf("temp%llx", r);
19703     if( zTempFile==0 ){
19704       sqlite3_result_error_nomem(context);
19705       return;
19706     }
19707   }
19708   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
19709   /* When writing the file to be edited, do \n to \r\n conversions on systems
19710   ** that want \r\n line endings */
19711   f = fopen(zTempFile, bBin ? "wb" : "w");
19712   if( f==0 ){
19713     sqlite3_result_error(context, "edit() cannot open temp file", -1);
19714     goto edit_func_end;
19715   }
19716   sz = sqlite3_value_bytes(argv[0]);
19717   if( bBin ){
19718     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
19719   }else{
19720     const char *z = (const char*)sqlite3_value_text(argv[0]);
19721     /* Remember whether or not the value originally contained \r\n */
19722     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
19723     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
19724   }
19725   fclose(f);
19726   f = 0;
19727   if( x!=sz ){
19728     sqlite3_result_error(context, "edit() could not write the whole file", -1);
19729     goto edit_func_end;
19730   }
19731   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
19732   if( zCmd==0 ){
19733     sqlite3_result_error_nomem(context);
19734     goto edit_func_end;
19735   }
19736   rc = system(zCmd);
19737   sqlite3_free(zCmd);
19738   if( rc ){
19739     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
19740     goto edit_func_end;
19741   }
19742   f = fopen(zTempFile, "rb");
19743   if( f==0 ){
19744     sqlite3_result_error(context,
19745       "edit() cannot reopen temp file after edit", -1);
19746     goto edit_func_end;
19747   }
19748   fseek(f, 0, SEEK_END);
19749   sz = ftell(f);
19750   rewind(f);
19751   p = sqlite3_malloc64( sz+1 );
19752   if( p==0 ){
19753     sqlite3_result_error_nomem(context);
19754     goto edit_func_end;
19755   }
19756   x = fread(p, 1, (size_t)sz, f);
19757   fclose(f);
19758   f = 0;
19759   if( x!=sz ){
19760     sqlite3_result_error(context, "could not read back the whole file", -1);
19761     goto edit_func_end;
19762   }
19763   if( bBin ){
19764     sqlite3_result_blob64(context, p, sz, sqlite3_free);
19765   }else{
19766     sqlite3_int64 i, j;
19767     if( hasCRNL ){
19768       /* If the original contains \r\n then do no conversions back to \n */
19769     }else{
19770       /* If the file did not originally contain \r\n then convert any new
19771       ** \r\n back into \n */
19772       p[sz] = 0;
19773       for(i=j=0; i<sz; i++){
19774         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
19775         p[j++] = p[i];
19776       }
19777       sz = j;
19778       p[sz] = 0;
19779     }
19780     sqlite3_result_text64(context, (const char*)p, sz,
19781                           sqlite3_free, SQLITE_UTF8);
19782   }
19783   p = 0;
19784 
19785 edit_func_end:
19786   if( f ) fclose(f);
19787   unlink(zTempFile);
19788   sqlite3_free(zTempFile);
19789   sqlite3_free(p);
19790 }
19791 #endif /* SQLITE_NOHAVE_SYSTEM */
19792 
19793 /*
19794 ** Save or restore the current output mode
19795 */
outputModePush(ShellState * p)19796 static void outputModePush(ShellState *p){
19797   p->modePrior = p->mode;
19798   p->priorShFlgs = p->shellFlgs;
19799   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
19800   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
19801 }
outputModePop(ShellState * p)19802 static void outputModePop(ShellState *p){
19803   p->mode = p->modePrior;
19804   p->shellFlgs = p->priorShFlgs;
19805   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
19806   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
19807 }
19808 
19809 /*
19810 ** Output the given string as a hex-encoded blob (eg. X'1234' )
19811 */
output_hex_blob(const void * pBlob,int nBlob)19812 static void output_hex_blob(const void *pBlob, int nBlob){
19813   int i;
19814   unsigned char *aBlob = (unsigned char*)pBlob;
19815 
19816   char *zStr = sqlite3_malloc(nBlob*2 + 1);
19817   shell_check_oom(zStr);
19818 
19819   for(i=0; i<nBlob; i++){
19820     static const char aHex[] = {
19821         '0', '1', '2', '3', '4', '5', '6', '7',
19822         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
19823     };
19824     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
19825     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
19826   }
19827   zStr[i*2] = '\0';
19828 
19829   oputf("X'%s'", zStr);
19830   sqlite3_free(zStr);
19831 }
19832 
19833 /*
19834 ** Find a string that is not found anywhere in z[].  Return a pointer
19835 ** to that string.
19836 **
19837 ** Try to use zA and zB first.  If both of those are already found in z[]
19838 ** then make up some string and store it in the buffer zBuf.
19839 */
unused_string(const char * z,const char * zA,const char * zB,char * zBuf)19840 static const char *unused_string(
19841   const char *z,                    /* Result must not appear anywhere in z */
19842   const char *zA, const char *zB,   /* Try these first */
19843   char *zBuf                        /* Space to store a generated string */
19844 ){
19845   unsigned i = 0;
19846   if( strstr(z, zA)==0 ) return zA;
19847   if( strstr(z, zB)==0 ) return zB;
19848   do{
19849     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
19850   }while( strstr(z,zBuf)!=0 );
19851   return zBuf;
19852 }
19853 
19854 /*
19855 ** Output the given string as a quoted string using SQL quoting conventions.
19856 **
19857 ** See also: output_quoted_escaped_string()
19858 */
output_quoted_string(const char * z)19859 static void output_quoted_string(const char *z){
19860   int i;
19861   char c;
19862 #ifndef SQLITE_SHELL_FIDDLE
19863   FILE *pfO = setOutputStream(invalidFileStream);
19864   setBinaryMode(pfO, 1);
19865 #endif
19866   if( z==0 ) return;
19867   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
19868   if( c==0 ){
19869     oputf("'%s'",z);
19870   }else{
19871     oputz("'");
19872     while( *z ){
19873       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
19874       if( c=='\'' ) i++;
19875       if( i ){
19876         oputf("%.*s", i, z);
19877         z += i;
19878       }
19879       if( c=='\'' ){
19880         oputz("'");
19881         continue;
19882       }
19883       if( c==0 ){
19884         break;
19885       }
19886       z++;
19887     }
19888     oputz("'");
19889   }
19890 #ifndef SQLITE_SHELL_FIDDLE
19891   setTextMode(pfO, 1);
19892 #else
19893   setTextMode(stdout, 1);
19894 #endif
19895 }
19896 
19897 /*
19898 ** Output the given string as a quoted string using SQL quoting conventions.
19899 ** Additionallly , escape the "\n" and "\r" characters so that they do not
19900 ** get corrupted by end-of-line translation facilities in some operating
19901 ** systems.
19902 **
19903 ** This is like output_quoted_string() but with the addition of the \r\n
19904 ** escape mechanism.
19905 */
output_quoted_escaped_string(const char * z)19906 static void output_quoted_escaped_string(const char *z){
19907   int i;
19908   char c;
19909 #ifndef SQLITE_SHELL_FIDDLE
19910   FILE *pfO = setOutputStream(invalidFileStream);
19911   setBinaryMode(pfO, 1);
19912 #endif
19913   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
19914   if( c==0 ){
19915     oputf("'%s'",z);
19916   }else{
19917     const char *zNL = 0;
19918     const char *zCR = 0;
19919     int nNL = 0;
19920     int nCR = 0;
19921     char zBuf1[20], zBuf2[20];
19922     for(i=0; z[i]; i++){
19923       if( z[i]=='\n' ) nNL++;
19924       if( z[i]=='\r' ) nCR++;
19925     }
19926     if( nNL ){
19927       oputz("replace(");
19928       zNL = unused_string(z, "\\n", "\\012", zBuf1);
19929     }
19930     if( nCR ){
19931       oputz("replace(");
19932       zCR = unused_string(z, "\\r", "\\015", zBuf2);
19933     }
19934     oputz("'");
19935     while( *z ){
19936       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
19937       if( c=='\'' ) i++;
19938       if( i ){
19939         oputf("%.*s", i, z);
19940         z += i;
19941       }
19942       if( c=='\'' ){
19943         oputz("'");
19944         continue;
19945       }
19946       if( c==0 ){
19947         break;
19948       }
19949       z++;
19950       if( c=='\n' ){
19951         oputz(zNL);
19952         continue;
19953       }
19954       oputz(zCR);
19955     }
19956     oputz("'");
19957     if( nCR ){
19958       oputf(",'%s',char(13))", zCR);
19959     }
19960     if( nNL ){
19961       oputf(",'%s',char(10))", zNL);
19962     }
19963   }
19964 #ifndef SQLITE_SHELL_FIDDLE
19965   setTextMode(pfO, 1);
19966 #else
19967   setTextMode(stdout, 1);
19968 #endif
19969 }
19970 
19971 /*
19972 ** Find earliest of chars within s specified in zAny.
19973 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
19974 */
anyOfInStr(const char * s,const char * zAny,size_t ns)19975 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
19976   const char *pcFirst = 0;
19977   if( ns == ~(size_t)0 ) ns = strlen(s);
19978   while(*zAny){
19979     const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
19980     if( pc ){
19981       pcFirst = pc;
19982       ns = pcFirst - s;
19983     }
19984     ++zAny;
19985   }
19986   return pcFirst;
19987 }
19988 /*
19989 ** Output the given string as a quoted according to C or TCL quoting rules.
19990 */
output_c_string(const char * z)19991 static void output_c_string(const char *z){
19992   char c;
19993   static const char *zq = "\"";
19994   static long ctrlMask = ~0L;
19995   static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
19996   char ace[3] = "\\?";
19997   char cbsSay;
19998   oputz(zq);
19999   while( *z!=0 ){
20000     const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
20001     const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
20002     const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
20003     if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
20004     if( (c = *pcEnd)==0 ) break;
20005     ++pcEnd;
20006     switch( c ){
20007     case '\\': case '"':
20008       cbsSay = (char)c;
20009       break;
20010     case '\t': cbsSay = 't'; break;
20011     case '\n': cbsSay = 'n'; break;
20012     case '\r': cbsSay = 'r'; break;
20013     case '\f': cbsSay = 'f'; break;
20014     default: cbsSay = 0; break;
20015     }
20016     if( cbsSay ){
20017       ace[1] = cbsSay;
20018       oputz(ace);
20019     }else if( !isprint(c&0xff) ){
20020       oputf("\\%03o", c&0xff);
20021     }else{
20022       ace[1] = (char)c;
20023       oputz(ace+1);
20024     }
20025     z = pcEnd;
20026   }
20027   oputz(zq);
20028 }
20029 
20030 /*
20031 ** Output the given string as a quoted according to JSON quoting rules.
20032 */
output_json_string(const char * z,i64 n)20033 static void output_json_string(const char *z, i64 n){
20034   char c;
20035   static const char *zq = "\"";
20036   static long ctrlMask = ~0L;
20037   static const char *zDQBS = "\"\\";
20038   const char *pcLimit;
20039   char ace[3] = "\\?";
20040   char cbsSay;
20041 
20042   if( z==0 ) z = "";
20043   pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
20044   oputz(zq);
20045   while( z < pcLimit ){
20046     const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
20047     const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
20048     const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
20049     if( pcEnd > z ){
20050       oputb(z, (int)(pcEnd-z));
20051       z = pcEnd;
20052     }
20053     if( z >= pcLimit ) break;
20054     c = *(z++);
20055     switch( c ){
20056     case '"': case '\\':
20057       cbsSay = (char)c;
20058       break;
20059     case '\b': cbsSay = 'b'; break;
20060     case '\f': cbsSay = 'f'; break;
20061     case '\n': cbsSay = 'n'; break;
20062     case '\r': cbsSay = 'r'; break;
20063     case '\t': cbsSay = 't'; break;
20064     default: cbsSay = 0; break;
20065     }
20066     if( cbsSay ){
20067       ace[1] = cbsSay;
20068       oputz(ace);
20069     }else if( c<=0x1f ){
20070       oputf("u%04x", c);
20071     }else{
20072       ace[1] = (char)c;
20073       oputz(ace+1);
20074     }
20075   }
20076   oputz(zq);
20077 }
20078 
20079 /*
20080 ** Output the given string with characters that are special to
20081 ** HTML escaped.
20082 */
output_html_string(const char * z)20083 static void output_html_string(const char *z){
20084   int i;
20085   if( z==0 ) z = "";
20086   while( *z ){
20087     for(i=0;   z[i]
20088             && z[i]!='<'
20089             && z[i]!='&'
20090             && z[i]!='>'
20091             && z[i]!='\"'
20092             && z[i]!='\'';
20093         i++){}
20094     if( i>0 ){
20095       oputf("%.*s",i,z);
20096     }
20097     if( z[i]=='<' ){
20098       oputz("&lt;");
20099     }else if( z[i]=='&' ){
20100       oputz("&amp;");
20101     }else if( z[i]=='>' ){
20102       oputz("&gt;");
20103     }else if( z[i]=='\"' ){
20104       oputz("&quot;");
20105     }else if( z[i]=='\'' ){
20106       oputz("&#39;");
20107     }else{
20108       break;
20109     }
20110     z += i + 1;
20111   }
20112 }
20113 
20114 /*
20115 ** If a field contains any character identified by a 1 in the following
20116 ** array, then the string must be quoted for CSV.
20117 */
20118 static const char needCsvQuote[] = {
20119   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20120   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20121   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
20122   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20123   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20124   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20125   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20126   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
20127   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20128   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20129   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20130   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20131   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20132   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20133   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20134   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20135 };
20136 
20137 /*
20138 ** Output a single term of CSV.  Actually, p->colSeparator is used for
20139 ** the separator, which may or may not be a comma.  p->nullValue is
20140 ** the null value.  Strings are quoted if necessary.  The separator
20141 ** is only issued if bSep is true.
20142 */
output_csv(ShellState * p,const char * z,int bSep)20143 static void output_csv(ShellState *p, const char *z, int bSep){
20144   if( z==0 ){
20145     oputf("%s",p->nullValue);
20146   }else{
20147     unsigned i;
20148     for(i=0; z[i]; i++){
20149       if( needCsvQuote[((unsigned char*)z)[i]] ){
20150         i = 0;
20151         break;
20152       }
20153     }
20154     if( i==0 || strstr(z, p->colSeparator)!=0 ){
20155       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
20156       shell_check_oom(zQuoted);
20157       oputz(zQuoted);
20158       sqlite3_free(zQuoted);
20159     }else{
20160       oputz(z);
20161     }
20162   }
20163   if( bSep ){
20164     oputz(p->colSeparator);
20165   }
20166 }
20167 
20168 /*
20169 ** This routine runs when the user presses Ctrl-C
20170 */
interrupt_handler(int NotUsed)20171 static void interrupt_handler(int NotUsed){
20172   UNUSED_PARAMETER(NotUsed);
20173   if( ++seenInterrupt>1 ) exit(1);
20174   if( globalDb ) sqlite3_interrupt(globalDb);
20175 }
20176 
20177 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
20178 /*
20179 ** This routine runs for console events (e.g. Ctrl-C) on Win32
20180 */
ConsoleCtrlHandler(DWORD dwCtrlType)20181 static BOOL WINAPI ConsoleCtrlHandler(
20182   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
20183 ){
20184   if( dwCtrlType==CTRL_C_EVENT ){
20185     interrupt_handler(0);
20186     return TRUE;
20187   }
20188   return FALSE;
20189 }
20190 #endif
20191 
20192 #ifndef SQLITE_OMIT_AUTHORIZATION
20193 /*
20194 ** This authorizer runs in safe mode.
20195 */
safeModeAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)20196 static int safeModeAuth(
20197   void *pClientData,
20198   int op,
20199   const char *zA1,
20200   const char *zA2,
20201   const char *zA3,
20202   const char *zA4
20203 ){
20204   ShellState *p = (ShellState*)pClientData;
20205   static const char *azProhibitedFunctions[] = {
20206     "edit",
20207     "fts3_tokenizer",
20208     "load_extension",
20209     "readfile",
20210     "writefile",
20211     "zipfile",
20212     "zipfile_cds",
20213   };
20214   UNUSED_PARAMETER(zA1);
20215   UNUSED_PARAMETER(zA3);
20216   UNUSED_PARAMETER(zA4);
20217   switch( op ){
20218     case SQLITE_ATTACH: {
20219 #ifndef SQLITE_SHELL_FIDDLE
20220       /* In WASM builds the filesystem is a virtual sandbox, so
20221       ** there's no harm in using ATTACH. */
20222       failIfSafeMode(p, "cannot run ATTACH in safe mode");
20223 #endif
20224       break;
20225     }
20226     case SQLITE_FUNCTION: {
20227       int i;
20228       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
20229         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
20230           failIfSafeMode(p, "cannot use the %s() function in safe mode",
20231                          azProhibitedFunctions[i]);
20232         }
20233       }
20234       break;
20235     }
20236   }
20237   return SQLITE_OK;
20238 }
20239 
20240 /*
20241 ** When the ".auth ON" is set, the following authorizer callback is
20242 ** invoked.  It always returns SQLITE_OK.
20243 */
shellAuth(void * pClientData,int op,const char * zA1,const char * zA2,const char * zA3,const char * zA4)20244 static int shellAuth(
20245   void *pClientData,
20246   int op,
20247   const char *zA1,
20248   const char *zA2,
20249   const char *zA3,
20250   const char *zA4
20251 ){
20252   ShellState *p = (ShellState*)pClientData;
20253   static const char *azAction[] = { 0,
20254      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
20255      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
20256      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
20257      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
20258      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
20259      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
20260      "PRAGMA",               "READ",                 "SELECT",
20261      "TRANSACTION",          "UPDATE",               "ATTACH",
20262      "DETACH",               "ALTER_TABLE",          "REINDEX",
20263      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
20264      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
20265   };
20266   int i;
20267   const char *az[4];
20268   az[0] = zA1;
20269   az[1] = zA2;
20270   az[2] = zA3;
20271   az[3] = zA4;
20272   oputf("authorizer: %s", azAction[op]);
20273   for(i=0; i<4; i++){
20274     oputz(" ");
20275     if( az[i] ){
20276       output_c_string(az[i]);
20277     }else{
20278       oputz("NULL");
20279     }
20280   }
20281   oputz("\n");
20282   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
20283   return SQLITE_OK;
20284 }
20285 #endif
20286 
20287 /*
20288 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
20289 **
20290 ** This routine converts some CREATE TABLE statements for shadow tables
20291 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
20292 **
20293 ** If the schema statement in z[] contains a start-of-comment and if
20294 ** sqlite3_complete() returns false, try to terminate the comment before
20295 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
20296 */
printSchemaLine(const char * z,const char * zTail)20297 static void printSchemaLine(const char *z, const char *zTail){
20298   char *zToFree = 0;
20299   if( z==0 ) return;
20300   if( zTail==0 ) return;
20301   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
20302     const char *zOrig = z;
20303     static const char *azTerm[] = { "", "*/", "\n" };
20304     int i;
20305     for(i=0; i<ArraySize(azTerm); i++){
20306       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
20307       shell_check_oom(zNew);
20308       if( sqlite3_complete(zNew) ){
20309         size_t n = strlen(zNew);
20310         zNew[n-1] = 0;
20311         zToFree = zNew;
20312         z = zNew;
20313         break;
20314       }
20315       sqlite3_free(zNew);
20316     }
20317   }
20318   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
20319     oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
20320   }else{
20321     oputf("%s%s", z, zTail);
20322   }
20323   sqlite3_free(zToFree);
20324 }
printSchemaLineN(char * z,int n,const char * zTail)20325 static void printSchemaLineN(char *z, int n, const char *zTail){
20326   char c = z[n];
20327   z[n] = 0;
20328   printSchemaLine(z, zTail);
20329   z[n] = c;
20330 }
20331 
20332 /*
20333 ** Return true if string z[] has nothing but whitespace and comments to the
20334 ** end of the first line.
20335 */
wsToEol(const char * z)20336 static int wsToEol(const char *z){
20337   int i;
20338   for(i=0; z[i]; i++){
20339     if( z[i]=='\n' ) return 1;
20340     if( IsSpace(z[i]) ) continue;
20341     if( z[i]=='-' && z[i+1]=='-' ) return 1;
20342     return 0;
20343   }
20344   return 1;
20345 }
20346 
20347 /*
20348 ** Add a new entry to the EXPLAIN QUERY PLAN data
20349 */
eqp_append(ShellState * p,int iEqpId,int p2,const char * zText)20350 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
20351   EQPGraphRow *pNew;
20352   i64 nText;
20353   if( zText==0 ) return;
20354   nText = strlen(zText);
20355   if( p->autoEQPtest ){
20356     oputf("%d,%d,%s\n", iEqpId, p2, zText);
20357   }
20358   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
20359   shell_check_oom(pNew);
20360   pNew->iEqpId = iEqpId;
20361   pNew->iParentId = p2;
20362   memcpy(pNew->zText, zText, nText+1);
20363   pNew->pNext = 0;
20364   if( p->sGraph.pLast ){
20365     p->sGraph.pLast->pNext = pNew;
20366   }else{
20367     p->sGraph.pRow = pNew;
20368   }
20369   p->sGraph.pLast = pNew;
20370 }
20371 
20372 /*
20373 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
20374 ** in p->sGraph.
20375 */
eqp_reset(ShellState * p)20376 static void eqp_reset(ShellState *p){
20377   EQPGraphRow *pRow, *pNext;
20378   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
20379     pNext = pRow->pNext;
20380     sqlite3_free(pRow);
20381   }
20382   memset(&p->sGraph, 0, sizeof(p->sGraph));
20383 }
20384 
20385 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
20386 ** pOld, or return the first such line if pOld is NULL
20387 */
eqp_next_row(ShellState * p,int iEqpId,EQPGraphRow * pOld)20388 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
20389   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
20390   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
20391   return pRow;
20392 }
20393 
20394 /* Render a single level of the graph that has iEqpId as its parent.  Called
20395 ** recursively to render sublevels.
20396 */
eqp_render_level(ShellState * p,int iEqpId)20397 static void eqp_render_level(ShellState *p, int iEqpId){
20398   EQPGraphRow *pRow, *pNext;
20399   i64 n = strlen(p->sGraph.zPrefix);
20400   char *z;
20401   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
20402     pNext = eqp_next_row(p, iEqpId, pRow);
20403     z = pRow->zText;
20404     oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
20405     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
20406       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
20407       eqp_render_level(p, pRow->iEqpId);
20408       p->sGraph.zPrefix[n] = 0;
20409     }
20410   }
20411 }
20412 
20413 /*
20414 ** Display and reset the EXPLAIN QUERY PLAN data
20415 */
eqp_render(ShellState * p,i64 nCycle)20416 static void eqp_render(ShellState *p, i64 nCycle){
20417   EQPGraphRow *pRow = p->sGraph.pRow;
20418   if( pRow ){
20419     if( pRow->zText[0]=='-' ){
20420       if( pRow->pNext==0 ){
20421         eqp_reset(p);
20422         return;
20423       }
20424       oputf("%s\n", pRow->zText+3);
20425       p->sGraph.pRow = pRow->pNext;
20426       sqlite3_free(pRow);
20427     }else if( nCycle>0 ){
20428       oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
20429     }else{
20430       oputz("QUERY PLAN\n");
20431     }
20432     p->sGraph.zPrefix[0] = 0;
20433     eqp_render_level(p, 0);
20434     eqp_reset(p);
20435   }
20436 }
20437 
20438 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
20439 /*
20440 ** Progress handler callback.
20441 */
progress_handler(void * pClientData)20442 static int progress_handler(void *pClientData) {
20443   ShellState *p = (ShellState*)pClientData;
20444   p->nProgress++;
20445   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
20446     oputf("Progress limit reached (%u)\n", p->nProgress);
20447     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
20448     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
20449     return 1;
20450   }
20451   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
20452     oputf("Progress %u\n", p->nProgress);
20453   }
20454   return 0;
20455 }
20456 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
20457 
20458 /*
20459 ** Print N dashes
20460 */
print_dashes(int N)20461 static void print_dashes(int N){
20462   const char zDash[] = "--------------------------------------------------";
20463   const int nDash = sizeof(zDash) - 1;
20464   while( N>nDash ){
20465     oputz(zDash);
20466     N -= nDash;
20467   }
20468   oputf("%.*s", N, zDash);
20469 }
20470 
20471 /*
20472 ** Print a markdown or table-style row separator using ascii-art
20473 */
print_row_separator(ShellState * p,int nArg,const char * zSep)20474 static void print_row_separator(
20475   ShellState *p,
20476   int nArg,
20477   const char *zSep
20478 ){
20479   int i;
20480   if( nArg>0 ){
20481     oputz(zSep);
20482     print_dashes(p->actualWidth[0]+2);
20483     for(i=1; i<nArg; i++){
20484       oputz(zSep);
20485       print_dashes(p->actualWidth[i]+2);
20486     }
20487     oputz(zSep);
20488   }
20489   oputz("\n");
20490 }
20491 
20492 /*
20493 ** This is the callback routine that the shell
20494 ** invokes for each row of a query result.
20495 */
shell_callback(void * pArg,int nArg,char ** azArg,char ** azCol,int * aiType)20496 static int shell_callback(
20497   void *pArg,
20498   int nArg,        /* Number of result columns */
20499   char **azArg,    /* Text of each result column */
20500   char **azCol,    /* Column names */
20501   int *aiType      /* Column types.  Might be NULL */
20502 ){
20503   int i;
20504   ShellState *p = (ShellState*)pArg;
20505 
20506   if( azArg==0 ) return 0;
20507   switch( p->cMode ){
20508     case MODE_Count:
20509     case MODE_Off: {
20510       break;
20511     }
20512     case MODE_Line: {
20513       int w = 5;
20514       if( azArg==0 ) break;
20515       for(i=0; i<nArg; i++){
20516         int len = strlen30(azCol[i] ? azCol[i] : "");
20517         if( len>w ) w = len;
20518       }
20519       if( p->cnt++>0 ) oputz(p->rowSeparator);
20520       for(i=0; i<nArg; i++){
20521         oputf("%*s = %s%s", w, azCol[i],
20522               azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
20523       }
20524       break;
20525     }
20526     case MODE_ScanExp:
20527     case MODE_Explain: {
20528       static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
20529       static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
20530       static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
20531       static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
20532 
20533       const int *aWidth = aExplainWidth;
20534       const int *aMap = aExplainMap;
20535       int nWidth = ArraySize(aExplainWidth);
20536       int iIndent = 1;
20537 
20538       if( p->cMode==MODE_ScanExp ){
20539         aWidth = aScanExpWidth;
20540         aMap = aScanExpMap;
20541         nWidth = ArraySize(aScanExpWidth);
20542         iIndent = 3;
20543       }
20544       if( nArg>nWidth ) nArg = nWidth;
20545 
20546       /* If this is the first row seen, print out the headers */
20547       if( p->cnt++==0 ){
20548         for(i=0; i<nArg; i++){
20549           utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
20550           oputz(i==nArg-1 ? "\n" : "  ");
20551         }
20552         for(i=0; i<nArg; i++){
20553           print_dashes(aWidth[i]);
20554           oputz(i==nArg-1 ? "\n" : "  ");
20555         }
20556       }
20557 
20558       /* If there is no data, exit early. */
20559       if( azArg==0 ) break;
20560 
20561       for(i=0; i<nArg; i++){
20562         const char *zSep = "  ";
20563         int w = aWidth[i];
20564         const char *zVal = azArg[ aMap[i] ];
20565         if( i==nArg-1 ) w = 0;
20566         if( zVal && strlenChar(zVal)>w ){
20567           w = strlenChar(zVal);
20568           zSep = " ";
20569         }
20570         if( i==iIndent && p->aiIndent && p->pStmt ){
20571           if( p->iIndent<p->nIndent ){
20572             oputf("%*.s", p->aiIndent[p->iIndent], "");
20573           }
20574           p->iIndent++;
20575         }
20576         utf8_width_print(w, zVal ? zVal : p->nullValue);
20577         oputz(i==nArg-1 ? "\n" : zSep);
20578       }
20579       break;
20580     }
20581     case MODE_Semi: {   /* .schema and .fullschema output */
20582       printSchemaLine(azArg[0], ";\n");
20583       break;
20584     }
20585     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
20586       char *z;
20587       int j;
20588       int nParen = 0;
20589       char cEnd = 0;
20590       char c;
20591       int nLine = 0;
20592       assert( nArg==1 );
20593       if( azArg[0]==0 ) break;
20594       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
20595        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
20596       ){
20597         oputf("%s;\n", azArg[0]);
20598         break;
20599       }
20600       z = sqlite3_mprintf("%s", azArg[0]);
20601       shell_check_oom(z);
20602       j = 0;
20603       for(i=0; IsSpace(z[i]); i++){}
20604       for(; (c = z[i])!=0; i++){
20605         if( IsSpace(c) ){
20606           if( z[j-1]=='\r' ) z[j-1] = '\n';
20607           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
20608         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
20609           j--;
20610         }
20611         z[j++] = c;
20612       }
20613       while( j>0 && IsSpace(z[j-1]) ){ j--; }
20614       z[j] = 0;
20615       if( strlen30(z)>=79 ){
20616         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
20617           if( c==cEnd ){
20618             cEnd = 0;
20619           }else if( c=='"' || c=='\'' || c=='`' ){
20620             cEnd = c;
20621           }else if( c=='[' ){
20622             cEnd = ']';
20623           }else if( c=='-' && z[i+1]=='-' ){
20624             cEnd = '\n';
20625           }else if( c=='(' ){
20626             nParen++;
20627           }else if( c==')' ){
20628             nParen--;
20629             if( nLine>0 && nParen==0 && j>0 ){
20630               printSchemaLineN(z, j, "\n");
20631               j = 0;
20632             }
20633           }
20634           z[j++] = c;
20635           if( nParen==1 && cEnd==0
20636            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
20637           ){
20638             if( c=='\n' ) j--;
20639             printSchemaLineN(z, j, "\n  ");
20640             j = 0;
20641             nLine++;
20642             while( IsSpace(z[i+1]) ){ i++; }
20643           }
20644         }
20645         z[j] = 0;
20646       }
20647       printSchemaLine(z, ";\n");
20648       sqlite3_free(z);
20649       break;
20650     }
20651     case MODE_List: {
20652       if( p->cnt++==0 && p->showHeader ){
20653         for(i=0; i<nArg; i++){
20654           oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
20655         }
20656       }
20657       if( azArg==0 ) break;
20658       for(i=0; i<nArg; i++){
20659         char *z = azArg[i];
20660         if( z==0 ) z = p->nullValue;
20661         oputz(z);
20662         oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
20663       }
20664       break;
20665     }
20666     case MODE_Html: {
20667       if( p->cnt++==0 && p->showHeader ){
20668         oputz("<TR>");
20669         for(i=0; i<nArg; i++){
20670           oputz("<TH>");
20671           output_html_string(azCol[i]);
20672           oputz("</TH>\n");
20673         }
20674         oputz("</TR>\n");
20675       }
20676       if( azArg==0 ) break;
20677       oputz("<TR>");
20678       for(i=0; i<nArg; i++){
20679         oputz("<TD>");
20680         output_html_string(azArg[i] ? azArg[i] : p->nullValue);
20681         oputz("</TD>\n");
20682       }
20683       oputz("</TR>\n");
20684       break;
20685     }
20686     case MODE_Tcl: {
20687       if( p->cnt++==0 && p->showHeader ){
20688         for(i=0; i<nArg; i++){
20689           output_c_string(azCol[i] ? azCol[i] : "");
20690           if(i<nArg-1) oputz(p->colSeparator);
20691         }
20692         oputz(p->rowSeparator);
20693       }
20694       if( azArg==0 ) break;
20695       for(i=0; i<nArg; i++){
20696         output_c_string(azArg[i] ? azArg[i] : p->nullValue);
20697         if(i<nArg-1) oputz(p->colSeparator);
20698       }
20699       oputz(p->rowSeparator);
20700       break;
20701     }
20702     case MODE_Csv: {
20703       setBinaryMode(p->out, 1);
20704       if( p->cnt++==0 && p->showHeader ){
20705         for(i=0; i<nArg; i++){
20706           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
20707         }
20708         oputz(p->rowSeparator);
20709       }
20710       if( nArg>0 ){
20711         for(i=0; i<nArg; i++){
20712           output_csv(p, azArg[i], i<nArg-1);
20713         }
20714         oputz(p->rowSeparator);
20715       }
20716       setTextMode(p->out, 1);
20717       break;
20718     }
20719     case MODE_Insert: {
20720       if( azArg==0 ) break;
20721       oputf("INSERT INTO %s",p->zDestTable);
20722       if( p->showHeader ){
20723         oputz("(");
20724         for(i=0; i<nArg; i++){
20725           if( i>0 ) oputz(",");
20726           if( quoteChar(azCol[i]) ){
20727             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
20728             shell_check_oom(z);
20729             oputz(z);
20730             sqlite3_free(z);
20731           }else{
20732             oputf("%s", azCol[i]);
20733           }
20734         }
20735         oputz(")");
20736       }
20737       p->cnt++;
20738       for(i=0; i<nArg; i++){
20739         oputz(i>0 ? "," : " VALUES(");
20740         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
20741           oputz("NULL");
20742         }else if( aiType && aiType[i]==SQLITE_TEXT ){
20743           if( ShellHasFlag(p, SHFLG_Newlines) ){
20744             output_quoted_string(azArg[i]);
20745           }else{
20746             output_quoted_escaped_string(azArg[i]);
20747           }
20748         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
20749           oputz(azArg[i]);
20750         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
20751           char z[50];
20752           double r = sqlite3_column_double(p->pStmt, i);
20753           sqlite3_uint64 ur;
20754           memcpy(&ur,&r,sizeof(r));
20755           if( ur==0x7ff0000000000000LL ){
20756             oputz("9.0e+999");
20757           }else if( ur==0xfff0000000000000LL ){
20758             oputz("-9.0e+999");
20759           }else{
20760             sqlite3_int64 ir = (sqlite3_int64)r;
20761             if( r==(double)ir ){
20762               sqlite3_snprintf(50,z,"%lld.0", ir);
20763             }else{
20764               sqlite3_snprintf(50,z,"%!.20g", r);
20765             }
20766             oputz(z);
20767           }
20768         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
20769           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
20770           int nBlob = sqlite3_column_bytes(p->pStmt, i);
20771           output_hex_blob(pBlob, nBlob);
20772         }else if( isNumber(azArg[i], 0) ){
20773           oputz(azArg[i]);
20774         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
20775           output_quoted_string(azArg[i]);
20776         }else{
20777           output_quoted_escaped_string(azArg[i]);
20778         }
20779       }
20780       oputz(");\n");
20781       break;
20782     }
20783     case MODE_Json: {
20784       if( azArg==0 ) break;
20785       if( p->cnt==0 ){
20786         fputs("[{", p->out);
20787       }else{
20788         fputs(",\n{", p->out);
20789       }
20790       p->cnt++;
20791       for(i=0; i<nArg; i++){
20792         output_json_string(azCol[i], -1);
20793         oputz(":");
20794         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
20795           oputz("null");
20796         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
20797           char z[50];
20798           double r = sqlite3_column_double(p->pStmt, i);
20799           sqlite3_uint64 ur;
20800           memcpy(&ur,&r,sizeof(r));
20801           if( ur==0x7ff0000000000000LL ){
20802             oputz("9.0e+999");
20803           }else if( ur==0xfff0000000000000LL ){
20804             oputz("-9.0e+999");
20805           }else{
20806             sqlite3_snprintf(50,z,"%!.20g", r);
20807             oputz(z);
20808           }
20809         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
20810           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
20811           int nBlob = sqlite3_column_bytes(p->pStmt, i);
20812           output_json_string(pBlob, nBlob);
20813         }else if( aiType && aiType[i]==SQLITE_TEXT ){
20814           output_json_string(azArg[i], -1);
20815         }else{
20816           oputz(azArg[i]);
20817         }
20818         if( i<nArg-1 ){
20819           oputz(",");
20820         }
20821       }
20822       oputz("}");
20823       break;
20824     }
20825     case MODE_Quote: {
20826       if( azArg==0 ) break;
20827       if( p->cnt==0 && p->showHeader ){
20828         for(i=0; i<nArg; i++){
20829           if( i>0 ) fputs(p->colSeparator, p->out);
20830           output_quoted_string(azCol[i]);
20831         }
20832         fputs(p->rowSeparator, p->out);
20833       }
20834       p->cnt++;
20835       for(i=0; i<nArg; i++){
20836         if( i>0 ) fputs(p->colSeparator, p->out);
20837         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
20838           oputz("NULL");
20839         }else if( aiType && aiType[i]==SQLITE_TEXT ){
20840           output_quoted_string(azArg[i]);
20841         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
20842           oputz(azArg[i]);
20843         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
20844           char z[50];
20845           double r = sqlite3_column_double(p->pStmt, i);
20846           sqlite3_snprintf(50,z,"%!.20g", r);
20847           oputz(z);
20848         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
20849           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
20850           int nBlob = sqlite3_column_bytes(p->pStmt, i);
20851           output_hex_blob(pBlob, nBlob);
20852         }else if( isNumber(azArg[i], 0) ){
20853           oputz(azArg[i]);
20854         }else{
20855           output_quoted_string(azArg[i]);
20856         }
20857       }
20858       fputs(p->rowSeparator, p->out);
20859       break;
20860     }
20861     case MODE_Ascii: {
20862       if( p->cnt++==0 && p->showHeader ){
20863         for(i=0; i<nArg; i++){
20864           if( i>0 ) oputz(p->colSeparator);
20865           oputz(azCol[i] ? azCol[i] : "");
20866         }
20867         oputz(p->rowSeparator);
20868       }
20869       if( azArg==0 ) break;
20870       for(i=0; i<nArg; i++){
20871         if( i>0 ) oputz(p->colSeparator);
20872         oputz(azArg[i] ? azArg[i] : p->nullValue);
20873       }
20874       oputz(p->rowSeparator);
20875       break;
20876     }
20877     case MODE_EQP: {
20878       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
20879       break;
20880     }
20881   }
20882   return 0;
20883 }
20884 
20885 /*
20886 ** This is the callback routine that the SQLite library
20887 ** invokes for each row of a query result.
20888 */
callback(void * pArg,int nArg,char ** azArg,char ** azCol)20889 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
20890   /* since we don't have type info, call the shell_callback with a NULL value */
20891   return shell_callback(pArg, nArg, azArg, azCol, NULL);
20892 }
20893 
20894 /*
20895 ** This is the callback routine from sqlite3_exec() that appends all
20896 ** output onto the end of a ShellText object.
20897 */
captureOutputCallback(void * pArg,int nArg,char ** azArg,char ** az)20898 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
20899   ShellText *p = (ShellText*)pArg;
20900   int i;
20901   UNUSED_PARAMETER(az);
20902   if( azArg==0 ) return 0;
20903   if( p->n ) appendText(p, "|", 0);
20904   for(i=0; i<nArg; i++){
20905     if( i ) appendText(p, ",", 0);
20906     if( azArg[i] ) appendText(p, azArg[i], 0);
20907   }
20908   return 0;
20909 }
20910 
20911 /*
20912 ** Generate an appropriate SELFTEST table in the main database.
20913 */
createSelftestTable(ShellState * p)20914 static void createSelftestTable(ShellState *p){
20915   char *zErrMsg = 0;
20916   sqlite3_exec(p->db,
20917     "SAVEPOINT selftest_init;\n"
20918     "CREATE TABLE IF NOT EXISTS selftest(\n"
20919     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
20920     "  op TEXT,\n"                   /* Operator:  memo run */
20921     "  cmd TEXT,\n"                  /* Command text */
20922     "  ans TEXT\n"                   /* Desired answer */
20923     ");"
20924     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
20925     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
20926     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
20927     "         'memo','Tests generated by --init');\n"
20928     "INSERT INTO [_shell$self]\n"
20929     "  SELECT 'run',\n"
20930     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
20931                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
20932     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
20933                           "FROM sqlite_schema ORDER BY 2',224));\n"
20934     "INSERT INTO [_shell$self]\n"
20935     "  SELECT 'run',"
20936     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
20937     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
20938     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
20939     "  FROM (\n"
20940     "    SELECT name FROM sqlite_schema\n"
20941     "     WHERE type='table'\n"
20942     "       AND name<>'selftest'\n"
20943     "       AND coalesce(rootpage,0)>0\n"
20944     "  )\n"
20945     " ORDER BY name;\n"
20946     "INSERT INTO [_shell$self]\n"
20947     "  VALUES('run','PRAGMA integrity_check','ok');\n"
20948     "INSERT INTO selftest(tno,op,cmd,ans)"
20949     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
20950     "DROP TABLE [_shell$self];"
20951     ,0,0,&zErrMsg);
20952   if( zErrMsg ){
20953     eputf("SELFTEST initialization failure: %s\n", zErrMsg);
20954     sqlite3_free(zErrMsg);
20955   }
20956   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
20957 }
20958 
20959 
20960 /*
20961 ** Set the destination table field of the ShellState structure to
20962 ** the name of the table given.  Escape any quote characters in the
20963 ** table name.
20964 */
set_table_name(ShellState * p,const char * zName)20965 static void set_table_name(ShellState *p, const char *zName){
20966   int i, n;
20967   char cQuote;
20968   char *z;
20969 
20970   if( p->zDestTable ){
20971     free(p->zDestTable);
20972     p->zDestTable = 0;
20973   }
20974   if( zName==0 ) return;
20975   cQuote = quoteChar(zName);
20976   n = strlen30(zName);
20977   if( cQuote ) n += n+2;
20978   z = p->zDestTable = malloc( n+1 );
20979   shell_check_oom(z);
20980   n = 0;
20981   if( cQuote ) z[n++] = cQuote;
20982   for(i=0; zName[i]; i++){
20983     z[n++] = zName[i];
20984     if( zName[i]==cQuote ) z[n++] = cQuote;
20985   }
20986   if( cQuote ) z[n++] = cQuote;
20987   z[n] = 0;
20988 }
20989 
20990 /*
20991 ** Maybe construct two lines of text that point out the position of a
20992 ** syntax error.  Return a pointer to the text, in memory obtained from
20993 ** sqlite3_malloc().  Or, if the most recent error does not involve a
20994 ** specific token that we can point to, return an empty string.
20995 **
20996 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
20997 ** and should be released by the caller invoking sqlite3_free().
20998 */
shell_error_context(const char * zSql,sqlite3 * db)20999 static char *shell_error_context(const char *zSql, sqlite3 *db){
21000   int iOffset;
21001   size_t len;
21002   char *zCode;
21003   char *zMsg;
21004   int i;
21005   if( db==0
21006    || zSql==0
21007    || (iOffset = sqlite3_error_offset(db))<0
21008    || iOffset>=(int)strlen(zSql)
21009   ){
21010     return sqlite3_mprintf("");
21011   }
21012   while( iOffset>50 ){
21013     iOffset--;
21014     zSql++;
21015     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
21016   }
21017   len = strlen(zSql);
21018   if( len>78 ){
21019     len = 78;
21020     while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
21021   }
21022   zCode = sqlite3_mprintf("%.*s", len, zSql);
21023   shell_check_oom(zCode);
21024   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
21025   if( iOffset<25 ){
21026     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
21027   }else{
21028     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
21029   }
21030   return zMsg;
21031 }
21032 
21033 
21034 /*
21035 ** Execute a query statement that will generate SQL output.  Print
21036 ** the result columns, comma-separated, on a line and then add a
21037 ** semicolon terminator to the end of that line.
21038 **
21039 ** If the number of columns is 1 and that column contains text "--"
21040 ** then write the semicolon on a separate line.  That way, if a
21041 ** "--" comment occurs at the end of the statement, the comment
21042 ** won't consume the semicolon terminator.
21043 */
run_table_dump_query(ShellState * p,const char * zSelect)21044 static int run_table_dump_query(
21045   ShellState *p,           /* Query context */
21046   const char *zSelect      /* SELECT statement to extract content */
21047 ){
21048   sqlite3_stmt *pSelect;
21049   int rc;
21050   int nResult;
21051   int i;
21052   const char *z;
21053   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
21054   if( rc!=SQLITE_OK || !pSelect ){
21055     char *zContext = shell_error_context(zSelect, p->db);
21056     oputf("/**** ERROR: (%d) %s *****/\n%s",
21057           rc, sqlite3_errmsg(p->db), zContext);
21058     sqlite3_free(zContext);
21059     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
21060     return rc;
21061   }
21062   rc = sqlite3_step(pSelect);
21063   nResult = sqlite3_column_count(pSelect);
21064   while( rc==SQLITE_ROW ){
21065     z = (const char*)sqlite3_column_text(pSelect, 0);
21066     oputf("%s", z);
21067     for(i=1; i<nResult; i++){
21068       oputf(",%s", sqlite3_column_text(pSelect, i));
21069     }
21070     if( z==0 ) z = "";
21071     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
21072     if( z[0] ){
21073       oputz("\n;\n");
21074     }else{
21075       oputz(";\n");
21076     }
21077     rc = sqlite3_step(pSelect);
21078   }
21079   rc = sqlite3_finalize(pSelect);
21080   if( rc!=SQLITE_OK ){
21081     oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
21082     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
21083   }
21084   return rc;
21085 }
21086 
21087 /*
21088 ** Allocate space and save off string indicating current error.
21089 */
save_err_msg(sqlite3 * db,const char * zPhase,int rc,const char * zSql)21090 static char *save_err_msg(
21091   sqlite3 *db,           /* Database to query */
21092   const char *zPhase,    /* When the error occurs */
21093   int rc,                /* Error code returned from API */
21094   const char *zSql       /* SQL string, or NULL */
21095 ){
21096   char *zErr;
21097   char *zContext;
21098   sqlite3_str *pStr = sqlite3_str_new(0);
21099   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
21100   if( rc>1 ){
21101     sqlite3_str_appendf(pStr, " (%d)", rc);
21102   }
21103   zContext = shell_error_context(zSql, db);
21104   if( zContext ){
21105     sqlite3_str_appendall(pStr, zContext);
21106     sqlite3_free(zContext);
21107   }
21108   zErr = sqlite3_str_finish(pStr);
21109   shell_check_oom(zErr);
21110   return zErr;
21111 }
21112 
21113 #ifdef __linux__
21114 /*
21115 ** Attempt to display I/O stats on Linux using /proc/PID/io
21116 */
displayLinuxIoStats(void)21117 static void displayLinuxIoStats(void){
21118   FILE *in;
21119   char z[200];
21120   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
21121   in = fopen(z, "rb");
21122   if( in==0 ) return;
21123   while( fgets(z, sizeof(z), in)!=0 ){
21124     static const struct {
21125       const char *zPattern;
21126       const char *zDesc;
21127     } aTrans[] = {
21128       { "rchar: ",                  "Bytes received by read():" },
21129       { "wchar: ",                  "Bytes sent to write():"    },
21130       { "syscr: ",                  "Read() system calls:"      },
21131       { "syscw: ",                  "Write() system calls:"     },
21132       { "read_bytes: ",             "Bytes read from storage:"  },
21133       { "write_bytes: ",            "Bytes written to storage:" },
21134       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
21135     };
21136     int i;
21137     for(i=0; i<ArraySize(aTrans); i++){
21138       int n = strlen30(aTrans[i].zPattern);
21139       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
21140         oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
21141         break;
21142       }
21143     }
21144   }
21145   fclose(in);
21146 }
21147 #endif
21148 
21149 /*
21150 ** Display a single line of status using 64-bit values.
21151 */
displayStatLine(char * zLabel,char * zFormat,int iStatusCtrl,int bReset)21152 static void displayStatLine(
21153   char *zLabel,             /* Label for this one line */
21154   char *zFormat,            /* Format for the result */
21155   int iStatusCtrl,          /* Which status to display */
21156   int bReset                /* True to reset the stats */
21157 ){
21158   sqlite3_int64 iCur = -1;
21159   sqlite3_int64 iHiwtr = -1;
21160   int i, nPercent;
21161   char zLine[200];
21162   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
21163   for(i=0, nPercent=0; zFormat[i]; i++){
21164     if( zFormat[i]=='%' ) nPercent++;
21165   }
21166   if( nPercent>1 ){
21167     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
21168   }else{
21169     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
21170   }
21171   oputf("%-36s %s\n", zLabel, zLine);
21172 }
21173 
21174 /*
21175 ** Display memory stats.
21176 */
display_stats(sqlite3 * db,ShellState * pArg,int bReset)21177 static int display_stats(
21178   sqlite3 *db,                /* Database to query */
21179   ShellState *pArg,           /* Pointer to ShellState */
21180   int bReset                  /* True to reset the stats */
21181 ){
21182   int iCur;
21183   int iHiwtr;
21184   if( pArg==0 || pArg->out==0 ) return 0;
21185 
21186   if( pArg->pStmt && pArg->statsOn==2 ){
21187     int nCol, i, x;
21188     sqlite3_stmt *pStmt = pArg->pStmt;
21189     char z[100];
21190     nCol = sqlite3_column_count(pStmt);
21191     oputf("%-36s %d\n", "Number of output columns:", nCol);
21192     for(i=0; i<nCol; i++){
21193       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
21194       oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
21195 #ifndef SQLITE_OMIT_DECLTYPE
21196       sqlite3_snprintf(30, z+x, "declared type:");
21197       oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
21198 #endif
21199 #ifdef SQLITE_ENABLE_COLUMN_METADATA
21200       sqlite3_snprintf(30, z+x, "database name:");
21201       oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
21202       sqlite3_snprintf(30, z+x, "table name:");
21203       oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
21204       sqlite3_snprintf(30, z+x, "origin name:");
21205       oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
21206 #endif
21207     }
21208   }
21209 
21210   if( pArg->statsOn==3 ){
21211     if( pArg->pStmt ){
21212       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
21213       oputf("VM-steps: %d\n", iCur);
21214     }
21215     return 0;
21216   }
21217 
21218   displayStatLine("Memory Used:",
21219      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
21220   displayStatLine("Number of Outstanding Allocations:",
21221      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
21222   if( pArg->shellFlgs & SHFLG_Pagecache ){
21223     displayStatLine("Number of Pcache Pages Used:",
21224        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
21225   }
21226   displayStatLine("Number of Pcache Overflow Bytes:",
21227      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
21228   displayStatLine("Largest Allocation:",
21229      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
21230   displayStatLine("Largest Pcache Allocation:",
21231      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
21232 #ifdef YYTRACKMAXSTACKDEPTH
21233   displayStatLine("Deepest Parser Stack:",
21234      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
21235 #endif
21236 
21237   if( db ){
21238     if( pArg->shellFlgs & SHFLG_Lookaside ){
21239       iHiwtr = iCur = -1;
21240       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
21241                         &iCur, &iHiwtr, bReset);
21242       oputf("Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
21243       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
21244                         &iCur, &iHiwtr, bReset);
21245       oputf("Successful lookaside attempts:       %d\n", iHiwtr);
21246       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
21247                         &iCur, &iHiwtr, bReset);
21248       oputf("Lookaside failures due to size:      %d\n", iHiwtr);
21249       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
21250                         &iCur, &iHiwtr, bReset);
21251       oputf("Lookaside failures due to OOM:       %d\n", iHiwtr);
21252     }
21253     iHiwtr = iCur = -1;
21254     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
21255     oputf("Pager Heap Usage:                    %d bytes\n", iCur);
21256     iHiwtr = iCur = -1;
21257     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
21258     oputf("Page cache hits:                     %d\n", iCur);
21259     iHiwtr = iCur = -1;
21260     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
21261     oputf("Page cache misses:                   %d\n", iCur);
21262     iHiwtr = iCur = -1;
21263     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
21264     oputf("Page cache writes:                   %d\n", iCur);
21265     iHiwtr = iCur = -1;
21266     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
21267     oputf("Page cache spills:                   %d\n", iCur);
21268     iHiwtr = iCur = -1;
21269     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
21270     oputf("Schema Heap Usage:                   %d bytes\n", iCur);
21271     iHiwtr = iCur = -1;
21272     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
21273     oputf("Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
21274   }
21275 
21276   if( pArg->pStmt ){
21277     int iHit, iMiss;
21278     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
21279                                bReset);
21280     oputf("Fullscan Steps:                      %d\n", iCur);
21281     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
21282     oputf("Sort Operations:                     %d\n", iCur);
21283     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
21284     oputf("Autoindex Inserts:                   %d\n", iCur);
21285     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
21286                                bReset);
21287     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
21288                                 bReset);
21289     if( iHit || iMiss ){
21290       oputf("Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
21291     }
21292     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
21293     oputf("Virtual Machine Steps:               %d\n", iCur);
21294     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
21295     oputf("Reprepare operations:                %d\n", iCur);
21296     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
21297     oputf("Number of times run:                 %d\n", iCur);
21298     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
21299     oputf("Memory used by prepared stmt:        %d\n", iCur);
21300   }
21301 
21302 #ifdef __linux__
21303   displayLinuxIoStats();
21304 #endif
21305 
21306   /* Do not remove this machine readable comment: extra-stats-output-here */
21307 
21308   return 0;
21309 }
21310 
21311 
21312 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
scanStatsHeight(sqlite3_stmt * p,int iEntry)21313 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
21314   int iPid = 0;
21315   int ret = 1;
21316   sqlite3_stmt_scanstatus_v2(p, iEntry,
21317       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
21318   );
21319   while( iPid!=0 ){
21320     int ii;
21321     for(ii=0; 1; ii++){
21322       int iId;
21323       int res;
21324       res = sqlite3_stmt_scanstatus_v2(p, ii,
21325           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
21326       );
21327       if( res ) break;
21328       if( iId==iPid ){
21329         sqlite3_stmt_scanstatus_v2(p, ii,
21330             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
21331         );
21332       }
21333     }
21334     ret++;
21335   }
21336   return ret;
21337 }
21338 #endif
21339 
21340 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
display_explain_scanstats(sqlite3 * db,ShellState * pArg)21341 static void display_explain_scanstats(
21342   sqlite3 *db,                    /* Database to query */
21343   ShellState *pArg                /* Pointer to ShellState */
21344 ){
21345   static const int f = SQLITE_SCANSTAT_COMPLEX;
21346   sqlite3_stmt *p = pArg->pStmt;
21347   int ii = 0;
21348   i64 nTotal = 0;
21349   int nWidth = 0;
21350   eqp_reset(pArg);
21351 
21352   for(ii=0; 1; ii++){
21353     const char *z = 0;
21354     int n = 0;
21355     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
21356       break;
21357     }
21358     n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
21359     if( n>nWidth ) nWidth = n;
21360   }
21361   nWidth += 4;
21362 
21363   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
21364   for(ii=0; 1; ii++){
21365     i64 nLoop = 0;
21366     i64 nRow = 0;
21367     i64 nCycle = 0;
21368     int iId = 0;
21369     int iPid = 0;
21370     const char *zo = 0;
21371     const char *zName = 0;
21372     char *zText = 0;
21373     double rEst = 0.0;
21374 
21375     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
21376       break;
21377     }
21378     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
21379     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
21380     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
21381     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
21382     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
21383     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
21384     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
21385 
21386     zText = sqlite3_mprintf("%s", zo);
21387     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
21388       char *z = 0;
21389       if( nCycle>=0 && nTotal>0 ){
21390         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
21391             nCycle, ((nCycle*100)+nTotal/2) / nTotal
21392         );
21393       }
21394       if( nLoop>=0 ){
21395         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
21396       }
21397       if( nRow>=0 ){
21398         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
21399       }
21400 
21401       if( zName && pArg->scanstatsOn>1 ){
21402         double rpl = (double)nRow / (double)nLoop;
21403         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
21404       }
21405 
21406       zText = sqlite3_mprintf(
21407           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
21408       );
21409     }
21410 
21411     eqp_append(pArg, iId, iPid, zText);
21412     sqlite3_free(zText);
21413   }
21414 
21415   eqp_render(pArg, nTotal);
21416 }
21417 #endif
21418 
21419 
21420 /*
21421 ** Parameter azArray points to a zero-terminated array of strings. zStr
21422 ** points to a single nul-terminated string. Return non-zero if zStr
21423 ** is equal, according to strcmp(), to any of the strings in the array.
21424 ** Otherwise, return zero.
21425 */
str_in_array(const char * zStr,const char ** azArray)21426 static int str_in_array(const char *zStr, const char **azArray){
21427   int i;
21428   for(i=0; azArray[i]; i++){
21429     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
21430   }
21431   return 0;
21432 }
21433 
21434 /*
21435 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
21436 ** and populate the ShellState.aiIndent[] array with the number of
21437 ** spaces each opcode should be indented before it is output.
21438 **
21439 ** The indenting rules are:
21440 **
21441 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
21442 **       all opcodes that occur between the p2 jump destination and the opcode
21443 **       itself by 2 spaces.
21444 **
21445 **     * Do the previous for "Return" instructions for when P2 is positive.
21446 **       See tag-20220407a in wherecode.c and vdbe.c.
21447 **
21448 **     * For each "Goto", if the jump destination is earlier in the program
21449 **       and ends on one of:
21450 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
21451 **       or if the P1 parameter is one instead of zero,
21452 **       then indent all opcodes between the earlier instruction
21453 **       and "Goto" by 2 spaces.
21454 */
explain_data_prepare(ShellState * p,sqlite3_stmt * pSql)21455 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
21456   int *abYield = 0;               /* True if op is an OP_Yield */
21457   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
21458   int iOp;                        /* Index of operation in p->aiIndent[] */
21459 
21460   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
21461                            "Return", 0 };
21462   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
21463                             "Rewind", 0 };
21464   const char *azGoto[] = { "Goto", 0 };
21465 
21466   /* The caller guarantees that the leftmost 4 columns of the statement
21467   ** passed to this function are equivalent to the leftmost 4 columns
21468   ** of EXPLAIN statement output. In practice the statement may be
21469   ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
21470   assert( sqlite3_column_count(pSql)>=4 );
21471   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
21472   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
21473   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
21474   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
21475 
21476   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
21477     int i;
21478     int iAddr = sqlite3_column_int(pSql, 0);
21479     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
21480     int p1 = sqlite3_column_int(pSql, 2);
21481     int p2 = sqlite3_column_int(pSql, 3);
21482 
21483     /* Assuming that p2 is an instruction address, set variable p2op to the
21484     ** index of that instruction in the aiIndent[] array. p2 and p2op may be
21485     ** different if the current instruction is part of a sub-program generated
21486     ** by an SQL trigger or foreign key.  */
21487     int p2op = (p2 + (iOp-iAddr));
21488 
21489     /* Grow the p->aiIndent array as required */
21490     if( iOp>=nAlloc ){
21491       nAlloc += 100;
21492       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
21493       shell_check_oom(p->aiIndent);
21494       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
21495       shell_check_oom(abYield);
21496     }
21497 
21498     abYield[iOp] = str_in_array(zOp, azYield);
21499     p->aiIndent[iOp] = 0;
21500     p->nIndent = iOp+1;
21501     if( str_in_array(zOp, azNext) && p2op>0 ){
21502       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
21503     }
21504     if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
21505       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
21506     }
21507   }
21508 
21509   p->iIndent = 0;
21510   sqlite3_free(abYield);
21511   sqlite3_reset(pSql);
21512 }
21513 
21514 /*
21515 ** Free the array allocated by explain_data_prepare().
21516 */
explain_data_delete(ShellState * p)21517 static void explain_data_delete(ShellState *p){
21518   sqlite3_free(p->aiIndent);
21519   p->aiIndent = 0;
21520   p->nIndent = 0;
21521   p->iIndent = 0;
21522 }
21523 
21524 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
21525 
21526 /*
21527 ** Display scan stats.
21528 */
display_scanstats(sqlite3 * db,ShellState * pArg)21529 static void display_scanstats(
21530   sqlite3 *db,                    /* Database to query */
21531   ShellState *pArg                /* Pointer to ShellState */
21532 ){
21533 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
21534   UNUSED_PARAMETER(db);
21535   UNUSED_PARAMETER(pArg);
21536 #else
21537   if( pArg->scanstatsOn==3 ){
21538     const char *zSql =
21539       "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
21540       "   round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
21541       "   FROM bytecode(?)";
21542 
21543     int rc = SQLITE_OK;
21544     sqlite3_stmt *pStmt = 0;
21545     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
21546     if( rc==SQLITE_OK ){
21547       sqlite3_stmt *pSave = pArg->pStmt;
21548       pArg->pStmt = pStmt;
21549       sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
21550 
21551       pArg->cnt = 0;
21552       pArg->cMode = MODE_ScanExp;
21553       explain_data_prepare(pArg, pStmt);
21554       exec_prepared_stmt(pArg, pStmt);
21555       explain_data_delete(pArg);
21556 
21557       sqlite3_finalize(pStmt);
21558       pArg->pStmt = pSave;
21559     }
21560   }else{
21561     display_explain_scanstats(db, pArg);
21562   }
21563 #endif
21564 }
21565 
21566 /*
21567 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
21568 */
21569 static unsigned int savedSelectTrace;
21570 static unsigned int savedWhereTrace;
disable_debug_trace_modes(void)21571 static void disable_debug_trace_modes(void){
21572   unsigned int zero = 0;
21573   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
21574   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
21575   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
21576   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
21577 }
restore_debug_trace_modes(void)21578 static void restore_debug_trace_modes(void){
21579   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
21580   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
21581 }
21582 
21583 /* Create the TEMP table used to store parameter bindings */
bind_table_init(ShellState * p)21584 static void bind_table_init(ShellState *p){
21585   int wrSchema = 0;
21586   int defensiveMode = 0;
21587   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
21588   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
21589   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
21590   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
21591   sqlite3_exec(p->db,
21592     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
21593     "  key TEXT PRIMARY KEY,\n"
21594     "  value\n"
21595     ") WITHOUT ROWID;",
21596     0, 0, 0);
21597   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
21598   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
21599 }
21600 
21601 /*
21602 ** Bind parameters on a prepared statement.
21603 **
21604 ** Parameter bindings are taken from a TEMP table of the form:
21605 **
21606 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
21607 **    WITHOUT ROWID;
21608 **
21609 ** No bindings occur if this table does not exist.  The name of the table
21610 ** begins with "sqlite_" so that it will not collide with ordinary application
21611 ** tables.  The table must be in the TEMP schema.
21612 */
bind_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)21613 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
21614   int nVar;
21615   int i;
21616   int rc;
21617   sqlite3_stmt *pQ = 0;
21618 
21619   nVar = sqlite3_bind_parameter_count(pStmt);
21620   if( nVar==0 ) return;  /* Nothing to do */
21621   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
21622                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
21623     rc = SQLITE_NOTFOUND;
21624     pQ = 0;
21625   }else{
21626     rc = sqlite3_prepare_v2(pArg->db,
21627             "SELECT value FROM temp.sqlite_parameters"
21628             " WHERE key=?1", -1, &pQ, 0);
21629   }
21630   for(i=1; i<=nVar; i++){
21631     char zNum[30];
21632     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
21633     if( zVar==0 ){
21634       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
21635       zVar = zNum;
21636     }
21637     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
21638     if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
21639       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
21640 #ifdef NAN
21641     }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
21642       sqlite3_bind_double(pStmt, i, NAN);
21643 #endif
21644 #ifdef INFINITY
21645     }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
21646       sqlite3_bind_double(pStmt, i, INFINITY);
21647 #endif
21648     }else{
21649       sqlite3_bind_null(pStmt, i);
21650     }
21651     sqlite3_reset(pQ);
21652   }
21653   sqlite3_finalize(pQ);
21654 }
21655 
21656 /*
21657 ** UTF8 box-drawing characters.  Imagine box lines like this:
21658 **
21659 **           1
21660 **           |
21661 **       4 --+-- 2
21662 **           |
21663 **           3
21664 **
21665 ** Each box characters has between 2 and 4 of the lines leading from
21666 ** the center.  The characters are here identified by the numbers of
21667 ** their corresponding lines.
21668 */
21669 #define BOX_24   "\342\224\200"  /* U+2500 --- */
21670 #define BOX_13   "\342\224\202"  /* U+2502  |  */
21671 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
21672 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
21673 #define BOX_12   "\342\224\224"  /* U+2514  '- */
21674 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
21675 #define BOX_123  "\342\224\234"  /* U+251c  |- */
21676 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
21677 #define BOX_234  "\342\224\254"  /* U+252c -,- */
21678 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
21679 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
21680 
21681 /* Draw horizontal line N characters long using unicode box
21682 ** characters
21683 */
print_box_line(int N)21684 static void print_box_line(int N){
21685   const char zDash[] =
21686       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
21687       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
21688   const int nDash = sizeof(zDash) - 1;
21689   N *= 3;
21690   while( N>nDash ){
21691     oputz(zDash);
21692     N -= nDash;
21693   }
21694   oputf("%.*s", N, zDash);
21695 }
21696 
21697 /*
21698 ** Draw a horizontal separator for a MODE_Box table.
21699 */
print_box_row_separator(ShellState * p,int nArg,const char * zSep1,const char * zSep2,const char * zSep3)21700 static void print_box_row_separator(
21701   ShellState *p,
21702   int nArg,
21703   const char *zSep1,
21704   const char *zSep2,
21705   const char *zSep3
21706 ){
21707   int i;
21708   if( nArg>0 ){
21709     oputz(zSep1);
21710     print_box_line(p->actualWidth[0]+2);
21711     for(i=1; i<nArg; i++){
21712       oputz(zSep2);
21713       print_box_line(p->actualWidth[i]+2);
21714     }
21715     oputz(zSep3);
21716   }
21717   oputz("\n");
21718 }
21719 
21720 /*
21721 ** z[] is a line of text that is to be displayed the .mode box or table or
21722 ** similar tabular formats.  z[] might contain control characters such
21723 ** as \n, \t, \f, or \r.
21724 **
21725 ** Compute characters to display on the first line of z[].  Stop at the
21726 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
21727 ** from malloc()) of that first line, which caller should free sometime.
21728 ** Write anything to display on the next line into *pzTail.  If this is
21729 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
21730 */
translateForDisplayAndDup(const unsigned char * z,const unsigned char ** pzTail,int mxWidth,u8 bWordWrap)21731 static char *translateForDisplayAndDup(
21732   const unsigned char *z,            /* Input text to be transformed */
21733   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
21734   int mxWidth,                       /* Max width.  0 means no limit */
21735   u8 bWordWrap                       /* If true, avoid breaking mid-word */
21736 ){
21737   int i;                 /* Input bytes consumed */
21738   int j;                 /* Output bytes generated */
21739   int k;                 /* Input bytes to be displayed */
21740   int n;                 /* Output column number */
21741   unsigned char *zOut;   /* Output text */
21742 
21743   if( z==0 ){
21744     *pzTail = 0;
21745     return 0;
21746   }
21747   if( mxWidth<0 ) mxWidth = -mxWidth;
21748   if( mxWidth==0 ) mxWidth = 1000000;
21749   i = j = n = 0;
21750   while( n<mxWidth ){
21751     if( z[i]>=' ' ){
21752       n++;
21753       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
21754       continue;
21755     }
21756     if( z[i]=='\t' ){
21757       do{
21758         n++;
21759         j++;
21760       }while( (n&7)!=0 && n<mxWidth );
21761       i++;
21762       continue;
21763     }
21764     break;
21765   }
21766   if( n>=mxWidth && bWordWrap  ){
21767     /* Perhaps try to back up to a better place to break the line */
21768     for(k=i; k>i/2; k--){
21769       if( isspace(z[k-1]) ) break;
21770     }
21771     if( k<=i/2 ){
21772       for(k=i; k>i/2; k--){
21773         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
21774       }
21775     }
21776     if( k<=i/2 ){
21777       k = i;
21778     }else{
21779       i = k;
21780       while( z[i]==' ' ) i++;
21781     }
21782   }else{
21783     k = i;
21784   }
21785   if( n>=mxWidth && z[i]>=' ' ){
21786    *pzTail = &z[i];
21787   }else if( z[i]=='\r' && z[i+1]=='\n' ){
21788     *pzTail = z[i+2] ? &z[i+2] : 0;
21789   }else if( z[i]==0 || z[i+1]==0 ){
21790     *pzTail = 0;
21791   }else{
21792     *pzTail = &z[i+1];
21793   }
21794   zOut = malloc( j+1 );
21795   shell_check_oom(zOut);
21796   i = j = n = 0;
21797   while( i<k ){
21798     if( z[i]>=' ' ){
21799       n++;
21800       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
21801       continue;
21802     }
21803     if( z[i]=='\t' ){
21804       do{
21805         n++;
21806         zOut[j++] = ' ';
21807       }while( (n&7)!=0 && n<mxWidth );
21808       i++;
21809       continue;
21810     }
21811     break;
21812   }
21813   zOut[j] = 0;
21814   return (char*)zOut;
21815 }
21816 
21817 /* Extract the value of the i-th current column for pStmt as an SQL literal
21818 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
21819 ** the caller.
21820 */
quoted_column(sqlite3_stmt * pStmt,int i)21821 static char *quoted_column(sqlite3_stmt *pStmt, int i){
21822   switch( sqlite3_column_type(pStmt, i) ){
21823     case SQLITE_NULL: {
21824       return sqlite3_mprintf("NULL");
21825     }
21826     case SQLITE_INTEGER:
21827     case SQLITE_FLOAT: {
21828       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
21829     }
21830     case SQLITE_TEXT: {
21831       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
21832     }
21833     case SQLITE_BLOB: {
21834       int j;
21835       sqlite3_str *pStr = sqlite3_str_new(0);
21836       const unsigned char *a = sqlite3_column_blob(pStmt,i);
21837       int n = sqlite3_column_bytes(pStmt,i);
21838       sqlite3_str_append(pStr, "x'", 2);
21839       for(j=0; j<n; j++){
21840         sqlite3_str_appendf(pStr, "%02x", a[j]);
21841       }
21842       sqlite3_str_append(pStr, "'", 1);
21843       return sqlite3_str_finish(pStr);
21844     }
21845   }
21846   return 0; /* Not reached */
21847 }
21848 
21849 /*
21850 ** Run a prepared statement and output the result in one of the
21851 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
21852 ** or MODE_Box.
21853 **
21854 ** This is different from ordinary exec_prepared_stmt() in that
21855 ** it has to run the entire query and gather the results into memory
21856 ** first, in order to determine column widths, before providing
21857 ** any output.
21858 */
exec_prepared_stmt_columnar(ShellState * p,sqlite3_stmt * pStmt)21859 static void exec_prepared_stmt_columnar(
21860   ShellState *p,                        /* Pointer to ShellState */
21861   sqlite3_stmt *pStmt                   /* Statement to run */
21862 ){
21863   sqlite3_int64 nRow = 0;
21864   int nColumn = 0;
21865   char **azData = 0;
21866   sqlite3_int64 nAlloc = 0;
21867   char *abRowDiv = 0;
21868   const unsigned char *uz;
21869   const char *z;
21870   char **azQuoted = 0;
21871   int rc;
21872   sqlite3_int64 i, nData;
21873   int j, nTotal, w, n;
21874   const char *colSep = 0;
21875   const char *rowSep = 0;
21876   const unsigned char **azNextLine = 0;
21877   int bNextLine = 0;
21878   int bMultiLineRowExists = 0;
21879   int bw = p->cmOpts.bWordWrap;
21880   const char *zEmpty = "";
21881   const char *zShowNull = p->nullValue;
21882 
21883   rc = sqlite3_step(pStmt);
21884   if( rc!=SQLITE_ROW ) return;
21885   nColumn = sqlite3_column_count(pStmt);
21886   if( nColumn==0 ) goto columnar_end;
21887   nAlloc = nColumn*4;
21888   if( nAlloc<=0 ) nAlloc = 1;
21889   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
21890   shell_check_oom(azData);
21891   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
21892   shell_check_oom(azNextLine);
21893   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
21894   if( p->cmOpts.bQuote ){
21895     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
21896     shell_check_oom(azQuoted);
21897     memset(azQuoted, 0, nColumn*sizeof(char*) );
21898   }
21899   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
21900   shell_check_oom(abRowDiv);
21901   if( nColumn>p->nWidth ){
21902     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
21903     shell_check_oom(p->colWidth);
21904     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
21905     p->nWidth = nColumn;
21906     p->actualWidth = &p->colWidth[nColumn];
21907   }
21908   memset(p->actualWidth, 0, nColumn*sizeof(int));
21909   for(i=0; i<nColumn; i++){
21910     w = p->colWidth[i];
21911     if( w<0 ) w = -w;
21912     p->actualWidth[i] = w;
21913   }
21914   for(i=0; i<nColumn; i++){
21915     const unsigned char *zNotUsed;
21916     int wx = p->colWidth[i];
21917     if( wx==0 ){
21918       wx = p->cmOpts.iWrap;
21919     }
21920     if( wx<0 ) wx = -wx;
21921     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
21922     if( uz==0 ) uz = (u8*)"";
21923     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
21924   }
21925   do{
21926     int useNextLine = bNextLine;
21927     bNextLine = 0;
21928     if( (nRow+2)*nColumn >= nAlloc ){
21929       nAlloc *= 2;
21930       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
21931       shell_check_oom(azData);
21932       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
21933       shell_check_oom(abRowDiv);
21934     }
21935     abRowDiv[nRow] = 1;
21936     nRow++;
21937     for(i=0; i<nColumn; i++){
21938       int wx = p->colWidth[i];
21939       if( wx==0 ){
21940         wx = p->cmOpts.iWrap;
21941       }
21942       if( wx<0 ) wx = -wx;
21943       if( useNextLine ){
21944         uz = azNextLine[i];
21945         if( uz==0 ) uz = (u8*)zEmpty;
21946       }else if( p->cmOpts.bQuote ){
21947         sqlite3_free(azQuoted[i]);
21948         azQuoted[i] = quoted_column(pStmt,i);
21949         uz = (const unsigned char*)azQuoted[i];
21950       }else{
21951         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
21952         if( uz==0 ) uz = (u8*)zShowNull;
21953       }
21954       azData[nRow*nColumn + i]
21955         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
21956       if( azNextLine[i] ){
21957         bNextLine = 1;
21958         abRowDiv[nRow-1] = 0;
21959         bMultiLineRowExists = 1;
21960       }
21961     }
21962   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
21963   nTotal = nColumn*(nRow+1);
21964   for(i=0; i<nTotal; i++){
21965     z = azData[i];
21966     if( z==0 ) z = (char*)zEmpty;
21967     n = strlenChar(z);
21968     j = i%nColumn;
21969     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
21970   }
21971   if( seenInterrupt ) goto columnar_end;
21972   switch( p->cMode ){
21973     case MODE_Column: {
21974       colSep = "  ";
21975       rowSep = "\n";
21976       if( p->showHeader ){
21977         for(i=0; i<nColumn; i++){
21978           w = p->actualWidth[i];
21979           if( p->colWidth[i]<0 ) w = -w;
21980           utf8_width_print(w, azData[i]);
21981           fputs(i==nColumn-1?"\n":"  ", p->out);
21982         }
21983         for(i=0; i<nColumn; i++){
21984           print_dashes(p->actualWidth[i]);
21985           fputs(i==nColumn-1?"\n":"  ", p->out);
21986         }
21987       }
21988       break;
21989     }
21990     case MODE_Table: {
21991       colSep = " | ";
21992       rowSep = " |\n";
21993       print_row_separator(p, nColumn, "+");
21994       fputs("| ", p->out);
21995       for(i=0; i<nColumn; i++){
21996         w = p->actualWidth[i];
21997         n = strlenChar(azData[i]);
21998         oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
21999         oputz(i==nColumn-1?" |\n":" | ");
22000       }
22001       print_row_separator(p, nColumn, "+");
22002       break;
22003     }
22004     case MODE_Markdown: {
22005       colSep = " | ";
22006       rowSep = " |\n";
22007       fputs("| ", p->out);
22008       for(i=0; i<nColumn; i++){
22009         w = p->actualWidth[i];
22010         n = strlenChar(azData[i]);
22011         oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
22012         oputz(i==nColumn-1?" |\n":" | ");
22013       }
22014       print_row_separator(p, nColumn, "|");
22015       break;
22016     }
22017     case MODE_Box: {
22018       colSep = " " BOX_13 " ";
22019       rowSep = " " BOX_13 "\n";
22020       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
22021       oputz(BOX_13 " ");
22022       for(i=0; i<nColumn; i++){
22023         w = p->actualWidth[i];
22024         n = strlenChar(azData[i]);
22025         oputf("%*s%s%*s%s",
22026               (w-n)/2, "", azData[i], (w-n+1)/2, "",
22027               i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
22028       }
22029       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
22030       break;
22031     }
22032   }
22033   for(i=nColumn, j=0; i<nTotal; i++, j++){
22034     if( j==0 && p->cMode!=MODE_Column ){
22035       oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
22036     }
22037     z = azData[i];
22038     if( z==0 ) z = p->nullValue;
22039     w = p->actualWidth[j];
22040     if( p->colWidth[j]<0 ) w = -w;
22041     utf8_width_print(w, z);
22042     if( j==nColumn-1 ){
22043       oputz(rowSep);
22044       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
22045         if( p->cMode==MODE_Table ){
22046           print_row_separator(p, nColumn, "+");
22047         }else if( p->cMode==MODE_Box ){
22048           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
22049         }else if( p->cMode==MODE_Column ){
22050           oputz("\n");
22051         }
22052       }
22053       j = -1;
22054       if( seenInterrupt ) goto columnar_end;
22055     }else{
22056       oputz(colSep);
22057     }
22058   }
22059   if( p->cMode==MODE_Table ){
22060     print_row_separator(p, nColumn, "+");
22061   }else if( p->cMode==MODE_Box ){
22062     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
22063   }
22064 columnar_end:
22065   if( seenInterrupt ){
22066     oputz("Interrupt\n");
22067   }
22068   nData = (nRow+1)*nColumn;
22069   for(i=0; i<nData; i++){
22070     z = azData[i];
22071     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
22072   }
22073   sqlite3_free(azData);
22074   sqlite3_free((void*)azNextLine);
22075   sqlite3_free(abRowDiv);
22076   if( azQuoted ){
22077     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
22078     sqlite3_free(azQuoted);
22079   }
22080 }
22081 
22082 /*
22083 ** Run a prepared statement
22084 */
exec_prepared_stmt(ShellState * pArg,sqlite3_stmt * pStmt)22085 static void exec_prepared_stmt(
22086   ShellState *pArg,                                /* Pointer to ShellState */
22087   sqlite3_stmt *pStmt                              /* Statement to run */
22088 ){
22089   int rc;
22090   sqlite3_uint64 nRow = 0;
22091 
22092   if( pArg->cMode==MODE_Column
22093    || pArg->cMode==MODE_Table
22094    || pArg->cMode==MODE_Box
22095    || pArg->cMode==MODE_Markdown
22096   ){
22097     exec_prepared_stmt_columnar(pArg, pStmt);
22098     return;
22099   }
22100 
22101   /* perform the first step.  this will tell us if we
22102   ** have a result set or not and how wide it is.
22103   */
22104   rc = sqlite3_step(pStmt);
22105   /* if we have a result set... */
22106   if( SQLITE_ROW == rc ){
22107     /* allocate space for col name ptr, value ptr, and type */
22108     int nCol = sqlite3_column_count(pStmt);
22109     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
22110     if( !pData ){
22111       shell_out_of_memory();
22112     }else{
22113       char **azCols = (char **)pData;      /* Names of result columns */
22114       char **azVals = &azCols[nCol];       /* Results */
22115       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
22116       int i, x;
22117       assert(sizeof(int) <= sizeof(char *));
22118       /* save off ptrs to column names */
22119       for(i=0; i<nCol; i++){
22120         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
22121       }
22122       do{
22123         nRow++;
22124         /* extract the data and data types */
22125         for(i=0; i<nCol; i++){
22126           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
22127           if( x==SQLITE_BLOB
22128            && pArg
22129            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
22130           ){
22131             azVals[i] = "";
22132           }else{
22133             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
22134           }
22135           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
22136             rc = SQLITE_NOMEM;
22137             break; /* from for */
22138           }
22139         } /* end for */
22140 
22141         /* if data and types extracted successfully... */
22142         if( SQLITE_ROW == rc ){
22143           /* call the supplied callback with the result row data */
22144           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
22145             rc = SQLITE_ABORT;
22146           }else{
22147             rc = sqlite3_step(pStmt);
22148           }
22149         }
22150       } while( SQLITE_ROW == rc );
22151       sqlite3_free(pData);
22152       if( pArg->cMode==MODE_Json ){
22153         fputs("]\n", pArg->out);
22154       }else if( pArg->cMode==MODE_Count ){
22155         char zBuf[200];
22156         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
22157                          nRow, nRow!=1 ? "s" : "");
22158         printf("%s", zBuf);
22159       }
22160     }
22161   }
22162 }
22163 
22164 #ifndef SQLITE_OMIT_VIRTUALTABLE
22165 /*
22166 ** This function is called to process SQL if the previous shell command
22167 ** was ".expert". It passes the SQL in the second argument directly to
22168 ** the sqlite3expert object.
22169 **
22170 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
22171 ** code. In this case, (*pzErr) may be set to point to a buffer containing
22172 ** an English language error message. It is the responsibility of the
22173 ** caller to eventually free this buffer using sqlite3_free().
22174 */
expertHandleSQL(ShellState * pState,const char * zSql,char ** pzErr)22175 static int expertHandleSQL(
22176   ShellState *pState,
22177   const char *zSql,
22178   char **pzErr
22179 ){
22180   assert( pState->expert.pExpert );
22181   assert( pzErr==0 || *pzErr==0 );
22182   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
22183 }
22184 
22185 /*
22186 ** This function is called either to silently clean up the object
22187 ** created by the ".expert" command (if bCancel==1), or to generate a
22188 ** report from it and then clean it up (if bCancel==0).
22189 **
22190 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
22191 ** code. In this case, (*pzErr) may be set to point to a buffer containing
22192 ** an English language error message. It is the responsibility of the
22193 ** caller to eventually free this buffer using sqlite3_free().
22194 */
expertFinish(ShellState * pState,int bCancel,char ** pzErr)22195 static int expertFinish(
22196   ShellState *pState,
22197   int bCancel,
22198   char **pzErr
22199 ){
22200   int rc = SQLITE_OK;
22201   sqlite3expert *p = pState->expert.pExpert;
22202   assert( p );
22203   assert( bCancel || pzErr==0 || *pzErr==0 );
22204   if( bCancel==0 ){
22205     int bVerbose = pState->expert.bVerbose;
22206 
22207     rc = sqlite3_expert_analyze(p, pzErr);
22208     if( rc==SQLITE_OK ){
22209       int nQuery = sqlite3_expert_count(p);
22210       int i;
22211 
22212       if( bVerbose ){
22213         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
22214         oputz("-- Candidates -----------------------------\n");
22215         oputf("%s\n", zCand);
22216       }
22217       for(i=0; i<nQuery; i++){
22218         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
22219         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
22220         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
22221         if( zIdx==0 ) zIdx = "(no new indexes)\n";
22222         if( bVerbose ){
22223           oputf("-- Query %d --------------------------------\n",i+1);
22224           oputf("%s\n\n", zSql);
22225         }
22226         oputf("%s\n", zIdx);
22227         oputf("%s\n", zEQP);
22228       }
22229     }
22230   }
22231   sqlite3_expert_destroy(p);
22232   pState->expert.pExpert = 0;
22233   return rc;
22234 }
22235 
22236 /*
22237 ** Implementation of ".expert" dot command.
22238 */
expertDotCommand(ShellState * pState,char ** azArg,int nArg)22239 static int expertDotCommand(
22240   ShellState *pState,             /* Current shell tool state */
22241   char **azArg,                   /* Array of arguments passed to dot command */
22242   int nArg                        /* Number of entries in azArg[] */
22243 ){
22244   int rc = SQLITE_OK;
22245   char *zErr = 0;
22246   int i;
22247   int iSample = 0;
22248 
22249   assert( pState->expert.pExpert==0 );
22250   memset(&pState->expert, 0, sizeof(ExpertInfo));
22251 
22252   for(i=1; rc==SQLITE_OK && i<nArg; i++){
22253     char *z = azArg[i];
22254     int n;
22255     if( z[0]=='-' && z[1]=='-' ) z++;
22256     n = strlen30(z);
22257     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
22258       pState->expert.bVerbose = 1;
22259     }
22260     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
22261       if( i==(nArg-1) ){
22262         eputf("option requires an argument: %s\n", z);
22263         rc = SQLITE_ERROR;
22264       }else{
22265         iSample = (int)integerValue(azArg[++i]);
22266         if( iSample<0 || iSample>100 ){
22267           eputf("value out of range: %s\n", azArg[i]);
22268           rc = SQLITE_ERROR;
22269         }
22270       }
22271     }
22272     else{
22273       eputf("unknown option: %s\n", z);
22274       rc = SQLITE_ERROR;
22275     }
22276   }
22277 
22278   if( rc==SQLITE_OK ){
22279     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
22280     if( pState->expert.pExpert==0 ){
22281       eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
22282       rc = SQLITE_ERROR;
22283     }else{
22284       sqlite3_expert_config(
22285           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
22286       );
22287     }
22288   }
22289   sqlite3_free(zErr);
22290 
22291   return rc;
22292 }
22293 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
22294 
22295 /*
22296 ** Execute a statement or set of statements.  Print
22297 ** any result rows/columns depending on the current mode
22298 ** set via the supplied callback.
22299 **
22300 ** This is very similar to SQLite's built-in sqlite3_exec()
22301 ** function except it takes a slightly different callback
22302 ** and callback data argument.
22303 */
shell_exec(ShellState * pArg,const char * zSql,char ** pzErrMsg)22304 static int shell_exec(
22305   ShellState *pArg,                         /* Pointer to ShellState */
22306   const char *zSql,                         /* SQL to be evaluated */
22307   char **pzErrMsg                           /* Error msg written here */
22308 ){
22309   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
22310   int rc = SQLITE_OK;             /* Return Code */
22311   int rc2;
22312   const char *zLeftover;          /* Tail of unprocessed SQL */
22313   sqlite3 *db = pArg->db;
22314 
22315   if( pzErrMsg ){
22316     *pzErrMsg = NULL;
22317   }
22318 
22319 #ifndef SQLITE_OMIT_VIRTUALTABLE
22320   if( pArg->expert.pExpert ){
22321     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
22322     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
22323   }
22324 #endif
22325 
22326   while( zSql[0] && (SQLITE_OK == rc) ){
22327     static const char *zStmtSql;
22328     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
22329     if( SQLITE_OK != rc ){
22330       if( pzErrMsg ){
22331         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
22332       }
22333     }else{
22334       if( !pStmt ){
22335         /* this happens for a comment or white-space */
22336         zSql = zLeftover;
22337         while( IsSpace(zSql[0]) ) zSql++;
22338         continue;
22339       }
22340       zStmtSql = sqlite3_sql(pStmt);
22341       if( zStmtSql==0 ) zStmtSql = "";
22342       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
22343 
22344       /* save off the prepared statement handle and reset row count */
22345       if( pArg ){
22346         pArg->pStmt = pStmt;
22347         pArg->cnt = 0;
22348       }
22349 
22350       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
22351       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
22352         sqlite3_stmt *pExplain;
22353         int triggerEQP = 0;
22354         disable_debug_trace_modes();
22355         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
22356         if( pArg->autoEQP>=AUTOEQP_trigger ){
22357           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
22358         }
22359         pExplain = pStmt;
22360         sqlite3_reset(pExplain);
22361         rc = sqlite3_stmt_explain(pExplain, 2);
22362         if( rc==SQLITE_OK ){
22363           while( sqlite3_step(pExplain)==SQLITE_ROW ){
22364             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
22365             int iEqpId = sqlite3_column_int(pExplain, 0);
22366             int iParentId = sqlite3_column_int(pExplain, 1);
22367             if( zEQPLine==0 ) zEQPLine = "";
22368             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
22369             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
22370           }
22371           eqp_render(pArg, 0);
22372         }
22373         if( pArg->autoEQP>=AUTOEQP_full ){
22374           /* Also do an EXPLAIN for ".eqp full" mode */
22375           sqlite3_reset(pExplain);
22376           rc = sqlite3_stmt_explain(pExplain, 1);
22377           if( rc==SQLITE_OK ){
22378             pArg->cMode = MODE_Explain;
22379             assert( sqlite3_stmt_isexplain(pExplain)==1 );
22380             explain_data_prepare(pArg, pExplain);
22381             exec_prepared_stmt(pArg, pExplain);
22382             explain_data_delete(pArg);
22383           }
22384         }
22385         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
22386           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
22387         }
22388         sqlite3_reset(pStmt);
22389         sqlite3_stmt_explain(pStmt, 0);
22390         restore_debug_trace_modes();
22391       }
22392 
22393       if( pArg ){
22394         int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
22395         pArg->cMode = pArg->mode;
22396         if( pArg->autoExplain ){
22397           if( bIsExplain ){
22398             pArg->cMode = MODE_Explain;
22399           }
22400           if( sqlite3_stmt_isexplain(pStmt)==2 ){
22401             pArg->cMode = MODE_EQP;
22402           }
22403         }
22404 
22405         /* If the shell is currently in ".explain" mode, gather the extra
22406         ** data required to add indents to the output.*/
22407         if( pArg->cMode==MODE_Explain && bIsExplain ){
22408           explain_data_prepare(pArg, pStmt);
22409         }
22410       }
22411 
22412       bind_prepared_stmt(pArg, pStmt);
22413       exec_prepared_stmt(pArg, pStmt);
22414       explain_data_delete(pArg);
22415       eqp_render(pArg, 0);
22416 
22417       /* print usage stats if stats on */
22418       if( pArg && pArg->statsOn ){
22419         display_stats(db, pArg, 0);
22420       }
22421 
22422       /* print loop-counters if required */
22423       if( pArg && pArg->scanstatsOn ){
22424         display_scanstats(db, pArg);
22425       }
22426 
22427       /* Finalize the statement just executed. If this fails, save a
22428       ** copy of the error message. Otherwise, set zSql to point to the
22429       ** next statement to execute. */
22430       rc2 = sqlite3_finalize(pStmt);
22431       if( rc!=SQLITE_NOMEM ) rc = rc2;
22432       if( rc==SQLITE_OK ){
22433         zSql = zLeftover;
22434         while( IsSpace(zSql[0]) ) zSql++;
22435       }else if( pzErrMsg ){
22436         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
22437       }
22438 
22439       /* clear saved stmt handle */
22440       if( pArg ){
22441         pArg->pStmt = NULL;
22442       }
22443     }
22444   } /* end while */
22445 
22446   return rc;
22447 }
22448 
22449 /*
22450 ** Release memory previously allocated by tableColumnList().
22451 */
freeColumnList(char ** azCol)22452 static void freeColumnList(char **azCol){
22453   int i;
22454   for(i=1; azCol[i]; i++){
22455     sqlite3_free(azCol[i]);
22456   }
22457   /* azCol[0] is a static string */
22458   sqlite3_free(azCol);
22459 }
22460 
22461 /*
22462 ** Return a list of pointers to strings which are the names of all
22463 ** columns in table zTab.   The memory to hold the names is dynamically
22464 ** allocated and must be released by the caller using a subsequent call
22465 ** to freeColumnList().
22466 **
22467 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
22468 ** value that needs to be preserved, then azCol[0] is filled in with the
22469 ** name of the rowid column.
22470 **
22471 ** The first regular column in the table is azCol[1].  The list is terminated
22472 ** by an entry with azCol[i]==0.
22473 */
tableColumnList(ShellState * p,const char * zTab)22474 static char **tableColumnList(ShellState *p, const char *zTab){
22475   char **azCol = 0;
22476   sqlite3_stmt *pStmt;
22477   char *zSql;
22478   int nCol = 0;
22479   int nAlloc = 0;
22480   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
22481   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
22482   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
22483   int rc;
22484 
22485   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
22486   shell_check_oom(zSql);
22487   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
22488   sqlite3_free(zSql);
22489   if( rc ) return 0;
22490   while( sqlite3_step(pStmt)==SQLITE_ROW ){
22491     if( nCol>=nAlloc-2 ){
22492       nAlloc = nAlloc*2 + nCol + 10;
22493       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
22494       shell_check_oom(azCol);
22495     }
22496     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
22497     shell_check_oom(azCol[nCol]);
22498     if( sqlite3_column_int(pStmt, 5) ){
22499       nPK++;
22500       if( nPK==1
22501        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
22502                           "INTEGER")==0
22503       ){
22504         isIPK = 1;
22505       }else{
22506         isIPK = 0;
22507       }
22508     }
22509   }
22510   sqlite3_finalize(pStmt);
22511   if( azCol==0 ) return 0;
22512   azCol[0] = 0;
22513   azCol[nCol+1] = 0;
22514 
22515   /* The decision of whether or not a rowid really needs to be preserved
22516   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
22517   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
22518   ** rowids on tables where the rowid is inaccessible because there are other
22519   ** columns in the table named "rowid", "_rowid_", and "oid".
22520   */
22521   if( preserveRowid && isIPK ){
22522     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
22523     ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
22524     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
22525     ** ROWID aliases.  To distinguish these cases, check to see if
22526     ** there is a "pk" entry in "PRAGMA index_list".  There will be
22527     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
22528     */
22529     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
22530                            " WHERE origin='pk'", zTab);
22531     shell_check_oom(zSql);
22532     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
22533     sqlite3_free(zSql);
22534     if( rc ){
22535       freeColumnList(azCol);
22536       return 0;
22537     }
22538     rc = sqlite3_step(pStmt);
22539     sqlite3_finalize(pStmt);
22540     preserveRowid = rc==SQLITE_ROW;
22541   }
22542   if( preserveRowid ){
22543     /* Only preserve the rowid if we can find a name to use for the
22544     ** rowid */
22545     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
22546     int i, j;
22547     for(j=0; j<3; j++){
22548       for(i=1; i<=nCol; i++){
22549         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
22550       }
22551       if( i>nCol ){
22552         /* At this point, we know that azRowid[j] is not the name of any
22553         ** ordinary column in the table.  Verify that azRowid[j] is a valid
22554         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
22555         ** tables will fail this last check */
22556         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
22557         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
22558         break;
22559       }
22560     }
22561   }
22562   return azCol;
22563 }
22564 
22565 /*
22566 ** Toggle the reverse_unordered_selects setting.
22567 */
toggleSelectOrder(sqlite3 * db)22568 static void toggleSelectOrder(sqlite3 *db){
22569   sqlite3_stmt *pStmt = 0;
22570   int iSetting = 0;
22571   char zStmt[100];
22572   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
22573   if( sqlite3_step(pStmt)==SQLITE_ROW ){
22574     iSetting = sqlite3_column_int(pStmt, 0);
22575   }
22576   sqlite3_finalize(pStmt);
22577   sqlite3_snprintf(sizeof(zStmt), zStmt,
22578        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
22579   sqlite3_exec(db, zStmt, 0, 0, 0);
22580 }
22581 
22582 /*
22583 ** This is a different callback routine used for dumping the database.
22584 ** Each row received by this callback consists of a table name,
22585 ** the table type ("index" or "table") and SQL to create the table.
22586 ** This routine should print text sufficient to recreate the table.
22587 */
dump_callback(void * pArg,int nArg,char ** azArg,char ** azNotUsed)22588 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
22589   int rc;
22590   const char *zTable;
22591   const char *zType;
22592   const char *zSql;
22593   ShellState *p = (ShellState *)pArg;
22594   int dataOnly;
22595   int noSys;
22596 
22597   UNUSED_PARAMETER(azNotUsed);
22598   if( nArg!=3 || azArg==0 ) return 0;
22599   zTable = azArg[0];
22600   zType = azArg[1];
22601   zSql = azArg[2];
22602   if( zTable==0 ) return 0;
22603   if( zType==0 ) return 0;
22604   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
22605   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
22606 
22607   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
22608     if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
22609   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
22610     if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
22611   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
22612     return 0;
22613   }else if( dataOnly ){
22614     /* no-op */
22615   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
22616     char *zIns;
22617     if( !p->writableSchema ){
22618       oputz("PRAGMA writable_schema=ON;\n");
22619       p->writableSchema = 1;
22620     }
22621     zIns = sqlite3_mprintf(
22622        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
22623        "VALUES('table','%q','%q',0,'%q');",
22624        zTable, zTable, zSql);
22625     shell_check_oom(zIns);
22626     oputf("%s\n", zIns);
22627     sqlite3_free(zIns);
22628     return 0;
22629   }else{
22630     printSchemaLine(zSql, ";\n");
22631   }
22632 
22633   if( cli_strcmp(zType, "table")==0 ){
22634     ShellText sSelect;
22635     ShellText sTable;
22636     char **azCol;
22637     int i;
22638     char *savedDestTable;
22639     int savedMode;
22640 
22641     azCol = tableColumnList(p, zTable);
22642     if( azCol==0 ){
22643       p->nErr++;
22644       return 0;
22645     }
22646 
22647     /* Always quote the table name, even if it appears to be pure ascii,
22648     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
22649     initText(&sTable);
22650     appendText(&sTable, zTable, quoteChar(zTable));
22651     /* If preserving the rowid, add a column list after the table name.
22652     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
22653     ** instead of the usual "INSERT INTO tab VALUES(...)".
22654     */
22655     if( azCol[0] ){
22656       appendText(&sTable, "(", 0);
22657       appendText(&sTable, azCol[0], 0);
22658       for(i=1; azCol[i]; i++){
22659         appendText(&sTable, ",", 0);
22660         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
22661       }
22662       appendText(&sTable, ")", 0);
22663     }
22664 
22665     /* Build an appropriate SELECT statement */
22666     initText(&sSelect);
22667     appendText(&sSelect, "SELECT ", 0);
22668     if( azCol[0] ){
22669       appendText(&sSelect, azCol[0], 0);
22670       appendText(&sSelect, ",", 0);
22671     }
22672     for(i=1; azCol[i]; i++){
22673       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
22674       if( azCol[i+1] ){
22675         appendText(&sSelect, ",", 0);
22676       }
22677     }
22678     freeColumnList(azCol);
22679     appendText(&sSelect, " FROM ", 0);
22680     appendText(&sSelect, zTable, quoteChar(zTable));
22681 
22682     savedDestTable = p->zDestTable;
22683     savedMode = p->mode;
22684     p->zDestTable = sTable.z;
22685     p->mode = p->cMode = MODE_Insert;
22686     rc = shell_exec(p, sSelect.z, 0);
22687     if( (rc&0xff)==SQLITE_CORRUPT ){
22688       oputz("/****** CORRUPTION ERROR *******/\n");
22689       toggleSelectOrder(p->db);
22690       shell_exec(p, sSelect.z, 0);
22691       toggleSelectOrder(p->db);
22692     }
22693     p->zDestTable = savedDestTable;
22694     p->mode = savedMode;
22695     freeText(&sTable);
22696     freeText(&sSelect);
22697     if( rc ) p->nErr++;
22698   }
22699   return 0;
22700 }
22701 
22702 /*
22703 ** Run zQuery.  Use dump_callback() as the callback routine so that
22704 ** the contents of the query are output as SQL statements.
22705 **
22706 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
22707 ** "ORDER BY rowid DESC" to the end.
22708 */
run_schema_dump_query(ShellState * p,const char * zQuery)22709 static int run_schema_dump_query(
22710   ShellState *p,
22711   const char *zQuery
22712 ){
22713   int rc;
22714   char *zErr = 0;
22715   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
22716   if( rc==SQLITE_CORRUPT ){
22717     char *zQ2;
22718     int len = strlen30(zQuery);
22719     oputz("/****** CORRUPTION ERROR *******/\n");
22720     if( zErr ){
22721       oputf("/****** %s ******/\n", zErr);
22722       sqlite3_free(zErr);
22723       zErr = 0;
22724     }
22725     zQ2 = malloc( len+100 );
22726     if( zQ2==0 ) return rc;
22727     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
22728     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
22729     if( rc ){
22730       oputf("/****** ERROR: %s ******/\n", zErr);
22731     }else{
22732       rc = SQLITE_CORRUPT;
22733     }
22734     sqlite3_free(zErr);
22735     free(zQ2);
22736   }
22737   return rc;
22738 }
22739 
22740 /*
22741 ** Text of help messages.
22742 **
22743 ** The help text for each individual command begins with a line that starts
22744 ** with ".".  Subsequent lines are supplemental information.
22745 **
22746 ** There must be two or more spaces between the end of the command and the
22747 ** start of the description of what that command does.
22748 */
22749 static const char *(azHelp[]) = {
22750 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
22751   && !defined(SQLITE_SHELL_FIDDLE)
22752   ".archive ...             Manage SQL archives",
22753   "   Each command must have exactly one of the following options:",
22754   "     -c, --create               Create a new archive",
22755   "     -u, --update               Add or update files with changed mtime",
22756   "     -i, --insert               Like -u but always add even if unchanged",
22757   "     -r, --remove               Remove files from archive",
22758   "     -t, --list                 List contents of archive",
22759   "     -x, --extract              Extract files from archive",
22760   "   Optional arguments:",
22761   "     -v, --verbose              Print each filename as it is processed",
22762   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
22763   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
22764   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
22765   "     -g, --glob                 Use glob matching for names in archive",
22766   "     -n, --dryrun               Show the SQL that would have occurred",
22767   "   Examples:",
22768   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
22769   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
22770   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
22771   "   See also:",
22772   "      http://sqlite.org/cli.html#sqlite_archive_support",
22773 #endif
22774 #ifndef SQLITE_OMIT_AUTHORIZATION
22775   ".auth ON|OFF             Show authorizer callbacks",
22776 #endif
22777 #ifndef SQLITE_SHELL_FIDDLE
22778   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
22779   "   Options:",
22780   "       --append            Use the appendvfs",
22781   "       --async             Write to FILE without journal and fsync()",
22782 #endif
22783   ".bail on|off             Stop after hitting an error.  Default OFF",
22784 #ifndef SQLITE_SHELL_FIDDLE
22785   ".cd DIRECTORY            Change the working directory to DIRECTORY",
22786 #endif
22787   ".changes on|off          Show number of rows changed by SQL",
22788 #ifndef SQLITE_SHELL_FIDDLE
22789   ".check GLOB              Fail if output since .testcase does not match",
22790   ".clone NEWDB             Clone data into NEWDB from the existing database",
22791 #endif
22792   ".connection [close] [#]  Open or close an auxiliary database connection",
22793 #if defined(_WIN32) || defined(WIN32)
22794   ".crnl on|off             Translate \\n to \\r\\n.  Default ON",
22795 #endif
22796   ".databases               List names and files of attached databases",
22797   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
22798 #if SQLITE_SHELL_HAVE_RECOVER
22799   ".dbinfo ?DB?             Show status information about the database",
22800 #endif
22801   ".dump ?OBJECTS?          Render database content as SQL",
22802   "   Options:",
22803   "     --data-only            Output only INSERT statements",
22804   "     --newlines             Allow unescaped newline characters in output",
22805   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
22806   "     --preserve-rowids      Include ROWID values in the output",
22807   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
22808   "   Additional LIKE patterns can be given in subsequent arguments",
22809   ".echo on|off             Turn command echo on or off",
22810   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
22811   "   Other Modes:",
22812 #ifdef SQLITE_DEBUG
22813   "      test                  Show raw EXPLAIN QUERY PLAN output",
22814   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
22815 #endif
22816   "      trigger               Like \"full\" but also show trigger bytecode",
22817 #ifndef SQLITE_SHELL_FIDDLE
22818   ".excel                   Display the output of next command in spreadsheet",
22819   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
22820 #endif
22821 #ifndef SQLITE_SHELL_FIDDLE
22822   ".exit ?CODE?             Exit this program with return-code CODE",
22823 #endif
22824   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
22825   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
22826   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
22827   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
22828   "   --help                  Show CMD details",
22829   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
22830   ".headers on|off          Turn display of headers on or off",
22831   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
22832 #ifndef SQLITE_SHELL_FIDDLE
22833   ".import FILE TABLE       Import data from FILE into TABLE",
22834   "   Options:",
22835   "     --ascii               Use \\037 and \\036 as column and row separators",
22836   "     --csv                 Use , and \\n as column and row separators",
22837   "     --skip N              Skip the first N rows of input",
22838   "     --schema S            Target table to be S.TABLE",
22839   "     -v                    \"Verbose\" - increase auxiliary output",
22840   "   Notes:",
22841   "     *  If TABLE does not exist, it is created.  The first row of input",
22842   "        determines the column names.",
22843   "     *  If neither --csv or --ascii are used, the input mode is derived",
22844   "        from the \".mode\" output mode",
22845   "     *  If FILE begins with \"|\" then it is a command that generates the",
22846   "        input text.",
22847 #endif
22848 #ifndef SQLITE_OMIT_TEST_CONTROL
22849   ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
22850 #endif
22851   ".indexes ?TABLE?         Show names of indexes",
22852   "                           If TABLE is specified, only show indexes for",
22853   "                           tables matching TABLE using the LIKE operator.",
22854   ".intck ?STEPS_PER_UNLOCK?  Run an incremental integrity check on the db",
22855 #ifdef SQLITE_ENABLE_IOTRACE
22856   ",iotrace FILE            Enable I/O diagnostic logging to FILE",
22857 #endif
22858   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
22859   ".lint OPTIONS            Report potential schema issues.",
22860   "     Options:",
22861   "        fkey-indexes     Find missing foreign key indexes",
22862 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
22863   ".load FILE ?ENTRY?       Load an extension library",
22864 #endif
22865 #if !defined(SQLITE_SHELL_FIDDLE)
22866   ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
22867 #else
22868   ".log on|off              Turn logging on or off.",
22869 #endif
22870   ".mode MODE ?OPTIONS?     Set output mode",
22871   "   MODE is one of:",
22872   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
22873   "     box         Tables using unicode box-drawing characters",
22874   "     csv         Comma-separated values",
22875   "     column      Output in columns.  (See .width)",
22876   "     html        HTML <table> code",
22877   "     insert      SQL insert statements for TABLE",
22878   "     json        Results in a JSON array",
22879   "     line        One value per line",
22880   "     list        Values delimited by \"|\"",
22881   "     markdown    Markdown table format",
22882   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
22883   "     quote       Escape answers as for SQL",
22884   "     table       ASCII-art table",
22885   "     tabs        Tab-separated values",
22886   "     tcl         TCL list elements",
22887   "   OPTIONS: (for columnar modes or insert mode):",
22888   "     --wrap N       Wrap output lines to no longer than N characters",
22889   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
22890   "     --ww           Shorthand for \"--wordwrap 1\"",
22891   "     --quote        Quote output text as SQL literals",
22892   "     --noquote      Do not quote output text",
22893   "     TABLE          The name of SQL table used for \"insert\" mode",
22894 #ifndef SQLITE_SHELL_FIDDLE
22895   ".nonce STRING            Suspend safe mode for one command if nonce matches",
22896 #endif
22897   ".nullvalue STRING        Use STRING in place of NULL values",
22898 #ifndef SQLITE_SHELL_FIDDLE
22899   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
22900   "     If FILE begins with '|' then open as a pipe",
22901   "       --bom  Put a UTF8 byte-order mark at the beginning",
22902   "       -e     Send output to the system text editor",
22903   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
22904   /* Note that .open is (partially) available in WASM builds but is
22905   ** currently only intended to be used by the fiddle tool, not
22906   ** end users, so is "undocumented." */
22907   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
22908   "     Options:",
22909   "        --append        Use appendvfs to append database to the end of FILE",
22910 #endif
22911 #ifndef SQLITE_OMIT_DESERIALIZE
22912   "        --deserialize   Load into memory using sqlite3_deserialize()",
22913   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
22914   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
22915 #endif
22916   "        --new           Initialize FILE to an empty database",
22917   "        --nofollow      Do not follow symbolic links",
22918   "        --readonly      Open FILE readonly",
22919   "        --zip           FILE is a ZIP archive",
22920 #ifndef SQLITE_SHELL_FIDDLE
22921   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
22922   "   If FILE begins with '|' then open it as a pipe.",
22923   "   Options:",
22924   "     --bom                 Prefix output with a UTF8 byte-order mark",
22925   "     -e                    Send output to the system text editor",
22926   "     -x                    Send output as CSV to a spreadsheet",
22927 #endif
22928   ".parameter CMD ...       Manage SQL parameter bindings",
22929   "   clear                   Erase all bindings",
22930   "   init                    Initialize the TEMP table that holds bindings",
22931   "   list                    List the current parameter bindings",
22932   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
22933   "                           PARAMETER should start with one of: $ : @ ?",
22934   "   unset PARAMETER         Remove PARAMETER from the binding table",
22935   ".print STRING...         Print literal STRING",
22936 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
22937   ".progress N              Invoke progress handler after every N opcodes",
22938   "   --limit N                 Interrupt after N progress callbacks",
22939   "   --once                    Do no more than one progress interrupt",
22940   "   --quiet|-q                No output except at interrupts",
22941   "   --reset                   Reset the count for each input and interrupt",
22942 #endif
22943   ".prompt MAIN CONTINUE    Replace the standard prompts",
22944 #ifndef SQLITE_SHELL_FIDDLE
22945   ".quit                    Stop interpreting input stream, exit if primary.",
22946   ".read FILE               Read input from FILE or command output",
22947   "    If FILE begins with \"|\", it is a command that generates the input.",
22948 #endif
22949 #if SQLITE_SHELL_HAVE_RECOVER
22950   ".recover                 Recover as much data as possible from corrupt db.",
22951   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
22952   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
22953   "   --no-rowids              Do not attempt to recover rowid values",
22954   "                            that are not also INTEGER PRIMARY KEYs",
22955 #endif
22956 #ifndef SQLITE_SHELL_FIDDLE
22957   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
22958   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
22959 #endif
22960   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
22961   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
22962   "   Options:",
22963   "      --indent             Try to pretty-print the schema",
22964   "      --nosys              Omit objects whose names start with \"sqlite_\"",
22965   ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
22966   "    Options:",
22967   "       --init               Create a new SELFTEST table",
22968   "       -v                   Verbose output",
22969   ".separator COL ?ROW?     Change the column and row separators",
22970 #if defined(SQLITE_ENABLE_SESSION)
22971   ".session ?NAME? CMD ...  Create or control sessions",
22972   "   Subcommands:",
22973   "     attach TABLE             Attach TABLE",
22974   "     changeset FILE           Write a changeset into FILE",
22975   "     close                    Close one session",
22976   "     enable ?BOOLEAN?         Set or query the enable bit",
22977   "     filter GLOB...           Reject tables matching GLOBs",
22978   "     indirect ?BOOLEAN?       Mark or query the indirect status",
22979   "     isempty                  Query whether the session is empty",
22980   "     list                     List currently open session names",
22981   "     open DB NAME             Open a new session on DB",
22982   "     patchset FILE            Write a patchset into FILE",
22983   "   If ?NAME? is omitted, the first defined session is used.",
22984 #endif
22985   ".sha3sum ...             Compute a SHA3 hash of database content",
22986   "    Options:",
22987   "      --schema              Also hash the sqlite_schema table",
22988   "      --sha3-224            Use the sha3-224 algorithm",
22989   "      --sha3-256            Use the sha3-256 algorithm (default)",
22990   "      --sha3-384            Use the sha3-384 algorithm",
22991   "      --sha3-512            Use the sha3-512 algorithm",
22992   "    Any other argument is a LIKE pattern for tables to hash",
22993 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
22994   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
22995 #endif
22996   ".show                    Show the current values for various settings",
22997   ".stats ?ARG?             Show stats or turn stats on or off",
22998   "   off                      Turn off automatic stat display",
22999   "   on                       Turn on automatic stat display",
23000   "   stmt                     Show statement stats",
23001   "   vmstep                   Show the virtual machine step count only",
23002 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
23003   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
23004 #endif
23005   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
23006 #ifndef SQLITE_SHELL_FIDDLE
23007   ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
23008 #endif
23009   ",testctrl CMD ...        Run various sqlite3_test_control() operations",
23010   "                           Run \".testctrl\" with no arguments for details",
23011   ".timeout MS              Try opening locked tables for MS milliseconds",
23012   ".timer on|off            Turn SQL timer on or off",
23013 #ifndef SQLITE_OMIT_TRACE
23014   ".trace ?OPTIONS?         Output each SQL statement as it is run",
23015   "    FILE                    Send output to FILE",
23016   "    stdout                  Send output to stdout",
23017   "    stderr                  Send output to stderr",
23018   "    off                     Disable tracing",
23019   "    --expanded              Expand query parameters",
23020 #ifdef SQLITE_ENABLE_NORMALIZE
23021   "    --normalized            Normal the SQL statements",
23022 #endif
23023   "    --plain                 Show SQL as it is input",
23024   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
23025   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
23026   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
23027   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
23028 #endif /* SQLITE_OMIT_TRACE */
23029 #ifdef SQLITE_DEBUG
23030   ".unmodule NAME ...       Unregister virtual table modules",
23031   "    --allexcept             Unregister everything except those named",
23032 #endif
23033   ".version                 Show source, library and compiler versions",
23034   ".vfsinfo ?AUX?           Information about the top-level VFS",
23035   ".vfslist                 List all available VFSes",
23036   ".vfsname ?AUX?           Print the name of the VFS stack",
23037   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
23038   "     Negative values right-justify",
23039 };
23040 
23041 /*
23042 ** Output help text.
23043 **
23044 ** zPattern describes the set of commands for which help text is provided.
23045 ** If zPattern is NULL, then show all commands, but only give a one-line
23046 ** description of each.
23047 **
23048 ** Return the number of matches.
23049 */
showHelp(FILE * out,const char * zPattern)23050 static int showHelp(FILE *out, const char *zPattern){
23051   int i = 0;
23052   int j = 0;
23053   int n = 0;
23054   char *zPat;
23055   if( zPattern==0
23056    || zPattern[0]=='0'
23057    || cli_strcmp(zPattern,"-a")==0
23058    || cli_strcmp(zPattern,"-all")==0
23059    || cli_strcmp(zPattern,"--all")==0
23060   ){
23061     enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
23062     enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
23063     /* Show all or most commands
23064     ** *zPattern==0   => summary of documented commands only
23065     ** *zPattern=='0' => whole help for undocumented commands
23066     ** Otherwise      => whole help for documented commands
23067     */
23068     enum HelpWanted hw = HW_SummaryOnly;
23069     enum HelpHave hh = HH_More;
23070     if( zPattern!=0 ){
23071       hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
23072     }
23073     for(i=0; i<ArraySize(azHelp); i++){
23074       switch( azHelp[i][0] ){
23075       case ',':
23076         hh = HH_Summary|HH_Undoc;
23077         break;
23078       case '.':
23079         hh = HH_Summary;
23080         break;
23081       default:
23082         hh &= ~HH_Summary;
23083         break;
23084       }
23085       if( ((hw^hh)&HH_Undoc)==0 ){
23086         if( (hh&HH_Summary)!=0 ){
23087           sputf(out, ".%s\n", azHelp[i]+1);
23088           ++n;
23089         }else if( (hw&HW_SummaryOnly)==0 ){
23090           sputf(out, "%s\n", azHelp[i]);
23091         }
23092       }
23093     }
23094   }else{
23095     /* Seek documented commands for which zPattern is an exact prefix */
23096     zPat = sqlite3_mprintf(".%s*", zPattern);
23097     shell_check_oom(zPat);
23098     for(i=0; i<ArraySize(azHelp); i++){
23099       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
23100         sputf(out, "%s\n", azHelp[i]);
23101         j = i+1;
23102         n++;
23103       }
23104     }
23105     sqlite3_free(zPat);
23106     if( n ){
23107       if( n==1 ){
23108         /* when zPattern is a prefix of exactly one command, then include
23109         ** the details of that command, which should begin at offset j */
23110         while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
23111           sputf(out, "%s\n", azHelp[j]);
23112           j++;
23113         }
23114       }
23115       return n;
23116     }
23117     /* Look for documented commands that contain zPattern anywhere.
23118     ** Show complete text of all documented commands that match. */
23119     zPat = sqlite3_mprintf("%%%s%%", zPattern);
23120     shell_check_oom(zPat);
23121     for(i=0; i<ArraySize(azHelp); i++){
23122       if( azHelp[i][0]==',' ){
23123         while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
23124         continue;
23125       }
23126       if( azHelp[i][0]=='.' ) j = i;
23127       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
23128         sputf(out, "%s\n", azHelp[j]);
23129         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
23130           j++;
23131           sputf(out, "%s\n", azHelp[j]);
23132         }
23133         i = j;
23134         n++;
23135       }
23136     }
23137     sqlite3_free(zPat);
23138   }
23139   return n;
23140 }
23141 
23142 /* Forward reference */
23143 static int process_input(ShellState *p);
23144 
23145 /*
23146 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
23147 ** and return a pointer to the buffer. The caller is responsible for freeing
23148 ** the memory.
23149 **
23150 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
23151 ** read.
23152 **
23153 ** For convenience, a nul-terminator byte is always appended to the data read
23154 ** from the file before the buffer is returned. This byte is not included in
23155 ** the final value of (*pnByte), if applicable.
23156 **
23157 ** NULL is returned if any error is encountered. The final value of *pnByte
23158 ** is undefined in this case.
23159 */
readFile(const char * zName,int * pnByte)23160 static char *readFile(const char *zName, int *pnByte){
23161   FILE *in = fopen(zName, "rb");
23162   long nIn;
23163   size_t nRead;
23164   char *pBuf;
23165   int rc;
23166   if( in==0 ) return 0;
23167   rc = fseek(in, 0, SEEK_END);
23168   if( rc!=0 ){
23169     eputf("Error: '%s' not seekable\n", zName);
23170     fclose(in);
23171     return 0;
23172   }
23173   nIn = ftell(in);
23174   rewind(in);
23175   pBuf = sqlite3_malloc64( nIn+1 );
23176   if( pBuf==0 ){
23177     eputz("Error: out of memory\n");
23178     fclose(in);
23179     return 0;
23180   }
23181   nRead = fread(pBuf, nIn, 1, in);
23182   fclose(in);
23183   if( nRead!=1 ){
23184     sqlite3_free(pBuf);
23185     eputf("Error: cannot read '%s'\n", zName);
23186     return 0;
23187   }
23188   pBuf[nIn] = 0;
23189   if( pnByte ) *pnByte = nIn;
23190   return pBuf;
23191 }
23192 
23193 #if defined(SQLITE_ENABLE_SESSION)
23194 /*
23195 ** Close a single OpenSession object and release all of its associated
23196 ** resources.
23197 */
session_close(OpenSession * pSession)23198 static void session_close(OpenSession *pSession){
23199   int i;
23200   sqlite3session_delete(pSession->p);
23201   sqlite3_free(pSession->zName);
23202   for(i=0; i<pSession->nFilter; i++){
23203     sqlite3_free(pSession->azFilter[i]);
23204   }
23205   sqlite3_free(pSession->azFilter);
23206   memset(pSession, 0, sizeof(OpenSession));
23207 }
23208 #endif
23209 
23210 /*
23211 ** Close all OpenSession objects and release all associated resources.
23212 */
23213 #if defined(SQLITE_ENABLE_SESSION)
session_close_all(ShellState * p,int i)23214 static void session_close_all(ShellState *p, int i){
23215   int j;
23216   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
23217   for(j=0; j<pAuxDb->nSession; j++){
23218     session_close(&pAuxDb->aSession[j]);
23219   }
23220   pAuxDb->nSession = 0;
23221 }
23222 #else
23223 # define session_close_all(X,Y)
23224 #endif
23225 
23226 /*
23227 ** Implementation of the xFilter function for an open session.  Omit
23228 ** any tables named by ".session filter" but let all other table through.
23229 */
23230 #if defined(SQLITE_ENABLE_SESSION)
session_filter(void * pCtx,const char * zTab)23231 static int session_filter(void *pCtx, const char *zTab){
23232   OpenSession *pSession = (OpenSession*)pCtx;
23233   int i;
23234   for(i=0; i<pSession->nFilter; i++){
23235     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
23236   }
23237   return 1;
23238 }
23239 #endif
23240 
23241 /*
23242 ** Try to deduce the type of file for zName based on its content.  Return
23243 ** one of the SHELL_OPEN_* constants.
23244 **
23245 ** If the file does not exist or is empty but its name looks like a ZIP
23246 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
23247 ** Otherwise, assume an ordinary database regardless of the filename if
23248 ** the type cannot be determined from content.
23249 */
deduceDatabaseType(const char * zName,int dfltZip)23250 int deduceDatabaseType(const char *zName, int dfltZip){
23251   FILE *f = fopen(zName, "rb");
23252   size_t n;
23253   int rc = SHELL_OPEN_UNSPEC;
23254   char zBuf[100];
23255   if( f==0 ){
23256     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
23257        return SHELL_OPEN_ZIPFILE;
23258     }else{
23259        return SHELL_OPEN_NORMAL;
23260     }
23261   }
23262   n = fread(zBuf, 16, 1, f);
23263   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
23264     fclose(f);
23265     return SHELL_OPEN_NORMAL;
23266   }
23267   fseek(f, -25, SEEK_END);
23268   n = fread(zBuf, 25, 1, f);
23269   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
23270     rc = SHELL_OPEN_APPENDVFS;
23271   }else{
23272     fseek(f, -22, SEEK_END);
23273     n = fread(zBuf, 22, 1, f);
23274     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
23275        && zBuf[3]==0x06 ){
23276       rc = SHELL_OPEN_ZIPFILE;
23277     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
23278       rc = SHELL_OPEN_ZIPFILE;
23279     }
23280   }
23281   fclose(f);
23282   return rc;
23283 }
23284 
23285 #ifndef SQLITE_OMIT_DESERIALIZE
23286 /*
23287 ** Reconstruct an in-memory database using the output from the "dbtotxt"
23288 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
23289 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
23290 */
readHexDb(ShellState * p,int * pnData)23291 static unsigned char *readHexDb(ShellState *p, int *pnData){
23292   unsigned char *a = 0;
23293   int nLine;
23294   int n = 0;
23295   int pgsz = 0;
23296   int iOffset = 0;
23297   int j, k;
23298   int rc;
23299   FILE *in;
23300   const char *zDbFilename = p->pAuxDb->zDbFilename;
23301   unsigned int x[16];
23302   char zLine[1000];
23303   if( zDbFilename ){
23304     in = fopen(zDbFilename, "r");
23305     if( in==0 ){
23306       eputf("cannot open \"%s\" for reading\n", zDbFilename);
23307       return 0;
23308     }
23309     nLine = 0;
23310   }else{
23311     in = p->in;
23312     nLine = p->lineno;
23313     if( in==0 ) in = stdin;
23314   }
23315   *pnData = 0;
23316   nLine++;
23317   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
23318   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
23319   if( rc!=2 ) goto readHexDb_error;
23320   if( n<0 ) goto readHexDb_error;
23321   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
23322   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
23323   a = sqlite3_malloc( n ? n : 1 );
23324   shell_check_oom(a);
23325   memset(a, 0, n);
23326   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
23327     eputz("invalid pagesize\n");
23328     goto readHexDb_error;
23329   }
23330   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
23331     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
23332     if( rc==2 ){
23333       iOffset = k;
23334       continue;
23335     }
23336     if( cli_strncmp(zLine, "| end ", 6)==0 ){
23337       break;
23338     }
23339     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
23340                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
23341                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
23342     if( rc==17 ){
23343       k = iOffset+j;
23344       if( k+16<=n && k>=0 ){
23345         int ii;
23346         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
23347       }
23348     }
23349   }
23350   *pnData = n;
23351   if( in!=p->in ){
23352     fclose(in);
23353   }else{
23354     p->lineno = nLine;
23355   }
23356   return a;
23357 
23358 readHexDb_error:
23359   if( in!=p->in ){
23360     fclose(in);
23361   }else{
23362     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
23363       nLine++;
23364       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
23365     }
23366     p->lineno = nLine;
23367   }
23368   sqlite3_free(a);
23369   eputf("Error on line %d of --hexdb input\n", nLine);
23370   return 0;
23371 }
23372 #endif /* SQLITE_OMIT_DESERIALIZE */
23373 
23374 /*
23375 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
23376 */
shellUSleepFunc(sqlite3_context * context,int argcUnused,sqlite3_value ** argv)23377 static void shellUSleepFunc(
23378   sqlite3_context *context,
23379   int argcUnused,
23380   sqlite3_value **argv
23381 ){
23382   int sleep = sqlite3_value_int(argv[0]);
23383   (void)argcUnused;
23384   sqlite3_sleep(sleep/1000);
23385   sqlite3_result_int(context, sleep);
23386 }
23387 
23388 /* Flags for open_db().
23389 **
23390 ** The default behavior of open_db() is to exit(1) if the database fails to
23391 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
23392 ** but still returns without calling exit.
23393 **
23394 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
23395 ** ZIP archive if the file does not exist or is empty and its name matches
23396 ** the *.zip pattern.
23397 */
23398 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
23399 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
23400 
23401 /*
23402 ** Make sure the database is open.  If it is not, then open it.  If
23403 ** the database fails to open, print an error message and exit.
23404 */
open_db(ShellState * p,int openFlags)23405 static void open_db(ShellState *p, int openFlags){
23406   if( p->db==0 ){
23407     const char *zDbFilename = p->pAuxDb->zDbFilename;
23408     if( p->openMode==SHELL_OPEN_UNSPEC ){
23409       if( zDbFilename==0 || zDbFilename[0]==0 ){
23410         p->openMode = SHELL_OPEN_NORMAL;
23411       }else{
23412         p->openMode = (u8)deduceDatabaseType(zDbFilename,
23413                              (openFlags & OPEN_DB_ZIPFILE)!=0);
23414       }
23415     }
23416     switch( p->openMode ){
23417       case SHELL_OPEN_APPENDVFS: {
23418         sqlite3_open_v2(zDbFilename, &p->db,
23419            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
23420         break;
23421       }
23422       case SHELL_OPEN_HEXDB:
23423       case SHELL_OPEN_DESERIALIZE: {
23424         sqlite3_open(0, &p->db);
23425         break;
23426       }
23427       case SHELL_OPEN_ZIPFILE: {
23428         sqlite3_open(":memory:", &p->db);
23429         break;
23430       }
23431       case SHELL_OPEN_READONLY: {
23432         sqlite3_open_v2(zDbFilename, &p->db,
23433             SQLITE_OPEN_READONLY|p->openFlags, 0);
23434         break;
23435       }
23436       case SHELL_OPEN_UNSPEC:
23437       case SHELL_OPEN_NORMAL: {
23438         sqlite3_open_v2(zDbFilename, &p->db,
23439            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
23440         break;
23441       }
23442     }
23443     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
23444       eputf("Error: unable to open database \"%s\": %s\n",
23445             zDbFilename, sqlite3_errmsg(p->db));
23446       if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
23447         exit(1);
23448       }
23449       sqlite3_close(p->db);
23450       sqlite3_open(":memory:", &p->db);
23451       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
23452         eputz("Also: unable to open substitute in-memory database.\n");
23453         exit(1);
23454       }else{
23455         eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
23456               zDbFilename);
23457       }
23458     }
23459     globalDb = p->db;
23460     sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
23461 
23462     /* Reflect the use or absence of --unsafe-testing invocation. */
23463     {
23464       int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
23465       sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
23466       sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
23467     }
23468 
23469 #ifndef SQLITE_OMIT_LOAD_EXTENSION
23470     sqlite3_enable_load_extension(p->db, 1);
23471 #endif
23472     sqlite3_shathree_init(p->db, 0, 0);
23473     sqlite3_uint_init(p->db, 0, 0);
23474     sqlite3_decimal_init(p->db, 0, 0);
23475     sqlite3_base64_init(p->db, 0, 0);
23476     sqlite3_base85_init(p->db, 0, 0);
23477     sqlite3_regexp_init(p->db, 0, 0);
23478     sqlite3_ieee_init(p->db, 0, 0);
23479     sqlite3_series_init(p->db, 0, 0);
23480 #ifndef SQLITE_SHELL_FIDDLE
23481     sqlite3_fileio_init(p->db, 0, 0);
23482     sqlite3_completion_init(p->db, 0, 0);
23483 #endif
23484 #ifdef SQLITE_HAVE_ZLIB
23485     if( !p->bSafeModePersist ){
23486       sqlite3_zipfile_init(p->db, 0, 0);
23487       sqlite3_sqlar_init(p->db, 0, 0);
23488     }
23489 #endif
23490 #ifdef SQLITE_SHELL_EXTFUNCS
23491     /* Create a preprocessing mechanism for extensions to make
23492      * their own provisions for being built into the shell.
23493      * This is a short-span macro. See further below for usage.
23494      */
23495 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
23496 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
23497     /* Let custom-included extensions get their ..._init() called.
23498      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
23499      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
23500      * initialization routine to be called.
23501      */
23502     {
23503       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
23504     /* Let custom-included extensions expose their functionality.
23505      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
23506      * the SQL functions, virtual tables, collating sequences or
23507      * VFS's implemented by the extension to be registered.
23508      */
23509       if( irc==SQLITE_OK
23510           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
23511         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
23512       }
23513 #undef SHELL_SUB_MACRO
23514 #undef SHELL_SUBMACRO
23515     }
23516 #endif
23517 
23518     sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
23519                             shellStrtod, 0, 0);
23520     sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
23521                             shellDtostr, 0, 0);
23522     sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
23523                             shellDtostr, 0, 0);
23524     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
23525                             shellAddSchemaName, 0, 0);
23526     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
23527                             shellModuleSchema, 0, 0);
23528     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
23529                             shellPutsFunc, 0, 0);
23530     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
23531                             shellUSleepFunc, 0, 0);
23532 #ifndef SQLITE_NOHAVE_SYSTEM
23533     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
23534                             editFunc, 0, 0);
23535     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
23536                             editFunc, 0, 0);
23537 #endif
23538 
23539     if( p->openMode==SHELL_OPEN_ZIPFILE ){
23540       char *zSql = sqlite3_mprintf(
23541          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
23542       shell_check_oom(zSql);
23543       sqlite3_exec(p->db, zSql, 0, 0, 0);
23544       sqlite3_free(zSql);
23545     }
23546 #ifndef SQLITE_OMIT_DESERIALIZE
23547     else
23548     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
23549       int rc;
23550       int nData = 0;
23551       unsigned char *aData;
23552       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
23553         aData = (unsigned char*)readFile(zDbFilename, &nData);
23554       }else{
23555         aData = readHexDb(p, &nData);
23556       }
23557       if( aData==0 ){
23558         return;
23559       }
23560       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
23561                    SQLITE_DESERIALIZE_RESIZEABLE |
23562                    SQLITE_DESERIALIZE_FREEONCLOSE);
23563       if( rc ){
23564         eputf("Error: sqlite3_deserialize() returns %d\n", rc);
23565       }
23566       if( p->szMax>0 ){
23567         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
23568       }
23569     }
23570 #endif
23571   }
23572   if( p->db!=0 ){
23573     if( p->bSafeModePersist ){
23574       sqlite3_set_authorizer(p->db, safeModeAuth, p);
23575     }
23576     sqlite3_db_config(
23577         p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
23578     );
23579   }
23580 }
23581 
23582 /*
23583 ** Attempt to close the database connection.  Report errors.
23584 */
close_db(sqlite3 * db)23585 void close_db(sqlite3 *db){
23586   int rc = sqlite3_close(db);
23587   if( rc ){
23588     eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
23589   }
23590 }
23591 
23592 #if HAVE_READLINE || HAVE_EDITLINE
23593 /*
23594 ** Readline completion callbacks
23595 */
readline_completion_generator(const char * text,int state)23596 static char *readline_completion_generator(const char *text, int state){
23597   static sqlite3_stmt *pStmt = 0;
23598   char *zRet;
23599   if( state==0 ){
23600     char *zSql;
23601     sqlite3_finalize(pStmt);
23602     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
23603                            "  FROM completion(%Q) ORDER BY 1", text);
23604     shell_check_oom(zSql);
23605     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
23606     sqlite3_free(zSql);
23607   }
23608   if( sqlite3_step(pStmt)==SQLITE_ROW ){
23609     const char *z = (const char*)sqlite3_column_text(pStmt,0);
23610     zRet = z ? strdup(z) : 0;
23611   }else{
23612     sqlite3_finalize(pStmt);
23613     pStmt = 0;
23614     zRet = 0;
23615   }
23616   return zRet;
23617 }
readline_completion(const char * zText,int iStart,int iEnd)23618 static char **readline_completion(const char *zText, int iStart, int iEnd){
23619   (void)iStart;
23620   (void)iEnd;
23621   rl_attempted_completion_over = 1;
23622   return rl_completion_matches(zText, readline_completion_generator);
23623 }
23624 
23625 #elif HAVE_LINENOISE
23626 /*
23627 ** Linenoise completion callback
23628 */
linenoise_completion(const char * zLine,linenoiseCompletions * lc)23629 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
23630   i64 nLine = strlen(zLine);
23631   i64 i, iStart;
23632   sqlite3_stmt *pStmt = 0;
23633   char *zSql;
23634   char zBuf[1000];
23635 
23636   if( nLine>(i64)sizeof(zBuf)-30 ) return;
23637   if( zLine[0]=='.' || zLine[0]=='#') return;
23638   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
23639   if( i==nLine-1 ) return;
23640   iStart = i+1;
23641   memcpy(zBuf, zLine, iStart);
23642   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
23643                          "  FROM completion(%Q,%Q) ORDER BY 1",
23644                          &zLine[iStart], zLine);
23645   shell_check_oom(zSql);
23646   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
23647   sqlite3_free(zSql);
23648   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
23649   while( sqlite3_step(pStmt)==SQLITE_ROW ){
23650     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
23651     int nCompletion = sqlite3_column_bytes(pStmt, 0);
23652     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
23653       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
23654       linenoiseAddCompletion(lc, zBuf);
23655     }
23656   }
23657   sqlite3_finalize(pStmt);
23658 }
23659 #endif
23660 
23661 /*
23662 ** Do C-language style dequoting.
23663 **
23664 **    \a    -> alarm
23665 **    \b    -> backspace
23666 **    \t    -> tab
23667 **    \n    -> newline
23668 **    \v    -> vertical tab
23669 **    \f    -> form feed
23670 **    \r    -> carriage return
23671 **    \s    -> space
23672 **    \"    -> "
23673 **    \'    -> '
23674 **    \\    -> backslash
23675 **    \NNN  -> ascii character NNN in octal
23676 **    \xHH  -> ascii character HH in hexadecimal
23677 */
resolve_backslashes(char * z)23678 static void resolve_backslashes(char *z){
23679   int i, j;
23680   char c;
23681   while( *z && *z!='\\' ) z++;
23682   for(i=j=0; (c = z[i])!=0; i++, j++){
23683     if( c=='\\' && z[i+1]!=0 ){
23684       c = z[++i];
23685       if( c=='a' ){
23686         c = '\a';
23687       }else if( c=='b' ){
23688         c = '\b';
23689       }else if( c=='t' ){
23690         c = '\t';
23691       }else if( c=='n' ){
23692         c = '\n';
23693       }else if( c=='v' ){
23694         c = '\v';
23695       }else if( c=='f' ){
23696         c = '\f';
23697       }else if( c=='r' ){
23698         c = '\r';
23699       }else if( c=='"' ){
23700         c = '"';
23701       }else if( c=='\'' ){
23702         c = '\'';
23703       }else if( c=='\\' ){
23704         c = '\\';
23705       }else if( c=='x' ){
23706         int nhd = 0, hdv;
23707         u8 hv = 0;
23708         while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
23709           hv = (u8)((hv<<4)|hdv);
23710           ++nhd;
23711         }
23712         i += nhd;
23713         c = (u8)hv;
23714       }else if( c>='0' && c<='7' ){
23715         c -= '0';
23716         if( z[i+1]>='0' && z[i+1]<='7' ){
23717           i++;
23718           c = (c<<3) + z[i] - '0';
23719           if( z[i+1]>='0' && z[i+1]<='7' ){
23720             i++;
23721             c = (c<<3) + z[i] - '0';
23722           }
23723         }
23724       }
23725     }
23726     z[j] = c;
23727   }
23728   if( j<i ) z[j] = 0;
23729 }
23730 
23731 /*
23732 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
23733 ** for TRUE and FALSE.  Return the integer value if appropriate.
23734 */
booleanValue(const char * zArg)23735 static int booleanValue(const char *zArg){
23736   int i;
23737   if( zArg[0]=='0' && zArg[1]=='x' ){
23738     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
23739   }else{
23740     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
23741   }
23742   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
23743   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
23744     return 1;
23745   }
23746   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
23747     return 0;
23748   }
23749   eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
23750   return 0;
23751 }
23752 
23753 /*
23754 ** Set or clear a shell flag according to a boolean value.
23755 */
setOrClearFlag(ShellState * p,unsigned mFlag,const char * zArg)23756 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
23757   if( booleanValue(zArg) ){
23758     ShellSetFlag(p, mFlag);
23759   }else{
23760     ShellClearFlag(p, mFlag);
23761   }
23762 }
23763 
23764 /*
23765 ** Close an output file, assuming it is not stderr or stdout
23766 */
output_file_close(FILE * f)23767 static void output_file_close(FILE *f){
23768   if( f && f!=stdout && f!=stderr ) fclose(f);
23769 }
23770 
23771 /*
23772 ** Try to open an output file.   The names "stdout" and "stderr" are
23773 ** recognized and do the right thing.  NULL is returned if the output
23774 ** filename is "off".
23775 */
output_file_open(const char * zFile,int bTextMode)23776 static FILE *output_file_open(const char *zFile, int bTextMode){
23777   FILE *f;
23778   if( cli_strcmp(zFile,"stdout")==0 ){
23779     f = stdout;
23780   }else if( cli_strcmp(zFile, "stderr")==0 ){
23781     f = stderr;
23782   }else if( cli_strcmp(zFile, "off")==0 ){
23783     f = 0;
23784   }else{
23785     f = fopen(zFile, bTextMode ? "w" : "wb");
23786     if( f==0 ){
23787       eputf("Error: cannot open \"%s\"\n", zFile);
23788     }
23789   }
23790   return f;
23791 }
23792 
23793 #ifndef SQLITE_OMIT_TRACE
23794 /*
23795 ** A routine for handling output from sqlite3_trace().
23796 */
sql_trace_callback(unsigned mType,void * pArg,void * pP,void * pX)23797 static int sql_trace_callback(
23798   unsigned mType,         /* The trace type */
23799   void *pArg,             /* The ShellState pointer */
23800   void *pP,               /* Usually a pointer to sqlite_stmt */
23801   void *pX                /* Auxiliary output */
23802 ){
23803   ShellState *p = (ShellState*)pArg;
23804   sqlite3_stmt *pStmt;
23805   const char *zSql;
23806   i64 nSql;
23807   if( p->traceOut==0 ) return 0;
23808   if( mType==SQLITE_TRACE_CLOSE ){
23809     sputz(p->traceOut, "-- closing database connection\n");
23810     return 0;
23811   }
23812   if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
23813     zSql = (const char*)pX;
23814   }else{
23815     pStmt = (sqlite3_stmt*)pP;
23816     switch( p->eTraceType ){
23817       case SHELL_TRACE_EXPANDED: {
23818         zSql = sqlite3_expanded_sql(pStmt);
23819         break;
23820       }
23821 #ifdef SQLITE_ENABLE_NORMALIZE
23822       case SHELL_TRACE_NORMALIZED: {
23823         zSql = sqlite3_normalized_sql(pStmt);
23824         break;
23825       }
23826 #endif
23827       default: {
23828         zSql = sqlite3_sql(pStmt);
23829         break;
23830       }
23831     }
23832   }
23833   if( zSql==0 ) return 0;
23834   nSql = strlen(zSql);
23835   if( nSql>1000000000 ) nSql = 1000000000;
23836   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
23837   switch( mType ){
23838     case SQLITE_TRACE_ROW:
23839     case SQLITE_TRACE_STMT: {
23840       sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
23841       break;
23842     }
23843     case SQLITE_TRACE_PROFILE: {
23844       sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
23845       sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
23846       break;
23847     }
23848   }
23849   return 0;
23850 }
23851 #endif
23852 
23853 /*
23854 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
23855 ** a useful spot to set a debugger breakpoint.
23856 **
23857 ** This routine does not do anything practical.  The code are there simply
23858 ** to prevent the compiler from optimizing this routine out.
23859 */
test_breakpoint(void)23860 static void test_breakpoint(void){
23861   static unsigned int nCall = 0;
23862   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
23863 }
23864 
23865 /*
23866 ** An object used to read a CSV and other files for import.
23867 */
23868 typedef struct ImportCtx ImportCtx;
23869 struct ImportCtx {
23870   const char *zFile;  /* Name of the input file */
23871   FILE *in;           /* Read the CSV text from this input stream */
23872   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
23873   char *z;            /* Accumulated text for a field */
23874   int n;              /* Number of bytes in z */
23875   int nAlloc;         /* Space allocated for z[] */
23876   int nLine;          /* Current line number */
23877   int nRow;           /* Number of rows imported */
23878   int nErr;           /* Number of errors encountered */
23879   int bNotFirst;      /* True if one or more bytes already read */
23880   int cTerm;          /* Character that terminated the most recent field */
23881   int cColSep;        /* The column separator character.  (Usually ",") */
23882   int cRowSep;        /* The row separator character.  (Usually "\n") */
23883 };
23884 
23885 /* Clean up resourced used by an ImportCtx */
import_cleanup(ImportCtx * p)23886 static void import_cleanup(ImportCtx *p){
23887   if( p->in!=0 && p->xCloser!=0 ){
23888     p->xCloser(p->in);
23889     p->in = 0;
23890   }
23891   sqlite3_free(p->z);
23892   p->z = 0;
23893 }
23894 
23895 /* Append a single byte to z[] */
import_append_char(ImportCtx * p,int c)23896 static void import_append_char(ImportCtx *p, int c){
23897   if( p->n+1>=p->nAlloc ){
23898     p->nAlloc += p->nAlloc + 100;
23899     p->z = sqlite3_realloc64(p->z, p->nAlloc);
23900     shell_check_oom(p->z);
23901   }
23902   p->z[p->n++] = (char)c;
23903 }
23904 
23905 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
23906 ** with the option of having a separator other than ",".
23907 **
23908 **   +  Input comes from p->in.
23909 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
23910 **      from sqlite3_malloc64().
23911 **   +  Use p->cSep as the column separator.  The default is ",".
23912 **   +  Use p->rSep as the row separator.  The default is "\n".
23913 **   +  Keep track of the line number in p->nLine.
23914 **   +  Store the character that terminates the field in p->cTerm.  Store
23915 **      EOF on end-of-file.
23916 **   +  Report syntax errors on stderr
23917 */
csv_read_one_field(ImportCtx * p)23918 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
23919   int c;
23920   int cSep = (u8)p->cColSep;
23921   int rSep = (u8)p->cRowSep;
23922   p->n = 0;
23923   c = fgetc(p->in);
23924   if( c==EOF || seenInterrupt ){
23925     p->cTerm = EOF;
23926     return 0;
23927   }
23928   if( c=='"' ){
23929     int pc, ppc;
23930     int startLine = p->nLine;
23931     int cQuote = c;
23932     pc = ppc = 0;
23933     while( 1 ){
23934       c = fgetc(p->in);
23935       if( c==rSep ) p->nLine++;
23936       if( c==cQuote ){
23937         if( pc==cQuote ){
23938           pc = 0;
23939           continue;
23940         }
23941       }
23942       if( (c==cSep && pc==cQuote)
23943        || (c==rSep && pc==cQuote)
23944        || (c==rSep && pc=='\r' && ppc==cQuote)
23945        || (c==EOF && pc==cQuote)
23946       ){
23947         do{ p->n--; }while( p->z[p->n]!=cQuote );
23948         p->cTerm = c;
23949         break;
23950       }
23951       if( pc==cQuote && c!='\r' ){
23952         eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
23953       }
23954       if( c==EOF ){
23955         eputf("%s:%d: unterminated %c-quoted field\n",
23956               p->zFile, startLine, cQuote);
23957         p->cTerm = c;
23958         break;
23959       }
23960       import_append_char(p, c);
23961       ppc = pc;
23962       pc = c;
23963     }
23964   }else{
23965     /* If this is the first field being parsed and it begins with the
23966     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
23967     if( (c&0xff)==0xef && p->bNotFirst==0 ){
23968       import_append_char(p, c);
23969       c = fgetc(p->in);
23970       if( (c&0xff)==0xbb ){
23971         import_append_char(p, c);
23972         c = fgetc(p->in);
23973         if( (c&0xff)==0xbf ){
23974           p->bNotFirst = 1;
23975           p->n = 0;
23976           return csv_read_one_field(p);
23977         }
23978       }
23979     }
23980     while( c!=EOF && c!=cSep && c!=rSep ){
23981       import_append_char(p, c);
23982       c = fgetc(p->in);
23983     }
23984     if( c==rSep ){
23985       p->nLine++;
23986       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
23987     }
23988     p->cTerm = c;
23989   }
23990   if( p->z ) p->z[p->n] = 0;
23991   p->bNotFirst = 1;
23992   return p->z;
23993 }
23994 
23995 /* Read a single field of ASCII delimited text.
23996 **
23997 **   +  Input comes from p->in.
23998 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
23999 **      from sqlite3_malloc64().
24000 **   +  Use p->cSep as the column separator.  The default is "\x1F".
24001 **   +  Use p->rSep as the row separator.  The default is "\x1E".
24002 **   +  Keep track of the row number in p->nLine.
24003 **   +  Store the character that terminates the field in p->cTerm.  Store
24004 **      EOF on end-of-file.
24005 **   +  Report syntax errors on stderr
24006 */
ascii_read_one_field(ImportCtx * p)24007 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
24008   int c;
24009   int cSep = (u8)p->cColSep;
24010   int rSep = (u8)p->cRowSep;
24011   p->n = 0;
24012   c = fgetc(p->in);
24013   if( c==EOF || seenInterrupt ){
24014     p->cTerm = EOF;
24015     return 0;
24016   }
24017   while( c!=EOF && c!=cSep && c!=rSep ){
24018     import_append_char(p, c);
24019     c = fgetc(p->in);
24020   }
24021   if( c==rSep ){
24022     p->nLine++;
24023   }
24024   p->cTerm = c;
24025   if( p->z ) p->z[p->n] = 0;
24026   return p->z;
24027 }
24028 
24029 /*
24030 ** Try to transfer data for table zTable.  If an error is seen while
24031 ** moving forward, try to go backwards.  The backwards movement won't
24032 ** work for WITHOUT ROWID tables.
24033 */
tryToCloneData(ShellState * p,sqlite3 * newDb,const char * zTable)24034 static void tryToCloneData(
24035   ShellState *p,
24036   sqlite3 *newDb,
24037   const char *zTable
24038 ){
24039   sqlite3_stmt *pQuery = 0;
24040   sqlite3_stmt *pInsert = 0;
24041   char *zQuery = 0;
24042   char *zInsert = 0;
24043   int rc;
24044   int i, j, n;
24045   int nTable = strlen30(zTable);
24046   int k = 0;
24047   int cnt = 0;
24048   const int spinRate = 10000;
24049 
24050   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
24051   shell_check_oom(zQuery);
24052   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24053   if( rc ){
24054     eputf("Error %d: %s on [%s]\n",
24055           sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
24056     goto end_data_xfer;
24057   }
24058   n = sqlite3_column_count(pQuery);
24059   zInsert = sqlite3_malloc64(200 + nTable + n*3);
24060   shell_check_oom(zInsert);
24061   sqlite3_snprintf(200+nTable,zInsert,
24062                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
24063   i = strlen30(zInsert);
24064   for(j=1; j<n; j++){
24065     memcpy(zInsert+i, ",?", 2);
24066     i += 2;
24067   }
24068   memcpy(zInsert+i, ");", 3);
24069   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
24070   if( rc ){
24071     eputf("Error %d: %s on [%s]\n",
24072           sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
24073     goto end_data_xfer;
24074   }
24075   for(k=0; k<2; k++){
24076     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
24077       for(i=0; i<n; i++){
24078         switch( sqlite3_column_type(pQuery, i) ){
24079           case SQLITE_NULL: {
24080             sqlite3_bind_null(pInsert, i+1);
24081             break;
24082           }
24083           case SQLITE_INTEGER: {
24084             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
24085             break;
24086           }
24087           case SQLITE_FLOAT: {
24088             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
24089             break;
24090           }
24091           case SQLITE_TEXT: {
24092             sqlite3_bind_text(pInsert, i+1,
24093                              (const char*)sqlite3_column_text(pQuery,i),
24094                              -1, SQLITE_STATIC);
24095             break;
24096           }
24097           case SQLITE_BLOB: {
24098             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
24099                                             sqlite3_column_bytes(pQuery,i),
24100                                             SQLITE_STATIC);
24101             break;
24102           }
24103         }
24104       } /* End for */
24105       rc = sqlite3_step(pInsert);
24106       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
24107         eputf("Error %d: %s\n",
24108               sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
24109       }
24110       sqlite3_reset(pInsert);
24111       cnt++;
24112       if( (cnt%spinRate)==0 ){
24113         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
24114         fflush(stdout);
24115       }
24116     } /* End while */
24117     if( rc==SQLITE_DONE ) break;
24118     sqlite3_finalize(pQuery);
24119     sqlite3_free(zQuery);
24120     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
24121                              zTable);
24122     shell_check_oom(zQuery);
24123     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24124     if( rc ){
24125       eputf("Warning: cannot step \"%s\" backwards", zTable);
24126       break;
24127     }
24128   } /* End for(k=0...) */
24129 
24130 end_data_xfer:
24131   sqlite3_finalize(pQuery);
24132   sqlite3_finalize(pInsert);
24133   sqlite3_free(zQuery);
24134   sqlite3_free(zInsert);
24135 }
24136 
24137 
24138 /*
24139 ** Try to transfer all rows of the schema that match zWhere.  For
24140 ** each row, invoke xForEach() on the object defined by that row.
24141 ** If an error is encountered while moving forward through the
24142 ** sqlite_schema table, try again moving backwards.
24143 */
tryToCloneSchema(ShellState * p,sqlite3 * newDb,const char * zWhere,void (* xForEach)(ShellState *,sqlite3 *,const char *))24144 static void tryToCloneSchema(
24145   ShellState *p,
24146   sqlite3 *newDb,
24147   const char *zWhere,
24148   void (*xForEach)(ShellState*,sqlite3*,const char*)
24149 ){
24150   sqlite3_stmt *pQuery = 0;
24151   char *zQuery = 0;
24152   int rc;
24153   const unsigned char *zName;
24154   const unsigned char *zSql;
24155   char *zErrMsg = 0;
24156 
24157   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
24158                            " WHERE %s ORDER BY rowid ASC", zWhere);
24159   shell_check_oom(zQuery);
24160   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24161   if( rc ){
24162     eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
24163           sqlite3_errmsg(p->db), zQuery);
24164     goto end_schema_xfer;
24165   }
24166   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
24167     zName = sqlite3_column_text(pQuery, 0);
24168     zSql = sqlite3_column_text(pQuery, 1);
24169     if( zName==0 || zSql==0 ) continue;
24170     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
24171       sputf(stdout, "%s... ", zName); fflush(stdout);
24172       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
24173       if( zErrMsg ){
24174         eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
24175         sqlite3_free(zErrMsg);
24176         zErrMsg = 0;
24177       }
24178     }
24179     if( xForEach ){
24180       xForEach(p, newDb, (const char*)zName);
24181     }
24182     sputz(stdout, "done\n");
24183   }
24184   if( rc!=SQLITE_DONE ){
24185     sqlite3_finalize(pQuery);
24186     sqlite3_free(zQuery);
24187     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
24188                              " WHERE %s ORDER BY rowid DESC", zWhere);
24189     shell_check_oom(zQuery);
24190     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24191     if( rc ){
24192       eputf("Error: (%d) %s on [%s]\n",
24193             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
24194       goto end_schema_xfer;
24195     }
24196     while( sqlite3_step(pQuery)==SQLITE_ROW ){
24197       zName = sqlite3_column_text(pQuery, 0);
24198       zSql = sqlite3_column_text(pQuery, 1);
24199       if( zName==0 || zSql==0 ) continue;
24200       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
24201       sputf(stdout, "%s... ", zName); fflush(stdout);
24202       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
24203       if( zErrMsg ){
24204         eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
24205         sqlite3_free(zErrMsg);
24206         zErrMsg = 0;
24207       }
24208       if( xForEach ){
24209         xForEach(p, newDb, (const char*)zName);
24210       }
24211       sputz(stdout, "done\n");
24212     }
24213   }
24214 end_schema_xfer:
24215   sqlite3_finalize(pQuery);
24216   sqlite3_free(zQuery);
24217 }
24218 
24219 /*
24220 ** Open a new database file named "zNewDb".  Try to recover as much information
24221 ** as possible out of the main database (which might be corrupt) and write it
24222 ** into zNewDb.
24223 */
tryToClone(ShellState * p,const char * zNewDb)24224 static void tryToClone(ShellState *p, const char *zNewDb){
24225   int rc;
24226   sqlite3 *newDb = 0;
24227   if( access(zNewDb,0)==0 ){
24228     eputf("File \"%s\" already exists.\n", zNewDb);
24229     return;
24230   }
24231   rc = sqlite3_open(zNewDb, &newDb);
24232   if( rc ){
24233     eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
24234   }else{
24235     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
24236     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
24237     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
24238     tryToCloneSchema(p, newDb, "type!='table'", 0);
24239     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
24240     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
24241   }
24242   close_db(newDb);
24243 }
24244 
24245 #ifndef SQLITE_SHELL_FIDDLE
24246 /*
24247 ** Change the output stream (file or pipe or console) to something else.
24248 */
output_redir(ShellState * p,FILE * pfNew)24249 static void output_redir(ShellState *p, FILE *pfNew){
24250   if( p->out != stdout ) eputz("Output already redirected.\n");
24251   else{
24252     p->out = pfNew;
24253     setOutputStream(pfNew);
24254   }
24255 }
24256 
24257 /*
24258 ** Change the output file back to stdout.
24259 **
24260 ** If the p->doXdgOpen flag is set, that means the output was being
24261 ** redirected to a temporary file named by p->zTempFile.  In that case,
24262 ** launch start/open/xdg-open on that temporary file.
24263 */
output_reset(ShellState * p)24264 static void output_reset(ShellState *p){
24265   if( p->outfile[0]=='|' ){
24266 #ifndef SQLITE_OMIT_POPEN
24267     pclose(p->out);
24268 #endif
24269   }else{
24270     output_file_close(p->out);
24271 #ifndef SQLITE_NOHAVE_SYSTEM
24272     if( p->doXdgOpen ){
24273       const char *zXdgOpenCmd =
24274 #if defined(_WIN32)
24275       "start";
24276 #elif defined(__APPLE__)
24277       "open";
24278 #else
24279       "xdg-open";
24280 #endif
24281       char *zCmd;
24282       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
24283       if( system(zCmd) ){
24284         eputf("Failed: [%s]\n", zCmd);
24285       }else{
24286         /* Give the start/open/xdg-open command some time to get
24287         ** going before we continue, and potential delete the
24288         ** p->zTempFile data file out from under it */
24289         sqlite3_sleep(2000);
24290       }
24291       sqlite3_free(zCmd);
24292       outputModePop(p);
24293       p->doXdgOpen = 0;
24294     }
24295 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
24296   }
24297   p->outfile[0] = 0;
24298   p->out = stdout;
24299   setOutputStream(stdout);
24300 }
24301 #else
24302 # define output_redir(SS,pfO)
24303 # define output_reset(SS)
24304 #endif
24305 
24306 /*
24307 ** Run an SQL command and return the single integer result.
24308 */
db_int(sqlite3 * db,const char * zSql)24309 static int db_int(sqlite3 *db, const char *zSql){
24310   sqlite3_stmt *pStmt;
24311   int res = 0;
24312   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
24313   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
24314     res = sqlite3_column_int(pStmt,0);
24315   }
24316   sqlite3_finalize(pStmt);
24317   return res;
24318 }
24319 
24320 #if SQLITE_SHELL_HAVE_RECOVER
24321 /*
24322 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
24323 */
get2byteInt(unsigned char * a)24324 static unsigned int get2byteInt(unsigned char *a){
24325   return (a[0]<<8) + a[1];
24326 }
get4byteInt(unsigned char * a)24327 static unsigned int get4byteInt(unsigned char *a){
24328   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
24329 }
24330 
24331 /*
24332 ** Implementation of the ".dbinfo" command.
24333 **
24334 ** Return 1 on error, 2 to exit, and 0 otherwise.
24335 */
shell_dbinfo_command(ShellState * p,int nArg,char ** azArg)24336 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
24337   static const struct { const char *zName; int ofst; } aField[] = {
24338      { "file change counter:",  24  },
24339      { "database page count:",  28  },
24340      { "freelist page count:",  36  },
24341      { "schema cookie:",        40  },
24342      { "schema format:",        44  },
24343      { "default cache size:",   48  },
24344      { "autovacuum top root:",  52  },
24345      { "incremental vacuum:",   64  },
24346      { "text encoding:",        56  },
24347      { "user version:",         60  },
24348      { "application id:",       68  },
24349      { "software version:",     96  },
24350   };
24351   static const struct { const char *zName; const char *zSql; } aQuery[] = {
24352      { "number of tables:",
24353        "SELECT count(*) FROM %s WHERE type='table'" },
24354      { "number of indexes:",
24355        "SELECT count(*) FROM %s WHERE type='index'" },
24356      { "number of triggers:",
24357        "SELECT count(*) FROM %s WHERE type='trigger'" },
24358      { "number of views:",
24359        "SELECT count(*) FROM %s WHERE type='view'" },
24360      { "schema size:",
24361        "SELECT total(length(sql)) FROM %s" },
24362   };
24363   int i, rc;
24364   unsigned iDataVersion;
24365   char *zSchemaTab;
24366   char *zDb = nArg>=2 ? azArg[1] : "main";
24367   sqlite3_stmt *pStmt = 0;
24368   unsigned char aHdr[100];
24369   open_db(p, 0);
24370   if( p->db==0 ) return 1;
24371   rc = sqlite3_prepare_v2(p->db,
24372              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
24373              -1, &pStmt, 0);
24374   if( rc ){
24375     eputf("error: %s\n", sqlite3_errmsg(p->db));
24376     sqlite3_finalize(pStmt);
24377     return 1;
24378   }
24379   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
24380   if( sqlite3_step(pStmt)==SQLITE_ROW
24381    && sqlite3_column_bytes(pStmt,0)>100
24382   ){
24383     const u8 *pb = sqlite3_column_blob(pStmt,0);
24384     shell_check_oom(pb);
24385     memcpy(aHdr, pb, 100);
24386     sqlite3_finalize(pStmt);
24387   }else{
24388     eputz("unable to read database header\n");
24389     sqlite3_finalize(pStmt);
24390     return 1;
24391   }
24392   i = get2byteInt(aHdr+16);
24393   if( i==1 ) i = 65536;
24394   oputf("%-20s %d\n", "database page size:", i);
24395   oputf("%-20s %d\n", "write format:", aHdr[18]);
24396   oputf("%-20s %d\n", "read format:", aHdr[19]);
24397   oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
24398   for(i=0; i<ArraySize(aField); i++){
24399     int ofst = aField[i].ofst;
24400     unsigned int val = get4byteInt(aHdr + ofst);
24401     oputf("%-20s %u", aField[i].zName, val);
24402     switch( ofst ){
24403       case 56: {
24404         if( val==1 ) oputz(" (utf8)");
24405         if( val==2 ) oputz(" (utf16le)");
24406         if( val==3 ) oputz(" (utf16be)");
24407       }
24408     }
24409     oputz("\n");
24410   }
24411   if( zDb==0 ){
24412     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
24413   }else if( cli_strcmp(zDb,"temp")==0 ){
24414     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
24415   }else{
24416     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
24417   }
24418   for(i=0; i<ArraySize(aQuery); i++){
24419     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
24420     int val = db_int(p->db, zSql);
24421     sqlite3_free(zSql);
24422     oputf("%-20s %d\n", aQuery[i].zName, val);
24423   }
24424   sqlite3_free(zSchemaTab);
24425   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
24426   oputf("%-20s %u\n", "data version", iDataVersion);
24427   return 0;
24428 }
24429 #endif /* SQLITE_SHELL_HAVE_RECOVER */
24430 
24431 /*
24432 ** Print the current sqlite3_errmsg() value to stderr and return 1.
24433 */
shellDatabaseError(sqlite3 * db)24434 static int shellDatabaseError(sqlite3 *db){
24435   const char *zErr = sqlite3_errmsg(db);
24436   eputf("Error: %s\n", zErr);
24437   return 1;
24438 }
24439 
24440 /*
24441 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
24442 ** if they match and FALSE (0) if they do not match.
24443 **
24444 ** Globbing rules:
24445 **
24446 **      '*'       Matches any sequence of zero or more characters.
24447 **
24448 **      '?'       Matches exactly one character.
24449 **
24450 **     [...]      Matches one character from the enclosed list of
24451 **                characters.
24452 **
24453 **     [^...]     Matches one character not in the enclosed list.
24454 **
24455 **      '#'       Matches any sequence of one or more digits with an
24456 **                optional + or - sign in front
24457 **
24458 **      ' '       Any span of whitespace matches any other span of
24459 **                whitespace.
24460 **
24461 ** Extra whitespace at the end of z[] is ignored.
24462 */
testcase_glob(const char * zGlob,const char * z)24463 static int testcase_glob(const char *zGlob, const char *z){
24464   int c, c2;
24465   int invert;
24466   int seen;
24467 
24468   while( (c = (*(zGlob++)))!=0 ){
24469     if( IsSpace(c) ){
24470       if( !IsSpace(*z) ) return 0;
24471       while( IsSpace(*zGlob) ) zGlob++;
24472       while( IsSpace(*z) ) z++;
24473     }else if( c=='*' ){
24474       while( (c=(*(zGlob++))) == '*' || c=='?' ){
24475         if( c=='?' && (*(z++))==0 ) return 0;
24476       }
24477       if( c==0 ){
24478         return 1;
24479       }else if( c=='[' ){
24480         while( *z && testcase_glob(zGlob-1,z)==0 ){
24481           z++;
24482         }
24483         return (*z)!=0;
24484       }
24485       while( (c2 = (*(z++)))!=0 ){
24486         while( c2!=c ){
24487           c2 = *(z++);
24488           if( c2==0 ) return 0;
24489         }
24490         if( testcase_glob(zGlob,z) ) return 1;
24491       }
24492       return 0;
24493     }else if( c=='?' ){
24494       if( (*(z++))==0 ) return 0;
24495     }else if( c=='[' ){
24496       int prior_c = 0;
24497       seen = 0;
24498       invert = 0;
24499       c = *(z++);
24500       if( c==0 ) return 0;
24501       c2 = *(zGlob++);
24502       if( c2=='^' ){
24503         invert = 1;
24504         c2 = *(zGlob++);
24505       }
24506       if( c2==']' ){
24507         if( c==']' ) seen = 1;
24508         c2 = *(zGlob++);
24509       }
24510       while( c2 && c2!=']' ){
24511         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
24512           c2 = *(zGlob++);
24513           if( c>=prior_c && c<=c2 ) seen = 1;
24514           prior_c = 0;
24515         }else{
24516           if( c==c2 ){
24517             seen = 1;
24518           }
24519           prior_c = c2;
24520         }
24521         c2 = *(zGlob++);
24522       }
24523       if( c2==0 || (seen ^ invert)==0 ) return 0;
24524     }else if( c=='#' ){
24525       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
24526       if( !IsDigit(z[0]) ) return 0;
24527       z++;
24528       while( IsDigit(z[0]) ){ z++; }
24529     }else{
24530       if( c!=(*(z++)) ) return 0;
24531     }
24532   }
24533   while( IsSpace(*z) ){ z++; }
24534   return *z==0;
24535 }
24536 
24537 
24538 /*
24539 ** Compare the string as a command-line option with either one or two
24540 ** initial "-" characters.
24541 */
optionMatch(const char * zStr,const char * zOpt)24542 static int optionMatch(const char *zStr, const char *zOpt){
24543   if( zStr[0]!='-' ) return 0;
24544   zStr++;
24545   if( zStr[0]=='-' ) zStr++;
24546   return cli_strcmp(zStr, zOpt)==0;
24547 }
24548 
24549 /*
24550 ** Delete a file.
24551 */
shellDeleteFile(const char * zFilename)24552 int shellDeleteFile(const char *zFilename){
24553   int rc;
24554 #ifdef _WIN32
24555   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
24556   rc = _wunlink(z);
24557   sqlite3_free(z);
24558 #else
24559   rc = unlink(zFilename);
24560 #endif
24561   return rc;
24562 }
24563 
24564 /*
24565 ** Try to delete the temporary file (if there is one) and free the
24566 ** memory used to hold the name of the temp file.
24567 */
clearTempFile(ShellState * p)24568 static void clearTempFile(ShellState *p){
24569   if( p->zTempFile==0 ) return;
24570   if( p->doXdgOpen ) return;
24571   if( shellDeleteFile(p->zTempFile) ) return;
24572   sqlite3_free(p->zTempFile);
24573   p->zTempFile = 0;
24574 }
24575 
24576 /*
24577 ** Create a new temp file name with the given suffix.
24578 */
newTempFile(ShellState * p,const char * zSuffix)24579 static void newTempFile(ShellState *p, const char *zSuffix){
24580   clearTempFile(p);
24581   sqlite3_free(p->zTempFile);
24582   p->zTempFile = 0;
24583   if( p->db ){
24584     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
24585   }
24586   if( p->zTempFile==0 ){
24587     /* If p->db is an in-memory database then the TEMPFILENAME file-control
24588     ** will not work and we will need to fallback to guessing */
24589     char *zTemp;
24590     sqlite3_uint64 r;
24591     sqlite3_randomness(sizeof(r), &r);
24592     zTemp = getenv("TEMP");
24593     if( zTemp==0 ) zTemp = getenv("TMP");
24594     if( zTemp==0 ){
24595 #ifdef _WIN32
24596       zTemp = "\\tmp";
24597 #else
24598       zTemp = "/tmp";
24599 #endif
24600     }
24601     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
24602   }else{
24603     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
24604   }
24605   shell_check_oom(p->zTempFile);
24606 }
24607 
24608 
24609 /*
24610 ** The implementation of SQL scalar function fkey_collate_clause(), used
24611 ** by the ".lint fkey-indexes" command. This scalar function is always
24612 ** called with four arguments - the parent table name, the parent column name,
24613 ** the child table name and the child column name.
24614 **
24615 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
24616 **
24617 ** If either of the named tables or columns do not exist, this function
24618 ** returns an empty string. An empty string is also returned if both tables
24619 ** and columns exist but have the same default collation sequence. Or,
24620 ** if both exist but the default collation sequences are different, this
24621 ** function returns the string " COLLATE <parent-collation>", where
24622 ** <parent-collation> is the default collation sequence of the parent column.
24623 */
shellFkeyCollateClause(sqlite3_context * pCtx,int nVal,sqlite3_value ** apVal)24624 static void shellFkeyCollateClause(
24625   sqlite3_context *pCtx,
24626   int nVal,
24627   sqlite3_value **apVal
24628 ){
24629   sqlite3 *db = sqlite3_context_db_handle(pCtx);
24630   const char *zParent;
24631   const char *zParentCol;
24632   const char *zParentSeq;
24633   const char *zChild;
24634   const char *zChildCol;
24635   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
24636   int rc;
24637 
24638   assert( nVal==4 );
24639   zParent = (const char*)sqlite3_value_text(apVal[0]);
24640   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
24641   zChild = (const char*)sqlite3_value_text(apVal[2]);
24642   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
24643 
24644   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
24645   rc = sqlite3_table_column_metadata(
24646       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
24647   );
24648   if( rc==SQLITE_OK ){
24649     rc = sqlite3_table_column_metadata(
24650         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
24651     );
24652   }
24653 
24654   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
24655     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
24656     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
24657     sqlite3_free(z);
24658   }
24659 }
24660 
24661 
24662 /*
24663 ** The implementation of dot-command ".lint fkey-indexes".
24664 */
lintFkeyIndexes(ShellState * pState,char ** azArg,int nArg)24665 static int lintFkeyIndexes(
24666   ShellState *pState,             /* Current shell tool state */
24667   char **azArg,                   /* Array of arguments passed to dot command */
24668   int nArg                        /* Number of entries in azArg[] */
24669 ){
24670   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
24671   int bVerbose = 0;               /* If -verbose is present */
24672   int bGroupByParent = 0;         /* If -groupbyparent is present */
24673   int i;                          /* To iterate through azArg[] */
24674   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
24675   int rc;                         /* Return code */
24676   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
24677 
24678   /*
24679   ** This SELECT statement returns one row for each foreign key constraint
24680   ** in the schema of the main database. The column values are:
24681   **
24682   ** 0. The text of an SQL statement similar to:
24683   **
24684   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
24685   **
24686   **    This SELECT is similar to the one that the foreign keys implementation
24687   **    needs to run internally on child tables. If there is an index that can
24688   **    be used to optimize this query, then it can also be used by the FK
24689   **    implementation to optimize DELETE or UPDATE statements on the parent
24690   **    table.
24691   **
24692   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
24693   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
24694   **    contains an index that can be used to optimize the query.
24695   **
24696   ** 2. Human readable text that describes the child table and columns. e.g.
24697   **
24698   **       "child_table(child_key1, child_key2)"
24699   **
24700   ** 3. Human readable text that describes the parent table and columns. e.g.
24701   **
24702   **       "parent_table(parent_key1, parent_key2)"
24703   **
24704   ** 4. A full CREATE INDEX statement for an index that could be used to
24705   **    optimize DELETE or UPDATE statements on the parent table. e.g.
24706   **
24707   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
24708   **
24709   ** 5. The name of the parent table.
24710   **
24711   ** These six values are used by the C logic below to generate the report.
24712   */
24713   const char *zSql =
24714   "SELECT "
24715     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
24716     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
24717     "  || fkey_collate_clause("
24718     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
24719     ", "
24720     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
24721     "  || group_concat('*=?', ' AND ') || ')'"
24722     ", "
24723     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
24724     ", "
24725     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
24726     ", "
24727     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
24728     "  || ' ON ' || quote(s.name) || '('"
24729     "  || group_concat(quote(f.[from]) ||"
24730     "        fkey_collate_clause("
24731     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
24732     "  || ');'"
24733     ", "
24734     "     f.[table] "
24735     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
24736     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
24737     "GROUP BY s.name, f.id "
24738     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
24739   ;
24740   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
24741 
24742   for(i=2; i<nArg; i++){
24743     int n = strlen30(azArg[i]);
24744     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
24745       bVerbose = 1;
24746     }
24747     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
24748       bGroupByParent = 1;
24749       zIndent = "    ";
24750     }
24751     else{
24752       eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
24753       return SQLITE_ERROR;
24754     }
24755   }
24756 
24757   /* Register the fkey_collate_clause() SQL function */
24758   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
24759       0, shellFkeyCollateClause, 0, 0
24760   );
24761 
24762 
24763   if( rc==SQLITE_OK ){
24764     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
24765   }
24766   if( rc==SQLITE_OK ){
24767     sqlite3_bind_int(pSql, 1, bGroupByParent);
24768   }
24769 
24770   if( rc==SQLITE_OK ){
24771     int rc2;
24772     char *zPrev = 0;
24773     while( SQLITE_ROW==sqlite3_step(pSql) ){
24774       int res = -1;
24775       sqlite3_stmt *pExplain = 0;
24776       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
24777       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
24778       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
24779       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
24780       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
24781       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
24782 
24783       if( zEQP==0 ) continue;
24784       if( zGlob==0 ) continue;
24785       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
24786       if( rc!=SQLITE_OK ) break;
24787       if( SQLITE_ROW==sqlite3_step(pExplain) ){
24788         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
24789         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
24790                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
24791       }
24792       rc = sqlite3_finalize(pExplain);
24793       if( rc!=SQLITE_OK ) break;
24794 
24795       if( res<0 ){
24796         eputz("Error: internal error");
24797         break;
24798       }else{
24799         if( bGroupByParent
24800         && (bVerbose || res==0)
24801         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
24802         ){
24803           oputf("-- Parent table %s\n", zParent);
24804           sqlite3_free(zPrev);
24805           zPrev = sqlite3_mprintf("%s", zParent);
24806         }
24807 
24808         if( res==0 ){
24809           oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
24810         }else if( bVerbose ){
24811           oputf("%s/* no extra indexes required for %s -> %s */\n",
24812                 zIndent, zFrom, zTarget
24813           );
24814         }
24815       }
24816     }
24817     sqlite3_free(zPrev);
24818 
24819     if( rc!=SQLITE_OK ){
24820       eputf("%s\n", sqlite3_errmsg(db));
24821     }
24822 
24823     rc2 = sqlite3_finalize(pSql);
24824     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
24825       rc = rc2;
24826       eputf("%s\n", sqlite3_errmsg(db));
24827     }
24828   }else{
24829     eputf("%s\n", sqlite3_errmsg(db));
24830   }
24831 
24832   return rc;
24833 }
24834 
24835 /*
24836 ** Implementation of ".lint" dot command.
24837 */
lintDotCommand(ShellState * pState,char ** azArg,int nArg)24838 static int lintDotCommand(
24839   ShellState *pState,             /* Current shell tool state */
24840   char **azArg,                   /* Array of arguments passed to dot command */
24841   int nArg                        /* Number of entries in azArg[] */
24842 ){
24843   int n;
24844   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
24845   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
24846   return lintFkeyIndexes(pState, azArg, nArg);
24847 
24848  usage:
24849   eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
24850   eputz("Where sub-commands are:\n");
24851   eputz("    fkey-indexes\n");
24852   return SQLITE_ERROR;
24853 }
24854 
shellPrepare(sqlite3 * db,int * pRc,const char * zSql,sqlite3_stmt ** ppStmt)24855 static void shellPrepare(
24856   sqlite3 *db,
24857   int *pRc,
24858   const char *zSql,
24859   sqlite3_stmt **ppStmt
24860 ){
24861   *ppStmt = 0;
24862   if( *pRc==SQLITE_OK ){
24863     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
24864     if( rc!=SQLITE_OK ){
24865       eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
24866       *pRc = rc;
24867     }
24868   }
24869 }
24870 
24871 /*
24872 ** Create a prepared statement using printf-style arguments for the SQL.
24873 */
shellPreparePrintf(sqlite3 * db,int * pRc,sqlite3_stmt ** ppStmt,const char * zFmt,...)24874 static void shellPreparePrintf(
24875   sqlite3 *db,
24876   int *pRc,
24877   sqlite3_stmt **ppStmt,
24878   const char *zFmt,
24879   ...
24880 ){
24881   *ppStmt = 0;
24882   if( *pRc==SQLITE_OK ){
24883     va_list ap;
24884     char *z;
24885     va_start(ap, zFmt);
24886     z = sqlite3_vmprintf(zFmt, ap);
24887     va_end(ap);
24888     if( z==0 ){
24889       *pRc = SQLITE_NOMEM;
24890     }else{
24891       shellPrepare(db, pRc, z, ppStmt);
24892       sqlite3_free(z);
24893     }
24894   }
24895 }
24896 
24897 /*
24898 ** Finalize the prepared statement created using shellPreparePrintf().
24899 */
shellFinalize(int * pRc,sqlite3_stmt * pStmt)24900 static void shellFinalize(
24901   int *pRc,
24902   sqlite3_stmt *pStmt
24903 ){
24904   if( pStmt ){
24905     sqlite3 *db = sqlite3_db_handle(pStmt);
24906     int rc = sqlite3_finalize(pStmt);
24907     if( *pRc==SQLITE_OK ){
24908       if( rc!=SQLITE_OK ){
24909         eputf("SQL error: %s\n", sqlite3_errmsg(db));
24910       }
24911       *pRc = rc;
24912     }
24913   }
24914 }
24915 
24916 #if !defined SQLITE_OMIT_VIRTUALTABLE
24917 /* Reset the prepared statement created using shellPreparePrintf().
24918 **
24919 ** This routine is could be marked "static".  But it is not always used,
24920 ** depending on compile-time options.  By omitting the "static", we avoid
24921 ** nuisance compiler warnings about "defined but not used".
24922 */
shellReset(int * pRc,sqlite3_stmt * pStmt)24923 void shellReset(
24924   int *pRc,
24925   sqlite3_stmt *pStmt
24926 ){
24927   int rc = sqlite3_reset(pStmt);
24928   if( *pRc==SQLITE_OK ){
24929     if( rc!=SQLITE_OK ){
24930       sqlite3 *db = sqlite3_db_handle(pStmt);
24931       eputf("SQL error: %s\n", sqlite3_errmsg(db));
24932     }
24933     *pRc = rc;
24934   }
24935 }
24936 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
24937 
24938 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
24939 /******************************************************************************
24940 ** The ".archive" or ".ar" command.
24941 */
24942 /*
24943 ** Structure representing a single ".ar" command.
24944 */
24945 typedef struct ArCommand ArCommand;
24946 struct ArCommand {
24947   u8 eCmd;                        /* An AR_CMD_* value */
24948   u8 bVerbose;                    /* True if --verbose */
24949   u8 bZip;                        /* True if the archive is a ZIP */
24950   u8 bDryRun;                     /* True if --dry-run */
24951   u8 bAppend;                     /* True if --append */
24952   u8 bGlob;                       /* True if --glob */
24953   u8 fromCmdLine;                 /* Run from -A instead of .archive */
24954   int nArg;                       /* Number of command arguments */
24955   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
24956   const char *zFile;              /* --file argument, or NULL */
24957   const char *zDir;               /* --directory argument, or NULL */
24958   char **azArg;                   /* Array of command arguments */
24959   ShellState *p;                  /* Shell state */
24960   sqlite3 *db;                    /* Database containing the archive */
24961 };
24962 
24963 /*
24964 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
24965 */
arUsage(FILE * f)24966 static int arUsage(FILE *f){
24967   showHelp(f,"archive");
24968   return SQLITE_ERROR;
24969 }
24970 
24971 /*
24972 ** Print an error message for the .ar command to stderr and return
24973 ** SQLITE_ERROR.
24974 */
arErrorMsg(ArCommand * pAr,const char * zFmt,...)24975 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
24976   va_list ap;
24977   char *z;
24978   va_start(ap, zFmt);
24979   z = sqlite3_vmprintf(zFmt, ap);
24980   va_end(ap);
24981   eputf("Error: %s\n", z);
24982   if( pAr->fromCmdLine ){
24983     eputz("Use \"-A\" for more help\n");
24984   }else{
24985     eputz("Use \".archive --help\" for more help\n");
24986   }
24987   sqlite3_free(z);
24988   return SQLITE_ERROR;
24989 }
24990 
24991 /*
24992 ** Values for ArCommand.eCmd.
24993 */
24994 #define AR_CMD_CREATE       1
24995 #define AR_CMD_UPDATE       2
24996 #define AR_CMD_INSERT       3
24997 #define AR_CMD_EXTRACT      4
24998 #define AR_CMD_LIST         5
24999 #define AR_CMD_HELP         6
25000 #define AR_CMD_REMOVE       7
25001 
25002 /*
25003 ** Other (non-command) switches.
25004 */
25005 #define AR_SWITCH_VERBOSE     8
25006 #define AR_SWITCH_FILE        9
25007 #define AR_SWITCH_DIRECTORY  10
25008 #define AR_SWITCH_APPEND     11
25009 #define AR_SWITCH_DRYRUN     12
25010 #define AR_SWITCH_GLOB       13
25011 
arProcessSwitch(ArCommand * pAr,int eSwitch,const char * zArg)25012 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
25013   switch( eSwitch ){
25014     case AR_CMD_CREATE:
25015     case AR_CMD_EXTRACT:
25016     case AR_CMD_LIST:
25017     case AR_CMD_REMOVE:
25018     case AR_CMD_UPDATE:
25019     case AR_CMD_INSERT:
25020     case AR_CMD_HELP:
25021       if( pAr->eCmd ){
25022         return arErrorMsg(pAr, "multiple command options");
25023       }
25024       pAr->eCmd = eSwitch;
25025       break;
25026 
25027     case AR_SWITCH_DRYRUN:
25028       pAr->bDryRun = 1;
25029       break;
25030     case AR_SWITCH_GLOB:
25031       pAr->bGlob = 1;
25032       break;
25033     case AR_SWITCH_VERBOSE:
25034       pAr->bVerbose = 1;
25035       break;
25036     case AR_SWITCH_APPEND:
25037       pAr->bAppend = 1;
25038       deliberate_fall_through;
25039     case AR_SWITCH_FILE:
25040       pAr->zFile = zArg;
25041       break;
25042     case AR_SWITCH_DIRECTORY:
25043       pAr->zDir = zArg;
25044       break;
25045   }
25046 
25047   return SQLITE_OK;
25048 }
25049 
25050 /*
25051 ** Parse the command line for an ".ar" command. The results are written into
25052 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
25053 ** successfully, otherwise an error message is written to stderr and
25054 ** SQLITE_ERROR returned.
25055 */
arParseCommand(char ** azArg,int nArg,ArCommand * pAr)25056 static int arParseCommand(
25057   char **azArg,                   /* Array of arguments passed to dot command */
25058   int nArg,                       /* Number of entries in azArg[] */
25059   ArCommand *pAr                  /* Populate this object */
25060 ){
25061   struct ArSwitch {
25062     const char *zLong;
25063     char cShort;
25064     u8 eSwitch;
25065     u8 bArg;
25066   } aSwitch[] = {
25067     { "create",    'c', AR_CMD_CREATE,       0 },
25068     { "extract",   'x', AR_CMD_EXTRACT,      0 },
25069     { "insert",    'i', AR_CMD_INSERT,       0 },
25070     { "list",      't', AR_CMD_LIST,         0 },
25071     { "remove",    'r', AR_CMD_REMOVE,       0 },
25072     { "update",    'u', AR_CMD_UPDATE,       0 },
25073     { "help",      'h', AR_CMD_HELP,         0 },
25074     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
25075     { "file",      'f', AR_SWITCH_FILE,      1 },
25076     { "append",    'a', AR_SWITCH_APPEND,    1 },
25077     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
25078     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
25079     { "glob",      'g', AR_SWITCH_GLOB,      0 },
25080   };
25081   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
25082   struct ArSwitch *pEnd = &aSwitch[nSwitch];
25083 
25084   if( nArg<=1 ){
25085     eputz("Wrong number of arguments.  Usage:\n");
25086     return arUsage(stderr);
25087   }else{
25088     char *z = azArg[1];
25089     if( z[0]!='-' ){
25090       /* Traditional style [tar] invocation */
25091       int i;
25092       int iArg = 2;
25093       for(i=0; z[i]; i++){
25094         const char *zArg = 0;
25095         struct ArSwitch *pOpt;
25096         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
25097           if( z[i]==pOpt->cShort ) break;
25098         }
25099         if( pOpt==pEnd ){
25100           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
25101         }
25102         if( pOpt->bArg ){
25103           if( iArg>=nArg ){
25104             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
25105           }
25106           zArg = azArg[iArg++];
25107         }
25108         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
25109       }
25110       pAr->nArg = nArg-iArg;
25111       if( pAr->nArg>0 ){
25112         pAr->azArg = &azArg[iArg];
25113       }
25114     }else{
25115       /* Non-traditional invocation */
25116       int iArg;
25117       for(iArg=1; iArg<nArg; iArg++){
25118         int n;
25119         z = azArg[iArg];
25120         if( z[0]!='-' ){
25121           /* All remaining command line words are command arguments. */
25122           pAr->azArg = &azArg[iArg];
25123           pAr->nArg = nArg-iArg;
25124           break;
25125         }
25126         n = strlen30(z);
25127 
25128         if( z[1]!='-' ){
25129           int i;
25130           /* One or more short options */
25131           for(i=1; i<n; i++){
25132             const char *zArg = 0;
25133             struct ArSwitch *pOpt;
25134             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
25135               if( z[i]==pOpt->cShort ) break;
25136             }
25137             if( pOpt==pEnd ){
25138               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
25139             }
25140             if( pOpt->bArg ){
25141               if( i<(n-1) ){
25142                 zArg = &z[i+1];
25143                 i = n;
25144               }else{
25145                 if( iArg>=(nArg-1) ){
25146                   return arErrorMsg(pAr, "option requires an argument: %c",
25147                                     z[i]);
25148                 }
25149                 zArg = azArg[++iArg];
25150               }
25151             }
25152             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
25153           }
25154         }else if( z[2]=='\0' ){
25155           /* A -- option, indicating that all remaining command line words
25156           ** are command arguments.  */
25157           pAr->azArg = &azArg[iArg+1];
25158           pAr->nArg = nArg-iArg-1;
25159           break;
25160         }else{
25161           /* A long option */
25162           const char *zArg = 0;             /* Argument for option, if any */
25163           struct ArSwitch *pMatch = 0;      /* Matching option */
25164           struct ArSwitch *pOpt;            /* Iterator */
25165           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
25166             const char *zLong = pOpt->zLong;
25167             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
25168               if( pMatch ){
25169                 return arErrorMsg(pAr, "ambiguous option: %s",z);
25170               }else{
25171                 pMatch = pOpt;
25172               }
25173             }
25174           }
25175 
25176           if( pMatch==0 ){
25177             return arErrorMsg(pAr, "unrecognized option: %s", z);
25178           }
25179           if( pMatch->bArg ){
25180             if( iArg>=(nArg-1) ){
25181               return arErrorMsg(pAr, "option requires an argument: %s", z);
25182             }
25183             zArg = azArg[++iArg];
25184           }
25185           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
25186         }
25187       }
25188     }
25189   }
25190   if( pAr->eCmd==0 ){
25191     eputz("Required argument missing.  Usage:\n");
25192     return arUsage(stderr);
25193   }
25194   return SQLITE_OK;
25195 }
25196 
25197 /*
25198 ** This function assumes that all arguments within the ArCommand.azArg[]
25199 ** array refer to archive members, as for the --extract, --list or --remove
25200 ** commands. It checks that each of them are "present". If any specified
25201 ** file is not present in the archive, an error is printed to stderr and an
25202 ** error code returned. Otherwise, if all specified arguments are present
25203 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
25204 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
25205 ** when pAr->bGlob is true.
25206 **
25207 ** This function strips any trailing '/' characters from each argument.
25208 ** This is consistent with the way the [tar] command seems to work on
25209 ** Linux.
25210 */
arCheckEntries(ArCommand * pAr)25211 static int arCheckEntries(ArCommand *pAr){
25212   int rc = SQLITE_OK;
25213   if( pAr->nArg ){
25214     int i, j;
25215     sqlite3_stmt *pTest = 0;
25216     const char *zSel = (pAr->bGlob)
25217       ? "SELECT name FROM %s WHERE glob($name,name)"
25218       : "SELECT name FROM %s WHERE name=$name";
25219 
25220     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
25221     j = sqlite3_bind_parameter_index(pTest, "$name");
25222     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
25223       char *z = pAr->azArg[i];
25224       int n = strlen30(z);
25225       int bOk = 0;
25226       while( n>0 && z[n-1]=='/' ) n--;
25227       z[n] = '\0';
25228       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
25229       if( SQLITE_ROW==sqlite3_step(pTest) ){
25230         bOk = 1;
25231       }
25232       shellReset(&rc, pTest);
25233       if( rc==SQLITE_OK && bOk==0 ){
25234         eputf("not found in archive: %s\n", z);
25235         rc = SQLITE_ERROR;
25236       }
25237     }
25238     shellFinalize(&rc, pTest);
25239   }
25240   return rc;
25241 }
25242 
25243 /*
25244 ** Format a WHERE clause that can be used against the "sqlar" table to
25245 ** identify all archive members that match the command arguments held
25246 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
25247 ** The caller is responsible for eventually calling sqlite3_free() on
25248 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
25249 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
25250 */
arWhereClause(int * pRc,ArCommand * pAr,char ** pzWhere)25251 static void arWhereClause(
25252   int *pRc,
25253   ArCommand *pAr,
25254   char **pzWhere                  /* OUT: New WHERE clause */
25255 ){
25256   char *zWhere = 0;
25257   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
25258   if( *pRc==SQLITE_OK ){
25259     if( pAr->nArg==0 ){
25260       zWhere = sqlite3_mprintf("1");
25261     }else{
25262       int i;
25263       const char *zSep = "";
25264       for(i=0; i<pAr->nArg; i++){
25265         const char *z = pAr->azArg[i];
25266         zWhere = sqlite3_mprintf(
25267           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
25268           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
25269         );
25270         if( zWhere==0 ){
25271           *pRc = SQLITE_NOMEM;
25272           break;
25273         }
25274         zSep = " OR ";
25275       }
25276     }
25277   }
25278   *pzWhere = zWhere;
25279 }
25280 
25281 /*
25282 ** Implementation of .ar "lisT" command.
25283 */
arListCommand(ArCommand * pAr)25284 static int arListCommand(ArCommand *pAr){
25285   const char *zSql = "SELECT %s FROM %s WHERE %s";
25286   const char *azCols[] = {
25287     "name",
25288     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
25289   };
25290 
25291   char *zWhere = 0;
25292   sqlite3_stmt *pSql = 0;
25293   int rc;
25294 
25295   rc = arCheckEntries(pAr);
25296   arWhereClause(&rc, pAr, &zWhere);
25297 
25298   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
25299                      pAr->zSrcTable, zWhere);
25300   if( pAr->bDryRun ){
25301     oputf("%s\n", sqlite3_sql(pSql));
25302   }else{
25303     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
25304       if( pAr->bVerbose ){
25305         oputf("%s % 10d  %s  %s\n",
25306               sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
25307               sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
25308       }else{
25309         oputf("%s\n", sqlite3_column_text(pSql, 0));
25310       }
25311     }
25312   }
25313   shellFinalize(&rc, pSql);
25314   sqlite3_free(zWhere);
25315   return rc;
25316 }
25317 
25318 /*
25319 ** Implementation of .ar "Remove" command.
25320 */
arRemoveCommand(ArCommand * pAr)25321 static int arRemoveCommand(ArCommand *pAr){
25322   int rc = 0;
25323   char *zSql = 0;
25324   char *zWhere = 0;
25325 
25326   if( pAr->nArg ){
25327     /* Verify that args actually exist within the archive before proceeding.
25328     ** And formulate a WHERE clause to match them.  */
25329     rc = arCheckEntries(pAr);
25330     arWhereClause(&rc, pAr, &zWhere);
25331   }
25332   if( rc==SQLITE_OK ){
25333     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
25334                            pAr->zSrcTable, zWhere);
25335     if( pAr->bDryRun ){
25336       oputf("%s\n", zSql);
25337     }else{
25338       char *zErr = 0;
25339       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
25340       if( rc==SQLITE_OK ){
25341         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
25342         if( rc!=SQLITE_OK ){
25343           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
25344         }else{
25345           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
25346         }
25347       }
25348       if( zErr ){
25349         sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
25350         sqlite3_free(zErr);
25351       }
25352     }
25353   }
25354   sqlite3_free(zWhere);
25355   sqlite3_free(zSql);
25356   return rc;
25357 }
25358 
25359 /*
25360 ** Implementation of .ar "eXtract" command.
25361 */
arExtractCommand(ArCommand * pAr)25362 static int arExtractCommand(ArCommand *pAr){
25363   const char *zSql1 =
25364     "SELECT "
25365     " ($dir || name),"
25366     " writefile(($dir || name), %s, mode, mtime) "
25367     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
25368     " AND name NOT GLOB '*..[/\\]*'";
25369 
25370   const char *azExtraArg[] = {
25371     "sqlar_uncompress(data, sz)",
25372     "data"
25373   };
25374 
25375   sqlite3_stmt *pSql = 0;
25376   int rc = SQLITE_OK;
25377   char *zDir = 0;
25378   char *zWhere = 0;
25379   int i, j;
25380 
25381   /* If arguments are specified, check that they actually exist within
25382   ** the archive before proceeding. And formulate a WHERE clause to
25383   ** match them.  */
25384   rc = arCheckEntries(pAr);
25385   arWhereClause(&rc, pAr, &zWhere);
25386 
25387   if( rc==SQLITE_OK ){
25388     if( pAr->zDir ){
25389       zDir = sqlite3_mprintf("%s/", pAr->zDir);
25390     }else{
25391       zDir = sqlite3_mprintf("");
25392     }
25393     if( zDir==0 ) rc = SQLITE_NOMEM;
25394   }
25395 
25396   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
25397       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
25398   );
25399 
25400   if( rc==SQLITE_OK ){
25401     j = sqlite3_bind_parameter_index(pSql, "$dir");
25402     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
25403 
25404     /* Run the SELECT statement twice. The first time, writefile() is called
25405     ** for all archive members that should be extracted. The second time,
25406     ** only for the directories. This is because the timestamps for
25407     ** extracted directories must be reset after they are populated (as
25408     ** populating them changes the timestamp).  */
25409     for(i=0; i<2; i++){
25410       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
25411       sqlite3_bind_int(pSql, j, i);
25412       if( pAr->bDryRun ){
25413         oputf("%s\n", sqlite3_sql(pSql));
25414       }else{
25415         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
25416           if( i==0 && pAr->bVerbose ){
25417             oputf("%s\n", sqlite3_column_text(pSql, 0));
25418           }
25419         }
25420       }
25421       shellReset(&rc, pSql);
25422     }
25423     shellFinalize(&rc, pSql);
25424   }
25425 
25426   sqlite3_free(zDir);
25427   sqlite3_free(zWhere);
25428   return rc;
25429 }
25430 
25431 /*
25432 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
25433 */
arExecSql(ArCommand * pAr,const char * zSql)25434 static int arExecSql(ArCommand *pAr, const char *zSql){
25435   int rc;
25436   if( pAr->bDryRun ){
25437     oputf("%s\n", zSql);
25438     rc = SQLITE_OK;
25439   }else{
25440     char *zErr = 0;
25441     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
25442     if( zErr ){
25443       sputf(stdout, "ERROR: %s\n", zErr);
25444       sqlite3_free(zErr);
25445     }
25446   }
25447   return rc;
25448 }
25449 
25450 
25451 /*
25452 ** Implementation of .ar "create", "insert", and "update" commands.
25453 **
25454 **     create    ->     Create a new SQL archive
25455 **     insert    ->     Insert or reinsert all files listed
25456 **     update    ->     Insert files that have changed or that were not
25457 **                      previously in the archive
25458 **
25459 ** Create the "sqlar" table in the database if it does not already exist.
25460 ** Then add each file in the azFile[] array to the archive. Directories
25461 ** are added recursively. If argument bVerbose is non-zero, a message is
25462 ** printed on stdout for each file archived.
25463 **
25464 ** The create command is the same as update, except that it drops
25465 ** any existing "sqlar" table before beginning.  The "insert" command
25466 ** always overwrites every file named on the command-line, where as
25467 ** "update" only overwrites if the size or mtime or mode has changed.
25468 */
arCreateOrUpdateCommand(ArCommand * pAr,int bUpdate,int bOnlyIfChanged)25469 static int arCreateOrUpdateCommand(
25470   ArCommand *pAr,                 /* Command arguments and options */
25471   int bUpdate,                    /* true for a --create. */
25472   int bOnlyIfChanged              /* Only update if file has changed */
25473 ){
25474   const char *zCreate =
25475       "CREATE TABLE IF NOT EXISTS sqlar(\n"
25476       "  name TEXT PRIMARY KEY,  -- name of the file\n"
25477       "  mode INT,               -- access permissions\n"
25478       "  mtime INT,              -- last modification time\n"
25479       "  sz INT,                 -- original file size\n"
25480       "  data BLOB               -- compressed content\n"
25481       ")";
25482   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
25483   const char *zInsertFmt[2] = {
25484      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
25485      "  SELECT\n"
25486      "    %s,\n"
25487      "    mode,\n"
25488      "    mtime,\n"
25489      "    CASE substr(lsmode(mode),1,1)\n"
25490      "      WHEN '-' THEN length(data)\n"
25491      "      WHEN 'd' THEN 0\n"
25492      "      ELSE -1 END,\n"
25493      "    sqlar_compress(data)\n"
25494      "  FROM fsdir(%Q,%Q) AS disk\n"
25495      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
25496      ,
25497      "REPLACE INTO %s(name,mode,mtime,data)\n"
25498      "  SELECT\n"
25499      "    %s,\n"
25500      "    mode,\n"
25501      "    mtime,\n"
25502      "    data\n"
25503      "  FROM fsdir(%Q,%Q) AS disk\n"
25504      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
25505   };
25506   int i;                          /* For iterating through azFile[] */
25507   int rc;                         /* Return code */
25508   const char *zTab = 0;           /* SQL table into which to insert */
25509   char *zSql;
25510   char zTemp[50];
25511   char *zExists = 0;
25512 
25513   arExecSql(pAr, "PRAGMA page_size=512");
25514   rc = arExecSql(pAr, "SAVEPOINT ar;");
25515   if( rc!=SQLITE_OK ) return rc;
25516   zTemp[0] = 0;
25517   if( pAr->bZip ){
25518     /* Initialize the zipfile virtual table, if necessary */
25519     if( pAr->zFile ){
25520       sqlite3_uint64 r;
25521       sqlite3_randomness(sizeof(r),&r);
25522       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
25523       zTab = zTemp;
25524       zSql = sqlite3_mprintf(
25525          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
25526          zTab, pAr->zFile
25527       );
25528       rc = arExecSql(pAr, zSql);
25529       sqlite3_free(zSql);
25530     }else{
25531       zTab = "zip";
25532     }
25533   }else{
25534     /* Initialize the table for an SQLAR */
25535     zTab = "sqlar";
25536     if( bUpdate==0 ){
25537       rc = arExecSql(pAr, zDrop);
25538       if( rc!=SQLITE_OK ) goto end_ar_transaction;
25539     }
25540     rc = arExecSql(pAr, zCreate);
25541   }
25542   if( bOnlyIfChanged ){
25543     zExists = sqlite3_mprintf(
25544       " AND NOT EXISTS("
25545           "SELECT 1 FROM %s AS mem"
25546           " WHERE mem.name=disk.name"
25547           " AND mem.mtime=disk.mtime"
25548           " AND mem.mode=disk.mode)", zTab);
25549   }else{
25550     zExists = sqlite3_mprintf("");
25551   }
25552   if( zExists==0 ) rc = SQLITE_NOMEM;
25553   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
25554     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
25555         pAr->bVerbose ? "shell_putsnl(name)" : "name",
25556         pAr->azArg[i], pAr->zDir, zExists);
25557     rc = arExecSql(pAr, zSql2);
25558     sqlite3_free(zSql2);
25559   }
25560 end_ar_transaction:
25561   if( rc!=SQLITE_OK ){
25562     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
25563   }else{
25564     rc = arExecSql(pAr, "RELEASE ar;");
25565     if( pAr->bZip && pAr->zFile ){
25566       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
25567       arExecSql(pAr, zSql);
25568       sqlite3_free(zSql);
25569     }
25570   }
25571   sqlite3_free(zExists);
25572   return rc;
25573 }
25574 
25575 /*
25576 ** Implementation of ".ar" dot command.
25577 */
arDotCommand(ShellState * pState,int fromCmdLine,char ** azArg,int nArg)25578 static int arDotCommand(
25579   ShellState *pState,          /* Current shell tool state */
25580   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
25581   char **azArg,                /* Array of arguments passed to dot command */
25582   int nArg                     /* Number of entries in azArg[] */
25583 ){
25584   ArCommand cmd;
25585   int rc;
25586   memset(&cmd, 0, sizeof(cmd));
25587   cmd.fromCmdLine = fromCmdLine;
25588   rc = arParseCommand(azArg, nArg, &cmd);
25589   if( rc==SQLITE_OK ){
25590     int eDbType = SHELL_OPEN_UNSPEC;
25591     cmd.p = pState;
25592     cmd.db = pState->db;
25593     if( cmd.zFile ){
25594       eDbType = deduceDatabaseType(cmd.zFile, 1);
25595     }else{
25596       eDbType = pState->openMode;
25597     }
25598     if( eDbType==SHELL_OPEN_ZIPFILE ){
25599       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
25600         if( cmd.zFile==0 ){
25601           cmd.zSrcTable = sqlite3_mprintf("zip");
25602         }else{
25603           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
25604         }
25605       }
25606       cmd.bZip = 1;
25607     }else if( cmd.zFile ){
25608       int flags;
25609       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
25610       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
25611            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
25612         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
25613       }else{
25614         flags = SQLITE_OPEN_READONLY;
25615       }
25616       cmd.db = 0;
25617       if( cmd.bDryRun ){
25618         oputf("-- open database '%s'%s\n", cmd.zFile,
25619               eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
25620       }
25621       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
25622              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
25623       if( rc!=SQLITE_OK ){
25624         eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
25625         goto end_ar_command;
25626       }
25627       sqlite3_fileio_init(cmd.db, 0, 0);
25628       sqlite3_sqlar_init(cmd.db, 0, 0);
25629       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
25630                               shellPutsFunc, 0, 0);
25631 
25632     }
25633     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
25634       if( cmd.eCmd!=AR_CMD_CREATE
25635        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
25636       ){
25637         eputz("database does not contain an 'sqlar' table\n");
25638         rc = SQLITE_ERROR;
25639         goto end_ar_command;
25640       }
25641       cmd.zSrcTable = sqlite3_mprintf("sqlar");
25642     }
25643 
25644     switch( cmd.eCmd ){
25645       case AR_CMD_CREATE:
25646         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
25647         break;
25648 
25649       case AR_CMD_EXTRACT:
25650         rc = arExtractCommand(&cmd);
25651         break;
25652 
25653       case AR_CMD_LIST:
25654         rc = arListCommand(&cmd);
25655         break;
25656 
25657       case AR_CMD_HELP:
25658         arUsage(pState->out);
25659         break;
25660 
25661       case AR_CMD_INSERT:
25662         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
25663         break;
25664 
25665       case AR_CMD_REMOVE:
25666         rc = arRemoveCommand(&cmd);
25667         break;
25668 
25669       default:
25670         assert( cmd.eCmd==AR_CMD_UPDATE );
25671         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
25672         break;
25673     }
25674   }
25675 end_ar_command:
25676   if( cmd.db!=pState->db ){
25677     close_db(cmd.db);
25678   }
25679   sqlite3_free(cmd.zSrcTable);
25680 
25681   return rc;
25682 }
25683 /* End of the ".archive" or ".ar" command logic
25684 *******************************************************************************/
25685 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
25686 
25687 #if SQLITE_SHELL_HAVE_RECOVER
25688 
25689 /*
25690 ** This function is used as a callback by the recover extension. Simply
25691 ** print the supplied SQL statement to stdout.
25692 */
recoverSqlCb(void * pCtx,const char * zSql)25693 static int recoverSqlCb(void *pCtx, const char *zSql){
25694   ShellState *pState = (ShellState*)pCtx;
25695   sputf(pState->out, "%s;\n", zSql);
25696   return SQLITE_OK;
25697 }
25698 
25699 /*
25700 ** This function is called to recover data from the database. A script
25701 ** to construct a new database containing all recovered data is output
25702 ** on stream pState->out.
25703 */
recoverDatabaseCmd(ShellState * pState,int nArg,char ** azArg)25704 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
25705   int rc = SQLITE_OK;
25706   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
25707   const char *zLAF = "lost_and_found";
25708   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
25709   int bRowids = 1;                /* 0 if --no-rowids */
25710   sqlite3_recover *p = 0;
25711   int i = 0;
25712 
25713   for(i=1; i<nArg; i++){
25714     char *z = azArg[i];
25715     int n;
25716     if( z[0]=='-' && z[1]=='-' ) z++;
25717     n = strlen30(z);
25718     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
25719       bFreelist = 0;
25720     }else
25721     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
25722       /* This option determines the name of the ATTACH-ed database used
25723       ** internally by the recovery extension.  The default is "" which
25724       ** means to use a temporary database that is automatically deleted
25725       ** when closed.  This option is undocumented and might disappear at
25726       ** any moment. */
25727       i++;
25728       zRecoveryDb = azArg[i];
25729     }else
25730     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
25731       i++;
25732       zLAF = azArg[i];
25733     }else
25734     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
25735       bRowids = 0;
25736     }
25737     else{
25738       eputf("unexpected option: %s\n", azArg[i]);
25739       showHelp(pState->out, azArg[0]);
25740       return 1;
25741     }
25742   }
25743 
25744   p = sqlite3_recover_init_sql(
25745       pState->db, "main", recoverSqlCb, (void*)pState
25746   );
25747 
25748   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
25749   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
25750   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
25751   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
25752 
25753   sqlite3_recover_run(p);
25754   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
25755     const char *zErr = sqlite3_recover_errmsg(p);
25756     int errCode = sqlite3_recover_errcode(p);
25757     eputf("sql error: %s (%d)\n", zErr, errCode);
25758   }
25759   rc = sqlite3_recover_finish(p);
25760   return rc;
25761 }
25762 #endif /* SQLITE_SHELL_HAVE_RECOVER */
25763 
25764 /*
25765 ** Implementation of ".intck STEPS_PER_UNLOCK" command.
25766 */
intckDatabaseCmd(ShellState * pState,i64 nStepPerUnlock)25767 static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){
25768   sqlite3_intck *p = 0;
25769   int rc = SQLITE_OK;
25770 
25771   rc = sqlite3_intck_open(pState->db, "main", &p);
25772   if( rc==SQLITE_OK ){
25773     i64 nStep = 0;
25774     i64 nError = 0;
25775     const char *zErr = 0;
25776     while( SQLITE_OK==sqlite3_intck_step(p) ){
25777       const char *zMsg = sqlite3_intck_message(p);
25778       if( zMsg ){
25779         oputf("%s\n", zMsg);
25780         nError++;
25781       }
25782       nStep++;
25783       if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){
25784         sqlite3_intck_unlock(p);
25785       }
25786     }
25787     rc = sqlite3_intck_error(p, &zErr);
25788     if( zErr ){
25789       eputf("%s\n", zErr);
25790     }
25791     sqlite3_intck_close(p);
25792 
25793     oputf("%lld steps, %lld errors\n", nStep, nError);
25794   }
25795 
25796   return rc;
25797 }
25798 
25799 /*
25800  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
25801  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
25802  *   close db and set it to 0, and return the columns spec, to later
25803  *   be sqlite3_free()'ed by the caller.
25804  * The return is 0 when either:
25805  *   (a) The db was not initialized and zCol==0 (There are no columns.)
25806  *   (b) zCol!=0  (Column was added, db initialized as needed.)
25807  * The 3rd argument, pRenamed, references an out parameter. If the
25808  * pointer is non-zero, its referent will be set to a summary of renames
25809  * done if renaming was necessary, or set to 0 if none was done. The out
25810  * string (if any) must be sqlite3_free()'ed by the caller.
25811  */
25812 #ifdef SHELL_DEBUG
25813 #define rc_err_oom_die(rc) \
25814   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
25815   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
25816     eputf("E:%d\n",rc), assert(0)
25817 #else
rc_err_oom_die(int rc)25818 static void rc_err_oom_die(int rc){
25819   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
25820   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
25821 }
25822 #endif
25823 
25824 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
25825 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
25826 #else  /* Otherwise, memory is faster/better for the transient DB. */
25827 static const char *zCOL_DB = ":memory:";
25828 #endif
25829 
25830 /* Define character (as C string) to separate generated column ordinal
25831  * from protected part of incoming column names. This defaults to "_"
25832  * so that incoming column identifiers that did not need not be quoted
25833  * remain usable without being quoted. It must be one character.
25834  */
25835 #ifndef SHELL_AUTOCOLUMN_SEP
25836 # define AUTOCOLUMN_SEP "_"
25837 #else
25838 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
25839 #endif
25840 
zAutoColumn(const char * zColNew,sqlite3 ** pDb,char ** pzRenamed)25841 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
25842   /* Queries and D{D,M}L used here */
25843   static const char * const zTabMake = "\
25844 CREATE TABLE ColNames(\
25845  cpos INTEGER PRIMARY KEY,\
25846  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
25847 CREATE VIEW RepeatedNames AS \
25848 SELECT DISTINCT t.name FROM ColNames t \
25849 WHERE t.name COLLATE NOCASE IN (\
25850  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
25851 );\
25852 ";
25853   static const char * const zTabFill = "\
25854 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
25855  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
25856 ";
25857   static const char * const zHasDupes = "\
25858 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
25859  <count(name) FROM ColNames\
25860 ";
25861 #ifdef SHELL_COLUMN_RENAME_CLEAN
25862   static const char * const zDedoctor = "\
25863 UPDATE ColNames SET chop=iif(\
25864   (substring(name,nlen,1) BETWEEN '0' AND '9')\
25865   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
25866  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
25867  0\
25868 )\
25869 ";
25870 #endif
25871   static const char * const zSetReps = "\
25872 UPDATE ColNames AS t SET reps=\
25873 (SELECT count(*) FROM ColNames d \
25874  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
25875  COLLATE NOCASE\
25876 )\
25877 ";
25878 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
25879   static const char * const zColDigits = "\
25880 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
25881 ";
25882 #else
25883   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
25884   static const char * const zColDigits = "\
25885 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
25886  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
25887  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
25888 ";
25889 #endif
25890   static const char * const zRenameRank =
25891 #ifdef SHELL_COLUMN_RENAME_CLEAN
25892     "UPDATE ColNames AS t SET suff="
25893     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
25894 #else /* ...RENAME_MINIMAL_ONE_PASS */
25895 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
25896 "  SELECT 0 AS nlz"
25897 "  UNION"
25898 "  SELECT nlz+1 AS nlz FROM Lzn"
25899 "  WHERE EXISTS("
25900 "   SELECT 1"
25901 "   FROM ColNames t, ColNames o"
25902 "   WHERE"
25903 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
25904 "     printf('%s"AUTOCOLUMN_SEP"%s',"
25905 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
25906 "     t.name"
25907 "    )"
25908 "    ="
25909 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
25910 "     printf('%s"AUTOCOLUMN_SEP"%s',"
25911 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
25912 "     o.name"
25913 "    )"
25914 "    COLLATE NOCASE"
25915 "    AND o.cpos<>t.cpos"
25916 "   GROUP BY t.cpos"
25917 "  )"
25918 ") UPDATE Colnames AS t SET"
25919 " chop = 0," /* No chopping, never touch incoming names. */
25920 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
25921 "  printf('"AUTOCOLUMN_SEP"%s', substring("
25922 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
25923 "  ''"
25924 " )"
25925 #endif
25926     ;
25927   static const char * const zCollectVar = "\
25928 SELECT\
25929  '('||x'0a'\
25930  || group_concat(\
25931   cname||' TEXT',\
25932   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
25933  ||')' AS ColsSpec \
25934 FROM (\
25935  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
25936  FROM ColNames ORDER BY cpos\
25937 )";
25938   static const char * const zRenamesDone =
25939     "SELECT group_concat("
25940     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
25941     " ','||x'0a')"
25942     "FROM ColNames WHERE suff<>'' OR chop!=0"
25943     ;
25944   int rc;
25945   sqlite3_stmt *pStmt = 0;
25946   assert(pDb!=0);
25947   if( zColNew ){
25948     /* Add initial or additional column. Init db if necessary. */
25949     if( *pDb==0 ){
25950       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
25951 #ifdef SHELL_COLFIX_DB
25952       if(*zCOL_DB!=':')
25953         sqlite3_exec(*pDb,"drop table if exists ColNames;"
25954                      "drop view if exists RepeatedNames;",0,0,0);
25955 #endif
25956 #undef SHELL_COLFIX_DB
25957       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
25958       rc_err_oom_die(rc);
25959     }
25960     assert(*pDb!=0);
25961     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
25962     rc_err_oom_die(rc);
25963     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
25964     rc_err_oom_die(rc);
25965     rc = sqlite3_step(pStmt);
25966     rc_err_oom_die(rc);
25967     sqlite3_finalize(pStmt);
25968     return 0;
25969   }else if( *pDb==0 ){
25970     return 0;
25971   }else{
25972     /* Formulate the columns spec, close the DB, zero *pDb. */
25973     char *zColsSpec = 0;
25974     int hasDupes = db_int(*pDb, zHasDupes);
25975     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
25976     if( hasDupes ){
25977 #ifdef SHELL_COLUMN_RENAME_CLEAN
25978       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
25979       rc_err_oom_die(rc);
25980 #endif
25981       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
25982       rc_err_oom_die(rc);
25983       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
25984       rc_err_oom_die(rc);
25985       sqlite3_bind_int(pStmt, 1, nDigits);
25986       rc = sqlite3_step(pStmt);
25987       sqlite3_finalize(pStmt);
25988       if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
25989     }
25990     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
25991     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
25992     rc_err_oom_die(rc);
25993     rc = sqlite3_step(pStmt);
25994     if( rc==SQLITE_ROW ){
25995       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
25996     }else{
25997       zColsSpec = 0;
25998     }
25999     if( pzRenamed!=0 ){
26000       if( !hasDupes ) *pzRenamed = 0;
26001       else{
26002         sqlite3_finalize(pStmt);
26003         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
26004             && SQLITE_ROW==sqlite3_step(pStmt) ){
26005           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
26006         }else
26007           *pzRenamed = 0;
26008       }
26009     }
26010     sqlite3_finalize(pStmt);
26011     sqlite3_close(*pDb);
26012     *pDb = 0;
26013     return zColsSpec;
26014   }
26015 }
26016 
26017 /*
26018 ** Check if the sqlite_schema table contains one or more virtual tables. If
26019 ** parameter zLike is not NULL, then it is an SQL expression that the
26020 ** sqlite_schema row must also match. If one or more such rows are found,
26021 ** print the following warning to the output:
26022 **
26023 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
26024 */
outputDumpWarning(ShellState * p,const char * zLike)26025 static int outputDumpWarning(ShellState *p, const char *zLike){
26026   int rc = SQLITE_OK;
26027   sqlite3_stmt *pStmt = 0;
26028   shellPreparePrintf(p->db, &rc, &pStmt,
26029     "SELECT 1 FROM sqlite_schema o WHERE "
26030     "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
26031   );
26032   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26033     oputz("/* WARNING: "
26034           "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
26035     );
26036   }
26037   shellFinalize(&rc, pStmt);
26038   return rc;
26039 }
26040 
26041 /*
26042 ** Fault-Simulator state and logic.
26043 */
26044 static struct {
26045   int iId;           /* ID that triggers a simulated fault.  -1 means "any" */
26046   int iErr;          /* The error code to return on a fault */
26047   int iCnt;          /* Trigger the fault only if iCnt is already zero */
26048   int iInterval;     /* Reset iCnt to this value after each fault */
26049   int eVerbose;      /* When to print output */
26050   int nHit;          /* Number of hits seen so far */
26051   int nRepeat;       /* Turn off after this many hits.  0 for never */
26052   int nSkip;         /* Skip this many before first fault */
26053 } faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};
26054 
26055 /*
26056 ** This is the fault-sim callback
26057 */
faultsim_callback(int iArg)26058 static int faultsim_callback(int iArg){
26059   if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
26060     return SQLITE_OK;
26061   }
26062   if( faultsim_state.iCnt ){
26063     if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--;
26064     if( faultsim_state.eVerbose>=2 ){
26065       oputf("FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
26066     }
26067     return SQLITE_OK;
26068   }
26069   if( faultsim_state.eVerbose>=1 ){
26070     oputf("FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
26071   }
26072   faultsim_state.iCnt = faultsim_state.iInterval;
26073   faultsim_state.nHit++;
26074   if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){
26075     faultsim_state.iCnt = -1;
26076   }
26077   return faultsim_state.iErr;
26078 }
26079 
26080 /*
26081 ** If an input line begins with "." then invoke this routine to
26082 ** process that line.
26083 **
26084 ** Return 1 on error, 2 to exit, and 0 otherwise.
26085 */
do_meta_command(char * zLine,ShellState * p)26086 static int do_meta_command(char *zLine, ShellState *p){
26087   int h = 1;
26088   int nArg = 0;
26089   int n, c;
26090   int rc = 0;
26091   char *azArg[52];
26092 
26093 #ifndef SQLITE_OMIT_VIRTUALTABLE
26094   if( p->expert.pExpert ){
26095     expertFinish(p, 1, 0);
26096   }
26097 #endif
26098 
26099   /* Parse the input line into tokens.
26100   */
26101   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
26102     while( IsSpace(zLine[h]) ){ h++; }
26103     if( zLine[h]==0 ) break;
26104     if( zLine[h]=='\'' || zLine[h]=='"' ){
26105       int delim = zLine[h++];
26106       azArg[nArg++] = &zLine[h];
26107       while( zLine[h] && zLine[h]!=delim ){
26108         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
26109         h++;
26110       }
26111       if( zLine[h]==delim ){
26112         zLine[h++] = 0;
26113       }
26114       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
26115     }else{
26116       azArg[nArg++] = &zLine[h];
26117       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
26118       if( zLine[h] ) zLine[h++] = 0;
26119     }
26120   }
26121   azArg[nArg] = 0;
26122 
26123   /* Process the input line.
26124   */
26125   if( nArg==0 ) return 0; /* no tokens, no error */
26126   n = strlen30(azArg[0]);
26127   c = azArg[0][0];
26128   clearTempFile(p);
26129 
26130 #ifndef SQLITE_OMIT_AUTHORIZATION
26131   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
26132     if( nArg!=2 ){
26133       eputz("Usage: .auth ON|OFF\n");
26134       rc = 1;
26135       goto meta_command_exit;
26136     }
26137     open_db(p, 0);
26138     if( booleanValue(azArg[1]) ){
26139       sqlite3_set_authorizer(p->db, shellAuth, p);
26140     }else if( p->bSafeModePersist ){
26141       sqlite3_set_authorizer(p->db, safeModeAuth, p);
26142     }else{
26143       sqlite3_set_authorizer(p->db, 0, 0);
26144     }
26145   }else
26146 #endif
26147 
26148 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
26149   && !defined(SQLITE_SHELL_FIDDLE)
26150   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
26151     open_db(p, 0);
26152     failIfSafeMode(p, "cannot run .archive in safe mode");
26153     rc = arDotCommand(p, 0, azArg, nArg);
26154   }else
26155 #endif
26156 
26157 #ifndef SQLITE_SHELL_FIDDLE
26158   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
26159    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
26160   ){
26161     const char *zDestFile = 0;
26162     const char *zDb = 0;
26163     sqlite3 *pDest;
26164     sqlite3_backup *pBackup;
26165     int j;
26166     int bAsync = 0;
26167     const char *zVfs = 0;
26168     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
26169     for(j=1; j<nArg; j++){
26170       const char *z = azArg[j];
26171       if( z[0]=='-' ){
26172         if( z[1]=='-' ) z++;
26173         if( cli_strcmp(z, "-append")==0 ){
26174           zVfs = "apndvfs";
26175         }else
26176         if( cli_strcmp(z, "-async")==0 ){
26177           bAsync = 1;
26178         }else
26179         {
26180           eputf("unknown option: %s\n", azArg[j]);
26181           return 1;
26182         }
26183       }else if( zDestFile==0 ){
26184         zDestFile = azArg[j];
26185       }else if( zDb==0 ){
26186         zDb = zDestFile;
26187         zDestFile = azArg[j];
26188       }else{
26189         eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
26190         return 1;
26191       }
26192     }
26193     if( zDestFile==0 ){
26194       eputz("missing FILENAME argument on .backup\n");
26195       return 1;
26196     }
26197     if( zDb==0 ) zDb = "main";
26198     rc = sqlite3_open_v2(zDestFile, &pDest,
26199                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
26200     if( rc!=SQLITE_OK ){
26201       eputf("Error: cannot open \"%s\"\n", zDestFile);
26202       close_db(pDest);
26203       return 1;
26204     }
26205     if( bAsync ){
26206       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
26207                    0, 0, 0);
26208     }
26209     open_db(p, 0);
26210     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
26211     if( pBackup==0 ){
26212       eputf("Error: %s\n", sqlite3_errmsg(pDest));
26213       close_db(pDest);
26214       return 1;
26215     }
26216     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
26217     sqlite3_backup_finish(pBackup);
26218     if( rc==SQLITE_DONE ){
26219       rc = 0;
26220     }else{
26221       eputf("Error: %s\n", sqlite3_errmsg(pDest));
26222       rc = 1;
26223     }
26224     close_db(pDest);
26225   }else
26226 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26227 
26228   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
26229     if( nArg==2 ){
26230       bail_on_error = booleanValue(azArg[1]);
26231     }else{
26232       eputz("Usage: .bail on|off\n");
26233       rc = 1;
26234     }
26235   }else
26236 
26237   /* Undocumented.  Legacy only.  See "crnl" below */
26238   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
26239     if( nArg==2 ){
26240       if( booleanValue(azArg[1]) ){
26241         setBinaryMode(p->out, 1);
26242       }else{
26243         setTextMode(p->out, 1);
26244       }
26245     }else{
26246       eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
26247             "Usage: .binary on|off\n");
26248       rc = 1;
26249     }
26250   }else
26251 
26252   /* The undocumented ".breakpoint" command causes a call to the no-op
26253   ** routine named test_breakpoint().
26254   */
26255   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
26256     test_breakpoint();
26257   }else
26258 
26259 #ifndef SQLITE_SHELL_FIDDLE
26260   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
26261     failIfSafeMode(p, "cannot run .cd in safe mode");
26262     if( nArg==2 ){
26263 #if defined(_WIN32) || defined(WIN32)
26264       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
26265       rc = !SetCurrentDirectoryW(z);
26266       sqlite3_free(z);
26267 #else
26268       rc = chdir(azArg[1]);
26269 #endif
26270       if( rc ){
26271         eputf("Cannot change to directory \"%s\"\n", azArg[1]);
26272         rc = 1;
26273       }
26274     }else{
26275       eputz("Usage: .cd DIRECTORY\n");
26276       rc = 1;
26277     }
26278   }else
26279 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26280 
26281   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
26282     if( nArg==2 ){
26283       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
26284     }else{
26285       eputz("Usage: .changes on|off\n");
26286       rc = 1;
26287     }
26288   }else
26289 
26290 #ifndef SQLITE_SHELL_FIDDLE
26291   /* Cancel output redirection, if it is currently set (by .testcase)
26292   ** Then read the content of the testcase-out.txt file and compare against
26293   ** azArg[1].  If there are differences, report an error and exit.
26294   */
26295   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
26296     char *zRes = 0;
26297     output_reset(p);
26298     if( nArg!=2 ){
26299       eputz("Usage: .check GLOB-PATTERN\n");
26300       rc = 2;
26301     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
26302       rc = 2;
26303     }else if( testcase_glob(azArg[1],zRes)==0 ){
26304       eputf("testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
26305             p->zTestcase, azArg[1], zRes);
26306       rc = 1;
26307     }else{
26308       oputf("testcase-%s ok\n", p->zTestcase);
26309       p->nCheck++;
26310     }
26311     sqlite3_free(zRes);
26312   }else
26313 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26314 
26315 #ifndef SQLITE_SHELL_FIDDLE
26316   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
26317     failIfSafeMode(p, "cannot run .clone in safe mode");
26318     if( nArg==2 ){
26319       tryToClone(p, azArg[1]);
26320     }else{
26321       eputz("Usage: .clone FILENAME\n");
26322       rc = 1;
26323     }
26324   }else
26325 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26326 
26327   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
26328     if( nArg==1 ){
26329       /* List available connections */
26330       int i;
26331       for(i=0; i<ArraySize(p->aAuxDb); i++){
26332         const char *zFile = p->aAuxDb[i].zDbFilename;
26333         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
26334           zFile = "(not open)";
26335         }else if( zFile==0 ){
26336           zFile = "(memory)";
26337         }else if( zFile[0]==0 ){
26338           zFile = "(temporary-file)";
26339         }
26340         if( p->pAuxDb == &p->aAuxDb[i] ){
26341           sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
26342         }else if( p->aAuxDb[i].db!=0 ){
26343           sputf(stdout, "       %d: %s\n", i, zFile);
26344         }
26345       }
26346     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
26347       int i = azArg[1][0] - '0';
26348       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
26349         p->pAuxDb->db = p->db;
26350         p->pAuxDb = &p->aAuxDb[i];
26351         globalDb = p->db = p->pAuxDb->db;
26352         p->pAuxDb->db = 0;
26353       }
26354     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
26355            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
26356       int i = azArg[2][0] - '0';
26357       if( i<0 || i>=ArraySize(p->aAuxDb) ){
26358         /* No-op */
26359       }else if( p->pAuxDb == &p->aAuxDb[i] ){
26360         eputz("cannot close the active database connection\n");
26361         rc = 1;
26362       }else if( p->aAuxDb[i].db ){
26363         session_close_all(p, i);
26364         close_db(p->aAuxDb[i].db);
26365         p->aAuxDb[i].db = 0;
26366       }
26367     }else{
26368       eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
26369       rc = 1;
26370     }
26371   }else
26372 
26373   if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
26374     if( nArg==2 ){
26375       if( booleanValue(azArg[1]) ){
26376         setTextMode(p->out, 1);
26377       }else{
26378         setBinaryMode(p->out, 1);
26379       }
26380     }else{
26381 #if !defined(_WIN32) && !defined(WIN32)
26382       eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
26383 #endif
26384       eputz("Usage: .crnl on|off\n");
26385       rc = 1;
26386     }
26387   }else
26388 
26389   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
26390     char **azName = 0;
26391     int nName = 0;
26392     sqlite3_stmt *pStmt;
26393     int i;
26394     open_db(p, 0);
26395     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
26396     if( rc ){
26397       eputf("Error: %s\n", sqlite3_errmsg(p->db));
26398       rc = 1;
26399     }else{
26400       while( sqlite3_step(pStmt)==SQLITE_ROW ){
26401         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
26402         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
26403         if( zSchema==0 || zFile==0 ) continue;
26404         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
26405         shell_check_oom(azName);
26406         azName[nName*2] = strdup(zSchema);
26407         azName[nName*2+1] = strdup(zFile);
26408         nName++;
26409       }
26410     }
26411     sqlite3_finalize(pStmt);
26412     for(i=0; i<nName; i++){
26413       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
26414       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
26415       const char *z = azName[i*2+1];
26416       oputf("%s: %s %s%s\n",
26417             azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
26418             eTxn==SQLITE_TXN_NONE ? "" :
26419             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
26420       free(azName[i*2]);
26421       free(azName[i*2+1]);
26422     }
26423     sqlite3_free(azName);
26424   }else
26425 
26426   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
26427     static const struct DbConfigChoices {
26428       const char *zName;
26429       int op;
26430     } aDbConfig[] = {
26431         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
26432         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
26433         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
26434         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
26435         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
26436         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
26437         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
26438         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
26439         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
26440         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
26441         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
26442         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
26443         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
26444         { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
26445         { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
26446         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
26447         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
26448         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
26449     };
26450     int ii, v;
26451     open_db(p, 0);
26452     for(ii=0; ii<ArraySize(aDbConfig); ii++){
26453       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
26454       if( nArg>=3 ){
26455         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
26456       }
26457       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
26458       oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
26459       if( nArg>1 ) break;
26460     }
26461     if( nArg>1 && ii==ArraySize(aDbConfig) ){
26462       eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
26463       eputz("Enter \".dbconfig\" with no arguments for a list\n");
26464     }
26465   }else
26466 
26467 #if SQLITE_SHELL_HAVE_RECOVER
26468   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
26469     rc = shell_dbinfo_command(p, nArg, azArg);
26470   }else
26471 
26472   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
26473     open_db(p, 0);
26474     rc = recoverDatabaseCmd(p, nArg, azArg);
26475   }else
26476 #endif /* SQLITE_SHELL_HAVE_RECOVER */
26477 
26478   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
26479     char *zLike = 0;
26480     char *zSql;
26481     int i;
26482     int savedShowHeader = p->showHeader;
26483     int savedShellFlags = p->shellFlgs;
26484     ShellClearFlag(p,
26485        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
26486        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
26487     for(i=1; i<nArg; i++){
26488       if( azArg[i][0]=='-' ){
26489         const char *z = azArg[i]+1;
26490         if( z[0]=='-' ) z++;
26491         if( cli_strcmp(z,"preserve-rowids")==0 ){
26492 #ifdef SQLITE_OMIT_VIRTUALTABLE
26493           eputz("The --preserve-rowids option is not compatible"
26494                 " with SQLITE_OMIT_VIRTUALTABLE\n");
26495           rc = 1;
26496           sqlite3_free(zLike);
26497           goto meta_command_exit;
26498 #else
26499           ShellSetFlag(p, SHFLG_PreserveRowid);
26500 #endif
26501         }else
26502         if( cli_strcmp(z,"newlines")==0 ){
26503           ShellSetFlag(p, SHFLG_Newlines);
26504         }else
26505         if( cli_strcmp(z,"data-only")==0 ){
26506           ShellSetFlag(p, SHFLG_DumpDataOnly);
26507         }else
26508         if( cli_strcmp(z,"nosys")==0 ){
26509           ShellSetFlag(p, SHFLG_DumpNoSys);
26510         }else
26511         {
26512           eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
26513           rc = 1;
26514           sqlite3_free(zLike);
26515           goto meta_command_exit;
26516         }
26517       }else{
26518         /* azArg[i] contains a LIKE pattern. This ".dump" request should
26519         ** only dump data for tables for which either the table name matches
26520         ** the LIKE pattern, or the table appears to be a shadow table of
26521         ** a virtual table for which the name matches the LIKE pattern.
26522         */
26523         char *zExpr = sqlite3_mprintf(
26524             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
26525             "  SELECT 1 FROM sqlite_schema WHERE "
26526             "    name LIKE %Q ESCAPE '\\' AND"
26527             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
26528             "    substr(o.name, 1, length(name)+1) == (name||'_')"
26529             ")", azArg[i], azArg[i]
26530         );
26531 
26532         if( zLike ){
26533           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
26534         }else{
26535           zLike = zExpr;
26536         }
26537       }
26538     }
26539 
26540     open_db(p, 0);
26541 
26542     outputDumpWarning(p, zLike);
26543     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
26544       /* When playing back a "dump", the content might appear in an order
26545       ** which causes immediate foreign key constraints to be violated.
26546       ** So disable foreign-key constraint enforcement to prevent problems. */
26547       oputz("PRAGMA foreign_keys=OFF;\n");
26548       oputz("BEGIN TRANSACTION;\n");
26549     }
26550     p->writableSchema = 0;
26551     p->showHeader = 0;
26552     /* Set writable_schema=ON since doing so forces SQLite to initialize
26553     ** as much of the schema as it can even if the sqlite_schema table is
26554     ** corrupt. */
26555     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
26556     p->nErr = 0;
26557     if( zLike==0 ) zLike = sqlite3_mprintf("true");
26558     zSql = sqlite3_mprintf(
26559       "SELECT name, type, sql FROM sqlite_schema AS o "
26560       "WHERE (%s) AND type=='table'"
26561       "  AND sql NOT NULL"
26562       " ORDER BY tbl_name='sqlite_sequence', rowid",
26563       zLike
26564     );
26565     run_schema_dump_query(p,zSql);
26566     sqlite3_free(zSql);
26567     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
26568       zSql = sqlite3_mprintf(
26569         "SELECT sql FROM sqlite_schema AS o "
26570         "WHERE (%s) AND sql NOT NULL"
26571         "  AND type IN ('index','trigger','view') "
26572         "ORDER BY type COLLATE NOCASE DESC",
26573         zLike
26574       );
26575       run_table_dump_query(p, zSql);
26576       sqlite3_free(zSql);
26577     }
26578     sqlite3_free(zLike);
26579     if( p->writableSchema ){
26580       oputz("PRAGMA writable_schema=OFF;\n");
26581       p->writableSchema = 0;
26582     }
26583     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
26584     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
26585     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
26586       oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
26587     }
26588     p->showHeader = savedShowHeader;
26589     p->shellFlgs = savedShellFlags;
26590   }else
26591 
26592   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
26593     if( nArg==2 ){
26594       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
26595     }else{
26596       eputz("Usage: .echo on|off\n");
26597       rc = 1;
26598     }
26599   }else
26600 
26601   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
26602     if( nArg==2 ){
26603       p->autoEQPtest = 0;
26604       if( p->autoEQPtrace ){
26605         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
26606         p->autoEQPtrace = 0;
26607       }
26608       if( cli_strcmp(azArg[1],"full")==0 ){
26609         p->autoEQP = AUTOEQP_full;
26610       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
26611         p->autoEQP = AUTOEQP_trigger;
26612 #ifdef SQLITE_DEBUG
26613       }else if( cli_strcmp(azArg[1],"test")==0 ){
26614         p->autoEQP = AUTOEQP_on;
26615         p->autoEQPtest = 1;
26616       }else if( cli_strcmp(azArg[1],"trace")==0 ){
26617         p->autoEQP = AUTOEQP_full;
26618         p->autoEQPtrace = 1;
26619         open_db(p, 0);
26620         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
26621         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
26622 #endif
26623       }else{
26624         p->autoEQP = (u8)booleanValue(azArg[1]);
26625       }
26626     }else{
26627       eputz("Usage: .eqp off|on|trace|trigger|full\n");
26628       rc = 1;
26629     }
26630   }else
26631 
26632 #ifndef SQLITE_SHELL_FIDDLE
26633   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
26634     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
26635     rc = 2;
26636   }else
26637 #endif
26638 
26639   /* The ".explain" command is automatic now.  It is largely pointless.  It
26640   ** retained purely for backwards compatibility */
26641   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
26642     int val = 1;
26643     if( nArg>=2 ){
26644       if( cli_strcmp(azArg[1],"auto")==0 ){
26645         val = 99;
26646       }else{
26647         val =  booleanValue(azArg[1]);
26648       }
26649     }
26650     if( val==1 && p->mode!=MODE_Explain ){
26651       p->normalMode = p->mode;
26652       p->mode = MODE_Explain;
26653       p->autoExplain = 0;
26654     }else if( val==0 ){
26655       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
26656       p->autoExplain = 0;
26657     }else if( val==99 ){
26658       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
26659       p->autoExplain = 1;
26660     }
26661   }else
26662 
26663 #ifndef SQLITE_OMIT_VIRTUALTABLE
26664   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
26665     if( p->bSafeMode ){
26666       eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
26667             azArg[0]);
26668       rc = 1;
26669     }else{
26670       open_db(p, 0);
26671       expertDotCommand(p, azArg, nArg);
26672     }
26673   }else
26674 #endif
26675 
26676   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
26677     static const struct {
26678        const char *zCtrlName;   /* Name of a test-control option */
26679        int ctrlCode;            /* Integer code for that option */
26680        const char *zUsage;      /* Usage notes */
26681     } aCtrl[] = {
26682       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
26683       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
26684       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
26685       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
26686       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
26687    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
26688       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
26689       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
26690       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
26691       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
26692    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
26693     };
26694     int filectrl = -1;
26695     int iCtrl = -1;
26696     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
26697     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
26698     int n2, i;
26699     const char *zCmd = 0;
26700     const char *zSchema = 0;
26701 
26702     open_db(p, 0);
26703     zCmd = nArg>=2 ? azArg[1] : "help";
26704 
26705     if( zCmd[0]=='-'
26706      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
26707      && nArg>=4
26708     ){
26709       zSchema = azArg[2];
26710       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
26711       nArg -= 2;
26712       zCmd = azArg[1];
26713     }
26714 
26715     /* The argument can optionally begin with "-" or "--" */
26716     if( zCmd[0]=='-' && zCmd[1] ){
26717       zCmd++;
26718       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
26719     }
26720 
26721     /* --help lists all file-controls */
26722     if( cli_strcmp(zCmd,"help")==0 ){
26723       oputz("Available file-controls:\n");
26724       for(i=0; i<ArraySize(aCtrl); i++){
26725         oputf("  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
26726       }
26727       rc = 1;
26728       goto meta_command_exit;
26729     }
26730 
26731     /* convert filectrl text option to value. allow any unique prefix
26732     ** of the option name, or a numerical value. */
26733     n2 = strlen30(zCmd);
26734     for(i=0; i<ArraySize(aCtrl); i++){
26735       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
26736         if( filectrl<0 ){
26737           filectrl = aCtrl[i].ctrlCode;
26738           iCtrl = i;
26739         }else{
26740           eputf("Error: ambiguous file-control: \"%s\"\n"
26741                 "Use \".filectrl --help\" for help\n", zCmd);
26742           rc = 1;
26743           goto meta_command_exit;
26744         }
26745       }
26746     }
26747     if( filectrl<0 ){
26748       eputf("Error: unknown file-control: %s\n"
26749             "Use \".filectrl --help\" for help\n", zCmd);
26750     }else{
26751       switch(filectrl){
26752         case SQLITE_FCNTL_SIZE_LIMIT: {
26753           if( nArg!=2 && nArg!=3 ) break;
26754           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
26755           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
26756           isOk = 1;
26757           break;
26758         }
26759         case SQLITE_FCNTL_LOCK_TIMEOUT:
26760         case SQLITE_FCNTL_CHUNK_SIZE: {
26761           int x;
26762           if( nArg!=3 ) break;
26763           x = (int)integerValue(azArg[2]);
26764           sqlite3_file_control(p->db, zSchema, filectrl, &x);
26765           isOk = 2;
26766           break;
26767         }
26768         case SQLITE_FCNTL_PERSIST_WAL:
26769         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26770           int x;
26771           if( nArg!=2 && nArg!=3 ) break;
26772           x = nArg==3 ? booleanValue(azArg[2]) : -1;
26773           sqlite3_file_control(p->db, zSchema, filectrl, &x);
26774           iRes = x;
26775           isOk = 1;
26776           break;
26777         }
26778         case SQLITE_FCNTL_DATA_VERSION:
26779         case SQLITE_FCNTL_HAS_MOVED: {
26780           int x;
26781           if( nArg!=2 ) break;
26782           sqlite3_file_control(p->db, zSchema, filectrl, &x);
26783           iRes = x;
26784           isOk = 1;
26785           break;
26786         }
26787         case SQLITE_FCNTL_TEMPFILENAME: {
26788           char *z = 0;
26789           if( nArg!=2 ) break;
26790           sqlite3_file_control(p->db, zSchema, filectrl, &z);
26791           if( z ){
26792             oputf("%s\n", z);
26793             sqlite3_free(z);
26794           }
26795           isOk = 2;
26796           break;
26797         }
26798         case SQLITE_FCNTL_RESERVE_BYTES: {
26799           int x;
26800           if( nArg>=3 ){
26801             x = atoi(azArg[2]);
26802             sqlite3_file_control(p->db, zSchema, filectrl, &x);
26803           }
26804           x = -1;
26805           sqlite3_file_control(p->db, zSchema, filectrl, &x);
26806           oputf("%d\n", x);
26807           isOk = 2;
26808           break;
26809         }
26810       }
26811     }
26812     if( isOk==0 && iCtrl>=0 ){
26813       oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
26814       rc = 1;
26815     }else if( isOk==1 ){
26816       char zBuf[100];
26817       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
26818       oputf("%s\n", zBuf);
26819     }
26820   }else
26821 
26822   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
26823     ShellState data;
26824     int doStats = 0;
26825     memcpy(&data, p, sizeof(data));
26826     data.showHeader = 0;
26827     data.cMode = data.mode = MODE_Semi;
26828     if( nArg==2 && optionMatch(azArg[1], "indent") ){
26829       data.cMode = data.mode = MODE_Pretty;
26830       nArg = 1;
26831     }
26832     if( nArg!=1 ){
26833       eputz("Usage: .fullschema ?--indent?\n");
26834       rc = 1;
26835       goto meta_command_exit;
26836     }
26837     open_db(p, 0);
26838     rc = sqlite3_exec(p->db,
26839        "SELECT sql FROM"
26840        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
26841        "     FROM sqlite_schema UNION ALL"
26842        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
26843        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
26844        "ORDER BY x",
26845        callback, &data, 0
26846     );
26847     if( rc==SQLITE_OK ){
26848       sqlite3_stmt *pStmt;
26849       rc = sqlite3_prepare_v2(p->db,
26850                "SELECT rowid FROM sqlite_schema"
26851                " WHERE name GLOB 'sqlite_stat[134]'",
26852                -1, &pStmt, 0);
26853       if( rc==SQLITE_OK ){
26854         doStats = sqlite3_step(pStmt)==SQLITE_ROW;
26855         sqlite3_finalize(pStmt);
26856       }
26857     }
26858     if( doStats==0 ){
26859       oputz("/* No STAT tables available */\n");
26860     }else{
26861       oputz("ANALYZE sqlite_schema;\n");
26862       data.cMode = data.mode = MODE_Insert;
26863       data.zDestTable = "sqlite_stat1";
26864       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
26865       data.zDestTable = "sqlite_stat4";
26866       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
26867       oputz("ANALYZE sqlite_schema;\n");
26868     }
26869   }else
26870 
26871   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
26872     if( nArg==2 ){
26873       p->showHeader = booleanValue(azArg[1]);
26874       p->shellFlgs |= SHFLG_HeaderSet;
26875     }else{
26876       eputz("Usage: .headers on|off\n");
26877       rc = 1;
26878     }
26879   }else
26880 
26881   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
26882     if( nArg>=2 ){
26883       n = showHelp(p->out, azArg[1]);
26884       if( n==0 ){
26885         oputf("Nothing matches '%s'\n", azArg[1]);
26886       }
26887     }else{
26888       showHelp(p->out, 0);
26889     }
26890   }else
26891 
26892 #ifndef SQLITE_SHELL_FIDDLE
26893   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
26894     char *zTable = 0;           /* Insert data into this table */
26895     char *zSchema = 0;          /* Schema of zTable */
26896     char *zFile = 0;            /* Name of file to extra content from */
26897     sqlite3_stmt *pStmt = NULL; /* A statement */
26898     int nCol;                   /* Number of columns in the table */
26899     i64 nByte;                  /* Number of bytes in an SQL string */
26900     int i, j;                   /* Loop counters */
26901     int needCommit;             /* True to COMMIT or ROLLBACK at end */
26902     int nSep;                   /* Number of bytes in p->colSeparator[] */
26903     char *zSql = 0;             /* An SQL statement */
26904     ImportCtx sCtx;             /* Reader context */
26905     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
26906     int eVerbose = 0;           /* Larger for more console output */
26907     int nSkip = 0;              /* Initial lines to skip */
26908     int useOutputMode = 1;      /* Use output mode to determine separators */
26909     char *zCreate = 0;          /* CREATE TABLE statement text */
26910 
26911     failIfSafeMode(p, "cannot run .import in safe mode");
26912     memset(&sCtx, 0, sizeof(sCtx));
26913     if( p->mode==MODE_Ascii ){
26914       xRead = ascii_read_one_field;
26915     }else{
26916       xRead = csv_read_one_field;
26917     }
26918     rc = 1;
26919     for(i=1; i<nArg; i++){
26920       char *z = azArg[i];
26921       if( z[0]=='-' && z[1]=='-' ) z++;
26922       if( z[0]!='-' ){
26923         if( zFile==0 ){
26924           zFile = z;
26925         }else if( zTable==0 ){
26926           zTable = z;
26927         }else{
26928           oputf("ERROR: extra argument: \"%s\".  Usage:\n", z);
26929           showHelp(p->out, "import");
26930           goto meta_command_exit;
26931         }
26932       }else if( cli_strcmp(z,"-v")==0 ){
26933         eVerbose++;
26934       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
26935         zSchema = azArg[++i];
26936       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
26937         nSkip = integerValue(azArg[++i]);
26938       }else if( cli_strcmp(z,"-ascii")==0 ){
26939         sCtx.cColSep = SEP_Unit[0];
26940         sCtx.cRowSep = SEP_Record[0];
26941         xRead = ascii_read_one_field;
26942         useOutputMode = 0;
26943       }else if( cli_strcmp(z,"-csv")==0 ){
26944         sCtx.cColSep = ',';
26945         sCtx.cRowSep = '\n';
26946         xRead = csv_read_one_field;
26947         useOutputMode = 0;
26948       }else{
26949         oputf("ERROR: unknown option: \"%s\".  Usage:\n", z);
26950         showHelp(p->out, "import");
26951         goto meta_command_exit;
26952       }
26953     }
26954     if( zTable==0 ){
26955       oputf("ERROR: missing %s argument. Usage:\n",
26956             zFile==0 ? "FILE" : "TABLE");
26957       showHelp(p->out, "import");
26958       goto meta_command_exit;
26959     }
26960     seenInterrupt = 0;
26961     open_db(p, 0);
26962     if( useOutputMode ){
26963       /* If neither the --csv or --ascii options are specified, then set
26964       ** the column and row separator characters from the output mode. */
26965       nSep = strlen30(p->colSeparator);
26966       if( nSep==0 ){
26967         eputz("Error: non-null column separator required for import\n");
26968         goto meta_command_exit;
26969       }
26970       if( nSep>1 ){
26971         eputz("Error: multi-character column separators not allowed"
26972               " for import\n");
26973         goto meta_command_exit;
26974       }
26975       nSep = strlen30(p->rowSeparator);
26976       if( nSep==0 ){
26977         eputz("Error: non-null row separator required for import\n");
26978         goto meta_command_exit;
26979       }
26980       if( nSep==2 && p->mode==MODE_Csv
26981        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
26982       ){
26983         /* When importing CSV (only), if the row separator is set to the
26984         ** default output row separator, change it to the default input
26985         ** row separator.  This avoids having to maintain different input
26986         ** and output row separators. */
26987         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26988         nSep = strlen30(p->rowSeparator);
26989       }
26990       if( nSep>1 ){
26991         eputz("Error: multi-character row separators not allowed"
26992               " for import\n");
26993         goto meta_command_exit;
26994       }
26995       sCtx.cColSep = (u8)p->colSeparator[0];
26996       sCtx.cRowSep = (u8)p->rowSeparator[0];
26997     }
26998     sCtx.zFile = zFile;
26999     sCtx.nLine = 1;
27000     if( sCtx.zFile[0]=='|' ){
27001 #ifdef SQLITE_OMIT_POPEN
27002       eputz("Error: pipes are not supported in this OS\n");
27003       goto meta_command_exit;
27004 #else
27005       sCtx.in = popen(sCtx.zFile+1, "r");
27006       sCtx.zFile = "<pipe>";
27007       sCtx.xCloser = pclose;
27008 #endif
27009     }else{
27010       sCtx.in = fopen(sCtx.zFile, "rb");
27011       sCtx.xCloser = fclose;
27012     }
27013     if( sCtx.in==0 ){
27014       eputf("Error: cannot open \"%s\"\n", zFile);
27015       goto meta_command_exit;
27016     }
27017     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
27018       char zSep[2];
27019       zSep[1] = 0;
27020       zSep[0] = sCtx.cColSep;
27021       oputz("Column separator ");
27022       output_c_string(zSep);
27023       oputz(", row separator ");
27024       zSep[0] = sCtx.cRowSep;
27025       output_c_string(zSep);
27026       oputz("\n");
27027     }
27028     sCtx.z = sqlite3_malloc64(120);
27029     if( sCtx.z==0 ){
27030       import_cleanup(&sCtx);
27031       shell_out_of_memory();
27032     }
27033     /* Below, resources must be freed before exit. */
27034     while( (nSkip--)>0 ){
27035       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
27036     }
27037     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
27038     if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0) ){
27039       /* Table does not exist.  Create it. */
27040       sqlite3 *dbCols = 0;
27041       char *zRenames = 0;
27042       char *zColDefs;
27043       zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"",
27044                     zSchema ? zSchema : "main", zTable);
27045       while( xRead(&sCtx) ){
27046         zAutoColumn(sCtx.z, &dbCols, 0);
27047         if( sCtx.cTerm!=sCtx.cColSep ) break;
27048       }
27049       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
27050       if( zRenames!=0 ){
27051         sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
27052               "Columns renamed during .import %s due to duplicates:\n"
27053               "%s\n", sCtx.zFile, zRenames);
27054         sqlite3_free(zRenames);
27055       }
27056       assert(dbCols==0);
27057       if( zColDefs==0 ){
27058         eputf("%s: empty file\n", sCtx.zFile);
27059         import_cleanup(&sCtx);
27060         rc = 1;
27061         goto meta_command_exit;
27062       }
27063       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
27064       if( zCreate==0 ){
27065         import_cleanup(&sCtx);
27066         shell_out_of_memory();
27067       }
27068       if( eVerbose>=1 ){
27069         oputf("%s\n", zCreate);
27070       }
27071       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
27072       sqlite3_free(zCreate);
27073       zCreate = 0;
27074       if( rc ){
27075         eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
27076         import_cleanup(&sCtx);
27077         rc = 1;
27078         goto meta_command_exit;
27079       }
27080     }
27081     zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
27082                            zTable, zSchema);
27083     if( zSql==0 ){
27084       import_cleanup(&sCtx);
27085       shell_out_of_memory();
27086     }
27087     rc =  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27088     sqlite3_free(zSql);
27089     zSql = 0;
27090     if( rc ){
27091       if (pStmt) sqlite3_finalize(pStmt);
27092       eputf("Error: %s\n", sqlite3_errmsg(p->db));
27093       import_cleanup(&sCtx);
27094       rc = 1;
27095       goto meta_command_exit;
27096     }
27097     if( sqlite3_step(pStmt)==SQLITE_ROW ){
27098       nCol = sqlite3_column_int(pStmt, 0);
27099     }else{
27100       nCol = 0;
27101     }
27102     sqlite3_finalize(pStmt);
27103     pStmt = 0;
27104     if( nCol==0 ) return 0; /* no columns, no error */
27105 
27106     nByte = 64                 /* space for "INSERT INTO", "VALUES(", ")\0" */
27107           + (zSchema ? strlen(zSchema)*2 + 2: 0)  /* Quoted schema name */
27108           + strlen(zTable)*2 + 2                  /* Quoted table name */
27109           + nCol*2;            /* Space for ",?" for each column */
27110     zSql = sqlite3_malloc64( nByte );
27111     if( zSql==0 ){
27112       import_cleanup(&sCtx);
27113       shell_out_of_memory();
27114     }
27115     if( zSchema ){
27116       sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?",
27117                        zSchema, zTable);
27118     }else{
27119       sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
27120     }
27121     j = strlen30(zSql);
27122     for(i=1; i<nCol; i++){
27123       zSql[j++] = ',';
27124       zSql[j++] = '?';
27125     }
27126     zSql[j++] = ')';
27127     zSql[j] = 0;
27128     assert( j<nByte );
27129     if( eVerbose>=2 ){
27130       oputf("Insert using: %s\n", zSql);
27131     }
27132     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27133     sqlite3_free(zSql);
27134     zSql = 0;
27135     if( rc ){
27136       eputf("Error: %s\n", sqlite3_errmsg(p->db));
27137       if (pStmt) sqlite3_finalize(pStmt);
27138       import_cleanup(&sCtx);
27139       rc = 1;
27140       goto meta_command_exit;
27141     }
27142     needCommit = sqlite3_get_autocommit(p->db);
27143     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
27144     do{
27145       int startLine = sCtx.nLine;
27146       for(i=0; i<nCol; i++){
27147         char *z = xRead(&sCtx);
27148         /*
27149         ** Did we reach end-of-file before finding any columns?
27150         ** If so, stop instead of NULL filling the remaining columns.
27151         */
27152         if( z==0 && i==0 ) break;
27153         /*
27154         ** Did we reach end-of-file OR end-of-line before finding any
27155         ** columns in ASCII mode?  If so, stop instead of NULL filling
27156         ** the remaining columns.
27157         */
27158         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
27159         /*
27160         ** For CSV mode, per RFC 4180, accept EOF in lieu of final
27161         ** record terminator but only for last field of multi-field row.
27162         ** (If there are too few fields, it's not valid CSV anyway.)
27163         */
27164         if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
27165           z = "";
27166         }
27167         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
27168         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
27169           eputf("%s:%d: expected %d columns but found %d"
27170                 " - filling the rest with NULL\n",
27171                 sCtx.zFile, startLine, nCol, i+1);
27172           i += 2;
27173           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
27174         }
27175       }
27176       if( sCtx.cTerm==sCtx.cColSep ){
27177         do{
27178           xRead(&sCtx);
27179           i++;
27180         }while( sCtx.cTerm==sCtx.cColSep );
27181         eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
27182               sCtx.zFile, startLine, nCol, i);
27183       }
27184       if( i>=nCol ){
27185         sqlite3_step(pStmt);
27186         rc = sqlite3_reset(pStmt);
27187         if( rc!=SQLITE_OK ){
27188           eputf("%s:%d: INSERT failed: %s\n",
27189                 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
27190           sCtx.nErr++;
27191         }else{
27192           sCtx.nRow++;
27193         }
27194       }
27195     }while( sCtx.cTerm!=EOF );
27196 
27197     import_cleanup(&sCtx);
27198     sqlite3_finalize(pStmt);
27199     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
27200     if( eVerbose>0 ){
27201       oputf("Added %d rows with %d errors using %d lines of input\n",
27202             sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
27203     }
27204   }else
27205 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
27206 
27207 #ifndef SQLITE_UNTESTABLE
27208   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
27209     char *zSql;
27210     char *zCollist = 0;
27211     sqlite3_stmt *pStmt;
27212     int tnum = 0;
27213     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
27214     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
27215     int i;
27216     if( !ShellHasFlag(p,SHFLG_TestingMode) ){
27217       eputf(".%s unavailable without --unsafe-testing\n",
27218             "imposter");
27219       rc = 1;
27220       goto meta_command_exit;
27221     }
27222     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
27223       eputz("Usage: .imposter INDEX IMPOSTER\n"
27224             "       .imposter off\n");
27225       /* Also allowed, but not documented:
27226       **
27227       **    .imposter TABLE IMPOSTER
27228       **
27229       ** where TABLE is a WITHOUT ROWID table.  In that case, the
27230       ** imposter is another WITHOUT ROWID table with the columns in
27231       ** storage order. */
27232       rc = 1;
27233       goto meta_command_exit;
27234     }
27235     open_db(p, 0);
27236     if( nArg==2 ){
27237       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
27238       goto meta_command_exit;
27239     }
27240     zSql = sqlite3_mprintf(
27241       "SELECT rootpage, 0 FROM sqlite_schema"
27242       " WHERE name='%q' AND type='index'"
27243       "UNION ALL "
27244       "SELECT rootpage, 1 FROM sqlite_schema"
27245       " WHERE name='%q' AND type='table'"
27246       "   AND sql LIKE '%%without%%rowid%%'",
27247       azArg[1], azArg[1]
27248     );
27249     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27250     sqlite3_free(zSql);
27251     if( sqlite3_step(pStmt)==SQLITE_ROW ){
27252       tnum = sqlite3_column_int(pStmt, 0);
27253       isWO = sqlite3_column_int(pStmt, 1);
27254     }
27255     sqlite3_finalize(pStmt);
27256     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
27257     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27258     sqlite3_free(zSql);
27259     i = 0;
27260     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
27261       char zLabel[20];
27262       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
27263       i++;
27264       if( zCol==0 ){
27265         if( sqlite3_column_int(pStmt,1)==-1 ){
27266           zCol = "_ROWID_";
27267         }else{
27268           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
27269           zCol = zLabel;
27270         }
27271       }
27272       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
27273         lenPK = (int)strlen(zCollist);
27274       }
27275       if( zCollist==0 ){
27276         zCollist = sqlite3_mprintf("\"%w\"", zCol);
27277       }else{
27278         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
27279       }
27280     }
27281     sqlite3_finalize(pStmt);
27282     if( i==0 || tnum==0 ){
27283       eputf("no such index: \"%s\"\n", azArg[1]);
27284       rc = 1;
27285       sqlite3_free(zCollist);
27286       goto meta_command_exit;
27287     }
27288     if( lenPK==0 ) lenPK = 100000;
27289     zSql = sqlite3_mprintf(
27290           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
27291           azArg[2], zCollist, lenPK, zCollist);
27292     sqlite3_free(zCollist);
27293     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
27294     if( rc==SQLITE_OK ){
27295       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
27296       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
27297       if( rc ){
27298         eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
27299       }else{
27300         sputf(stdout, "%s;\n", zSql);
27301         sputf(stdout, "WARNING: writing to an imposter table will corrupt"
27302               " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
27303       }
27304     }else{
27305       eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
27306       rc = 1;
27307     }
27308     sqlite3_free(zSql);
27309   }else
27310 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
27311 
27312   if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
27313     i64 iArg = 0;
27314     if( nArg==2 ){
27315       iArg = integerValue(azArg[1]);
27316       if( iArg==0 ) iArg = -1;
27317     }
27318     if( (nArg!=1 && nArg!=2) || iArg<0 ){
27319       eputf("%s","Usage: .intck STEPS_PER_UNLOCK\n");
27320       rc = 1;
27321       goto meta_command_exit;
27322     }
27323     open_db(p, 0);
27324     rc = intckDatabaseCmd(p, iArg);
27325   }else
27326 
27327 #ifdef SQLITE_ENABLE_IOTRACE
27328   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
27329     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
27330     if( iotrace && iotrace!=stdout ) fclose(iotrace);
27331     iotrace = 0;
27332     if( nArg<2 ){
27333       sqlite3IoTrace = 0;
27334     }else if( cli_strcmp(azArg[1], "-")==0 ){
27335       sqlite3IoTrace = iotracePrintf;
27336       iotrace = stdout;
27337     }else{
27338       iotrace = fopen(azArg[1], "w");
27339       if( iotrace==0 ){
27340         eputf("Error: cannot open \"%s\"\n", azArg[1]);
27341         sqlite3IoTrace = 0;
27342         rc = 1;
27343       }else{
27344         sqlite3IoTrace = iotracePrintf;
27345       }
27346     }
27347   }else
27348 #endif
27349 
27350   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
27351     static const struct {
27352        const char *zLimitName;   /* Name of a limit */
27353        int limitCode;            /* Integer code for that limit */
27354     } aLimit[] = {
27355       { "length",                SQLITE_LIMIT_LENGTH                    },
27356       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
27357       { "column",                SQLITE_LIMIT_COLUMN                    },
27358       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
27359       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
27360       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
27361       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
27362       { "attached",              SQLITE_LIMIT_ATTACHED                  },
27363       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
27364       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
27365       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
27366       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
27367     };
27368     int i, n2;
27369     open_db(p, 0);
27370     if( nArg==1 ){
27371       for(i=0; i<ArraySize(aLimit); i++){
27372         sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
27373               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
27374       }
27375     }else if( nArg>3 ){
27376       eputz("Usage: .limit NAME ?NEW-VALUE?\n");
27377       rc = 1;
27378       goto meta_command_exit;
27379     }else{
27380       int iLimit = -1;
27381       n2 = strlen30(azArg[1]);
27382       for(i=0; i<ArraySize(aLimit); i++){
27383         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
27384           if( iLimit<0 ){
27385             iLimit = i;
27386           }else{
27387             eputf("ambiguous limit: \"%s\"\n", azArg[1]);
27388             rc = 1;
27389             goto meta_command_exit;
27390           }
27391         }
27392       }
27393       if( iLimit<0 ){
27394         eputf("unknown limit: \"%s\"\n"
27395               "enter \".limits\" with no arguments for a list.\n",
27396               azArg[1]);
27397         rc = 1;
27398         goto meta_command_exit;
27399       }
27400       if( nArg==3 ){
27401         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
27402                       (int)integerValue(azArg[2]));
27403       }
27404       sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
27405             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
27406     }
27407   }else
27408 
27409   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
27410     open_db(p, 0);
27411     lintDotCommand(p, azArg, nArg);
27412   }else
27413 
27414 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
27415   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
27416     const char *zFile, *zProc;
27417     char *zErrMsg = 0;
27418     failIfSafeMode(p, "cannot run .load in safe mode");
27419     if( nArg<2 || azArg[1][0]==0 ){
27420       /* Must have a non-empty FILE. (Will not load self.) */
27421       eputz("Usage: .load FILE ?ENTRYPOINT?\n");
27422       rc = 1;
27423       goto meta_command_exit;
27424     }
27425     zFile = azArg[1];
27426     zProc = nArg>=3 ? azArg[2] : 0;
27427     open_db(p, 0);
27428     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
27429     if( rc!=SQLITE_OK ){
27430       eputf("Error: %s\n", zErrMsg);
27431       sqlite3_free(zErrMsg);
27432       rc = 1;
27433     }
27434   }else
27435 #endif
27436 
27437   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
27438     if( nArg!=2 ){
27439       eputz("Usage: .log FILENAME\n");
27440       rc = 1;
27441     }else{
27442       const char *zFile = azArg[1];
27443       if( p->bSafeMode
27444        && cli_strcmp(zFile,"on")!=0
27445        && cli_strcmp(zFile,"off")!=0
27446       ){
27447         sputz(stdout, "cannot set .log to anything other"
27448               " than \"on\" or \"off\"\n");
27449         zFile = "off";
27450       }
27451       output_file_close(p->pLog);
27452       if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
27453       p->pLog = output_file_open(zFile, 0);
27454     }
27455   }else
27456 
27457   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
27458     const char *zMode = 0;
27459     const char *zTabname = 0;
27460     int i, n2;
27461     ColModeOpts cmOpts = ColModeOpts_default;
27462     for(i=1; i<nArg; i++){
27463       const char *z = azArg[i];
27464       if( optionMatch(z,"wrap") && i+1<nArg ){
27465         cmOpts.iWrap = integerValue(azArg[++i]);
27466       }else if( optionMatch(z,"ww") ){
27467         cmOpts.bWordWrap = 1;
27468       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
27469         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
27470       }else if( optionMatch(z,"quote") ){
27471         cmOpts.bQuote = 1;
27472       }else if( optionMatch(z,"noquote") ){
27473         cmOpts.bQuote = 0;
27474       }else if( zMode==0 ){
27475         zMode = z;
27476         /* Apply defaults for qbox pseudo-mode.  If that
27477          * overwrites already-set values, user was informed of this.
27478          */
27479         if( cli_strcmp(z, "qbox")==0 ){
27480           ColModeOpts cmo = ColModeOpts_default_qbox;
27481           zMode = "box";
27482           cmOpts = cmo;
27483         }
27484       }else if( zTabname==0 ){
27485         zTabname = z;
27486       }else if( z[0]=='-' ){
27487         eputf("unknown option: %s\n", z);
27488         eputz("options:\n"
27489               "  --noquote\n"
27490               "  --quote\n"
27491               "  --wordwrap on/off\n"
27492               "  --wrap N\n"
27493               "  --ww\n");
27494         rc = 1;
27495         goto meta_command_exit;
27496       }else{
27497         eputf("extra argument: \"%s\"\n", z);
27498         rc = 1;
27499         goto meta_command_exit;
27500       }
27501     }
27502     if( zMode==0 ){
27503       if( p->mode==MODE_Column
27504        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
27505       ){
27506         oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
27507               modeDescr[p->mode], p->cmOpts.iWrap,
27508               p->cmOpts.bWordWrap ? "on" : "off",
27509               p->cmOpts.bQuote ? "" : "no");
27510       }else{
27511         oputf("current output mode: %s\n", modeDescr[p->mode]);
27512       }
27513       zMode = modeDescr[p->mode];
27514     }
27515     n2 = strlen30(zMode);
27516     if( cli_strncmp(zMode,"lines",n2)==0 ){
27517       p->mode = MODE_Line;
27518       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27519     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
27520       p->mode = MODE_Column;
27521       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
27522         p->showHeader = 1;
27523       }
27524       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27525       p->cmOpts = cmOpts;
27526     }else if( cli_strncmp(zMode,"list",n2)==0 ){
27527       p->mode = MODE_List;
27528       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
27529       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27530     }else if( cli_strncmp(zMode,"html",n2)==0 ){
27531       p->mode = MODE_Html;
27532     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
27533       p->mode = MODE_Tcl;
27534       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
27535       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27536     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
27537       p->mode = MODE_Csv;
27538       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
27539       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
27540     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
27541       p->mode = MODE_List;
27542       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
27543     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
27544       p->mode = MODE_Insert;
27545       set_table_name(p, zTabname ? zTabname : "table");
27546     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
27547       p->mode = MODE_Quote;
27548       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
27549       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27550     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
27551       p->mode = MODE_Ascii;
27552       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
27553       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
27554     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
27555       p->mode = MODE_Markdown;
27556       p->cmOpts = cmOpts;
27557     }else if( cli_strncmp(zMode,"table",n2)==0 ){
27558       p->mode = MODE_Table;
27559       p->cmOpts = cmOpts;
27560     }else if( cli_strncmp(zMode,"box",n2)==0 ){
27561       p->mode = MODE_Box;
27562       p->cmOpts = cmOpts;
27563     }else if( cli_strncmp(zMode,"count",n2)==0 ){
27564       p->mode = MODE_Count;
27565     }else if( cli_strncmp(zMode,"off",n2)==0 ){
27566       p->mode = MODE_Off;
27567     }else if( cli_strncmp(zMode,"json",n2)==0 ){
27568       p->mode = MODE_Json;
27569     }else{
27570       eputz("Error: mode should be one of: "
27571             "ascii box column csv html insert json line list markdown "
27572             "qbox quote table tabs tcl\n");
27573       rc = 1;
27574     }
27575     p->cMode = p->mode;
27576   }else
27577 
27578 #ifndef SQLITE_SHELL_FIDDLE
27579   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
27580     if( nArg!=2 ){
27581       eputz("Usage: .nonce NONCE\n");
27582       rc = 1;
27583     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
27584       eputf("line %d: incorrect nonce: \"%s\"\n",
27585             p->lineno, azArg[1]);
27586       exit(1);
27587     }else{
27588       p->bSafeMode = 0;
27589       return 0;  /* Return immediately to bypass the safe mode reset
27590                  ** at the end of this procedure */
27591     }
27592   }else
27593 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
27594 
27595   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
27596     if( nArg==2 ){
27597       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
27598                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
27599     }else{
27600       eputz("Usage: .nullvalue STRING\n");
27601       rc = 1;
27602     }
27603   }else
27604 
27605   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
27606     const char *zFN = 0;     /* Pointer to constant filename */
27607     char *zNewFilename = 0;  /* Name of the database file to open */
27608     int iName = 1;           /* Index in azArg[] of the filename */
27609     int newFlag = 0;         /* True to delete file before opening */
27610     int openMode = SHELL_OPEN_UNSPEC;
27611 
27612     /* Check for command-line arguments */
27613     for(iName=1; iName<nArg; iName++){
27614       const char *z = azArg[iName];
27615 #ifndef SQLITE_SHELL_FIDDLE
27616       if( optionMatch(z,"new") ){
27617         newFlag = 1;
27618 #ifdef SQLITE_HAVE_ZLIB
27619       }else if( optionMatch(z, "zip") ){
27620         openMode = SHELL_OPEN_ZIPFILE;
27621 #endif
27622       }else if( optionMatch(z, "append") ){
27623         openMode = SHELL_OPEN_APPENDVFS;
27624       }else if( optionMatch(z, "readonly") ){
27625         openMode = SHELL_OPEN_READONLY;
27626       }else if( optionMatch(z, "nofollow") ){
27627         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
27628 #ifndef SQLITE_OMIT_DESERIALIZE
27629       }else if( optionMatch(z, "deserialize") ){
27630         openMode = SHELL_OPEN_DESERIALIZE;
27631       }else if( optionMatch(z, "hexdb") ){
27632         openMode = SHELL_OPEN_HEXDB;
27633       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
27634         p->szMax = integerValue(azArg[++iName]);
27635 #endif /* SQLITE_OMIT_DESERIALIZE */
27636       }else
27637 #endif /* !SQLITE_SHELL_FIDDLE */
27638       if( z[0]=='-' ){
27639         eputf("unknown option: %s\n", z);
27640         rc = 1;
27641         goto meta_command_exit;
27642       }else if( zFN ){
27643         eputf("extra argument: \"%s\"\n", z);
27644         rc = 1;
27645         goto meta_command_exit;
27646       }else{
27647         zFN = z;
27648       }
27649     }
27650 
27651     /* Close the existing database */
27652     session_close_all(p, -1);
27653     close_db(p->db);
27654     p->db = 0;
27655     p->pAuxDb->zDbFilename = 0;
27656     sqlite3_free(p->pAuxDb->zFreeOnClose);
27657     p->pAuxDb->zFreeOnClose = 0;
27658     p->openMode = openMode;
27659     p->openFlags = 0;
27660     p->szMax = 0;
27661 
27662     /* If a filename is specified, try to open it first */
27663     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
27664       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
27665 #ifndef SQLITE_SHELL_FIDDLE
27666       if( p->bSafeMode
27667        && p->openMode!=SHELL_OPEN_HEXDB
27668        && zFN
27669        && cli_strcmp(zFN,":memory:")!=0
27670       ){
27671         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
27672       }
27673 #else
27674       /* WASM mode has its own sandboxed pseudo-filesystem. */
27675 #endif
27676       if( zFN ){
27677         zNewFilename = sqlite3_mprintf("%s", zFN);
27678         shell_check_oom(zNewFilename);
27679       }else{
27680         zNewFilename = 0;
27681       }
27682       p->pAuxDb->zDbFilename = zNewFilename;
27683       open_db(p, OPEN_DB_KEEPALIVE);
27684       if( p->db==0 ){
27685         eputf("Error: cannot open '%s'\n", zNewFilename);
27686         sqlite3_free(zNewFilename);
27687       }else{
27688         p->pAuxDb->zFreeOnClose = zNewFilename;
27689       }
27690     }
27691     if( p->db==0 ){
27692       /* As a fall-back open a TEMP database */
27693       p->pAuxDb->zDbFilename = 0;
27694       open_db(p, 0);
27695     }
27696   }else
27697 
27698 #ifndef SQLITE_SHELL_FIDDLE
27699   if( (c=='o'
27700         && (cli_strncmp(azArg[0], "output", n)==0
27701             || cli_strncmp(azArg[0], "once", n)==0))
27702    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
27703   ){
27704     char *zFile = 0;
27705     int bTxtMode = 0;
27706     int i;
27707     int eMode = 0;
27708     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
27709     static const char *zBomUtf8 = "\xef\xbb\xbf";
27710     const char *zBom = 0;
27711 
27712     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
27713     if( c=='e' ){
27714       eMode = 'x';
27715       bOnce = 2;
27716     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
27717       bOnce = 1;
27718     }
27719     for(i=1; i<nArg; i++){
27720       char *z = azArg[i];
27721       if( z[0]=='-' ){
27722         if( z[1]=='-' ) z++;
27723         if( cli_strcmp(z,"-bom")==0 ){
27724           zBom = zBomUtf8;
27725         }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
27726           eMode = 'x';  /* spreadsheet */
27727         }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
27728           eMode = 'e';  /* text editor */
27729         }else{
27730           oputf("ERROR: unknown option: \"%s\".  Usage:\n", azArg[i]);
27731           showHelp(p->out, azArg[0]);
27732           rc = 1;
27733           goto meta_command_exit;
27734         }
27735       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
27736         zFile = sqlite3_mprintf("%s", z);
27737         if( zFile && zFile[0]=='|' ){
27738           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
27739           break;
27740         }
27741       }else{
27742         oputf("ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
27743         showHelp(p->out, azArg[0]);
27744         rc = 1;
27745         sqlite3_free(zFile);
27746         goto meta_command_exit;
27747       }
27748     }
27749     if( zFile==0 ){
27750       zFile = sqlite3_mprintf("stdout");
27751     }
27752     if( bOnce ){
27753       p->outCount = 2;
27754     }else{
27755       p->outCount = 0;
27756     }
27757     output_reset(p);
27758 #ifndef SQLITE_NOHAVE_SYSTEM
27759     if( eMode=='e' || eMode=='x' ){
27760       p->doXdgOpen = 1;
27761       outputModePush(p);
27762       if( eMode=='x' ){
27763         /* spreadsheet mode.  Output as CSV. */
27764         newTempFile(p, "csv");
27765         ShellClearFlag(p, SHFLG_Echo);
27766         p->mode = MODE_Csv;
27767         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
27768         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
27769       }else{
27770         /* text editor mode */
27771         newTempFile(p, "txt");
27772         bTxtMode = 1;
27773       }
27774       sqlite3_free(zFile);
27775       zFile = sqlite3_mprintf("%s", p->zTempFile);
27776     }
27777 #endif /* SQLITE_NOHAVE_SYSTEM */
27778     shell_check_oom(zFile);
27779     if( zFile[0]=='|' ){
27780 #ifdef SQLITE_OMIT_POPEN
27781       eputz("Error: pipes are not supported in this OS\n");
27782       rc = 1;
27783       output_redir(p, stdout);
27784 #else
27785       FILE *pfPipe = popen(zFile + 1, "w");
27786       if( pfPipe==0 ){
27787         eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
27788         rc = 1;
27789       }else{
27790         output_redir(p, pfPipe);
27791         if( zBom ) oputz(zBom);
27792         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
27793       }
27794 #endif
27795     }else{
27796       FILE *pfFile = output_file_open(zFile, bTxtMode);
27797       if( pfFile==0 ){
27798         if( cli_strcmp(zFile,"off")!=0 ){
27799           eputf("Error: cannot write to \"%s\"\n", zFile);
27800         }
27801         rc = 1;
27802       } else {
27803         output_redir(p, pfFile);
27804         if( zBom ) oputz(zBom);
27805         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
27806       }
27807     }
27808     sqlite3_free(zFile);
27809   }else
27810 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
27811 
27812   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
27813     open_db(p,0);
27814     if( nArg<=1 ) goto parameter_syntax_error;
27815 
27816     /* .parameter clear
27817     ** Clear all bind parameters by dropping the TEMP table that holds them.
27818     */
27819     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
27820       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
27821                    0, 0, 0);
27822     }else
27823 
27824     /* .parameter list
27825     ** List all bind parameters.
27826     */
27827     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
27828       sqlite3_stmt *pStmt = 0;
27829       int rx;
27830       int len = 0;
27831       rx = sqlite3_prepare_v2(p->db,
27832              "SELECT max(length(key)) "
27833              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
27834       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
27835         len = sqlite3_column_int(pStmt, 0);
27836         if( len>40 ) len = 40;
27837       }
27838       sqlite3_finalize(pStmt);
27839       pStmt = 0;
27840       if( len ){
27841         rx = sqlite3_prepare_v2(p->db,
27842              "SELECT key, quote(value) "
27843              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
27844         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
27845           oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
27846                 sqlite3_column_text(pStmt,1));
27847         }
27848         sqlite3_finalize(pStmt);
27849       }
27850     }else
27851 
27852     /* .parameter init
27853     ** Make sure the TEMP table used to hold bind parameters exists.
27854     ** Create it if necessary.
27855     */
27856     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
27857       bind_table_init(p);
27858     }else
27859 
27860     /* .parameter set NAME VALUE
27861     ** Set or reset a bind parameter.  NAME should be the full parameter
27862     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
27863     ** VALUE can be in either SQL literal notation, or if not it will be
27864     ** understood to be a text string.
27865     */
27866     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
27867       int rx;
27868       char *zSql;
27869       sqlite3_stmt *pStmt;
27870       const char *zKey = azArg[2];
27871       const char *zValue = azArg[3];
27872       bind_table_init(p);
27873       zSql = sqlite3_mprintf(
27874                   "REPLACE INTO temp.sqlite_parameters(key,value)"
27875                   "VALUES(%Q,%s);", zKey, zValue);
27876       shell_check_oom(zSql);
27877       pStmt = 0;
27878       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27879       sqlite3_free(zSql);
27880       if( rx!=SQLITE_OK ){
27881         sqlite3_finalize(pStmt);
27882         pStmt = 0;
27883         zSql = sqlite3_mprintf(
27884                    "REPLACE INTO temp.sqlite_parameters(key,value)"
27885                    "VALUES(%Q,%Q);", zKey, zValue);
27886         shell_check_oom(zSql);
27887         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27888         sqlite3_free(zSql);
27889         if( rx!=SQLITE_OK ){
27890           oputf("Error: %s\n", sqlite3_errmsg(p->db));
27891           sqlite3_finalize(pStmt);
27892           pStmt = 0;
27893           rc = 1;
27894         }
27895       }
27896       sqlite3_step(pStmt);
27897       sqlite3_finalize(pStmt);
27898     }else
27899 
27900     /* .parameter unset NAME
27901     ** Remove the NAME binding from the parameter binding table, if it
27902     ** exists.
27903     */
27904     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
27905       char *zSql = sqlite3_mprintf(
27906           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
27907       shell_check_oom(zSql);
27908       sqlite3_exec(p->db, zSql, 0, 0, 0);
27909       sqlite3_free(zSql);
27910     }else
27911     /* If no command name matches, show a syntax error */
27912     parameter_syntax_error:
27913     showHelp(p->out, "parameter");
27914   }else
27915 
27916   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
27917     int i;
27918     for(i=1; i<nArg; i++){
27919       if( i>1 ) oputz(" ");
27920       oputz(azArg[i]);
27921     }
27922     oputz("\n");
27923   }else
27924 
27925 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
27926   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
27927     int i;
27928     int nn = 0;
27929     p->flgProgress = 0;
27930     p->mxProgress = 0;
27931     p->nProgress = 0;
27932     for(i=1; i<nArg; i++){
27933       const char *z = azArg[i];
27934       if( z[0]=='-' ){
27935         z++;
27936         if( z[0]=='-' ) z++;
27937         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
27938           p->flgProgress |= SHELL_PROGRESS_QUIET;
27939           continue;
27940         }
27941         if( cli_strcmp(z,"reset")==0 ){
27942           p->flgProgress |= SHELL_PROGRESS_RESET;
27943           continue;
27944         }
27945         if( cli_strcmp(z,"once")==0 ){
27946           p->flgProgress |= SHELL_PROGRESS_ONCE;
27947           continue;
27948         }
27949         if( cli_strcmp(z,"limit")==0 ){
27950           if( i+1>=nArg ){
27951             eputz("Error: missing argument on --limit\n");
27952             rc = 1;
27953             goto meta_command_exit;
27954           }else{
27955             p->mxProgress = (int)integerValue(azArg[++i]);
27956           }
27957           continue;
27958         }
27959         eputf("Error: unknown option: \"%s\"\n", azArg[i]);
27960         rc = 1;
27961         goto meta_command_exit;
27962       }else{
27963         nn = (int)integerValue(z);
27964       }
27965     }
27966     open_db(p, 0);
27967     sqlite3_progress_handler(p->db, nn, progress_handler, p);
27968   }else
27969 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
27970 
27971   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
27972     if( nArg >= 2) {
27973       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
27974     }
27975     if( nArg >= 3) {
27976       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
27977     }
27978   }else
27979 
27980 #ifndef SQLITE_SHELL_FIDDLE
27981   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
27982     rc = 2;
27983   }else
27984 #endif
27985 
27986 #ifndef SQLITE_SHELL_FIDDLE
27987   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
27988     FILE *inSaved = p->in;
27989     int savedLineno = p->lineno;
27990     failIfSafeMode(p, "cannot run .read in safe mode");
27991     if( nArg!=2 ){
27992       eputz("Usage: .read FILE\n");
27993       rc = 1;
27994       goto meta_command_exit;
27995     }
27996     if( azArg[1][0]=='|' ){
27997 #ifdef SQLITE_OMIT_POPEN
27998       eputz("Error: pipes are not supported in this OS\n");
27999       rc = 1;
28000       p->out = stdout;
28001 #else
28002       p->in = popen(azArg[1]+1, "r");
28003       if( p->in==0 ){
28004         eputf("Error: cannot open \"%s\"\n", azArg[1]);
28005         rc = 1;
28006       }else{
28007         rc = process_input(p);
28008         pclose(p->in);
28009       }
28010 #endif
28011     }else if( (p->in = openChrSource(azArg[1]))==0 ){
28012       eputf("Error: cannot open \"%s\"\n", azArg[1]);
28013       rc = 1;
28014     }else{
28015       rc = process_input(p);
28016       fclose(p->in);
28017     }
28018     p->in = inSaved;
28019     p->lineno = savedLineno;
28020   }else
28021 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
28022 
28023 #ifndef SQLITE_SHELL_FIDDLE
28024   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
28025     const char *zSrcFile;
28026     const char *zDb;
28027     sqlite3 *pSrc;
28028     sqlite3_backup *pBackup;
28029     int nTimeout = 0;
28030 
28031     failIfSafeMode(p, "cannot run .restore in safe mode");
28032     if( nArg==2 ){
28033       zSrcFile = azArg[1];
28034       zDb = "main";
28035     }else if( nArg==3 ){
28036       zSrcFile = azArg[2];
28037       zDb = azArg[1];
28038     }else{
28039       eputz("Usage: .restore ?DB? FILE\n");
28040       rc = 1;
28041       goto meta_command_exit;
28042     }
28043     rc = sqlite3_open(zSrcFile, &pSrc);
28044     if( rc!=SQLITE_OK ){
28045       eputf("Error: cannot open \"%s\"\n", zSrcFile);
28046       close_db(pSrc);
28047       return 1;
28048     }
28049     open_db(p, 0);
28050     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
28051     if( pBackup==0 ){
28052       eputf("Error: %s\n", sqlite3_errmsg(p->db));
28053       close_db(pSrc);
28054       return 1;
28055     }
28056     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
28057           || rc==SQLITE_BUSY  ){
28058       if( rc==SQLITE_BUSY ){
28059         if( nTimeout++ >= 3 ) break;
28060         sqlite3_sleep(100);
28061       }
28062     }
28063     sqlite3_backup_finish(pBackup);
28064     if( rc==SQLITE_DONE ){
28065       rc = 0;
28066     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
28067       eputz("Error: source database is busy\n");
28068       rc = 1;
28069     }else{
28070       eputf("Error: %s\n", sqlite3_errmsg(p->db));
28071       rc = 1;
28072     }
28073     close_db(pSrc);
28074   }else
28075 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
28076 
28077   if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
28078     if( nArg==2 ){
28079       if( cli_strcmp(azArg[1], "vm")==0 ){
28080         p->scanstatsOn = 3;
28081       }else
28082       if( cli_strcmp(azArg[1], "est")==0 ){
28083         p->scanstatsOn = 2;
28084       }else{
28085         p->scanstatsOn = (u8)booleanValue(azArg[1]);
28086       }
28087       open_db(p, 0);
28088       sqlite3_db_config(
28089           p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
28090       );
28091 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
28092       eputz("Warning: .scanstats not available in this build.\n");
28093 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
28094       if( p->scanstatsOn==3 ){
28095         eputz("Warning: \".scanstats vm\" not available in this build.\n");
28096       }
28097 #endif
28098     }else{
28099       eputz("Usage: .scanstats on|off|est\n");
28100       rc = 1;
28101     }
28102   }else
28103 
28104   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
28105     ShellText sSelect;
28106     ShellState data;
28107     char *zErrMsg = 0;
28108     const char *zDiv = "(";
28109     const char *zName = 0;
28110     int iSchema = 0;
28111     int bDebug = 0;
28112     int bNoSystemTabs = 0;
28113     int ii;
28114 
28115     open_db(p, 0);
28116     memcpy(&data, p, sizeof(data));
28117     data.showHeader = 0;
28118     data.cMode = data.mode = MODE_Semi;
28119     initText(&sSelect);
28120     for(ii=1; ii<nArg; ii++){
28121       if( optionMatch(azArg[ii],"indent") ){
28122         data.cMode = data.mode = MODE_Pretty;
28123       }else if( optionMatch(azArg[ii],"debug") ){
28124         bDebug = 1;
28125       }else if( optionMatch(azArg[ii],"nosys") ){
28126         bNoSystemTabs = 1;
28127       }else if( azArg[ii][0]=='-' ){
28128         eputf("Unknown option: \"%s\"\n", azArg[ii]);
28129         rc = 1;
28130         goto meta_command_exit;
28131       }else if( zName==0 ){
28132         zName = azArg[ii];
28133       }else{
28134         eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
28135         rc = 1;
28136         goto meta_command_exit;
28137       }
28138     }
28139     if( zName!=0 ){
28140       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
28141                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
28142                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
28143                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
28144       if( isSchema ){
28145         char *new_argv[2], *new_colv[2];
28146         new_argv[0] = sqlite3_mprintf(
28147                       "CREATE TABLE %s (\n"
28148                       "  type text,\n"
28149                       "  name text,\n"
28150                       "  tbl_name text,\n"
28151                       "  rootpage integer,\n"
28152                       "  sql text\n"
28153                       ")", zName);
28154         shell_check_oom(new_argv[0]);
28155         new_argv[1] = 0;
28156         new_colv[0] = "sql";
28157         new_colv[1] = 0;
28158         callback(&data, 1, new_argv, new_colv);
28159         sqlite3_free(new_argv[0]);
28160       }
28161     }
28162     if( zDiv ){
28163       sqlite3_stmt *pStmt = 0;
28164       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
28165                               -1, &pStmt, 0);
28166       if( rc ){
28167         eputf("Error: %s\n", sqlite3_errmsg(p->db));
28168         sqlite3_finalize(pStmt);
28169         rc = 1;
28170         goto meta_command_exit;
28171       }
28172       appendText(&sSelect, "SELECT sql FROM", 0);
28173       iSchema = 0;
28174       while( sqlite3_step(pStmt)==SQLITE_ROW ){
28175         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
28176         char zScNum[30];
28177         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
28178         appendText(&sSelect, zDiv, 0);
28179         zDiv = " UNION ALL ";
28180         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
28181         if( sqlite3_stricmp(zDb, "main")!=0 ){
28182           appendText(&sSelect, zDb, '\'');
28183         }else{
28184           appendText(&sSelect, "NULL", 0);
28185         }
28186         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
28187         appendText(&sSelect, zScNum, 0);
28188         appendText(&sSelect, " AS snum, ", 0);
28189         appendText(&sSelect, zDb, '\'');
28190         appendText(&sSelect, " AS sname FROM ", 0);
28191         appendText(&sSelect, zDb, quoteChar(zDb));
28192         appendText(&sSelect, ".sqlite_schema", 0);
28193       }
28194       sqlite3_finalize(pStmt);
28195 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
28196       if( zName ){
28197         appendText(&sSelect,
28198            " UNION ALL SELECT shell_module_schema(name),"
28199            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
28200         0);
28201       }
28202 #endif
28203       appendText(&sSelect, ") WHERE ", 0);
28204       if( zName ){
28205         char *zQarg = sqlite3_mprintf("%Q", zName);
28206         int bGlob;
28207         shell_check_oom(zQarg);
28208         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
28209                 strchr(zName, '[') != 0;
28210         if( strchr(zName, '.') ){
28211           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
28212         }else{
28213           appendText(&sSelect, "lower(tbl_name)", 0);
28214         }
28215         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
28216         appendText(&sSelect, zQarg, 0);
28217         if( !bGlob ){
28218           appendText(&sSelect, " ESCAPE '\\' ", 0);
28219         }
28220         appendText(&sSelect, " AND ", 0);
28221         sqlite3_free(zQarg);
28222       }
28223       if( bNoSystemTabs ){
28224         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
28225       }
28226       appendText(&sSelect, "sql IS NOT NULL"
28227                            " ORDER BY snum, rowid", 0);
28228       if( bDebug ){
28229         oputf("SQL: %s;\n", sSelect.z);
28230       }else{
28231         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
28232       }
28233       freeText(&sSelect);
28234     }
28235     if( zErrMsg ){
28236       eputf("Error: %s\n", zErrMsg);
28237       sqlite3_free(zErrMsg);
28238       rc = 1;
28239     }else if( rc != SQLITE_OK ){
28240       eputz("Error: querying schema information\n");
28241       rc = 1;
28242     }else{
28243       rc = 0;
28244     }
28245   }else
28246 
28247   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
28248    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
28249   ){
28250     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
28251     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
28252   }else
28253 
28254 #if defined(SQLITE_ENABLE_SESSION)
28255   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
28256     struct AuxDb *pAuxDb = p->pAuxDb;
28257     OpenSession *pSession = &pAuxDb->aSession[0];
28258     char **azCmd = &azArg[1];
28259     int iSes = 0;
28260     int nCmd = nArg - 1;
28261     int i;
28262     if( nArg<=1 ) goto session_syntax_error;
28263     open_db(p, 0);
28264     if( nArg>=3 ){
28265       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
28266         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
28267       }
28268       if( iSes<pAuxDb->nSession ){
28269         pSession = &pAuxDb->aSession[iSes];
28270         azCmd++;
28271         nCmd--;
28272       }else{
28273         pSession = &pAuxDb->aSession[0];
28274         iSes = 0;
28275       }
28276     }
28277 
28278     /* .session attach TABLE
28279     ** Invoke the sqlite3session_attach() interface to attach a particular
28280     ** table so that it is never filtered.
28281     */
28282     if( cli_strcmp(azCmd[0],"attach")==0 ){
28283       if( nCmd!=2 ) goto session_syntax_error;
28284       if( pSession->p==0 ){
28285         session_not_open:
28286         eputz("ERROR: No sessions are open\n");
28287       }else{
28288         rc = sqlite3session_attach(pSession->p, azCmd[1]);
28289         if( rc ){
28290           eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
28291           rc = 0;
28292         }
28293       }
28294     }else
28295 
28296     /* .session changeset FILE
28297     ** .session patchset FILE
28298     ** Write a changeset or patchset into a file.  The file is overwritten.
28299     */
28300     if( cli_strcmp(azCmd[0],"changeset")==0
28301      || cli_strcmp(azCmd[0],"patchset")==0
28302     ){
28303       FILE *out = 0;
28304       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
28305       if( nCmd!=2 ) goto session_syntax_error;
28306       if( pSession->p==0 ) goto session_not_open;
28307       out = fopen(azCmd[1], "wb");
28308       if( out==0 ){
28309         eputf("ERROR: cannot open \"%s\" for writing\n",
28310               azCmd[1]);
28311       }else{
28312         int szChng;
28313         void *pChng;
28314         if( azCmd[0][0]=='c' ){
28315           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
28316         }else{
28317           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
28318         }
28319         if( rc ){
28320           sputf(stdout, "Error: error code %d\n", rc);
28321           rc = 0;
28322         }
28323         if( pChng
28324           && fwrite(pChng, szChng, 1, out)!=1 ){
28325           eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
28326         }
28327         sqlite3_free(pChng);
28328         fclose(out);
28329       }
28330     }else
28331 
28332     /* .session close
28333     ** Close the identified session
28334     */
28335     if( cli_strcmp(azCmd[0], "close")==0 ){
28336       if( nCmd!=1 ) goto session_syntax_error;
28337       if( pAuxDb->nSession ){
28338         session_close(pSession);
28339         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
28340       }
28341     }else
28342 
28343     /* .session enable ?BOOLEAN?
28344     ** Query or set the enable flag
28345     */
28346     if( cli_strcmp(azCmd[0], "enable")==0 ){
28347       int ii;
28348       if( nCmd>2 ) goto session_syntax_error;
28349       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
28350       if( pAuxDb->nSession ){
28351         ii = sqlite3session_enable(pSession->p, ii);
28352         oputf("session %s enable flag = %d\n", pSession->zName, ii);
28353       }
28354     }else
28355 
28356     /* .session filter GLOB ....
28357     ** Set a list of GLOB patterns of table names to be excluded.
28358     */
28359     if( cli_strcmp(azCmd[0], "filter")==0 ){
28360       int ii, nByte;
28361       if( nCmd<2 ) goto session_syntax_error;
28362       if( pAuxDb->nSession ){
28363         for(ii=0; ii<pSession->nFilter; ii++){
28364           sqlite3_free(pSession->azFilter[ii]);
28365         }
28366         sqlite3_free(pSession->azFilter);
28367         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
28368         pSession->azFilter = sqlite3_malloc( nByte );
28369         shell_check_oom( pSession->azFilter );
28370         for(ii=1; ii<nCmd; ii++){
28371           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
28372           shell_check_oom(x);
28373         }
28374         pSession->nFilter = ii-1;
28375       }
28376     }else
28377 
28378     /* .session indirect ?BOOLEAN?
28379     ** Query or set the indirect flag
28380     */
28381     if( cli_strcmp(azCmd[0], "indirect")==0 ){
28382       int ii;
28383       if( nCmd>2 ) goto session_syntax_error;
28384       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
28385       if( pAuxDb->nSession ){
28386         ii = sqlite3session_indirect(pSession->p, ii);
28387         oputf("session %s indirect flag = %d\n", pSession->zName, ii);
28388       }
28389     }else
28390 
28391     /* .session isempty
28392     ** Determine if the session is empty
28393     */
28394     if( cli_strcmp(azCmd[0], "isempty")==0 ){
28395       int ii;
28396       if( nCmd!=1 ) goto session_syntax_error;
28397       if( pAuxDb->nSession ){
28398         ii = sqlite3session_isempty(pSession->p);
28399         oputf("session %s isempty flag = %d\n", pSession->zName, ii);
28400       }
28401     }else
28402 
28403     /* .session list
28404     ** List all currently open sessions
28405     */
28406     if( cli_strcmp(azCmd[0],"list")==0 ){
28407       for(i=0; i<pAuxDb->nSession; i++){
28408         oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
28409       }
28410     }else
28411 
28412     /* .session open DB NAME
28413     ** Open a new session called NAME on the attached database DB.
28414     ** DB is normally "main".
28415     */
28416     if( cli_strcmp(azCmd[0],"open")==0 ){
28417       char *zName;
28418       if( nCmd!=3 ) goto session_syntax_error;
28419       zName = azCmd[2];
28420       if( zName[0]==0 ) goto session_syntax_error;
28421       for(i=0; i<pAuxDb->nSession; i++){
28422         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
28423           eputf("Session \"%s\" already exists\n", zName);
28424           goto meta_command_exit;
28425         }
28426       }
28427       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
28428         eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
28429         goto meta_command_exit;
28430       }
28431       pSession = &pAuxDb->aSession[pAuxDb->nSession];
28432       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
28433       if( rc ){
28434         eputf("Cannot open session: error code=%d\n", rc);
28435         rc = 0;
28436         goto meta_command_exit;
28437       }
28438       pSession->nFilter = 0;
28439       sqlite3session_table_filter(pSession->p, session_filter, pSession);
28440       pAuxDb->nSession++;
28441       pSession->zName = sqlite3_mprintf("%s", zName);
28442       shell_check_oom(pSession->zName);
28443     }else
28444     /* If no command name matches, show a syntax error */
28445     session_syntax_error:
28446     showHelp(p->out, "session");
28447   }else
28448 #endif
28449 
28450 #ifdef SQLITE_DEBUG
28451   /* Undocumented commands for internal testing.  Subject to change
28452   ** without notice. */
28453   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
28454     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
28455       int i, v;
28456       for(i=1; i<nArg; i++){
28457         v = booleanValue(azArg[i]);
28458         oputf("%s: %d 0x%x\n", azArg[i], v, v);
28459       }
28460     }
28461     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
28462       int i; sqlite3_int64 v;
28463       for(i=1; i<nArg; i++){
28464         char zBuf[200];
28465         v = integerValue(azArg[i]);
28466         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
28467         oputz(zBuf);
28468       }
28469     }
28470   }else
28471 #endif
28472 
28473   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
28474     int bIsInit = 0;         /* True to initialize the SELFTEST table */
28475     int bVerbose = 0;        /* Verbose output */
28476     int bSelftestExists;     /* True if SELFTEST already exists */
28477     int i, k;                /* Loop counters */
28478     int nTest = 0;           /* Number of tests runs */
28479     int nErr = 0;            /* Number of errors seen */
28480     ShellText str;           /* Answer for a query */
28481     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
28482 
28483     open_db(p,0);
28484     for(i=1; i<nArg; i++){
28485       const char *z = azArg[i];
28486       if( z[0]=='-' && z[1]=='-' ) z++;
28487       if( cli_strcmp(z,"-init")==0 ){
28488         bIsInit = 1;
28489       }else
28490       if( cli_strcmp(z,"-v")==0 ){
28491         bVerbose++;
28492       }else
28493       {
28494         eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
28495         eputz("Should be one of: --init -v\n");
28496         rc = 1;
28497         goto meta_command_exit;
28498       }
28499     }
28500     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
28501            != SQLITE_OK ){
28502       bSelftestExists = 0;
28503     }else{
28504       bSelftestExists = 1;
28505     }
28506     if( bIsInit ){
28507       createSelftestTable(p);
28508       bSelftestExists = 1;
28509     }
28510     initText(&str);
28511     appendText(&str, "x", 0);
28512     for(k=bSelftestExists; k>=0; k--){
28513       if( k==1 ){
28514         rc = sqlite3_prepare_v2(p->db,
28515             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
28516             -1, &pStmt, 0);
28517       }else{
28518         rc = sqlite3_prepare_v2(p->db,
28519           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
28520           "      (1,'run','PRAGMA integrity_check','ok')",
28521           -1, &pStmt, 0);
28522       }
28523       if( rc ){
28524         eputz("Error querying the selftest table\n");
28525         rc = 1;
28526         sqlite3_finalize(pStmt);
28527         goto meta_command_exit;
28528       }
28529       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
28530         int tno = sqlite3_column_int(pStmt, 0);
28531         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
28532         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
28533         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
28534 
28535         if( zOp==0 ) continue;
28536         if( zSql==0 ) continue;
28537         if( zAns==0 ) continue;
28538         k = 0;
28539         if( bVerbose>0 ){
28540           sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
28541         }
28542         if( cli_strcmp(zOp,"memo")==0 ){
28543           oputf("%s\n", zSql);
28544         }else
28545         if( cli_strcmp(zOp,"run")==0 ){
28546           char *zErrMsg = 0;
28547           str.n = 0;
28548           str.z[0] = 0;
28549           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
28550           nTest++;
28551           if( bVerbose ){
28552             oputf("Result: %s\n", str.z);
28553           }
28554           if( rc || zErrMsg ){
28555             nErr++;
28556             rc = 1;
28557             oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
28558             sqlite3_free(zErrMsg);
28559           }else if( cli_strcmp(zAns,str.z)!=0 ){
28560             nErr++;
28561             rc = 1;
28562             oputf("%d: Expected: [%s]\n", tno, zAns);
28563             oputf("%d:      Got: [%s]\n", tno, str.z);
28564           }
28565         }
28566         else{
28567           eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
28568           rc = 1;
28569           break;
28570         }
28571       } /* End loop over rows of content from SELFTEST */
28572       sqlite3_finalize(pStmt);
28573     } /* End loop over k */
28574     freeText(&str);
28575     oputf("%d errors out of %d tests\n", nErr, nTest);
28576   }else
28577 
28578   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
28579     if( nArg<2 || nArg>3 ){
28580       eputz("Usage: .separator COL ?ROW?\n");
28581       rc = 1;
28582     }
28583     if( nArg>=2 ){
28584       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
28585                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
28586     }
28587     if( nArg>=3 ){
28588       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
28589                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
28590     }
28591   }else
28592 
28593   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
28594     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
28595     int i;                   /* Loop counter */
28596     int bSchema = 0;         /* Also hash the schema */
28597     int bSeparate = 0;       /* Hash each table separately */
28598     int iSize = 224;         /* Hash algorithm to use */
28599     int bDebug = 0;          /* Only show the query that would have run */
28600     sqlite3_stmt *pStmt;     /* For querying tables names */
28601     char *zSql;              /* SQL to be run */
28602     char *zSep;              /* Separator */
28603     ShellText sSql;          /* Complete SQL for the query to run the hash */
28604     ShellText sQuery;        /* Set of queries used to read all content */
28605     open_db(p, 0);
28606     for(i=1; i<nArg; i++){
28607       const char *z = azArg[i];
28608       if( z[0]=='-' ){
28609         z++;
28610         if( z[0]=='-' ) z++;
28611         if( cli_strcmp(z,"schema")==0 ){
28612           bSchema = 1;
28613         }else
28614         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
28615          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
28616         ){
28617           iSize = atoi(&z[5]);
28618         }else
28619         if( cli_strcmp(z,"debug")==0 ){
28620           bDebug = 1;
28621         }else
28622         {
28623           eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
28624           showHelp(p->out, azArg[0]);
28625           rc = 1;
28626           goto meta_command_exit;
28627         }
28628       }else if( zLike ){
28629         eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
28630         rc = 1;
28631         goto meta_command_exit;
28632       }else{
28633         zLike = z;
28634         bSeparate = 1;
28635         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
28636       }
28637     }
28638     if( bSchema ){
28639       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
28640              " WHERE type='table' AND coalesce(rootpage,0)>1"
28641              " UNION ALL SELECT 'sqlite_schema'"
28642              " ORDER BY 1 collate nocase";
28643     }else{
28644       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
28645              " WHERE type='table' AND coalesce(rootpage,0)>1"
28646              " AND name NOT LIKE 'sqlite_%'"
28647              " ORDER BY 1 collate nocase";
28648     }
28649     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
28650     initText(&sQuery);
28651     initText(&sSql);
28652     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
28653     zSep = "VALUES(";
28654     while( SQLITE_ROW==sqlite3_step(pStmt) ){
28655       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
28656       if( zTab==0 ) continue;
28657       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
28658       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
28659         appendText(&sQuery,"SELECT * FROM ", 0);
28660         appendText(&sQuery,zTab,'"');
28661         appendText(&sQuery," NOT INDEXED;", 0);
28662       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
28663         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
28664                            " ORDER BY name;", 0);
28665       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
28666         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
28667                            " ORDER BY name;", 0);
28668       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
28669         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
28670                            " ORDER BY tbl,idx;", 0);
28671       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
28672         appendText(&sQuery, "SELECT * FROM ", 0);
28673         appendText(&sQuery, zTab, 0);
28674         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
28675       }
28676       appendText(&sSql, zSep, 0);
28677       appendText(&sSql, sQuery.z, '\'');
28678       sQuery.n = 0;
28679       appendText(&sSql, ",", 0);
28680       appendText(&sSql, zTab, '\'');
28681       zSep = "),(";
28682     }
28683     sqlite3_finalize(pStmt);
28684     if( bSeparate ){
28685       zSql = sqlite3_mprintf(
28686           "%s))"
28687           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
28688           "   FROM [sha3sum$query]",
28689           sSql.z, iSize);
28690     }else{
28691       zSql = sqlite3_mprintf(
28692           "%s))"
28693           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
28694           "   FROM [sha3sum$query]",
28695           sSql.z, iSize);
28696     }
28697     shell_check_oom(zSql);
28698     freeText(&sQuery);
28699     freeText(&sSql);
28700     if( bDebug ){
28701       oputf("%s\n", zSql);
28702     }else{
28703       shell_exec(p, zSql, 0);
28704     }
28705 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
28706     {
28707       int lrc;
28708       char *zRevText = /* Query for reversible to-blob-to-text check */
28709         "SELECT lower(name) as tname FROM sqlite_schema\n"
28710         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
28711         "AND name NOT LIKE 'sqlite_%%'%s\n"
28712         "ORDER BY 1 collate nocase";
28713       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
28714       zRevText = sqlite3_mprintf(
28715           /* lower-case query is first run, producing upper-case query. */
28716           "with tabcols as materialized(\n"
28717           "select tname, cname\n"
28718           "from ("
28719           " select printf('\"%%w\"',ss.tname) as tname,"
28720           " printf('\"%%w\"',ti.name) as cname\n"
28721           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
28722           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
28723           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
28724           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
28725           "FROM '||tname||' WHERE '\n"
28726           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
28727           "|| ' AND typeof('||cname||')=''text'' ',\n"
28728           "' OR ') as query, tname from tabcols group by tname)"
28729           , zRevText);
28730       shell_check_oom(zRevText);
28731       if( bDebug ) oputf("%s\n", zRevText);
28732       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
28733       if( lrc!=SQLITE_OK ){
28734         /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
28735         ** user does cruel and unnatural things like ".limit expr_depth 0". */
28736         rc = 1;
28737       }else{
28738         if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
28739         lrc = SQLITE_ROW==sqlite3_step(pStmt);
28740         if( lrc ){
28741           const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
28742           sqlite3_stmt *pCheckStmt;
28743           lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
28744           if( bDebug ) oputf("%s\n", zGenQuery);
28745           if( lrc!=SQLITE_OK ){
28746             rc = 1;
28747           }else{
28748             if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
28749               double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
28750               if( countIrreversible>0 ){
28751                 int sz = (int)(countIrreversible + 0.5);
28752                 eputf("Digest includes %d invalidly encoded text field%s.\n",
28753                       sz, (sz>1)? "s": "");
28754               }
28755             }
28756             sqlite3_finalize(pCheckStmt);
28757           }
28758           sqlite3_finalize(pStmt);
28759         }
28760       }
28761       if( rc ) eputz(".sha3sum failed.\n");
28762       sqlite3_free(zRevText);
28763     }
28764 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
28765     sqlite3_free(zSql);
28766   }else
28767 
28768 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
28769   if( c=='s'
28770    && (cli_strncmp(azArg[0], "shell", n)==0
28771        || cli_strncmp(azArg[0],"system",n)==0)
28772   ){
28773     char *zCmd;
28774     int i, x;
28775     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
28776     if( nArg<2 ){
28777       eputz("Usage: .system COMMAND\n");
28778       rc = 1;
28779       goto meta_command_exit;
28780     }
28781     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
28782     for(i=2; i<nArg && zCmd!=0; i++){
28783       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
28784                              zCmd, azArg[i]);
28785     }
28786     consoleRestore();
28787     x = zCmd!=0 ? system(zCmd) : 1;
28788     consoleRenewSetup();
28789     sqlite3_free(zCmd);
28790     if( x ) eputf("System command returns %d\n", x);
28791   }else
28792 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
28793 
28794   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
28795     static const char *azBool[] = { "off", "on", "trigger", "full"};
28796     const char *zOut;
28797     int i;
28798     if( nArg!=1 ){
28799       eputz("Usage: .show\n");
28800       rc = 1;
28801       goto meta_command_exit;
28802     }
28803     oputf("%12.12s: %s\n","echo",
28804           azBool[ShellHasFlag(p, SHFLG_Echo)]);
28805     oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
28806     oputf("%12.12s: %s\n","explain",
28807           p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
28808     oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
28809     if( p->mode==MODE_Column
28810      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
28811     ){
28812       oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
28813             modeDescr[p->mode], p->cmOpts.iWrap,
28814             p->cmOpts.bWordWrap ? "on" : "off",
28815             p->cmOpts.bQuote ? "" : "no");
28816     }else{
28817       oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
28818     }
28819     oputf("%12.12s: ", "nullvalue");
28820     output_c_string(p->nullValue);
28821     oputz("\n");
28822     oputf("%12.12s: %s\n","output",
28823           strlen30(p->outfile) ? p->outfile : "stdout");
28824     oputf("%12.12s: ", "colseparator");
28825      output_c_string(p->colSeparator);
28826      oputz("\n");
28827     oputf("%12.12s: ", "rowseparator");
28828      output_c_string(p->rowSeparator);
28829      oputz("\n");
28830     switch( p->statsOn ){
28831       case 0:  zOut = "off";     break;
28832       default: zOut = "on";      break;
28833       case 2:  zOut = "stmt";    break;
28834       case 3:  zOut = "vmstep";  break;
28835     }
28836     oputf("%12.12s: %s\n","stats", zOut);
28837     oputf("%12.12s: ", "width");
28838     for (i=0;i<p->nWidth;i++) {
28839       oputf("%d ", p->colWidth[i]);
28840     }
28841     oputz("\n");
28842     oputf("%12.12s: %s\n", "filename",
28843           p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
28844   }else
28845 
28846   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
28847     if( nArg==2 ){
28848       if( cli_strcmp(azArg[1],"stmt")==0 ){
28849         p->statsOn = 2;
28850       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
28851         p->statsOn = 3;
28852       }else{
28853         p->statsOn = (u8)booleanValue(azArg[1]);
28854       }
28855     }else if( nArg==1 ){
28856       display_stats(p->db, p, 0);
28857     }else{
28858       eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
28859       rc = 1;
28860     }
28861   }else
28862 
28863   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
28864    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
28865                  || cli_strncmp(azArg[0], "indexes", n)==0) )
28866   ){
28867     sqlite3_stmt *pStmt;
28868     char **azResult;
28869     int nRow, nAlloc;
28870     int ii;
28871     ShellText s;
28872     initText(&s);
28873     open_db(p, 0);
28874     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
28875     if( rc ){
28876       sqlite3_finalize(pStmt);
28877       return shellDatabaseError(p->db);
28878     }
28879 
28880     if( nArg>2 && c=='i' ){
28881       /* It is an historical accident that the .indexes command shows an error
28882       ** when called with the wrong number of arguments whereas the .tables
28883       ** command does not. */
28884       eputz("Usage: .indexes ?LIKE-PATTERN?\n");
28885       rc = 1;
28886       sqlite3_finalize(pStmt);
28887       goto meta_command_exit;
28888     }
28889     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
28890       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
28891       if( zDbName==0 ) continue;
28892       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
28893       if( sqlite3_stricmp(zDbName, "main")==0 ){
28894         appendText(&s, "SELECT name FROM ", 0);
28895       }else{
28896         appendText(&s, "SELECT ", 0);
28897         appendText(&s, zDbName, '\'');
28898         appendText(&s, "||'.'||name FROM ", 0);
28899       }
28900       appendText(&s, zDbName, '"');
28901       appendText(&s, ".sqlite_schema ", 0);
28902       if( c=='t' ){
28903         appendText(&s," WHERE type IN ('table','view')"
28904                       "   AND name NOT LIKE 'sqlite_%'"
28905                       "   AND name LIKE ?1", 0);
28906       }else{
28907         appendText(&s," WHERE type='index'"
28908                       "   AND tbl_name LIKE ?1", 0);
28909       }
28910     }
28911     rc = sqlite3_finalize(pStmt);
28912     if( rc==SQLITE_OK ){
28913       appendText(&s, " ORDER BY 1", 0);
28914       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
28915     }
28916     freeText(&s);
28917     if( rc ) return shellDatabaseError(p->db);
28918 
28919     /* Run the SQL statement prepared by the above block. Store the results
28920     ** as an array of nul-terminated strings in azResult[].  */
28921     nRow = nAlloc = 0;
28922     azResult = 0;
28923     if( nArg>1 ){
28924       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
28925     }else{
28926       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
28927     }
28928     while( sqlite3_step(pStmt)==SQLITE_ROW ){
28929       if( nRow>=nAlloc ){
28930         char **azNew;
28931         int n2 = nAlloc*2 + 10;
28932         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
28933         shell_check_oom(azNew);
28934         nAlloc = n2;
28935         azResult = azNew;
28936       }
28937       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
28938       shell_check_oom(azResult[nRow]);
28939       nRow++;
28940     }
28941     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
28942       rc = shellDatabaseError(p->db);
28943     }
28944 
28945     /* Pretty-print the contents of array azResult[] to the output */
28946     if( rc==0 && nRow>0 ){
28947       int len, maxlen = 0;
28948       int i, j;
28949       int nPrintCol, nPrintRow;
28950       for(i=0; i<nRow; i++){
28951         len = strlen30(azResult[i]);
28952         if( len>maxlen ) maxlen = len;
28953       }
28954       nPrintCol = 80/(maxlen+2);
28955       if( nPrintCol<1 ) nPrintCol = 1;
28956       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
28957       for(i=0; i<nPrintRow; i++){
28958         for(j=i; j<nRow; j+=nPrintRow){
28959           char *zSp = j<nPrintRow ? "" : "  ";
28960           oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
28961         }
28962         oputz("\n");
28963       }
28964     }
28965 
28966     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
28967     sqlite3_free(azResult);
28968   }else
28969 
28970 #ifndef SQLITE_SHELL_FIDDLE
28971   /* Begin redirecting output to the file "testcase-out.txt" */
28972   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
28973     output_reset(p);
28974     p->out = output_file_open("testcase-out.txt", 0);
28975     if( p->out==0 ){
28976       eputz("Error: cannot open 'testcase-out.txt'\n");
28977     }
28978     if( nArg>=2 ){
28979       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
28980     }else{
28981       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
28982     }
28983   }else
28984 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
28985 
28986 #ifndef SQLITE_UNTESTABLE
28987   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
28988     static const struct {
28989        const char *zCtrlName;   /* Name of a test-control option */
28990        int ctrlCode;            /* Integer code for that option */
28991        int unSafe;              /* Not valid unless --unsafe-testing */
28992        const char *zUsage;      /* Usage notes */
28993     } aCtrl[] = {
28994     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
28995     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
28996   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
28997   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
28998     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
28999     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
29000     {"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..."       },
29001     {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
29002     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
29003     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
29004     {"json_selfcheck",     SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN"      },
29005     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
29006     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
29007     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
29008 #ifdef YYCOVERAGE
29009     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
29010 #endif
29011     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
29012     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
29013     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
29014     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
29015     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
29016     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
29017     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
29018     {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
29019     };
29020     int testctrl = -1;
29021     int iCtrl = -1;
29022     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
29023     int isOk = 0;
29024     int i, n2;
29025     const char *zCmd = 0;
29026 
29027     open_db(p, 0);
29028     zCmd = nArg>=2 ? azArg[1] : "help";
29029 
29030     /* The argument can optionally begin with "-" or "--" */
29031     if( zCmd[0]=='-' && zCmd[1] ){
29032       zCmd++;
29033       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
29034     }
29035 
29036     /* --help lists all test-controls */
29037     if( cli_strcmp(zCmd,"help")==0 ){
29038       oputz("Available test-controls:\n");
29039       for(i=0; i<ArraySize(aCtrl); i++){
29040         if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
29041         oputf("  .testctrl %s %s\n",
29042               aCtrl[i].zCtrlName, aCtrl[i].zUsage);
29043       }
29044       rc = 1;
29045       goto meta_command_exit;
29046     }
29047 
29048     /* convert testctrl text option to value. allow any unique prefix
29049     ** of the option name, or a numerical value. */
29050     n2 = strlen30(zCmd);
29051     for(i=0; i<ArraySize(aCtrl); i++){
29052       if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
29053       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
29054         if( testctrl<0 ){
29055           testctrl = aCtrl[i].ctrlCode;
29056           iCtrl = i;
29057         }else{
29058           eputf("Error: ambiguous test-control: \"%s\"\n"
29059                 "Use \".testctrl --help\" for help\n", zCmd);
29060           rc = 1;
29061           goto meta_command_exit;
29062         }
29063       }
29064     }
29065     if( testctrl<0 ){
29066       eputf("Error: unknown test-control: %s\n"
29067             "Use \".testctrl --help\" for help\n", zCmd);
29068     }else{
29069       switch(testctrl){
29070 
29071         /* sqlite3_test_control(int, db, int) */
29072         case SQLITE_TESTCTRL_OPTIMIZATIONS:
29073         case SQLITE_TESTCTRL_FK_NO_ACTION:
29074           if( nArg==3 ){
29075             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
29076             rc2 = sqlite3_test_control(testctrl, p->db, opt);
29077             isOk = 3;
29078           }
29079           break;
29080 
29081         /* sqlite3_test_control(int) */
29082         case SQLITE_TESTCTRL_PRNG_SAVE:
29083         case SQLITE_TESTCTRL_PRNG_RESTORE:
29084         case SQLITE_TESTCTRL_BYTEORDER:
29085           if( nArg==2 ){
29086             rc2 = sqlite3_test_control(testctrl);
29087             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
29088           }
29089           break;
29090 
29091         /* sqlite3_test_control(int, uint) */
29092         case SQLITE_TESTCTRL_PENDING_BYTE:
29093           if( nArg==3 ){
29094             unsigned int opt = (unsigned int)integerValue(azArg[2]);
29095             rc2 = sqlite3_test_control(testctrl, opt);
29096             isOk = 3;
29097           }
29098           break;
29099 
29100         /* sqlite3_test_control(int, int, sqlite3*) */
29101         case SQLITE_TESTCTRL_PRNG_SEED:
29102           if( nArg==3 || nArg==4 ){
29103             int ii = (int)integerValue(azArg[2]);
29104             sqlite3 *db;
29105             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
29106               sqlite3_randomness(sizeof(ii),&ii);
29107               sputf(stdout, "-- random seed: %d\n", ii);
29108             }
29109             if( nArg==3 ){
29110               db = 0;
29111             }else{
29112               db = p->db;
29113               /* Make sure the schema has been loaded */
29114               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
29115             }
29116             rc2 = sqlite3_test_control(testctrl, ii, db);
29117             isOk = 3;
29118           }
29119           break;
29120 
29121         /* sqlite3_test_control(int, int) */
29122         case SQLITE_TESTCTRL_ASSERT:
29123         case SQLITE_TESTCTRL_ALWAYS:
29124           if( nArg==3 ){
29125             int opt = booleanValue(azArg[2]);
29126             rc2 = sqlite3_test_control(testctrl, opt);
29127             isOk = 1;
29128           }
29129           break;
29130 
29131         /* sqlite3_test_control(int, int) */
29132         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
29133         case SQLITE_TESTCTRL_NEVER_CORRUPT:
29134           if( nArg==3 ){
29135             int opt = booleanValue(azArg[2]);
29136             rc2 = sqlite3_test_control(testctrl, opt);
29137             isOk = 3;
29138           }
29139           break;
29140 
29141         /* sqlite3_test_control(int, int) */
29142         case SQLITE_TESTCTRL_USELONGDOUBLE: {
29143           int opt = -1;
29144           if( nArg==3 ){
29145             if( cli_strcmp(azArg[2],"default")==0 ){
29146               opt = 2;
29147             }else{
29148               opt = booleanValue(azArg[2]);
29149             }
29150           }
29151           rc2 = sqlite3_test_control(testctrl, opt);
29152           isOk = 1;
29153           break;
29154         }
29155 
29156         /* sqlite3_test_control(sqlite3*) */
29157         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
29158           rc2 = sqlite3_test_control(testctrl, p->db);
29159           isOk = 3;
29160           break;
29161 
29162         case SQLITE_TESTCTRL_IMPOSTER:
29163           if( nArg==5 ){
29164             rc2 = sqlite3_test_control(testctrl, p->db,
29165                           azArg[2],
29166                           integerValue(azArg[3]),
29167                           integerValue(azArg[4]));
29168             isOk = 3;
29169           }
29170           break;
29171 
29172         case SQLITE_TESTCTRL_SEEK_COUNT: {
29173           u64 x = 0;
29174           rc2 = sqlite3_test_control(testctrl, p->db, &x);
29175           oputf("%llu\n", x);
29176           isOk = 3;
29177           break;
29178         }
29179 
29180 #ifdef YYCOVERAGE
29181         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
29182           if( nArg==2 ){
29183             sqlite3_test_control(testctrl, p->out);
29184             isOk = 3;
29185           }
29186           break;
29187         }
29188 #endif
29189 #ifdef SQLITE_DEBUG
29190         case SQLITE_TESTCTRL_TUNE: {
29191           if( nArg==4 ){
29192             int id = (int)integerValue(azArg[2]);
29193             int val = (int)integerValue(azArg[3]);
29194             sqlite3_test_control(testctrl, id, &val);
29195             isOk = 3;
29196           }else if( nArg==3 ){
29197             int id = (int)integerValue(azArg[2]);
29198             sqlite3_test_control(testctrl, -id, &rc2);
29199             isOk = 1;
29200           }else if( nArg==2 ){
29201             int id = 1;
29202             while(1){
29203               int val = 0;
29204               rc2 = sqlite3_test_control(testctrl, -id, &val);
29205               if( rc2!=SQLITE_OK ) break;
29206               if( id>1 ) oputz("  ");
29207               oputf("%d: %d", id, val);
29208               id++;
29209             }
29210             if( id>1 ) oputz("\n");
29211             isOk = 3;
29212           }
29213           break;
29214         }
29215 #endif
29216         case SQLITE_TESTCTRL_SORTER_MMAP:
29217           if( nArg==3 ){
29218             int opt = (unsigned int)integerValue(azArg[2]);
29219             rc2 = sqlite3_test_control(testctrl, p->db, opt);
29220             isOk = 3;
29221           }
29222           break;
29223         case SQLITE_TESTCTRL_JSON_SELFCHECK:
29224           if( nArg==2 ){
29225             rc2 = -1;
29226             isOk = 1;
29227           }else{
29228             rc2 = booleanValue(azArg[2]);
29229             isOk = 3;
29230           }
29231           sqlite3_test_control(testctrl, &rc2);
29232           break;
29233         case SQLITE_TESTCTRL_FAULT_INSTALL: {
29234           int kk;
29235           int bShowHelp = nArg<=2;
29236           isOk = 3;
29237           for(kk=2; kk<nArg; kk++){
29238             const char *z = azArg[kk];
29239             if( z[0]=='-' && z[1]=='-' ) z++;
29240             if( cli_strcmp(z,"off")==0 ){
29241               sqlite3_test_control(testctrl, 0);
29242             }else if( cli_strcmp(z,"on")==0 ){
29243               faultsim_state.iCnt = faultsim_state.nSkip;
29244               if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;
29245               faultsim_state.nHit = 0;
29246               sqlite3_test_control(testctrl, faultsim_callback);
29247             }else if( cli_strcmp(z,"reset")==0 ){
29248               faultsim_state.iCnt = faultsim_state.nSkip;
29249               faultsim_state.nHit = 0;
29250               sqlite3_test_control(testctrl, faultsim_callback);
29251             }else if( cli_strcmp(z,"status")==0 ){
29252               oputf("faultsim.iId:       %d\n", faultsim_state.iId);
29253               oputf("faultsim.iErr:      %d\n", faultsim_state.iErr);
29254               oputf("faultsim.iCnt:      %d\n", faultsim_state.iCnt);
29255               oputf("faultsim.nHit:      %d\n", faultsim_state.nHit);
29256               oputf("faultsim.iInterval: %d\n", faultsim_state.iInterval);
29257               oputf("faultsim.eVerbose:  %d\n", faultsim_state.eVerbose);
29258               oputf("faultsim.nRepeat:   %d\n", faultsim_state.nRepeat);
29259               oputf("faultsim.nSkip:     %d\n", faultsim_state.nSkip);
29260             }else if( cli_strcmp(z,"-v")==0 ){
29261               if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
29262             }else if( cli_strcmp(z,"-q")==0 ){
29263               if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
29264             }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
29265               faultsim_state.iId = atoi(azArg[++kk]);
29266             }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
29267               faultsim_state.iErr = atoi(azArg[++kk]);
29268             }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
29269               faultsim_state.iInterval = atoi(azArg[++kk]);
29270             }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){
29271               faultsim_state.nRepeat = atoi(azArg[++kk]);
29272            }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){
29273               faultsim_state.nSkip = atoi(azArg[++kk]);
29274             }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
29275               bShowHelp = 1;
29276             }else{
29277               eputf("Unrecognized fault_install argument: \"%s\"\n",
29278                   azArg[kk]);
29279               rc = 1;
29280               bShowHelp = 1;
29281               break;
29282             }
29283           }
29284           if( bShowHelp ){
29285             oputz(
29286                "Usage: .testctrl fault_install ARGS\n"
29287                "Possible arguments:\n"
29288                "   off               Disable faultsim\n"
29289                "   on                Activate faultsim\n"
29290                "   reset             Reset the trigger counter\n"
29291                "   status            Show current status\n"
29292                "   -v                Increase verbosity\n"
29293                "   -q                Decrease verbosity\n"
29294                "   --errcode N       When triggered, return N as error code\n"
29295                "   --id ID           Trigger only for the ID specified\n"
29296                "   --interval N      Trigger only after every N-th call\n"
29297                "   --repeat N        Turn off after N hits.  0 means never\n"
29298                "   --skip N          Skip the first N encounters\n"
29299             );
29300           }
29301           break;
29302         }
29303       }
29304     }
29305     if( isOk==0 && iCtrl>=0 ){
29306       oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
29307       rc = 1;
29308     }else if( isOk==1 ){
29309       oputf("%d\n", rc2);
29310     }else if( isOk==2 ){
29311       oputf("0x%08x\n", rc2);
29312     }
29313   }else
29314 #endif /* !defined(SQLITE_UNTESTABLE) */
29315 
29316   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
29317     open_db(p, 0);
29318     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
29319   }else
29320 
29321   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
29322     if( nArg==2 ){
29323       enableTimer = booleanValue(azArg[1]);
29324       if( enableTimer && !HAS_TIMER ){
29325         eputz("Error: timer not available on this system.\n");
29326         enableTimer = 0;
29327       }
29328     }else{
29329       eputz("Usage: .timer on|off\n");
29330       rc = 1;
29331     }
29332   }else
29333 
29334 #ifndef SQLITE_OMIT_TRACE
29335   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
29336     int mType = 0;
29337     int jj;
29338     open_db(p, 0);
29339     for(jj=1; jj<nArg; jj++){
29340       const char *z = azArg[jj];
29341       if( z[0]=='-' ){
29342         if( optionMatch(z, "expanded") ){
29343           p->eTraceType = SHELL_TRACE_EXPANDED;
29344         }
29345 #ifdef SQLITE_ENABLE_NORMALIZE
29346         else if( optionMatch(z, "normalized") ){
29347           p->eTraceType = SHELL_TRACE_NORMALIZED;
29348         }
29349 #endif
29350         else if( optionMatch(z, "plain") ){
29351           p->eTraceType = SHELL_TRACE_PLAIN;
29352         }
29353         else if( optionMatch(z, "profile") ){
29354           mType |= SQLITE_TRACE_PROFILE;
29355         }
29356         else if( optionMatch(z, "row") ){
29357           mType |= SQLITE_TRACE_ROW;
29358         }
29359         else if( optionMatch(z, "stmt") ){
29360           mType |= SQLITE_TRACE_STMT;
29361         }
29362         else if( optionMatch(z, "close") ){
29363           mType |= SQLITE_TRACE_CLOSE;
29364         }
29365         else {
29366           eputf("Unknown option \"%s\" on \".trace\"\n", z);
29367           rc = 1;
29368           goto meta_command_exit;
29369         }
29370       }else{
29371         output_file_close(p->traceOut);
29372         p->traceOut = output_file_open(z, 0);
29373       }
29374     }
29375     if( p->traceOut==0 ){
29376       sqlite3_trace_v2(p->db, 0, 0, 0);
29377     }else{
29378       if( mType==0 ) mType = SQLITE_TRACE_STMT;
29379       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
29380     }
29381   }else
29382 #endif /* !defined(SQLITE_OMIT_TRACE) */
29383 
29384 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
29385   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
29386     int ii;
29387     int lenOpt;
29388     char *zOpt;
29389     if( nArg<2 ){
29390       eputz("Usage: .unmodule [--allexcept] NAME ...\n");
29391       rc = 1;
29392       goto meta_command_exit;
29393     }
29394     open_db(p, 0);
29395     zOpt = azArg[1];
29396     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
29397     lenOpt = (int)strlen(zOpt);
29398     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
29399       assert( azArg[nArg]==0 );
29400       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
29401     }else{
29402       for(ii=1; ii<nArg; ii++){
29403         sqlite3_create_module(p->db, azArg[ii], 0, 0);
29404       }
29405     }
29406   }else
29407 #endif
29408 
29409 #if SQLITE_USER_AUTHENTICATION
29410   if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
29411     if( nArg<2 ){
29412       eputz("Usage: .user SUBCOMMAND ...\n");
29413       rc = 1;
29414       goto meta_command_exit;
29415     }
29416     open_db(p, 0);
29417     if( cli_strcmp(azArg[1],"login")==0 ){
29418       if( nArg!=4 ){
29419         eputz("Usage: .user login USER PASSWORD\n");
29420         rc = 1;
29421         goto meta_command_exit;
29422       }
29423       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
29424                                      strlen30(azArg[3]));
29425       if( rc ){
29426         eputf("Authentication failed for user %s\n", azArg[2]);
29427         rc = 1;
29428       }
29429     }else if( cli_strcmp(azArg[1],"add")==0 ){
29430       if( nArg!=5 ){
29431         eputz("Usage: .user add USER PASSWORD ISADMIN\n");
29432         rc = 1;
29433         goto meta_command_exit;
29434       }
29435       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
29436                             booleanValue(azArg[4]));
29437       if( rc ){
29438         eputf("User-Add failed: %d\n", rc);
29439         rc = 1;
29440       }
29441     }else if( cli_strcmp(azArg[1],"edit")==0 ){
29442       if( nArg!=5 ){
29443         eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
29444         rc = 1;
29445         goto meta_command_exit;
29446       }
29447       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
29448                               booleanValue(azArg[4]));
29449       if( rc ){
29450         eputf("User-Edit failed: %d\n", rc);
29451         rc = 1;
29452       }
29453     }else if( cli_strcmp(azArg[1],"delete")==0 ){
29454       if( nArg!=3 ){
29455         eputz("Usage: .user delete USER\n");
29456         rc = 1;
29457         goto meta_command_exit;
29458       }
29459       rc = sqlite3_user_delete(p->db, azArg[2]);
29460       if( rc ){
29461         eputf("User-Delete failed: %d\n", rc);
29462         rc = 1;
29463       }
29464     }else{
29465       eputz("Usage: .user login|add|edit|delete ...\n");
29466       rc = 1;
29467       goto meta_command_exit;
29468     }
29469   }else
29470 #endif /* SQLITE_USER_AUTHENTICATION */
29471 
29472   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
29473     char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
29474     oputf("SQLite %s %s\n" /*extra-version-info*/,
29475           sqlite3_libversion(), sqlite3_sourceid());
29476 #if SQLITE_HAVE_ZLIB
29477     oputf("zlib version %s\n", zlibVersion());
29478 #endif
29479 #define CTIMEOPT_VAL_(opt) #opt
29480 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
29481 #if defined(__clang__) && defined(__clang_major__)
29482     oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
29483           CTIMEOPT_VAL(__clang_minor__) "."
29484           CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
29485 #elif defined(_MSC_VER)
29486     oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
29487 #elif defined(__GNUC__) && defined(__VERSION__)
29488     oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
29489 #endif
29490   }else
29491 
29492   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
29493     const char *zDbName = nArg==2 ? azArg[1] : "main";
29494     sqlite3_vfs *pVfs = 0;
29495     if( p->db ){
29496       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
29497       if( pVfs ){
29498         oputf("vfs.zName      = \"%s\"\n", pVfs->zName);
29499         oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
29500         oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
29501         oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
29502       }
29503     }
29504   }else
29505 
29506   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
29507     sqlite3_vfs *pVfs;
29508     sqlite3_vfs *pCurrent = 0;
29509     if( p->db ){
29510       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
29511     }
29512     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
29513       oputf("vfs.zName      = \"%s\"%s\n", pVfs->zName,
29514             pVfs==pCurrent ? "  <--- CURRENT" : "");
29515       oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
29516       oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
29517       oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
29518       if( pVfs->pNext ){
29519         oputz("-----------------------------------\n");
29520       }
29521     }
29522   }else
29523 
29524   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
29525     const char *zDbName = nArg==2 ? azArg[1] : "main";
29526     char *zVfsName = 0;
29527     if( p->db ){
29528       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
29529       if( zVfsName ){
29530         oputf("%s\n", zVfsName);
29531         sqlite3_free(zVfsName);
29532       }
29533     }
29534   }else
29535 
29536   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
29537     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
29538     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
29539   }else
29540 
29541   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
29542     int j;
29543     assert( nArg<=ArraySize(azArg) );
29544     p->nWidth = nArg-1;
29545     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
29546     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
29547     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
29548     for(j=1; j<nArg; j++){
29549       p->colWidth[j-1] = (int)integerValue(azArg[j]);
29550     }
29551   }else
29552 
29553   {
29554     eputf("Error: unknown command or invalid arguments: "
29555           " \"%s\". Enter \".help\" for help\n", azArg[0]);
29556     rc = 1;
29557   }
29558 
29559 meta_command_exit:
29560   if( p->outCount ){
29561     p->outCount--;
29562     if( p->outCount==0 ) output_reset(p);
29563   }
29564   p->bSafeMode = p->bSafeModePersist;
29565   return rc;
29566 }
29567 
29568 /* Line scan result and intermediate states (supporting scan resumption)
29569 */
29570 #ifndef CHAR_BIT
29571 # define CHAR_BIT 8
29572 #endif
29573 typedef enum {
29574   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
29575   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
29576   QSS_Start = 0
29577 } QuickScanState;
29578 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
29579 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
29580 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
29581 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
29582 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
29583 
29584 /*
29585 ** Scan line for classification to guide shell's handling.
29586 ** The scan is resumable for subsequent lines when prior
29587 ** return values are passed as the 2nd argument.
29588 */
quickscan(char * zLine,QuickScanState qss,SCAN_TRACKER_REFTYPE pst)29589 static QuickScanState quickscan(char *zLine, QuickScanState qss,
29590                                 SCAN_TRACKER_REFTYPE pst){
29591   char cin;
29592   char cWait = (char)qss; /* intentional narrowing loss */
29593   if( cWait==0 ){
29594   PlainScan:
29595     assert( cWait==0 );
29596     while( (cin = *zLine++)!=0 ){
29597       if( IsSpace(cin) )
29598         continue;
29599       switch (cin){
29600       case '-':
29601         if( *zLine!='-' )
29602           break;
29603         while((cin = *++zLine)!=0 )
29604           if( cin=='\n')
29605             goto PlainScan;
29606         return qss;
29607       case ';':
29608         qss |= QSS_EndingSemi;
29609         continue;
29610       case '/':
29611         if( *zLine=='*' ){
29612           ++zLine;
29613           cWait = '*';
29614           CONTINUE_PROMPT_AWAITS(pst, "/*");
29615           qss = QSS_SETV(qss, cWait);
29616           goto TermScan;
29617         }
29618         break;
29619       case '[':
29620         cin = ']';
29621         deliberate_fall_through;
29622       case '`': case '\'': case '"':
29623         cWait = cin;
29624         qss = QSS_HasDark | cWait;
29625         CONTINUE_PROMPT_AWAITC(pst, cin);
29626         goto TermScan;
29627       case '(':
29628         CONTINUE_PAREN_INCR(pst, 1);
29629         break;
29630       case ')':
29631         CONTINUE_PAREN_INCR(pst, -1);
29632         break;
29633       default:
29634         break;
29635       }
29636       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
29637     }
29638   }else{
29639   TermScan:
29640     while( (cin = *zLine++)!=0 ){
29641       if( cin==cWait ){
29642         switch( cWait ){
29643         case '*':
29644           if( *zLine != '/' )
29645             continue;
29646           ++zLine;
29647           cWait = 0;
29648           CONTINUE_PROMPT_AWAITC(pst, 0);
29649           qss = QSS_SETV(qss, 0);
29650           goto PlainScan;
29651         case '`': case '\'': case '"':
29652           if(*zLine==cWait){
29653             /* Swallow doubled end-delimiter.*/
29654             ++zLine;
29655             continue;
29656           }
29657           deliberate_fall_through;
29658         case ']':
29659           cWait = 0;
29660           CONTINUE_PROMPT_AWAITC(pst, 0);
29661           qss = QSS_SETV(qss, 0);
29662           goto PlainScan;
29663         default: assert(0);
29664         }
29665       }
29666     }
29667   }
29668   return qss;
29669 }
29670 
29671 /*
29672 ** Return TRUE if the line typed in is an SQL command terminator other
29673 ** than a semi-colon.  The SQL Server style "go" command is understood
29674 ** as is the Oracle "/".
29675 */
line_is_command_terminator(char * zLine)29676 static int line_is_command_terminator(char *zLine){
29677   while( IsSpace(zLine[0]) ){ zLine++; };
29678   if( zLine[0]=='/' )
29679     zLine += 1; /* Oracle */
29680   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
29681     zLine += 2; /* SQL Server */
29682   else
29683     return 0;
29684   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
29685 }
29686 
29687 /*
29688 ** The CLI needs a working sqlite3_complete() to work properly.  So error
29689 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
29690 */
29691 #ifdef SQLITE_OMIT_COMPLETE
29692 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
29693 #endif
29694 
29695 /*
29696 ** Return true if zSql is a complete SQL statement.  Return false if it
29697 ** ends in the middle of a string literal or C-style comment.
29698 */
line_is_complete(char * zSql,int nSql)29699 static int line_is_complete(char *zSql, int nSql){
29700   int rc;
29701   if( zSql==0 ) return 1;
29702   zSql[nSql] = ';';
29703   zSql[nSql+1] = 0;
29704   rc = sqlite3_complete(zSql);
29705   zSql[nSql] = 0;
29706   return rc;
29707 }
29708 
29709 /*
29710 ** This function is called after processing each line of SQL in the
29711 ** runOneSqlLine() function. Its purpose is to detect scenarios where
29712 ** defensive mode should be automatically turned off. Specifically, when
29713 **
29714 **   1. The first line of input is "PRAGMA foreign_keys=OFF;",
29715 **   2. The second line of input is "BEGIN TRANSACTION;",
29716 **   3. The database is empty, and
29717 **   4. The shell is not running in --safe mode.
29718 **
29719 ** The implementation uses the ShellState.eRestoreState to maintain state:
29720 **
29721 **    0: Have not seen any SQL.
29722 **    1: Have seen "PRAGMA foreign_keys=OFF;".
29723 **    2-6: Currently running .dump transaction. If the "2" bit is set,
29724 **         disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
29725 **    7: Nothing left to do. This function becomes a no-op.
29726 */
doAutoDetectRestore(ShellState * p,const char * zSql)29727 static int doAutoDetectRestore(ShellState *p, const char *zSql){
29728   int rc = SQLITE_OK;
29729 
29730   if( p->eRestoreState<7 ){
29731     switch( p->eRestoreState ){
29732       case 0: {
29733         const char *zExpect = "PRAGMA foreign_keys=OFF;";
29734         assert( strlen(zExpect)==24 );
29735         if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
29736           p->eRestoreState = 1;
29737         }else{
29738           p->eRestoreState = 7;
29739         }
29740         break;
29741       };
29742 
29743       case 1: {
29744         int bIsDump = 0;
29745         const char *zExpect = "BEGIN TRANSACTION;";
29746         assert( strlen(zExpect)==18 );
29747         if( memcmp(zSql, zExpect, 19)==0 ){
29748           /* Now check if the database is empty. */
29749           const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
29750           sqlite3_stmt *pStmt = 0;
29751 
29752           bIsDump = 1;
29753           shellPrepare(p->db, &rc, zQuery, &pStmt);
29754           if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
29755             bIsDump = 0;
29756           }
29757           shellFinalize(&rc, pStmt);
29758         }
29759         if( bIsDump && rc==SQLITE_OK ){
29760           int bDefense = 0;
29761           int bDqsDdl = 0;
29762           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
29763           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
29764           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
29765           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
29766           p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
29767         }else{
29768           p->eRestoreState = 7;
29769         }
29770         break;
29771       }
29772 
29773       default: {
29774         if( sqlite3_get_autocommit(p->db) ){
29775           if( (p->eRestoreState & 2) ){
29776             sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
29777           }
29778           if( (p->eRestoreState & 4) ){
29779             sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
29780           }
29781           p->eRestoreState = 7;
29782         }
29783         break;
29784       }
29785     }
29786   }
29787 
29788   return rc;
29789 }
29790 
29791 /*
29792 ** Run a single line of SQL.  Return the number of errors.
29793 */
runOneSqlLine(ShellState * p,char * zSql,FILE * in,int startline)29794 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
29795   int rc;
29796   char *zErrMsg = 0;
29797 
29798   open_db(p, 0);
29799   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
29800   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
29801   BEGIN_TIMER;
29802   rc = shell_exec(p, zSql, &zErrMsg);
29803   END_TIMER;
29804   if( rc || zErrMsg ){
29805     char zPrefix[100];
29806     const char *zErrorTail;
29807     const char *zErrorType;
29808     if( zErrMsg==0 ){
29809       zErrorType = "Error";
29810       zErrorTail = sqlite3_errmsg(p->db);
29811     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
29812       zErrorType = "Parse error";
29813       zErrorTail = &zErrMsg[12];
29814     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
29815       zErrorType = "Runtime error";
29816       zErrorTail = &zErrMsg[10];
29817     }else{
29818       zErrorType = "Error";
29819       zErrorTail = zErrMsg;
29820     }
29821     if( in!=0 || !stdin_is_interactive ){
29822       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
29823                        "%s near line %d:", zErrorType, startline);
29824     }else{
29825       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
29826     }
29827     eputf("%s %s\n", zPrefix, zErrorTail);
29828     sqlite3_free(zErrMsg);
29829     zErrMsg = 0;
29830     return 1;
29831   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
29832     char zLineBuf[2000];
29833     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
29834             "changes: %lld   total_changes: %lld",
29835             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
29836     oputf("%s\n", zLineBuf);
29837   }
29838 
29839   if( doAutoDetectRestore(p, zSql) ) return 1;
29840   return 0;
29841 }
29842 
echo_group_input(ShellState * p,const char * zDo)29843 static void echo_group_input(ShellState *p, const char *zDo){
29844   if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
29845 }
29846 
29847 #ifdef SQLITE_SHELL_FIDDLE
29848 /*
29849 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
29850 ** impl because we need the global shellState and cannot access it from that
29851 ** function without moving lots of code around (creating a larger/messier diff).
29852 */
one_input_line(FILE * in,char * zPrior,int isContinuation)29853 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
29854   /* Parse the next line from shellState.wasm.zInput. */
29855   const char *zBegin = shellState.wasm.zPos;
29856   const char *z = zBegin;
29857   char *zLine = 0;
29858   i64 nZ = 0;
29859 
29860   UNUSED_PARAMETER(in);
29861   UNUSED_PARAMETER(isContinuation);
29862   if(!z || !*z){
29863     return 0;
29864   }
29865   while(*z && isspace(*z)) ++z;
29866   zBegin = z;
29867   for(; *z && '\n'!=*z; ++nZ, ++z){}
29868   if(nZ>0 && '\r'==zBegin[nZ-1]){
29869     --nZ;
29870   }
29871   shellState.wasm.zPos = z;
29872   zLine = realloc(zPrior, nZ+1);
29873   shell_check_oom(zLine);
29874   memcpy(zLine, zBegin, nZ);
29875   zLine[nZ] = 0;
29876   return zLine;
29877 }
29878 #endif /* SQLITE_SHELL_FIDDLE */
29879 
29880 /*
29881 ** Read input from *in and process it.  If *in==0 then input
29882 ** is interactive - the user is typing it it.  Otherwise, input
29883 ** is coming from a file or device.  A prompt is issued and history
29884 ** is saved only if input is interactive.  An interrupt signal will
29885 ** cause this routine to exit immediately, unless input is interactive.
29886 **
29887 ** Return the number of errors.
29888 */
process_input(ShellState * p)29889 static int process_input(ShellState *p){
29890   char *zLine = 0;          /* A single input line */
29891   char *zSql = 0;           /* Accumulated SQL text */
29892   i64 nLine;                /* Length of current line */
29893   i64 nSql = 0;             /* Bytes of zSql[] used */
29894   i64 nAlloc = 0;           /* Allocated zSql[] space */
29895   int rc;                   /* Error code */
29896   int errCnt = 0;           /* Number of errors seen */
29897   i64 startline = 0;        /* Line number for start of current input */
29898   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
29899 
29900   if( p->inputNesting==MAX_INPUT_NESTING ){
29901     /* This will be more informative in a later version. */
29902     eputf("Input nesting limit (%d) reached at line %d."
29903           " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
29904     return 1;
29905   }
29906   ++p->inputNesting;
29907   p->lineno = 0;
29908   CONTINUE_PROMPT_RESET;
29909   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
29910     fflush(p->out);
29911     zLine = one_input_line(p->in, zLine, nSql>0);
29912     if( zLine==0 ){
29913       /* End of input */
29914       if( p->in==0 && stdin_is_interactive ) oputz("\n");
29915       break;
29916     }
29917     if( seenInterrupt ){
29918       if( p->in!=0 ) break;
29919       seenInterrupt = 0;
29920     }
29921     p->lineno++;
29922     if( QSS_INPLAIN(qss)
29923         && line_is_command_terminator(zLine)
29924         && line_is_complete(zSql, nSql) ){
29925       memcpy(zLine,";",2);
29926     }
29927     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
29928     if( QSS_PLAINWHITE(qss) && nSql==0 ){
29929       /* Just swallow single-line whitespace */
29930       echo_group_input(p, zLine);
29931       qss = QSS_Start;
29932       continue;
29933     }
29934     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
29935       CONTINUE_PROMPT_RESET;
29936       echo_group_input(p, zLine);
29937       if( zLine[0]=='.' ){
29938         rc = do_meta_command(zLine, p);
29939         if( rc==2 ){ /* exit requested */
29940           break;
29941         }else if( rc ){
29942           errCnt++;
29943         }
29944       }
29945       qss = QSS_Start;
29946       continue;
29947     }
29948     /* No single-line dispositions remain; accumulate line(s). */
29949     nLine = strlen(zLine);
29950     if( nSql+nLine+2>=nAlloc ){
29951       /* Grow buffer by half-again increments when big. */
29952       nAlloc = nSql+(nSql>>1)+nLine+100;
29953       zSql = realloc(zSql, nAlloc);
29954       shell_check_oom(zSql);
29955     }
29956     if( nSql==0 ){
29957       i64 i;
29958       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
29959       assert( nAlloc>0 && zSql!=0 );
29960       memcpy(zSql, zLine+i, nLine+1-i);
29961       startline = p->lineno;
29962       nSql = nLine-i;
29963     }else{
29964       zSql[nSql++] = '\n';
29965       memcpy(zSql+nSql, zLine, nLine+1);
29966       nSql += nLine;
29967     }
29968     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
29969       echo_group_input(p, zSql);
29970       errCnt += runOneSqlLine(p, zSql, p->in, startline);
29971       CONTINUE_PROMPT_RESET;
29972       nSql = 0;
29973       if( p->outCount ){
29974         output_reset(p);
29975         p->outCount = 0;
29976       }else{
29977         clearTempFile(p);
29978       }
29979       p->bSafeMode = p->bSafeModePersist;
29980       qss = QSS_Start;
29981     }else if( nSql && QSS_PLAINWHITE(qss) ){
29982       echo_group_input(p, zSql);
29983       nSql = 0;
29984       qss = QSS_Start;
29985     }
29986   }
29987   if( nSql ){
29988     /* This may be incomplete. Let the SQL parser deal with that. */
29989     echo_group_input(p, zSql);
29990     errCnt += runOneSqlLine(p, zSql, p->in, startline);
29991     CONTINUE_PROMPT_RESET;
29992   }
29993   free(zSql);
29994   free(zLine);
29995   --p->inputNesting;
29996   return errCnt>0;
29997 }
29998 
29999 /*
30000 ** Return a pathname which is the user's home directory.  A
30001 ** 0 return indicates an error of some kind.
30002 */
find_home_dir(int clearFlag)30003 static char *find_home_dir(int clearFlag){
30004   static char *home_dir = NULL;
30005   if( clearFlag ){
30006     free(home_dir);
30007     home_dir = 0;
30008     return 0;
30009   }
30010   if( home_dir ) return home_dir;
30011 
30012 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
30013      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
30014   {
30015     struct passwd *pwent;
30016     uid_t uid = getuid();
30017     if( (pwent=getpwuid(uid)) != NULL) {
30018       home_dir = pwent->pw_dir;
30019     }
30020   }
30021 #endif
30022 
30023 #if defined(_WIN32_WCE)
30024   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
30025    */
30026   home_dir = "/";
30027 #else
30028 
30029 #if defined(_WIN32) || defined(WIN32)
30030   if (!home_dir) {
30031     home_dir = getenv("USERPROFILE");
30032   }
30033 #endif
30034 
30035   if (!home_dir) {
30036     home_dir = getenv("HOME");
30037   }
30038 
30039 #if defined(_WIN32) || defined(WIN32)
30040   if (!home_dir) {
30041     char *zDrive, *zPath;
30042     int n;
30043     zDrive = getenv("HOMEDRIVE");
30044     zPath = getenv("HOMEPATH");
30045     if( zDrive && zPath ){
30046       n = strlen30(zDrive) + strlen30(zPath) + 1;
30047       home_dir = malloc( n );
30048       if( home_dir==0 ) return 0;
30049       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
30050       return home_dir;
30051     }
30052     home_dir = "c:\\";
30053   }
30054 #endif
30055 
30056 #endif /* !_WIN32_WCE */
30057 
30058   if( home_dir ){
30059     i64 n = strlen(home_dir) + 1;
30060     char *z = malloc( n );
30061     if( z ) memcpy(z, home_dir, n);
30062     home_dir = z;
30063   }
30064 
30065   return home_dir;
30066 }
30067 
30068 /*
30069 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
30070 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
30071 ** the path to it, else return 0. The result is cached for
30072 ** subsequent calls.
30073 */
find_xdg_config(void)30074 static const char *find_xdg_config(void){
30075 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
30076      || defined(__RTP__) || defined(_WRS_KERNEL)
30077   return 0;
30078 #else
30079   static int alreadyTried = 0;
30080   static char *zConfig = 0;
30081   const char *zXdgHome;
30082 
30083   if( alreadyTried!=0 ){
30084     return zConfig;
30085   }
30086   alreadyTried = 1;
30087   zXdgHome = getenv("XDG_CONFIG_HOME");
30088   if( zXdgHome==0 ){
30089     return 0;
30090   }
30091   zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
30092   shell_check_oom(zConfig);
30093   if( access(zConfig,0)!=0 ){
30094     sqlite3_free(zConfig);
30095     zConfig = 0;
30096   }
30097   return zConfig;
30098 #endif
30099 }
30100 
30101 /*
30102 ** Read input from the file given by sqliterc_override.  Or if that
30103 ** parameter is NULL, take input from the first of find_xdg_config()
30104 ** or ~/.sqliterc which is found.
30105 **
30106 ** Returns the number of errors.
30107 */
process_sqliterc(ShellState * p,const char * sqliterc_override)30108 static void process_sqliterc(
30109   ShellState *p,                  /* Configuration data */
30110   const char *sqliterc_override   /* Name of config file. NULL to use default */
30111 ){
30112   char *home_dir = NULL;
30113   const char *sqliterc = sqliterc_override;
30114   char *zBuf = 0;
30115   FILE *inSaved = p->in;
30116   int savedLineno = p->lineno;
30117 
30118   if( sqliterc == NULL ){
30119     sqliterc = find_xdg_config();
30120   }
30121   if( sqliterc == NULL ){
30122     home_dir = find_home_dir(0);
30123     if( home_dir==0 ){
30124       eputz("-- warning: cannot find home directory;"
30125             " cannot read ~/.sqliterc\n");
30126       return;
30127     }
30128     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
30129     shell_check_oom(zBuf);
30130     sqliterc = zBuf;
30131   }
30132   p->in = fopen(sqliterc,"rb");
30133   if( p->in ){
30134     if( stdin_is_interactive ){
30135       eputf("-- Loading resources from %s\n", sqliterc);
30136     }
30137     if( process_input(p) && bail_on_error ) exit(1);
30138     fclose(p->in);
30139   }else if( sqliterc_override!=0 ){
30140     eputf("cannot open: \"%s\"\n", sqliterc);
30141     if( bail_on_error ) exit(1);
30142   }
30143   p->in = inSaved;
30144   p->lineno = savedLineno;
30145   sqlite3_free(zBuf);
30146 }
30147 
30148 /*
30149 ** Show available command line options
30150 */
30151 static const char zOptions[] =
30152   "   --                   treat no subsequent arguments as options\n"
30153 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
30154   "   -A ARGS...           run \".archive ARGS\" and exit\n"
30155 #endif
30156   "   -append              append the database to the end of the file\n"
30157   "   -ascii               set output mode to 'ascii'\n"
30158   "   -bail                stop after hitting an error\n"
30159   "   -batch               force batch I/O\n"
30160   "   -box                 set output mode to 'box'\n"
30161   "   -column              set output mode to 'column'\n"
30162   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
30163   "   -csv                 set output mode to 'csv'\n"
30164 #if !defined(SQLITE_OMIT_DESERIALIZE)
30165   "   -deserialize         open the database using sqlite3_deserialize()\n"
30166 #endif
30167   "   -echo                print inputs before execution\n"
30168   "   -init FILENAME       read/process named file\n"
30169   "   -[no]header          turn headers on or off\n"
30170 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
30171   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
30172 #endif
30173   "   -help                show this message\n"
30174   "   -html                set output mode to HTML\n"
30175   "   -interactive         force interactive I/O\n"
30176   "   -json                set output mode to 'json'\n"
30177   "   -line                set output mode to 'line'\n"
30178   "   -list                set output mode to 'list'\n"
30179   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
30180   "   -markdown            set output mode to 'markdown'\n"
30181 #if !defined(SQLITE_OMIT_DESERIALIZE)
30182   "   -maxsize N           maximum size for a --deserialize database\n"
30183 #endif
30184   "   -memtrace            trace all memory allocations and deallocations\n"
30185   "   -mmap N              default mmap size set to N\n"
30186 #ifdef SQLITE_ENABLE_MULTIPLEX
30187   "   -multiplex           enable the multiplexor VFS\n"
30188 #endif
30189   "   -newline SEP         set output row separator. Default: '\\n'\n"
30190   "   -nofollow            refuse to open symbolic links to database files\n"
30191   "   -nonce STRING        set the safe-mode escape nonce\n"
30192   "   -no-rowid-in-view    Disable rowid-in-view using sqlite3_config()\n"
30193   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
30194   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
30195   "   -pcachetrace         trace all page cache operations\n"
30196   "   -quote               set output mode to 'quote'\n"
30197   "   -readonly            open the database read-only\n"
30198   "   -safe                enable safe-mode\n"
30199   "   -separator SEP       set output column separator. Default: '|'\n"
30200 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
30201   "   -sorterref SIZE      sorter references threshold size\n"
30202 #endif
30203   "   -stats               print memory stats before each finalize\n"
30204   "   -table               set output mode to 'table'\n"
30205   "   -tabs                set output mode to 'tabs'\n"
30206   "   -unsafe-testing      allow unsafe commands and modes for testing\n"
30207   "   -version             show SQLite version\n"
30208   "   -vfs NAME            use NAME as the default VFS\n"
30209 #ifdef SQLITE_ENABLE_VFSTRACE
30210   "   -vfstrace            enable tracing of all VFS calls\n"
30211 #endif
30212 #ifdef SQLITE_HAVE_ZLIB
30213   "   -zip                 open the file as a ZIP Archive\n"
30214 #endif
30215 ;
usage(int showDetail)30216 static void usage(int showDetail){
30217   eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
30218        "FILENAME is the name of an SQLite database. A new database is created\n"
30219        "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
30220   if( showDetail ){
30221     eputf("OPTIONS include:\n%s", zOptions);
30222   }else{
30223     eputz("Use the -help option for additional information\n");
30224   }
30225   exit(0);
30226 }
30227 
30228 /*
30229 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
30230 ** error message if it is initialized.
30231 */
verify_uninitialized(void)30232 static void verify_uninitialized(void){
30233   if( sqlite3_config(-1)==SQLITE_MISUSE ){
30234     sputz(stdout, "WARNING: attempt to configure SQLite after"
30235           " initialization.\n");
30236   }
30237 }
30238 
30239 /*
30240 ** Initialize the state information in data
30241 */
main_init(ShellState * data)30242 static void main_init(ShellState *data) {
30243   memset(data, 0, sizeof(*data));
30244   data->normalMode = data->cMode = data->mode = MODE_List;
30245   data->autoExplain = 1;
30246   data->pAuxDb = &data->aAuxDb[0];
30247   memcpy(data->colSeparator,SEP_Column, 2);
30248   memcpy(data->rowSeparator,SEP_Row, 2);
30249   data->showHeader = 0;
30250   data->shellFlgs = SHFLG_Lookaside;
30251   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
30252 #if !defined(SQLITE_SHELL_FIDDLE)
30253   verify_uninitialized();
30254 #endif
30255   sqlite3_config(SQLITE_CONFIG_URI, 1);
30256   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
30257   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
30258   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
30259 }
30260 
30261 /*
30262 ** Output text to the console in a font that attracts extra attention.
30263 */
30264 #if defined(_WIN32) || defined(WIN32)
printBold(const char * zText)30265 static void printBold(const char *zText){
30266 #if !SQLITE_OS_WINRT
30267   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
30268   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
30269   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
30270   SetConsoleTextAttribute(out,
30271          FOREGROUND_RED|FOREGROUND_INTENSITY
30272   );
30273 #endif
30274   sputz(stdout, zText);
30275 #if !SQLITE_OS_WINRT
30276   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
30277 #endif
30278 }
30279 #else
printBold(const char * zText)30280 static void printBold(const char *zText){
30281   sputf(stdout, "\033[1m%s\033[0m", zText);
30282 }
30283 #endif
30284 
30285 /*
30286 ** Get the argument to an --option.  Throw an error and die if no argument
30287 ** is available.
30288 */
cmdline_option_value(int argc,char ** argv,int i)30289 static char *cmdline_option_value(int argc, char **argv, int i){
30290   if( i==argc ){
30291     eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
30292     exit(1);
30293   }
30294   return argv[i];
30295 }
30296 
sayAbnormalExit(void)30297 static void sayAbnormalExit(void){
30298   if( seenInterrupt ) eputz("Program interrupted.\n");
30299 }
30300 
30301 #ifndef SQLITE_SHELL_IS_UTF8
30302 #  if (defined(_WIN32) || defined(WIN32)) \
30303    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
30304 #    define SQLITE_SHELL_IS_UTF8          (0)
30305 #  else
30306 #    define SQLITE_SHELL_IS_UTF8          (1)
30307 #  endif
30308 #endif
30309 
30310 #ifdef SQLITE_SHELL_FIDDLE
30311 #  define main fiddle_main
30312 #endif
30313 
30314 #if SQLITE_SHELL_IS_UTF8
main(int argc,char ** argv)30315 int SQLITE_CDECL main(int argc, char **argv){
30316 #else
30317 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
30318   char **argv;
30319 #endif
30320 #ifdef SQLITE_DEBUG
30321   sqlite3_int64 mem_main_enter = 0;
30322 #endif
30323   char *zErrMsg = 0;
30324 #ifdef SQLITE_SHELL_FIDDLE
30325 #  define data shellState
30326 #else
30327   ShellState data;
30328   StreamsAreConsole consStreams = SAC_NoConsole;
30329 #endif
30330   const char *zInitFile = 0;
30331   int i;
30332   int rc = 0;
30333   int warnInmemoryDb = 0;
30334   int readStdin = 1;
30335   int nCmd = 0;
30336   int nOptsEnd = argc;
30337   char **azCmd = 0;
30338   const char *zVfs = 0;           /* Value of -vfs command-line option */
30339 #if !SQLITE_SHELL_IS_UTF8
30340   char **argvToFree = 0;
30341   int argcToFree = 0;
30342 #endif
30343   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
30344 
30345 #ifdef SQLITE_SHELL_FIDDLE
30346   stdin_is_interactive = 0;
30347   stdout_is_console = 1;
30348   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
30349 #else
30350   consStreams = consoleClassifySetup(stdin, stdout, stderr);
30351   stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
30352   stdout_is_console = (consStreams & SAC_OutConsole)!=0;
30353   atexit(consoleRestore);
30354 #endif
30355   atexit(sayAbnormalExit);
30356 #ifdef SQLITE_DEBUG
30357   mem_main_enter = sqlite3_memory_used();
30358 #endif
30359 #if !defined(_WIN32_WCE)
30360   if( getenv("SQLITE_DEBUG_BREAK") ){
30361     if( isatty(0) && isatty(2) ){
30362       eputf("attach debugger to process %d and press any key to continue.\n",
30363             GETPID());
30364       fgetc(stdin);
30365     }else{
30366 #if defined(_WIN32) || defined(WIN32)
30367 #if SQLITE_OS_WINRT
30368       __debugbreak();
30369 #else
30370       DebugBreak();
30371 #endif
30372 #elif defined(SIGTRAP)
30373       raise(SIGTRAP);
30374 #endif
30375     }
30376   }
30377 #endif
30378   /* Register a valid signal handler early, before much else is done. */
30379 #ifdef SIGINT
30380   signal(SIGINT, interrupt_handler);
30381 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
30382   if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
30383     eputz("No ^C handler.\n");
30384   }
30385 #endif
30386 
30387 #if USE_SYSTEM_SQLITE+0!=1
30388   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
30389     eputf("SQLite header and source version mismatch\n%s\n%s\n",
30390           sqlite3_sourceid(), SQLITE_SOURCE_ID);
30391     exit(1);
30392   }
30393 #endif
30394   main_init(&data);
30395 
30396   /* On Windows, we must translate command-line arguments into UTF-8.
30397   ** The SQLite memory allocator subsystem has to be enabled in order to
30398   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
30399   ** subsequent sqlite3_config() calls will work.  So copy all results into
30400   ** memory that does not come from the SQLite memory allocator.
30401   */
30402 #if !SQLITE_SHELL_IS_UTF8
30403   sqlite3_initialize();
30404   argvToFree = malloc(sizeof(argv[0])*argc*2);
30405   shell_check_oom(argvToFree);
30406   argcToFree = argc;
30407   argv = argvToFree + argc;
30408   for(i=0; i<argc; i++){
30409     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
30410     i64 n;
30411     shell_check_oom(z);
30412     n = strlen(z);
30413     argv[i] = malloc( n+1 );
30414     shell_check_oom(argv[i]);
30415     memcpy(argv[i], z, n+1);
30416     argvToFree[i] = argv[i];
30417     sqlite3_free(z);
30418   }
30419   sqlite3_shutdown();
30420 #endif
30421 
30422   assert( argc>=1 && argv && argv[0] );
30423   Argv0 = argv[0];
30424 
30425 #ifdef SQLITE_SHELL_DBNAME_PROC
30426   {
30427     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
30428     ** of a C-function that will provide the name of the database file.  Use
30429     ** this compile-time option to embed this shell program in larger
30430     ** applications. */
30431     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
30432     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
30433     warnInmemoryDb = 0;
30434   }
30435 #endif
30436 
30437   /* Do an initial pass through the command-line argument to locate
30438   ** the name of the database file, the name of the initialization file,
30439   ** the size of the alternative malloc heap, options affecting commands
30440   ** or SQL run from the command line, and the first command to execute.
30441   */
30442 #ifndef SQLITE_SHELL_FIDDLE
30443   verify_uninitialized();
30444 #endif
30445   for(i=1; i<argc; i++){
30446     char *z;
30447     z = argv[i];
30448     if( z[0]!='-' || i>nOptsEnd ){
30449       if( data.aAuxDb->zDbFilename==0 ){
30450         data.aAuxDb->zDbFilename = z;
30451       }else{
30452         /* Excess arguments are interpreted as SQL (or dot-commands) and
30453         ** mean that nothing is read from stdin */
30454         readStdin = 0;
30455         nCmd++;
30456         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
30457         shell_check_oom(azCmd);
30458         azCmd[nCmd-1] = z;
30459       }
30460       continue;
30461     }
30462     if( z[1]=='-' ) z++;
30463     if( cli_strcmp(z, "-")==0 ){
30464       nOptsEnd = i;
30465       continue;
30466     }else if( cli_strcmp(z,"-separator")==0
30467      || cli_strcmp(z,"-nullvalue")==0
30468      || cli_strcmp(z,"-newline")==0
30469      || cli_strcmp(z,"-cmd")==0
30470     ){
30471       (void)cmdline_option_value(argc, argv, ++i);
30472     }else if( cli_strcmp(z,"-init")==0 ){
30473       zInitFile = cmdline_option_value(argc, argv, ++i);
30474     }else if( cli_strcmp(z,"-interactive")==0 ){
30475     }else if( cli_strcmp(z,"-batch")==0 ){
30476       /* Need to check for batch mode here to so we can avoid printing
30477       ** informational messages (like from process_sqliterc) before
30478       ** we do the actual processing of arguments later in a second pass.
30479       */
30480       stdin_is_interactive = 0;
30481     }else if( cli_strcmp(z,"-utf8")==0 ){
30482     }else if( cli_strcmp(z,"-no-utf8")==0 ){
30483     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
30484       int val = 0;
30485       sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
30486       assert( val==0 );
30487     }else if( cli_strcmp(z,"-heap")==0 ){
30488 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
30489       const char *zSize;
30490       sqlite3_int64 szHeap;
30491 
30492       zSize = cmdline_option_value(argc, argv, ++i);
30493       szHeap = integerValue(zSize);
30494       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
30495       verify_uninitialized();
30496       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
30497 #else
30498       (void)cmdline_option_value(argc, argv, ++i);
30499 #endif
30500     }else if( cli_strcmp(z,"-pagecache")==0 ){
30501       sqlite3_int64 n, sz;
30502       sz = integerValue(cmdline_option_value(argc,argv,++i));
30503       if( sz>70000 ) sz = 70000;
30504       if( sz<0 ) sz = 0;
30505       n = integerValue(cmdline_option_value(argc,argv,++i));
30506       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
30507         n = 0xffffffffffffLL/sz;
30508       }
30509       verify_uninitialized();
30510       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
30511                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
30512       data.shellFlgs |= SHFLG_Pagecache;
30513     }else if( cli_strcmp(z,"-lookaside")==0 ){
30514       int n, sz;
30515       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
30516       if( sz<0 ) sz = 0;
30517       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
30518       if( n<0 ) n = 0;
30519       verify_uninitialized();
30520       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
30521       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
30522     }else if( cli_strcmp(z,"-threadsafe")==0 ){
30523       int n;
30524       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
30525       verify_uninitialized();
30526       switch( n ){
30527          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
30528          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
30529          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
30530       }
30531 #ifdef SQLITE_ENABLE_VFSTRACE
30532     }else if( cli_strcmp(z,"-vfstrace")==0 ){
30533       extern int vfstrace_register(
30534          const char *zTraceName,
30535          const char *zOldVfsName,
30536          int (*xOut)(const char*,void*),
30537          void *pOutArg,
30538          int makeDefault
30539       );
30540       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
30541 #endif
30542 #ifdef SQLITE_ENABLE_MULTIPLEX
30543     }else if( cli_strcmp(z,"-multiplex")==0 ){
30544       extern int sqlite3_multiplex_initialize(const char*,int);
30545       sqlite3_multiplex_initialize(0, 1);
30546 #endif
30547     }else if( cli_strcmp(z,"-mmap")==0 ){
30548       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
30549       verify_uninitialized();
30550       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
30551 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
30552     }else if( cli_strcmp(z,"-sorterref")==0 ){
30553       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
30554       verify_uninitialized();
30555       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
30556 #endif
30557     }else if( cli_strcmp(z,"-vfs")==0 ){
30558       zVfs = cmdline_option_value(argc, argv, ++i);
30559 #ifdef SQLITE_HAVE_ZLIB
30560     }else if( cli_strcmp(z,"-zip")==0 ){
30561       data.openMode = SHELL_OPEN_ZIPFILE;
30562 #endif
30563     }else if( cli_strcmp(z,"-append")==0 ){
30564       data.openMode = SHELL_OPEN_APPENDVFS;
30565 #ifndef SQLITE_OMIT_DESERIALIZE
30566     }else if( cli_strcmp(z,"-deserialize")==0 ){
30567       data.openMode = SHELL_OPEN_DESERIALIZE;
30568     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
30569       data.szMax = integerValue(argv[++i]);
30570 #endif
30571     }else if( cli_strcmp(z,"-readonly")==0 ){
30572       data.openMode = SHELL_OPEN_READONLY;
30573     }else if( cli_strcmp(z,"-nofollow")==0 ){
30574       data.openFlags = SQLITE_OPEN_NOFOLLOW;
30575 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
30576     }else if( cli_strncmp(z, "-A",2)==0 ){
30577       /* All remaining command-line arguments are passed to the ".archive"
30578       ** command, so ignore them */
30579       break;
30580 #endif
30581     }else if( cli_strcmp(z, "-memtrace")==0 ){
30582       sqlite3MemTraceActivate(stderr);
30583     }else if( cli_strcmp(z, "-pcachetrace")==0 ){
30584       sqlite3PcacheTraceActivate(stderr);
30585     }else if( cli_strcmp(z,"-bail")==0 ){
30586       bail_on_error = 1;
30587     }else if( cli_strcmp(z,"-nonce")==0 ){
30588       free(data.zNonce);
30589       data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
30590     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
30591       ShellSetFlag(&data,SHFLG_TestingMode);
30592     }else if( cli_strcmp(z,"-safe")==0 ){
30593       /* no-op - catch this on the second pass */
30594     }
30595   }
30596 #ifndef SQLITE_SHELL_FIDDLE
30597   verify_uninitialized();
30598 #endif
30599 
30600 
30601 #ifdef SQLITE_SHELL_INIT_PROC
30602   {
30603     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
30604     ** of a C-function that will perform initialization actions on SQLite that
30605     ** occur just before or after sqlite3_initialize(). Use this compile-time
30606     ** option to embed this shell program in larger applications. */
30607     extern void SQLITE_SHELL_INIT_PROC(void);
30608     SQLITE_SHELL_INIT_PROC();
30609   }
30610 #else
30611   /* All the sqlite3_config() calls have now been made. So it is safe
30612   ** to call sqlite3_initialize() and process any command line -vfs option. */
30613   sqlite3_initialize();
30614 #endif
30615 
30616   if( zVfs ){
30617     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
30618     if( pVfs ){
30619       sqlite3_vfs_register(pVfs, 1);
30620     }else{
30621       eputf("no such VFS: \"%s\"\n", zVfs);
30622       exit(1);
30623     }
30624   }
30625 
30626   if( data.pAuxDb->zDbFilename==0 ){
30627 #ifndef SQLITE_OMIT_MEMORYDB
30628     data.pAuxDb->zDbFilename = ":memory:";
30629     warnInmemoryDb = argc==1;
30630 #else
30631     eputf("%s: Error: no database filename specified\n", Argv0);
30632     return 1;
30633 #endif
30634   }
30635   data.out = stdout;
30636 #ifndef SQLITE_SHELL_FIDDLE
30637   sqlite3_appendvfs_init(0,0,0);
30638 #endif
30639 
30640   /* Go ahead and open the database file if it already exists.  If the
30641   ** file does not exist, delay opening it.  This prevents empty database
30642   ** files from being created if a user mistypes the database name argument
30643   ** to the sqlite command-line tool.
30644   */
30645   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
30646     open_db(&data, 0);
30647   }
30648 
30649   /* Process the initialization file if there is one.  If no -init option
30650   ** is given on the command line, look for a file named ~/.sqliterc and
30651   ** try to process it.
30652   */
30653   process_sqliterc(&data,zInitFile);
30654 
30655   /* Make a second pass through the command-line argument and set
30656   ** options.  This second pass is delayed until after the initialization
30657   ** file is processed so that the command-line arguments will override
30658   ** settings in the initialization file.
30659   */
30660   for(i=1; i<argc; i++){
30661     char *z = argv[i];
30662     if( z[0]!='-' || i>=nOptsEnd ) continue;
30663     if( z[1]=='-' ){ z++; }
30664     if( cli_strcmp(z,"-init")==0 ){
30665       i++;
30666     }else if( cli_strcmp(z,"-html")==0 ){
30667       data.mode = MODE_Html;
30668     }else if( cli_strcmp(z,"-list")==0 ){
30669       data.mode = MODE_List;
30670     }else if( cli_strcmp(z,"-quote")==0 ){
30671       data.mode = MODE_Quote;
30672       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
30673       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
30674     }else if( cli_strcmp(z,"-line")==0 ){
30675       data.mode = MODE_Line;
30676     }else if( cli_strcmp(z,"-column")==0 ){
30677       data.mode = MODE_Column;
30678     }else if( cli_strcmp(z,"-json")==0 ){
30679       data.mode = MODE_Json;
30680     }else if( cli_strcmp(z,"-markdown")==0 ){
30681       data.mode = MODE_Markdown;
30682     }else if( cli_strcmp(z,"-table")==0 ){
30683       data.mode = MODE_Table;
30684     }else if( cli_strcmp(z,"-box")==0 ){
30685       data.mode = MODE_Box;
30686     }else if( cli_strcmp(z,"-csv")==0 ){
30687       data.mode = MODE_Csv;
30688       memcpy(data.colSeparator,",",2);
30689 #ifdef SQLITE_HAVE_ZLIB
30690     }else if( cli_strcmp(z,"-zip")==0 ){
30691       data.openMode = SHELL_OPEN_ZIPFILE;
30692 #endif
30693     }else if( cli_strcmp(z,"-append")==0 ){
30694       data.openMode = SHELL_OPEN_APPENDVFS;
30695 #ifndef SQLITE_OMIT_DESERIALIZE
30696     }else if( cli_strcmp(z,"-deserialize")==0 ){
30697       data.openMode = SHELL_OPEN_DESERIALIZE;
30698     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
30699       data.szMax = integerValue(argv[++i]);
30700 #endif
30701     }else if( cli_strcmp(z,"-readonly")==0 ){
30702       data.openMode = SHELL_OPEN_READONLY;
30703     }else if( cli_strcmp(z,"-nofollow")==0 ){
30704       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
30705     }else if( cli_strcmp(z,"-ascii")==0 ){
30706       data.mode = MODE_Ascii;
30707       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
30708       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
30709     }else if( cli_strcmp(z,"-tabs")==0 ){
30710       data.mode = MODE_List;
30711       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
30712       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
30713     }else if( cli_strcmp(z,"-separator")==0 ){
30714       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
30715                        "%s",cmdline_option_value(argc,argv,++i));
30716     }else if( cli_strcmp(z,"-newline")==0 ){
30717       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
30718                        "%s",cmdline_option_value(argc,argv,++i));
30719     }else if( cli_strcmp(z,"-nullvalue")==0 ){
30720       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
30721                        "%s",cmdline_option_value(argc,argv,++i));
30722     }else if( cli_strcmp(z,"-header")==0 ){
30723       data.showHeader = 1;
30724       ShellSetFlag(&data, SHFLG_HeaderSet);
30725      }else if( cli_strcmp(z,"-noheader")==0 ){
30726       data.showHeader = 0;
30727       ShellSetFlag(&data, SHFLG_HeaderSet);
30728     }else if( cli_strcmp(z,"-echo")==0 ){
30729       ShellSetFlag(&data, SHFLG_Echo);
30730     }else if( cli_strcmp(z,"-eqp")==0 ){
30731       data.autoEQP = AUTOEQP_on;
30732     }else if( cli_strcmp(z,"-eqpfull")==0 ){
30733       data.autoEQP = AUTOEQP_full;
30734     }else if( cli_strcmp(z,"-stats")==0 ){
30735       data.statsOn = 1;
30736     }else if( cli_strcmp(z,"-scanstats")==0 ){
30737       data.scanstatsOn = 1;
30738     }else if( cli_strcmp(z,"-backslash")==0 ){
30739       /* Undocumented command-line option: -backslash
30740       ** Causes C-style backslash escapes to be evaluated in SQL statements
30741       ** prior to sending the SQL into SQLite.  Useful for injecting
30742       ** crazy bytes in the middle of SQL statements for testing and debugging.
30743       */
30744       ShellSetFlag(&data, SHFLG_Backslash);
30745     }else if( cli_strcmp(z,"-bail")==0 ){
30746       /* No-op.  The bail_on_error flag should already be set. */
30747     }else if( cli_strcmp(z,"-version")==0 ){
30748       sputf(stdout, "%s %s (%d-bit)\n",
30749             sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
30750       return 0;
30751     }else if( cli_strcmp(z,"-interactive")==0 ){
30752       /* Need to check for interactive override here to so that it can
30753       ** affect console setup (for Windows only) and testing thereof.
30754       */
30755       stdin_is_interactive = 1;
30756     }else if( cli_strcmp(z,"-batch")==0 ){
30757       /* already handled */
30758     }else if( cli_strcmp(z,"-utf8")==0 ){
30759       /* already handled */
30760     }else if( cli_strcmp(z,"-no-utf8")==0 ){
30761       /* already handled */
30762     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
30763       /* already handled */
30764     }else if( cli_strcmp(z,"-heap")==0 ){
30765       i++;
30766     }else if( cli_strcmp(z,"-pagecache")==0 ){
30767       i+=2;
30768     }else if( cli_strcmp(z,"-lookaside")==0 ){
30769       i+=2;
30770     }else if( cli_strcmp(z,"-threadsafe")==0 ){
30771       i+=2;
30772     }else if( cli_strcmp(z,"-nonce")==0 ){
30773       i += 2;
30774     }else if( cli_strcmp(z,"-mmap")==0 ){
30775       i++;
30776     }else if( cli_strcmp(z,"-memtrace")==0 ){
30777       i++;
30778     }else if( cli_strcmp(z,"-pcachetrace")==0 ){
30779       i++;
30780 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
30781     }else if( cli_strcmp(z,"-sorterref")==0 ){
30782       i++;
30783 #endif
30784     }else if( cli_strcmp(z,"-vfs")==0 ){
30785       i++;
30786 #ifdef SQLITE_ENABLE_VFSTRACE
30787     }else if( cli_strcmp(z,"-vfstrace")==0 ){
30788       i++;
30789 #endif
30790 #ifdef SQLITE_ENABLE_MULTIPLEX
30791     }else if( cli_strcmp(z,"-multiplex")==0 ){
30792       i++;
30793 #endif
30794     }else if( cli_strcmp(z,"-help")==0 ){
30795       usage(1);
30796     }else if( cli_strcmp(z,"-cmd")==0 ){
30797       /* Run commands that follow -cmd first and separately from commands
30798       ** that simply appear on the command-line.  This seems goofy.  It would
30799       ** be better if all commands ran in the order that they appear.  But
30800       ** we retain the goofy behavior for historical compatibility. */
30801       if( i==argc-1 ) break;
30802       z = cmdline_option_value(argc,argv,++i);
30803       if( z[0]=='.' ){
30804         rc = do_meta_command(z, &data);
30805         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
30806       }else{
30807         open_db(&data, 0);
30808         rc = shell_exec(&data, z, &zErrMsg);
30809         if( zErrMsg!=0 ){
30810           eputf("Error: %s\n", zErrMsg);
30811           if( bail_on_error ) return rc!=0 ? rc : 1;
30812         }else if( rc!=0 ){
30813           eputf("Error: unable to process SQL \"%s\"\n", z);
30814           if( bail_on_error ) return rc;
30815         }
30816       }
30817 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
30818     }else if( cli_strncmp(z, "-A", 2)==0 ){
30819       if( nCmd>0 ){
30820         eputf("Error: cannot mix regular SQL or dot-commands"
30821               " with \"%s\"\n", z);
30822         return 1;
30823       }
30824       open_db(&data, OPEN_DB_ZIPFILE);
30825       if( z[2] ){
30826         argv[i] = &z[2];
30827         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
30828       }else{
30829         arDotCommand(&data, 1, argv+i, argc-i);
30830       }
30831       readStdin = 0;
30832       break;
30833 #endif
30834     }else if( cli_strcmp(z,"-safe")==0 ){
30835       data.bSafeMode = data.bSafeModePersist = 1;
30836     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
30837       /* Acted upon in first pass. */
30838     }else{
30839       eputf("%s: Error: unknown option: %s\n", Argv0, z);
30840       eputz("Use -help for a list of options.\n");
30841       return 1;
30842     }
30843     data.cMode = data.mode;
30844   }
30845 
30846   if( !readStdin ){
30847     /* Run all arguments that do not begin with '-' as if they were separate
30848     ** command-line inputs, except for the argToSkip argument which contains
30849     ** the database filename.
30850     */
30851     for(i=0; i<nCmd; i++){
30852       if( azCmd[i][0]=='.' ){
30853         rc = do_meta_command(azCmd[i], &data);
30854         if( rc ){
30855           free(azCmd);
30856           return rc==2 ? 0 : rc;
30857         }
30858       }else{
30859         open_db(&data, 0);
30860         echo_group_input(&data, azCmd[i]);
30861         rc = shell_exec(&data, azCmd[i], &zErrMsg);
30862         if( zErrMsg || rc ){
30863           if( zErrMsg!=0 ){
30864             eputf("Error: %s\n", zErrMsg);
30865           }else{
30866             eputf("Error: unable to process SQL: %s\n", azCmd[i]);
30867           }
30868           sqlite3_free(zErrMsg);
30869           free(azCmd);
30870           return rc!=0 ? rc : 1;
30871         }
30872       }
30873     }
30874   }else{
30875     /* Run commands received from standard input
30876     */
30877     if( stdin_is_interactive ){
30878       char *zHome;
30879       char *zHistory;
30880       int nHistory;
30881 #if CIO_WIN_WC_XLATE
30882 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
30883 #else
30884 # define SHELL_CIO_CHAR_SET ""
30885 #endif
30886       sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
30887             "Enter \".help\" for usage hints.\n",
30888             sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
30889       if( warnInmemoryDb ){
30890         sputz(stdout, "Connected to a ");
30891         printBold("transient in-memory database");
30892         sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
30893               " persistent database.\n");
30894       }
30895       zHistory = getenv("SQLITE_HISTORY");
30896       if( zHistory ){
30897         zHistory = strdup(zHistory);
30898       }else if( (zHome = find_home_dir(0))!=0 ){
30899         nHistory = strlen30(zHome) + 20;
30900         if( (zHistory = malloc(nHistory))!=0 ){
30901           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
30902         }
30903       }
30904       if( zHistory ){ shell_read_history(zHistory); }
30905 #if HAVE_READLINE || HAVE_EDITLINE
30906       rl_attempted_completion_function = readline_completion;
30907 #elif HAVE_LINENOISE
30908       linenoiseSetCompletionCallback(linenoise_completion);
30909 #endif
30910       data.in = 0;
30911       rc = process_input(&data);
30912       if( zHistory ){
30913         shell_stifle_history(2000);
30914         shell_write_history(zHistory);
30915         free(zHistory);
30916       }
30917     }else{
30918       data.in = stdin;
30919       rc = process_input(&data);
30920     }
30921   }
30922 #ifndef SQLITE_SHELL_FIDDLE
30923   /* In WASM mode we have to leave the db state in place so that
30924   ** client code can "push" SQL into it after this call returns. */
30925 #ifndef SQLITE_OMIT_VIRTUALTABLE
30926   if( data.expert.pExpert ){
30927     expertFinish(&data, 1, 0);
30928   }
30929 #endif
30930   free(azCmd);
30931   set_table_name(&data, 0);
30932   if( data.db ){
30933     session_close_all(&data, -1);
30934     close_db(data.db);
30935   }
30936   for(i=0; i<ArraySize(data.aAuxDb); i++){
30937     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
30938     if( data.aAuxDb[i].db ){
30939       session_close_all(&data, i);
30940       close_db(data.aAuxDb[i].db);
30941     }
30942   }
30943   find_home_dir(1);
30944   output_reset(&data);
30945   data.doXdgOpen = 0;
30946   clearTempFile(&data);
30947 #if !SQLITE_SHELL_IS_UTF8
30948   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
30949   free(argvToFree);
30950 #endif
30951   free(data.colWidth);
30952   free(data.zNonce);
30953   /* Clear the global data structure so that valgrind will detect memory
30954   ** leaks */
30955   memset(&data, 0, sizeof(data));
30956 #ifdef SQLITE_DEBUG
30957   if( sqlite3_memory_used()>mem_main_enter ){
30958     eputf("Memory leaked: %u bytes\n",
30959           (unsigned int)(sqlite3_memory_used()-mem_main_enter));
30960   }
30961 #endif
30962 #endif /* !SQLITE_SHELL_FIDDLE */
30963   return rc;
30964 }
30965 
30966 
30967 #ifdef SQLITE_SHELL_FIDDLE
30968 /* Only for emcc experimentation purposes. */
30969 int fiddle_experiment(int a,int b){
30970   return a + b;
30971 }
30972 
30973 /*
30974 ** Returns a pointer to the current DB handle.
30975 */
30976 sqlite3 * fiddle_db_handle(){
30977   return globalDb;
30978 }
30979 
30980 /*
30981 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
30982 ** "main" is assumed. Returns 0 if no db with the given name is
30983 ** open.
30984 */
30985 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
30986   sqlite3_vfs * pVfs = 0;
30987   if(globalDb){
30988     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
30989                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
30990   }
30991   return pVfs;
30992 }
30993 
30994 /* Only for emcc experimentation purposes. */
30995 sqlite3 * fiddle_db_arg(sqlite3 *arg){
30996     oputf("fiddle_db_arg(%p)\n", (const void*)arg);
30997     return arg;
30998 }
30999 
31000 /*
31001 ** Intended to be called via a SharedWorker() while a separate
31002 ** SharedWorker() (which manages the wasm module) is performing work
31003 ** which should be interrupted. Unfortunately, SharedWorker is not
31004 ** portable enough to make real use of.
31005 */
31006 void fiddle_interrupt(void){
31007   if( globalDb ) sqlite3_interrupt(globalDb);
31008 }
31009 
31010 /*
31011 ** Returns the filename of the given db name, assuming "main" if
31012 ** zDbName is NULL. Returns NULL if globalDb is not opened.
31013 */
31014 const char * fiddle_db_filename(const char * zDbName){
31015     return globalDb
31016       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
31017       : NULL;
31018 }
31019 
31020 /*
31021 ** Completely wipes out the contents of the currently-opened database
31022 ** but leaves its storage intact for reuse. If any transactions are
31023 ** active, they are forcibly rolled back.
31024 */
31025 void fiddle_reset_db(void){
31026   if( globalDb ){
31027     int rc;
31028     while( sqlite3_txn_state(globalDb,0)>0 ){
31029       /*
31030       ** Resolve problem reported in
31031       ** https://sqlite.org/forum/forumpost/0b41a25d65
31032       */
31033       oputz("Rolling back in-progress transaction.\n");
31034       sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
31035     }
31036     rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
31037     if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
31038     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
31039   }
31040 }
31041 
31042 /*
31043 ** Uses the current database's VFS xRead to stream the db file's
31044 ** contents out to the given callback. The callback gets a single
31045 ** chunk of size n (its 2nd argument) on each call and must return 0
31046 ** on success, non-0 on error. This function returns 0 on success,
31047 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
31048 ** code from the callback. Note that this is not thread-friendly: it
31049 ** expects that it will be the only thread reading the db file and
31050 ** takes no measures to ensure that is the case.
31051 */
31052 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
31053   sqlite3_int64 nSize = 0;
31054   sqlite3_int64 nPos = 0;
31055   sqlite3_file * pFile = 0;
31056   unsigned char buf[1024 * 8];
31057   int nBuf = (int)sizeof(buf);
31058   int rc = shellState.db
31059     ? sqlite3_file_control(shellState.db, "main",
31060                            SQLITE_FCNTL_FILE_POINTER, &pFile)
31061     : SQLITE_NOTFOUND;
31062   if( rc ) return rc;
31063   rc = pFile->pMethods->xFileSize(pFile, &nSize);
31064   if( rc ) return rc;
31065   if(nSize % nBuf){
31066     /* DB size is not an even multiple of the buffer size. Reduce
31067     ** buffer size so that we do not unduly inflate the db size when
31068     ** exporting. */
31069     if(0 == nSize % 4096) nBuf = 4096;
31070     else if(0 == nSize % 2048) nBuf = 2048;
31071     else if(0 == nSize % 1024) nBuf = 1024;
31072     else nBuf = 512;
31073   }
31074   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
31075     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
31076     if(SQLITE_IOERR_SHORT_READ == rc){
31077       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
31078     }
31079     if( 0==rc ) rc = xCallback(buf, nBuf);
31080   }
31081   return rc;
31082 }
31083 
31084 /*
31085 ** Trivial exportable function for emscripten. It processes zSql as if
31086 ** it were input to the sqlite3 shell and redirects all output to the
31087 ** wasm binding. fiddle_main() must have been called before this
31088 ** is called, or results are undefined.
31089 */
31090 void fiddle_exec(const char * zSql){
31091   if(zSql && *zSql){
31092     if('.'==*zSql) puts(zSql);
31093     shellState.wasm.zInput = zSql;
31094     shellState.wasm.zPos = zSql;
31095     process_input(&shellState);
31096     shellState.wasm.zInput = shellState.wasm.zPos = 0;
31097   }
31098 }
31099 #endif /* SQLITE_SHELL_FIDDLE */
31100