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
37typedef unsigned int u32;
38typedef 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"
122typedef sqlite3_int64 i64;
123typedef sqlite3_uint64 u64;
124typedef 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 */
254extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
255extern 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. */
314typedef 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*/
337SQLITE_INTERNAL_LINKAGE StreamsAreConsole
338consoleClassifySetup( 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*/
351SQLITE_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*/
367SQLITE_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*/
391SQLITE_INTERNAL_LINKAGE FILE *invalidFileStream;
392SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf);
393# ifdef CONSIO_SET_ERROR_STREAM
394SQLITE_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*/
409SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...);
410/* Like fPrintfUtf8 except stream is always the designated output. */
411SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...);
412/* Like fPrintfUtf8 except stream is always the designated error. */
413SQLITE_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*/
422SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO);
423/* Like fPutsUtf8 except stream is always the designated output. */
424SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z);
425/* Like fPutsUtf8 except stream is always the designated error. */
426SQLITE_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
435SQLITE_INTERNAL_LINKAGE int
436fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
437/* Like fPutbUtf8 except stream is always the designated output. */
438#endif
439SQLITE_INTERNAL_LINKAGE int
440oPutbUtf8(const char *cBuf, int nAccept);
441/* Like fPutbUtf8 except stream is always the designated error. */
442#ifdef CONSIO_EPUTB
443SQLITE_INTERNAL_LINKAGE int
444ePutbUtf8(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*/
454SQLITE_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*/
474SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *, short bFlush);
475SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *, short bFlush);
476#endif
477
478#ifdef SQLITE_CIO_PROMPTED_IN
479typedef 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*/
523SQLITE_INTERNAL_LINKAGE char *
524shellGetLine(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 */
545SQLITE_INTERNAL_LINKAGE const char*
546zSkipValidUtf8(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
584#ifndef SQLITE_CIO_NO_TRANSLATE
585# if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
586#  ifndef SHELL_NO_SYSINC
587#   include <io.h>
588#   include <fcntl.h>
589#   undef WIN32_LEAN_AND_MEAN
590#   define WIN32_LEAN_AND_MEAN
591#   include <windows.h>
592#  endif
593#  define CIO_WIN_WC_XLATE 1 /* Use WCHAR Windows APIs for console I/O */
594# else
595#  ifndef SHELL_NO_SYSINC
596#   include <unistd.h>
597#  endif
598#  define CIO_WIN_WC_XLATE 0 /* Use plain C library stream I/O at console */
599# endif
600#else
601# define CIO_WIN_WC_XLATE 0 /* Not exposing translation routines at all */
602#endif
603
604#if CIO_WIN_WC_XLATE
605/* Character used to represent a known-incomplete UTF-8 char group (���) */
606static WCHAR cBadGroup = 0xfffd;
607#endif
608
609#if CIO_WIN_WC_XLATE
610static HANDLE handleOfFile(FILE *pf){
611  int fileDesc = _fileno(pf);
612  union { intptr_t osfh; HANDLE fh; } fid = {
613    (fileDesc>=0)? _get_osfhandle(fileDesc) : (intptr_t)INVALID_HANDLE_VALUE
614  };
615  return fid.fh;
616}
617#endif
618
619#ifndef SQLITE_CIO_NO_TRANSLATE
620typedef struct PerStreamTags {
621# if CIO_WIN_WC_XLATE
622  HANDLE hx;
623  DWORD consMode;
624  char acIncomplete[4];
625# else
626  short reachesConsole;
627# endif
628  FILE *pf;
629} PerStreamTags;
630
631/* Define NULL-like value for things which can validly be 0. */
632# define SHELL_INVALID_FILE_PTR ((FILE *)~0)
633# if CIO_WIN_WC_XLATE
634#  define SHELL_INVALID_CONS_MODE 0xFFFF0000
635# endif
636
637# if CIO_WIN_WC_XLATE
638#  define PST_INITIALIZER { INVALID_HANDLE_VALUE, SHELL_INVALID_CONS_MODE, \
639      {0,0,0,0}, SHELL_INVALID_FILE_PTR }
640# else
641#  define PST_INITIALIZER { 0, SHELL_INVALID_FILE_PTR }
642# endif
643
644/* Quickly say whether a known output is going to the console. */
645# if CIO_WIN_WC_XLATE
646static short pstReachesConsole(PerStreamTags *ppst){
647  return (ppst->hx != INVALID_HANDLE_VALUE);
648}
649# else
650#  define pstReachesConsole(ppst) 0
651# endif
652
653# if CIO_WIN_WC_XLATE
654static void restoreConsoleArb(PerStreamTags *ppst){
655  if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode);
656}
657# else
658#  define restoreConsoleArb(ppst)
659# endif
660
661/* Say whether FILE* appears to be a console, collect associated info. */
662static short streamOfConsole(FILE *pf, /* out */ PerStreamTags *ppst){
663# if CIO_WIN_WC_XLATE
664  short rv = 0;
665  DWORD dwCM = SHELL_INVALID_CONS_MODE;
666  HANDLE fh = handleOfFile(pf);
667  ppst->pf = pf;
668  if( INVALID_HANDLE_VALUE != fh ){
669    rv = (GetFileType(fh) == FILE_TYPE_CHAR && GetConsoleMode(fh,&dwCM));
670  }
671  ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE;
672  ppst->consMode = dwCM;
673  return rv;
674# else
675  ppst->pf = pf;
676  ppst->reachesConsole = ( (short)isatty(fileno(pf)) );
677  return ppst->reachesConsole;
678# endif
679}
680
681# if CIO_WIN_WC_XLATE
682/* Define console modes for use with the Windows Console API. */
683#  define SHELL_CONI_MODE \
684  (ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE | ENABLE_LINE_INPUT | 0x80 \
685  | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS | ENABLE_PROCESSED_INPUT)
686#  define SHELL_CONO_MODE (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT \
687  | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
688# endif
689
690typedef struct ConsoleInfo {
691  PerStreamTags pstSetup[3];
692  PerStreamTags pstDesignated[3];
693  StreamsAreConsole sacSetup;
694} ConsoleInfo;
695
696static short isValidStreamInfo(PerStreamTags *ppst){
697  return (ppst->pf != SHELL_INVALID_FILE_PTR);
698}
699
700static ConsoleInfo consoleInfo = {
701  { /* pstSetup */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
702  { /* pstDesignated[] */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
703  SAC_NoConsole /* sacSetup */
704};
705
706SQLITE_INTERNAL_LINKAGE FILE* invalidFileStream = (FILE *)~0;
707
708# if CIO_WIN_WC_XLATE
709static void maybeSetupAsConsole(PerStreamTags *ppst, short odir){
710  if( pstReachesConsole(ppst) ){
711    DWORD cm = odir? SHELL_CONO_MODE : SHELL_CONI_MODE;
712    SetConsoleMode(ppst->hx, cm);
713  }
714}
715# else
716#  define maybeSetupAsConsole(ppst,odir)
717# endif
718
719SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void){
720# if CIO_WIN_WC_XLATE
721  int ix = 0;
722  while( ix < 6 ){
723    PerStreamTags *ppst = (ix<3)?
724      &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3];
725    maybeSetupAsConsole(ppst, (ix % 3)>0);
726    ++ix;
727  }
728# endif
729}
730
731SQLITE_INTERNAL_LINKAGE StreamsAreConsole
732consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr ){
733  StreamsAreConsole rv = SAC_NoConsole;
734  FILE* apf[3] = { pfIn, pfOut, pfErr };
735  int ix;
736  for( ix = 2; ix >= 0; --ix ){
737    PerStreamTags *ppst = &consoleInfo.pstSetup[ix];
738    if( streamOfConsole(apf[ix], ppst) ){
739      rv |= (SAC_InConsole<<ix);
740    }
741    consoleInfo.pstDesignated[ix] = *ppst;
742    if( ix > 0 ) fflush(apf[ix]);
743  }
744  consoleInfo.sacSetup = rv;
745  consoleRenewSetup();
746  return rv;
747}
748
749SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void ){
750# if CIO_WIN_WC_XLATE
751  static ConsoleInfo *pci = &consoleInfo;
752  if( pci->sacSetup ){
753    int ix;
754    for( ix=0; ix<3; ++ix ){
755      if( pci->sacSetup & (SAC_InConsole<<ix) ){
756        PerStreamTags *ppst = &pci->pstSetup[ix];
757        SetConsoleMode(ppst->hx, ppst->consMode);
758      }
759    }
760  }
761# endif
762}
763#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
764
765#ifdef SQLITE_CIO_INPUT_REDIR
766/* Say whether given FILE* is among those known, via either
767** consoleClassifySetup() or set{Output,Error}Stream, as
768** readable, and return an associated PerStreamTags pointer
769** if so. Otherwise, return 0.
770*/
771static PerStreamTags * isKnownReadable(FILE *pf){
772  static PerStreamTags *apst[] = {
773    &consoleInfo.pstDesignated[0], &consoleInfo.pstSetup[0], 0
774  };
775  int ix = 0;
776  do {
777    if( apst[ix]->pf == pf ) break;
778  } while( apst[++ix] != 0 );
779  return apst[ix];
780}
781#endif
782
783#ifndef SQLITE_CIO_NO_TRANSLATE
784/* Say whether given FILE* is among those known, via either
785** consoleClassifySetup() or set{Output,Error}Stream, as
786** writable, and return an associated PerStreamTags pointer
787** if so. Otherwise, return 0.
788*/
789static PerStreamTags * isKnownWritable(FILE *pf){
790  static PerStreamTags *apst[] = {
791    &consoleInfo.pstDesignated[1], &consoleInfo.pstDesignated[2],
792    &consoleInfo.pstSetup[1], &consoleInfo.pstSetup[2], 0
793  };
794  int ix = 0;
795  do {
796    if( apst[ix]->pf == pf ) break;
797  } while( apst[++ix] != 0 );
798  return apst[ix];
799}
800
801static FILE *designateEmitStream(FILE *pf, unsigned chix){
802  FILE *rv = consoleInfo.pstDesignated[chix].pf;
803  if( pf == invalidFileStream ) return rv;
804  else{
805    /* Setting a possibly new output stream. */
806    PerStreamTags *ppst = isKnownWritable(pf);
807    if( ppst != 0 ){
808      PerStreamTags pst = *ppst;
809      consoleInfo.pstDesignated[chix] = pst;
810    }else streamOfConsole(pf, &consoleInfo.pstDesignated[chix]);
811  }
812  return rv;
813}
814
815SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf){
816  return designateEmitStream(pf, 1);
817}
818# ifdef CONSIO_SET_ERROR_STREAM
819SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf){
820  return designateEmitStream(pf, 2);
821}
822# endif
823#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
824
825#ifndef SQLITE_CIO_NO_SETMODE
826# if CIO_WIN_WC_XLATE
827static void setModeFlushQ(FILE *pf, short bFlush, int mode){
828  if( bFlush ) fflush(pf);
829  _setmode(_fileno(pf), mode);
830}
831# else
832#  define setModeFlushQ(f, b, m) if(b) fflush(f)
833# endif
834
835SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *pf, short bFlush){
836  setModeFlushQ(pf, bFlush, _O_BINARY);
837}
838SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *pf, short bFlush){
839  setModeFlushQ(pf, bFlush, _O_TEXT);
840}
841# undef setModeFlushQ
842
843#else /* defined(SQLITE_CIO_NO_SETMODE) */
844# define setBinaryMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
845# define setTextMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
846#endif /* defined(SQLITE_CIO_NO_SETMODE) */
847
848#ifndef SQLITE_CIO_NO_TRANSLATE
849# if CIO_WIN_WC_XLATE
850/* Write buffer cBuf as output to stream known to reach console,
851** limited to ncTake char's. Return ncTake on success, else 0. */
852static int conZstrEmit(PerStreamTags *ppst, const char *z, int ncTake){
853  int rv = 0;
854  if( z!=NULL ){
855    int nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, 0,0);
856    if( nwc > 0 ){
857      WCHAR *zw = sqlite3_malloc64(nwc*sizeof(WCHAR));
858      if( zw!=NULL ){
859        nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, zw,nwc);
860        if( nwc > 0 ){
861          /* Translation from UTF-8 to UTF-16, then WCHARs out. */
862          if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){
863            rv = ncTake;
864          }
865        }
866        sqlite3_free(zw);
867      }
868    }
869  }
870  return rv;
871}
872
873/* For {f,o,e}PrintfUtf8() when stream is known to reach console. */
874static int conioVmPrintf(PerStreamTags *ppst, const char *zFormat, va_list ap){
875  char *z = sqlite3_vmprintf(zFormat, ap);
876  if( z ){
877    int rv = conZstrEmit(ppst, z, (int)strlen(z));
878    sqlite3_free(z);
879    return rv;
880  }else return 0;
881}
882# endif /* CIO_WIN_WC_XLATE */
883
884# ifdef CONSIO_GET_EMIT_STREAM
885static PerStreamTags * getDesignatedEmitStream(FILE *pf, unsigned chix,
886                                               PerStreamTags *ppst){
887  PerStreamTags *rv = isKnownWritable(pf);
888  short isValid = (rv!=0)? isValidStreamInfo(rv) : 0;
889  if( rv != 0 && isValid ) return rv;
890  streamOfConsole(pf, ppst);
891  return ppst;
892}
893# endif
894
895/* Get stream info, either for designated output or error stream when
896** chix equals 1 or 2, or for an arbitrary stream when chix == 0.
897** In either case, ppst references a caller-owned PerStreamTags
898** struct which may be filled in if none of the known writable
899** streams is being held by consoleInfo. The ppf parameter is a
900** byref output when chix!=0 and a byref input when chix==0.
901 */
902static PerStreamTags *
903getEmitStreamInfo(unsigned chix, PerStreamTags *ppst,
904                  /* in/out */ FILE **ppf){
905  PerStreamTags *ppstTry;
906  FILE *pfEmit;
907  if( chix > 0 ){
908    ppstTry = &consoleInfo.pstDesignated[chix];
909    if( !isValidStreamInfo(ppstTry) ){
910      ppstTry = &consoleInfo.pstSetup[chix];
911      pfEmit = ppst->pf;
912    }else pfEmit = ppstTry->pf;
913    if( !isValidStreamInfo(ppstTry) ){
914      pfEmit = (chix > 1)? stderr : stdout;
915      ppstTry = ppst;
916      streamOfConsole(pfEmit, ppstTry);
917    }
918    *ppf = pfEmit;
919  }else{
920    ppstTry = isKnownWritable(*ppf);
921    if( ppstTry != 0 ) return ppstTry;
922    streamOfConsole(*ppf, ppst);
923    return ppst;
924  }
925  return ppstTry;
926}
927
928SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...){
929  va_list ap;
930  int rv;
931  FILE *pfOut;
932  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
933# if CIO_WIN_WC_XLATE
934  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
935# else
936  getEmitStreamInfo(1, &pst, &pfOut);
937# endif
938  assert(zFormat!=0);
939  va_start(ap, zFormat);
940# if CIO_WIN_WC_XLATE
941  if( pstReachesConsole(ppst) ){
942    rv = conioVmPrintf(ppst, zFormat, ap);
943  }else{
944# endif
945    rv = vfprintf(pfOut, zFormat, ap);
946# if CIO_WIN_WC_XLATE
947  }
948# endif
949  va_end(ap);
950  return rv;
951}
952
953SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...){
954  va_list ap;
955  int rv;
956  FILE *pfErr;
957  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
958# if CIO_WIN_WC_XLATE
959  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
960# else
961  getEmitStreamInfo(2, &pst, &pfErr);
962# endif
963  assert(zFormat!=0);
964  va_start(ap, zFormat);
965# if CIO_WIN_WC_XLATE
966  if( pstReachesConsole(ppst) ){
967    rv = conioVmPrintf(ppst, zFormat, ap);
968  }else{
969# endif
970    rv = vfprintf(pfErr, zFormat, ap);
971# if CIO_WIN_WC_XLATE
972  }
973# endif
974  va_end(ap);
975  return rv;
976}
977
978SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...){
979  va_list ap;
980  int rv;
981  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
982# if CIO_WIN_WC_XLATE
983  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
984# else
985  getEmitStreamInfo(0, &pst, &pfO);
986# endif
987  assert(zFormat!=0);
988  va_start(ap, zFormat);
989# if CIO_WIN_WC_XLATE
990  if( pstReachesConsole(ppst) ){
991    maybeSetupAsConsole(ppst, 1);
992    rv = conioVmPrintf(ppst, zFormat, ap);
993    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
994  }else{
995# endif
996    rv = vfprintf(pfO, zFormat, ap);
997# if CIO_WIN_WC_XLATE
998  }
999# endif
1000  va_end(ap);
1001  return rv;
1002}
1003
1004SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO){
1005  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1006# if CIO_WIN_WC_XLATE
1007  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1008# else
1009  getEmitStreamInfo(0, &pst, &pfO);
1010# endif
1011  assert(z!=0);
1012# if CIO_WIN_WC_XLATE
1013  if( pstReachesConsole(ppst) ){
1014    int rv;
1015    maybeSetupAsConsole(ppst, 1);
1016    rv = conZstrEmit(ppst, z, (int)strlen(z));
1017    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1018    return rv;
1019  }else {
1020# endif
1021    return (fputs(z, pfO)<0)? 0 : (int)strlen(z);
1022# if CIO_WIN_WC_XLATE
1023  }
1024# endif
1025}
1026
1027SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z){
1028  FILE *pfErr;
1029  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1030# if CIO_WIN_WC_XLATE
1031  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1032# else
1033  getEmitStreamInfo(2, &pst, &pfErr);
1034# endif
1035  assert(z!=0);
1036# if CIO_WIN_WC_XLATE
1037  if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1038  else {
1039# endif
1040    return (fputs(z, pfErr)<0)? 0 : (int)strlen(z);
1041# if CIO_WIN_WC_XLATE
1042  }
1043# endif
1044}
1045
1046SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z){
1047  FILE *pfOut;
1048  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1049# if CIO_WIN_WC_XLATE
1050  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1051# else
1052  getEmitStreamInfo(1, &pst, &pfOut);
1053# endif
1054  assert(z!=0);
1055# if CIO_WIN_WC_XLATE
1056  if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1057  else {
1058# endif
1059    return (fputs(z, pfOut)<0)? 0 : (int)strlen(z);
1060# if CIO_WIN_WC_XLATE
1061  }
1062# endif
1063}
1064
1065#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1066
1067#if !(defined(SQLITE_CIO_NO_UTF8SCAN) && defined(SQLITE_CIO_NO_TRANSLATE))
1068/* Skip over as much z[] input char sequence as is valid UTF-8,
1069** limited per nAccept char's or whole characters and containing
1070** no char cn such that ((1<<cn) & ccm)!=0. On return, the
1071** sequence z:return (inclusive:exclusive) is validated UTF-8.
1072** Limit: nAccept>=0 => char count, nAccept<0 => character
1073 */
1074SQLITE_INTERNAL_LINKAGE const char*
1075zSkipValidUtf8(const char *z, int nAccept, long ccm){
1076  int ng = (nAccept<0)? -nAccept : 0;
1077  const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
1078  assert(z!=0);
1079  while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
1080    char c = *z;
1081    if( (c & 0x80) == 0 ){
1082      if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
1083      ++z; /* ASCII */
1084    }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
1085    else{
1086      const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
1087      do{
1088        if( pcLimit && zt >= pcLimit ) return z;
1089        else{
1090          char ct = *zt++;
1091          if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
1092            /* Trailing bytes are too few, too many, or invalid. */
1093            return z;
1094          }
1095        }
1096      } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
1097      z = zt;
1098    }
1099  }
1100  return z;
1101}
1102#endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
1103
1104#ifndef SQLITE_CIO_NO_TRANSLATE
1105# ifdef CONSIO_SPUTB
1106SQLITE_INTERNAL_LINKAGE int
1107fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
1108  assert(pfO!=0);
1109#  if CIO_WIN_WC_XLATE
1110  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1111  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1112  if( pstReachesConsole(ppst) ){
1113    int rv;
1114    maybeSetupAsConsole(ppst, 1);
1115    rv = conZstrEmit(ppst, cBuf, nAccept);
1116    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1117    return rv;
1118  }else {
1119#  endif
1120    return (int)fwrite(cBuf, 1, nAccept, pfO);
1121#  if CIO_WIN_WC_XLATE
1122  }
1123#  endif
1124}
1125# endif
1126
1127SQLITE_INTERNAL_LINKAGE int
1128oPutbUtf8(const char *cBuf, int nAccept){
1129  FILE *pfOut;
1130  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1131# if CIO_WIN_WC_XLATE
1132  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1133# else
1134  getEmitStreamInfo(1, &pst, &pfOut);
1135# endif
1136# if CIO_WIN_WC_XLATE
1137  if( pstReachesConsole(ppst) ){
1138    return conZstrEmit(ppst, cBuf, nAccept);
1139  }else {
1140# endif
1141    return (int)fwrite(cBuf, 1, nAccept, pfOut);
1142# if CIO_WIN_WC_XLATE
1143  }
1144# endif
1145}
1146
1147# ifdef CONSIO_EPUTB
1148SQLITE_INTERNAL_LINKAGE int
1149ePutbUtf8(const char *cBuf, int nAccept){
1150  FILE *pfErr;
1151  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1152  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1153#  if CIO_WIN_WC_XLATE
1154  if( pstReachesConsole(ppst) ){
1155    return conZstrEmit(ppst, cBuf, nAccept);
1156  }else {
1157#  endif
1158    return (int)fwrite(cBuf, 1, nAccept, pfErr);
1159#  if CIO_WIN_WC_XLATE
1160  }
1161#  endif
1162}
1163# endif /* defined(CONSIO_EPUTB) */
1164
1165SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn){
1166  if( pfIn==0 ) pfIn = stdin;
1167# if CIO_WIN_WC_XLATE
1168  if( pfIn == consoleInfo.pstSetup[0].pf
1169      && (consoleInfo.sacSetup & SAC_InConsole)!=0 ){
1170#  if CIO_WIN_WC_XLATE==1
1171#   define SHELL_GULP 150 /* Count of WCHARS to be gulped at a time */
1172    WCHAR wcBuf[SHELL_GULP+1];
1173    int lend = 0, noc = 0;
1174    if( ncMax > 0 ) cBuf[0] = 0;
1175    while( noc < ncMax-8-1 && !lend ){
1176      /* There is room for at least 2 more characters and a 0-terminator. */
1177      int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4;
1178#   undef SHELL_GULP
1179      DWORD nbr = 0;
1180      BOOL bRC = ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf, na, &nbr, 0);
1181      if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){
1182        /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */
1183        DWORD nbrx;
1184        bRC &= ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf+nbr, 1, &nbrx, 0);
1185        if( bRC ) nbr += nbrx;
1186      }
1187      if( !bRC || (noc==0 && nbr==0) ) return 0;
1188      if( nbr > 0 ){
1189        int nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,0,0,0,0);
1190        if( nmb != 0 && noc+nmb <= ncMax ){
1191          int iseg = noc;
1192          nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,cBuf+noc,nmb,0,0);
1193          noc += nmb;
1194          /* Fixup line-ends as coded by Windows for CR (or "Enter".)
1195          ** This is done without regard for any setMode{Text,Binary}()
1196          ** call that might have been done on the interactive input.
1197          */
1198          if( noc > 0 ){
1199            if( cBuf[noc-1]=='\n' ){
1200              lend = 1;
1201              if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n';
1202            }
1203          }
1204          /* Check for ^Z (anywhere in line) too, to act as EOF. */
1205          while( iseg < noc ){
1206            if( cBuf[iseg]=='\x1a' ){
1207              noc = iseg; /* Chop ^Z and anything following. */
1208              lend = 1; /* Counts as end of line too. */
1209              break;
1210            }
1211            ++iseg;
1212          }
1213        }else break; /* Drop apparent garbage in. (Could assert.) */
1214      }else break;
1215    }
1216    /* If got nothing, (after ^Z chop), must be at end-of-file. */
1217    if( noc > 0 ){
1218      cBuf[noc] = 0;
1219      return cBuf;
1220    }else return 0;
1221#  endif
1222  }else{
1223# endif
1224    return fgets(cBuf, ncMax, pfIn);
1225# if CIO_WIN_WC_XLATE
1226  }
1227# endif
1228}
1229#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1230
1231#undef SHELL_INVALID_FILE_PTR
1232
1233/************************* End ../ext/consio/console_io.c ********************/
1234
1235#ifndef SQLITE_SHELL_FIDDLE
1236
1237/* From here onward, fgets() is redirected to the console_io library. */
1238#undef fgets
1239# define fgets(b,n,f) fGetsUtf8(b,n,f)
1240/*
1241 * Define macros for emitting output text in various ways:
1242 *  sputz(s, z)      => emit 0-terminated string z to given stream s
1243 *  sputf(s, f, ...) => emit varargs per format f to given stream s
1244 *  oputz(z)         => emit 0-terminated string z to default stream
1245 *  oputf(f, ...)    => emit varargs per format f to default stream
1246 *  eputz(z)         => emit 0-terminated string z to error stream
1247 *  eputf(f, ...)    => emit varargs per format f to error stream
1248 *  oputb(b, n)      => emit char buffer b[0..n-1] to default stream
1249 *
1250 * Note that the default stream is whatever has been last set via:
1251 *   setOutputStream(FILE *pf)
1252 * This is normally the stream that CLI normal output goes to.
1253 * For the stand-alone CLI, it is stdout with no .output redirect.
1254 */
1255# define sputz(s,z) fPutsUtf8(z,s)
1256# define sputf fPrintfUtf8
1257# define oputz(z) oPutsUtf8(z)
1258# define oputf oPrintfUtf8
1259# define eputz(z) ePutsUtf8(z)
1260# define eputf ePrintfUtf8
1261# define oputb(buf,na) oPutbUtf8(buf,na)
1262
1263#else
1264/* For Fiddle, all console handling and emit redirection is omitted. */
1265# define sputz(fp,z) fputs(z,fp)
1266# define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
1267# define oputz(z) fputs(z,stdout)
1268# define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
1269# define eputz(z) fputs(z,stderr)
1270# define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
1271# define oputb(buf,na) fwrite(buf,1,na,stdout)
1272#endif
1273
1274/* True if the timer is enabled */
1275static int enableTimer = 0;
1276
1277/* A version of strcmp() that works with NULL values */
1278static int cli_strcmp(const char *a, const char *b){
1279  if( a==0 ) a = "";
1280  if( b==0 ) b = "";
1281  return strcmp(a,b);
1282}
1283static int cli_strncmp(const char *a, const char *b, size_t n){
1284  if( a==0 ) a = "";
1285  if( b==0 ) b = "";
1286  return strncmp(a,b,n);
1287}
1288
1289/* Return the current wall-clock time */
1290static sqlite3_int64 timeOfDay(void){
1291  static sqlite3_vfs *clockVfs = 0;
1292  sqlite3_int64 t;
1293  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
1294  if( clockVfs==0 ) return 0;  /* Never actually happens */
1295  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
1296    clockVfs->xCurrentTimeInt64(clockVfs, &t);
1297  }else{
1298    double r;
1299    clockVfs->xCurrentTime(clockVfs, &r);
1300    t = (sqlite3_int64)(r*86400000.0);
1301  }
1302  return t;
1303}
1304
1305#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
1306#include <sys/time.h>
1307#include <sys/resource.h>
1308
1309/* VxWorks does not support getrusage() as far as we can determine */
1310#if defined(_WRS_KERNEL) || defined(__RTP__)
1311struct rusage {
1312  struct timeval ru_utime; /* user CPU time used */
1313  struct timeval ru_stime; /* system CPU time used */
1314};
1315#define getrusage(A,B) memset(B,0,sizeof(*B))
1316#endif
1317
1318/* Saved resource information for the beginning of an operation */
1319static struct rusage sBegin;  /* CPU time at start */
1320static sqlite3_int64 iBegin;  /* Wall-clock time at start */
1321
1322/*
1323** Begin timing an operation
1324*/
1325static void beginTimer(void){
1326  if( enableTimer ){
1327    getrusage(RUSAGE_SELF, &sBegin);
1328    iBegin = timeOfDay();
1329  }
1330}
1331
1332/* Return the difference of two time_structs in seconds */
1333static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
1334  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
1335         (double)(pEnd->tv_sec - pStart->tv_sec);
1336}
1337
1338/*
1339** Print the timing results.
1340*/
1341static void endTimer(void){
1342  if( enableTimer ){
1343    sqlite3_int64 iEnd = timeOfDay();
1344    struct rusage sEnd;
1345    getrusage(RUSAGE_SELF, &sEnd);
1346    sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1347          (iEnd - iBegin)*0.001,
1348          timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
1349          timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
1350  }
1351}
1352
1353#define BEGIN_TIMER beginTimer()
1354#define END_TIMER endTimer()
1355#define HAS_TIMER 1
1356
1357#elif (defined(_WIN32) || defined(WIN32))
1358
1359/* Saved resource information for the beginning of an operation */
1360static HANDLE hProcess;
1361static FILETIME ftKernelBegin;
1362static FILETIME ftUserBegin;
1363static sqlite3_int64 ftWallBegin;
1364typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
1365                                    LPFILETIME, LPFILETIME);
1366static GETPROCTIMES getProcessTimesAddr = NULL;
1367
1368/*
1369** Check to see if we have timer support.  Return 1 if necessary
1370** support found (or found previously).
1371*/
1372static int hasTimer(void){
1373  if( getProcessTimesAddr ){
1374    return 1;
1375  } else {
1376#if !SQLITE_OS_WINRT
1377    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
1378    ** versions. See if the version we are running on has it, and if it
1379    ** does, save off a pointer to it and the current process handle.
1380    */
1381    hProcess = GetCurrentProcess();
1382    if( hProcess ){
1383      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
1384      if( NULL != hinstLib ){
1385        getProcessTimesAddr =
1386            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
1387        if( NULL != getProcessTimesAddr ){
1388          return 1;
1389        }
1390        FreeLibrary(hinstLib);
1391      }
1392    }
1393#endif
1394  }
1395  return 0;
1396}
1397
1398/*
1399** Begin timing an operation
1400*/
1401static void beginTimer(void){
1402  if( enableTimer && getProcessTimesAddr ){
1403    FILETIME ftCreation, ftExit;
1404    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
1405                        &ftKernelBegin,&ftUserBegin);
1406    ftWallBegin = timeOfDay();
1407  }
1408}
1409
1410/* Return the difference of two FILETIME structs in seconds */
1411static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
1412  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
1413  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
1414  return (double) ((i64End - i64Start) / 10000000.0);
1415}
1416
1417/*
1418** Print the timing results.
1419*/
1420static void endTimer(void){
1421  if( enableTimer && getProcessTimesAddr){
1422    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
1423    sqlite3_int64 ftWallEnd = timeOfDay();
1424    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1425    sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1426          (ftWallEnd - ftWallBegin)*0.001,
1427          timeDiff(&ftUserBegin, &ftUserEnd),
1428          timeDiff(&ftKernelBegin, &ftKernelEnd));
1429  }
1430}
1431
1432#define BEGIN_TIMER beginTimer()
1433#define END_TIMER endTimer()
1434#define HAS_TIMER hasTimer()
1435
1436#else
1437#define BEGIN_TIMER
1438#define END_TIMER
1439#define HAS_TIMER 0
1440#endif
1441
1442/*
1443** Used to prevent warnings about unused parameters
1444*/
1445#define UNUSED_PARAMETER(x) (void)(x)
1446
1447/*
1448** Number of elements in an array
1449*/
1450#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
1451
1452/*
1453** If the following flag is set, then command execution stops
1454** at an error if we are not interactive.
1455*/
1456static int bail_on_error = 0;
1457
1458/*
1459** Treat stdin as an interactive input if the following variable
1460** is true.  Otherwise, assume stdin is connected to a file or pipe.
1461*/
1462static int stdin_is_interactive = 1;
1463
1464/*
1465** On Windows systems we need to know if standard output is a console
1466** in order to show that UTF-16 translation is done in the sign-on
1467** banner. The following variable is true if it is the console.
1468*/
1469static int stdout_is_console = 1;
1470
1471/*
1472** The following is the open SQLite database.  We make a pointer
1473** to this database a static variable so that it can be accessed
1474** by the SIGINT handler to interrupt database processing.
1475*/
1476static sqlite3 *globalDb = 0;
1477
1478/*
1479** True if an interrupt (Control-C) has been received.
1480*/
1481static volatile int seenInterrupt = 0;
1482
1483/*
1484** This is the name of our program. It is set in main(), used
1485** in a number of other places, mostly for error messages.
1486*/
1487static char *Argv0;
1488
1489/*
1490** Prompt strings. Initialized in main. Settable with
1491**   .prompt main continue
1492*/
1493#define PROMPT_LEN_MAX 20
1494/* First line prompt.   default: "sqlite> " */
1495static char mainPrompt[PROMPT_LEN_MAX];
1496/* Continuation prompt. default: "   ...> " */
1497static char continuePrompt[PROMPT_LEN_MAX];
1498
1499/* This is variant of the standard-library strncpy() routine with the
1500** one change that the destination string is always zero-terminated, even
1501** if there is no zero-terminator in the first n-1 characters of the source
1502** string.
1503*/
1504static char *shell_strncpy(char *dest, const char *src, size_t n){
1505  size_t i;
1506  for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
1507  dest[i] = 0;
1508  return dest;
1509}
1510
1511/*
1512** Optionally disable dynamic continuation prompt.
1513** Unless disabled, the continuation prompt shows open SQL lexemes if any,
1514** or open parentheses level if non-zero, or continuation prompt as set.
1515** This facility interacts with the scanner and process_input() where the
1516** below 5 macros are used.
1517*/
1518#ifdef SQLITE_OMIT_DYNAPROMPT
1519# define CONTINUATION_PROMPT continuePrompt
1520# define CONTINUE_PROMPT_RESET
1521# define CONTINUE_PROMPT_AWAITS(p,s)
1522# define CONTINUE_PROMPT_AWAITC(p,c)
1523# define CONTINUE_PAREN_INCR(p,n)
1524# define CONTINUE_PROMPT_PSTATE 0
1525typedef void *t_NoDynaPrompt;
1526# define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
1527#else
1528# define CONTINUATION_PROMPT dynamicContinuePrompt()
1529# define CONTINUE_PROMPT_RESET \
1530  do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
1531# define CONTINUE_PROMPT_AWAITS(p,s) \
1532  if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
1533# define CONTINUE_PROMPT_AWAITC(p,c) \
1534  if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
1535# define CONTINUE_PAREN_INCR(p,n) \
1536  if(p && stdin_is_interactive) (trackParenLevel(p,n))
1537# define CONTINUE_PROMPT_PSTATE (&dynPrompt)
1538typedef struct DynaPrompt *t_DynaPromptRef;
1539# define SCAN_TRACKER_REFTYPE t_DynaPromptRef
1540
1541static struct DynaPrompt {
1542  char dynamicPrompt[PROMPT_LEN_MAX];
1543  char acAwait[2];
1544  int inParenLevel;
1545  char *zScannerAwaits;
1546} dynPrompt = { {0}, {0}, 0, 0 };
1547
1548/* Record parenthesis nesting level change, or force level to 0. */
1549static void trackParenLevel(struct DynaPrompt *p, int ni){
1550  p->inParenLevel += ni;
1551  if( ni==0 ) p->inParenLevel = 0;
1552  p->zScannerAwaits = 0;
1553}
1554
1555/* Record that a lexeme is opened, or closed with args==0. */
1556static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
1557  if( s!=0 || c==0 ){
1558    p->zScannerAwaits = s;
1559    p->acAwait[0] = 0;
1560  }else{
1561    p->acAwait[0] = c;
1562    p->zScannerAwaits = p->acAwait;
1563  }
1564}
1565
1566/* Upon demand, derive the continuation prompt to display. */
1567static char *dynamicContinuePrompt(void){
1568  if( continuePrompt[0]==0
1569      || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
1570    return continuePrompt;
1571  }else{
1572    if( dynPrompt.zScannerAwaits ){
1573      size_t ncp = strlen(continuePrompt);
1574      size_t ndp = strlen(dynPrompt.zScannerAwaits);
1575      if( ndp > ncp-3 ) return continuePrompt;
1576      strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
1577      while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
1578      shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1579              PROMPT_LEN_MAX-4);
1580    }else{
1581      if( dynPrompt.inParenLevel>9 ){
1582        shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
1583      }else if( dynPrompt.inParenLevel<0 ){
1584        shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
1585      }else{
1586        shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
1587        dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
1588      }
1589      shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1590                    PROMPT_LEN_MAX-4);
1591    }
1592  }
1593  return dynPrompt.dynamicPrompt;
1594}
1595#endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
1596
1597/* Indicate out-of-memory and exit. */
1598static void shell_out_of_memory(void){
1599  eputz("Error: out of memory\n");
1600  exit(1);
1601}
1602
1603/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
1604** out-of-memory error.
1605*/
1606static void shell_check_oom(const void *p){
1607  if( p==0 ) shell_out_of_memory();
1608}
1609
1610/*
1611** Write I/O traces to the following stream.
1612*/
1613#ifdef SQLITE_ENABLE_IOTRACE
1614static FILE *iotrace = 0;
1615#endif
1616
1617/*
1618** This routine works like printf in that its first argument is a
1619** format string and subsequent arguments are values to be substituted
1620** in place of % fields.  The result of formatting this string
1621** is written to iotrace.
1622*/
1623#ifdef SQLITE_ENABLE_IOTRACE
1624static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
1625  va_list ap;
1626  char *z;
1627  if( iotrace==0 ) return;
1628  va_start(ap, zFormat);
1629  z = sqlite3_vmprintf(zFormat, ap);
1630  va_end(ap);
1631  sputf(iotrace, "%s", z);
1632  sqlite3_free(z);
1633}
1634#endif
1635
1636/*
1637** Output string zUtf to Out stream as w characters.  If w is negative,
1638** then right-justify the text.  W is the width in UTF-8 characters, not
1639** in bytes.  This is different from the %*.*s specification in printf
1640** since with %*.*s the width is measured in bytes, not characters.
1641*/
1642static void utf8_width_print(int w, const char *zUtf){
1643  int i;
1644  int n;
1645  int aw = w<0 ? -w : w;
1646  if( zUtf==0 ) zUtf = "";
1647  for(i=n=0; zUtf[i]; i++){
1648    if( (zUtf[i]&0xc0)!=0x80 ){
1649      n++;
1650      if( n==aw ){
1651        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
1652        break;
1653      }
1654    }
1655  }
1656  if( n>=aw ){
1657    oputf("%.*s", i, zUtf);
1658  }else if( w<0 ){
1659    oputf("%*s%s", aw-n, "", zUtf);
1660  }else{
1661    oputf("%s%*s", zUtf, aw-n, "");
1662  }
1663}
1664
1665
1666/*
1667** Determines if a string is a number of not.
1668*/
1669static int isNumber(const char *z, int *realnum){
1670  if( *z=='-' || *z=='+' ) z++;
1671  if( !IsDigit(*z) ){
1672    return 0;
1673  }
1674  z++;
1675  if( realnum ) *realnum = 0;
1676  while( IsDigit(*z) ){ z++; }
1677  if( *z=='.' ){
1678    z++;
1679    if( !IsDigit(*z) ) return 0;
1680    while( IsDigit(*z) ){ z++; }
1681    if( realnum ) *realnum = 1;
1682  }
1683  if( *z=='e' || *z=='E' ){
1684    z++;
1685    if( *z=='+' || *z=='-' ) z++;
1686    if( !IsDigit(*z) ) return 0;
1687    while( IsDigit(*z) ){ z++; }
1688    if( realnum ) *realnum = 1;
1689  }
1690  return *z==0;
1691}
1692
1693/*
1694** Compute a string length that is limited to what can be stored in
1695** lower 30 bits of a 32-bit signed integer.
1696*/
1697static int strlen30(const char *z){
1698  const char *z2 = z;
1699  while( *z2 ){ z2++; }
1700  return 0x3fffffff & (int)(z2 - z);
1701}
1702
1703/*
1704** Return the length of a string in characters.  Multibyte UTF8 characters
1705** count as a single character.
1706*/
1707static int strlenChar(const char *z){
1708  int n = 0;
1709  while( *z ){
1710    if( (0xc0&*(z++))!=0x80 ) n++;
1711  }
1712  return n;
1713}
1714
1715/*
1716** Return open FILE * if zFile exists, can be opened for read
1717** and is an ordinary file or a character stream source.
1718** Otherwise return 0.
1719*/
1720static FILE * openChrSource(const char *zFile){
1721#if defined(_WIN32) || defined(WIN32)
1722  struct __stat64 x = {0};
1723# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1724  /* On Windows, open first, then check the stream nature. This order
1725  ** is necessary because _stat() and sibs, when checking a named pipe,
1726  ** effectively break the pipe as its supplier sees it. */
1727  FILE *rv = fopen(zFile, "rb");
1728  if( rv==0 ) return 0;
1729  if( _fstat64(_fileno(rv), &x) != 0
1730      || !STAT_CHR_SRC(x.st_mode)){
1731    fclose(rv);
1732    rv = 0;
1733  }
1734  return rv;
1735#else
1736  struct stat x = {0};
1737  int rc = stat(zFile, &x);
1738# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
1739  if( rc!=0 ) return 0;
1740  if( STAT_CHR_SRC(x.st_mode) ){
1741    return fopen(zFile, "rb");
1742  }else{
1743    return 0;
1744  }
1745#endif
1746#undef STAT_CHR_SRC
1747}
1748
1749/*
1750** This routine reads a line of text from FILE in, stores
1751** the text in memory obtained from malloc() and returns a pointer
1752** to the text.  NULL is returned at end of file, or if malloc()
1753** fails.
1754**
1755** If zLine is not NULL then it is a malloced buffer returned from
1756** a previous call to this routine that may be reused.
1757*/
1758static char *local_getline(char *zLine, FILE *in){
1759  int nLine = zLine==0 ? 0 : 100;
1760  int n = 0;
1761
1762  while( 1 ){
1763    if( n+100>nLine ){
1764      nLine = nLine*2 + 100;
1765      zLine = realloc(zLine, nLine);
1766      shell_check_oom(zLine);
1767    }
1768    if( fgets(&zLine[n], nLine - n, in)==0 ){
1769      if( n==0 ){
1770        free(zLine);
1771        return 0;
1772      }
1773      zLine[n] = 0;
1774      break;
1775    }
1776    while( zLine[n] ) n++;
1777    if( n>0 && zLine[n-1]=='\n' ){
1778      n--;
1779      if( n>0 && zLine[n-1]=='\r' ) n--;
1780      zLine[n] = 0;
1781      break;
1782    }
1783  }
1784  return zLine;
1785}
1786
1787/*
1788** Retrieve a single line of input text.
1789**
1790** If in==0 then read from standard input and prompt before each line.
1791** If isContinuation is true, then a continuation prompt is appropriate.
1792** If isContinuation is zero, then the main prompt should be used.
1793**
1794** If zPrior is not NULL then it is a buffer from a prior call to this
1795** routine that can be reused.
1796**
1797** The result is stored in space obtained from malloc() and must either
1798** be freed by the caller or else passed back into this routine via the
1799** zPrior argument for reuse.
1800*/
1801#ifndef SQLITE_SHELL_FIDDLE
1802static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1803  char *zPrompt;
1804  char *zResult;
1805  if( in!=0 ){
1806    zResult = local_getline(zPrior, in);
1807  }else{
1808    zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1809#if SHELL_USE_LOCAL_GETLINE
1810    sputz(stdout, zPrompt);
1811    fflush(stdout);
1812    do{
1813      zResult = local_getline(zPrior, stdin);
1814      zPrior = 0;
1815      /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1816      if( zResult==0 ) sqlite3_sleep(50);
1817    }while( zResult==0 && seenInterrupt>0 );
1818#else
1819    free(zPrior);
1820    zResult = shell_readline(zPrompt);
1821    while( zResult==0 ){
1822      /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1823      sqlite3_sleep(50);
1824      if( seenInterrupt==0 ) break;
1825      zResult = shell_readline("");
1826    }
1827    if( zResult && *zResult ) shell_add_history(zResult);
1828#endif
1829  }
1830  return zResult;
1831}
1832#endif /* !SQLITE_SHELL_FIDDLE */
1833
1834/*
1835** Return the value of a hexadecimal digit.  Return -1 if the input
1836** is not a hex digit.
1837*/
1838static int hexDigitValue(char c){
1839  if( c>='0' && c<='9' ) return c - '0';
1840  if( c>='a' && c<='f' ) return c - 'a' + 10;
1841  if( c>='A' && c<='F' ) return c - 'A' + 10;
1842  return -1;
1843}
1844
1845/*
1846** Interpret zArg as an integer value, possibly with suffixes.
1847*/
1848static sqlite3_int64 integerValue(const char *zArg){
1849  sqlite3_int64 v = 0;
1850  static const struct { char *zSuffix; int iMult; } aMult[] = {
1851    { "KiB", 1024 },
1852    { "MiB", 1024*1024 },
1853    { "GiB", 1024*1024*1024 },
1854    { "KB",  1000 },
1855    { "MB",  1000000 },
1856    { "GB",  1000000000 },
1857    { "K",   1000 },
1858    { "M",   1000000 },
1859    { "G",   1000000000 },
1860  };
1861  int i;
1862  int isNeg = 0;
1863  if( zArg[0]=='-' ){
1864    isNeg = 1;
1865    zArg++;
1866  }else if( zArg[0]=='+' ){
1867    zArg++;
1868  }
1869  if( zArg[0]=='0' && zArg[1]=='x' ){
1870    int x;
1871    zArg += 2;
1872    while( (x = hexDigitValue(zArg[0]))>=0 ){
1873      v = (v<<4) + x;
1874      zArg++;
1875    }
1876  }else{
1877    while( IsDigit(zArg[0]) ){
1878      v = v*10 + zArg[0] - '0';
1879      zArg++;
1880    }
1881  }
1882  for(i=0; i<ArraySize(aMult); i++){
1883    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1884      v *= aMult[i].iMult;
1885      break;
1886    }
1887  }
1888  return isNeg? -v : v;
1889}
1890
1891/*
1892** A variable length string to which one can append text.
1893*/
1894typedef struct ShellText ShellText;
1895struct ShellText {
1896  char *z;
1897  int n;
1898  int nAlloc;
1899};
1900
1901/*
1902** Initialize and destroy a ShellText object
1903*/
1904static void initText(ShellText *p){
1905  memset(p, 0, sizeof(*p));
1906}
1907static void freeText(ShellText *p){
1908  free(p->z);
1909  initText(p);
1910}
1911
1912/* zIn is either a pointer to a NULL-terminated string in memory obtained
1913** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1914** added to zIn, and the result returned in memory obtained from malloc().
1915** zIn, if it was not NULL, is freed.
1916**
1917** If the third argument, quote, is not '\0', then it is used as a
1918** quote character for zAppend.
1919*/
1920static void appendText(ShellText *p, const char *zAppend, char quote){
1921  i64 len;
1922  i64 i;
1923  i64 nAppend = strlen30(zAppend);
1924
1925  len = nAppend+p->n+1;
1926  if( quote ){
1927    len += 2;
1928    for(i=0; i<nAppend; i++){
1929      if( zAppend[i]==quote ) len++;
1930    }
1931  }
1932
1933  if( p->z==0 || p->n+len>=p->nAlloc ){
1934    p->nAlloc = p->nAlloc*2 + len + 20;
1935    p->z = realloc(p->z, p->nAlloc);
1936    shell_check_oom(p->z);
1937  }
1938
1939  if( quote ){
1940    char *zCsr = p->z+p->n;
1941    *zCsr++ = quote;
1942    for(i=0; i<nAppend; i++){
1943      *zCsr++ = zAppend[i];
1944      if( zAppend[i]==quote ) *zCsr++ = quote;
1945    }
1946    *zCsr++ = quote;
1947    p->n = (int)(zCsr - p->z);
1948    *zCsr = '\0';
1949  }else{
1950    memcpy(p->z+p->n, zAppend, nAppend);
1951    p->n += nAppend;
1952    p->z[p->n] = '\0';
1953  }
1954}
1955
1956/*
1957** Attempt to determine if identifier zName needs to be quoted, either
1958** because it contains non-alphanumeric characters, or because it is an
1959** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1960** that quoting is required.
1961**
1962** Return '"' if quoting is required.  Return 0 if no quoting is required.
1963*/
1964static char quoteChar(const char *zName){
1965  int i;
1966  if( zName==0 ) return '"';
1967  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1968  for(i=0; zName[i]; i++){
1969    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1970  }
1971  return sqlite3_keyword_check(zName, i) ? '"' : 0;
1972}
1973
1974/*
1975** Construct a fake object name and column list to describe the structure
1976** of the view, virtual table, or table valued function zSchema.zName.
1977*/
1978static char *shellFakeSchema(
1979  sqlite3 *db,            /* The database connection containing the vtab */
1980  const char *zSchema,    /* Schema of the database holding the vtab */
1981  const char *zName       /* The name of the virtual table */
1982){
1983  sqlite3_stmt *pStmt = 0;
1984  char *zSql;
1985  ShellText s;
1986  char cQuote;
1987  char *zDiv = "(";
1988  int nRow = 0;
1989
1990  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1991                         zSchema ? zSchema : "main", zName);
1992  shell_check_oom(zSql);
1993  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1994  sqlite3_free(zSql);
1995  initText(&s);
1996  if( zSchema ){
1997    cQuote = quoteChar(zSchema);
1998    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1999    appendText(&s, zSchema, cQuote);
2000    appendText(&s, ".", 0);
2001  }
2002  cQuote = quoteChar(zName);
2003  appendText(&s, zName, cQuote);
2004  while( sqlite3_step(pStmt)==SQLITE_ROW ){
2005    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
2006    nRow++;
2007    appendText(&s, zDiv, 0);
2008    zDiv = ",";
2009    if( zCol==0 ) zCol = "";
2010    cQuote = quoteChar(zCol);
2011    appendText(&s, zCol, cQuote);
2012  }
2013  appendText(&s, ")", 0);
2014  sqlite3_finalize(pStmt);
2015  if( nRow==0 ){
2016    freeText(&s);
2017    s.z = 0;
2018  }
2019  return s.z;
2020}
2021
2022/*
2023** SQL function:  strtod(X)
2024**
2025** Use the C-library strtod() function to convert string X into a double.
2026** Used for comparing the accuracy of SQLite's internal text-to-float conversion
2027** routines against the C-library.
2028*/
2029static void shellStrtod(
2030  sqlite3_context *pCtx,
2031  int nVal,
2032  sqlite3_value **apVal
2033){
2034  char *z = (char*)sqlite3_value_text(apVal[0]);
2035  UNUSED_PARAMETER(nVal);
2036  if( z==0 ) return;
2037  sqlite3_result_double(pCtx, strtod(z,0));
2038}
2039
2040/*
2041** SQL function:  dtostr(X)
2042**
2043** Use the C-library printf() function to convert real value X into a string.
2044** Used for comparing the accuracy of SQLite's internal float-to-text conversion
2045** routines against the C-library.
2046*/
2047static void shellDtostr(
2048  sqlite3_context *pCtx,
2049  int nVal,
2050  sqlite3_value **apVal
2051){
2052  double r = sqlite3_value_double(apVal[0]);
2053  int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
2054  char z[400];
2055  if( n<1 ) n = 1;
2056  if( n>350 ) n = 350;
2057  sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
2058  sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
2059}
2060
2061
2062/*
2063** SQL function:  shell_module_schema(X)
2064**
2065** Return a fake schema for the table-valued function or eponymous virtual
2066** table X.
2067*/
2068static void shellModuleSchema(
2069  sqlite3_context *pCtx,
2070  int nVal,
2071  sqlite3_value **apVal
2072){
2073  const char *zName;
2074  char *zFake;
2075  UNUSED_PARAMETER(nVal);
2076  zName = (const char*)sqlite3_value_text(apVal[0]);
2077  zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
2078  if( zFake ){
2079    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
2080                        -1, sqlite3_free);
2081    free(zFake);
2082  }
2083}
2084
2085/*
2086** SQL function:  shell_add_schema(S,X)
2087**
2088** Add the schema name X to the CREATE statement in S and return the result.
2089** Examples:
2090**
2091**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
2092**
2093** Also works on
2094**
2095**    CREATE INDEX
2096**    CREATE UNIQUE INDEX
2097**    CREATE VIEW
2098**    CREATE TRIGGER
2099**    CREATE VIRTUAL TABLE
2100**
2101** This UDF is used by the .schema command to insert the schema name of
2102** attached databases into the middle of the sqlite_schema.sql field.
2103*/
2104static void shellAddSchemaName(
2105  sqlite3_context *pCtx,
2106  int nVal,
2107  sqlite3_value **apVal
2108){
2109  static const char *aPrefix[] = {
2110     "TABLE",
2111     "INDEX",
2112     "UNIQUE INDEX",
2113     "VIEW",
2114     "TRIGGER",
2115     "VIRTUAL TABLE"
2116  };
2117  int i = 0;
2118  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
2119  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
2120  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
2121  sqlite3 *db = sqlite3_context_db_handle(pCtx);
2122  UNUSED_PARAMETER(nVal);
2123  if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
2124    for(i=0; i<ArraySize(aPrefix); i++){
2125      int n = strlen30(aPrefix[i]);
2126      if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
2127        char *z = 0;
2128        char *zFake = 0;
2129        if( zSchema ){
2130          char cQuote = quoteChar(zSchema);
2131          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
2132            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
2133          }else{
2134            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
2135          }
2136        }
2137        if( zName
2138         && aPrefix[i][0]=='V'
2139         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
2140        ){
2141          if( z==0 ){
2142            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
2143          }else{
2144            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
2145          }
2146          free(zFake);
2147        }
2148        if( z ){
2149          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
2150          return;
2151        }
2152      }
2153    }
2154  }
2155  sqlite3_result_value(pCtx, apVal[0]);
2156}
2157
2158/*
2159** The source code for several run-time loadable extensions is inserted
2160** below by the ../tool/mkshellc.tcl script.  Before processing that included
2161** code, we need to override some macros to make the included program code
2162** work here in the middle of this regular program.
2163*/
2164#define SQLITE_EXTENSION_INIT1
2165#define SQLITE_EXTENSION_INIT2(X) (void)(X)
2166
2167#if defined(_WIN32) && defined(_MSC_VER)
2168/************************* Begin test_windirent.h ******************/
2169/*
2170** 2015 November 30
2171**
2172** The author disclaims copyright to this source code.  In place of
2173** a legal notice, here is a blessing:
2174**
2175**    May you do good and not evil.
2176**    May you find forgiveness for yourself and forgive others.
2177**    May you share freely, never taking more than you give.
2178**
2179*************************************************************************
2180** This file contains declarations for most of the opendir() family of
2181** POSIX functions on Win32 using the MSVCRT.
2182*/
2183
2184#if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
2185#define SQLITE_WINDIRENT_H
2186
2187/*
2188** We need several data types from the Windows SDK header.
2189*/
2190
2191#ifndef WIN32_LEAN_AND_MEAN
2192#define WIN32_LEAN_AND_MEAN
2193#endif
2194
2195#include "windows.h"
2196
2197/*
2198** We need several support functions from the SQLite core.
2199*/
2200
2201/* #include "sqlite3.h" */
2202
2203/*
2204** We need several things from the ANSI and MSVCRT headers.
2205*/
2206
2207#include <stdio.h>
2208#include <stdlib.h>
2209#include <errno.h>
2210#include <io.h>
2211#include <limits.h>
2212#include <sys/types.h>
2213#include <sys/stat.h>
2214
2215/*
2216** We may need several defines that should have been in "sys/stat.h".
2217*/
2218
2219#ifndef S_ISREG
2220#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
2221#endif
2222
2223#ifndef S_ISDIR
2224#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
2225#endif
2226
2227#ifndef S_ISLNK
2228#define S_ISLNK(mode) (0)
2229#endif
2230
2231/*
2232** We may need to provide the "mode_t" type.
2233*/
2234
2235#ifndef MODE_T_DEFINED
2236  #define MODE_T_DEFINED
2237  typedef unsigned short mode_t;
2238#endif
2239
2240/*
2241** We may need to provide the "ino_t" type.
2242*/
2243
2244#ifndef INO_T_DEFINED
2245  #define INO_T_DEFINED
2246  typedef unsigned short ino_t;
2247#endif
2248
2249/*
2250** We need to define "NAME_MAX" if it was not present in "limits.h".
2251*/
2252
2253#ifndef NAME_MAX
2254#  ifdef FILENAME_MAX
2255#    define NAME_MAX (FILENAME_MAX)
2256#  else
2257#    define NAME_MAX (260)
2258#  endif
2259#endif
2260
2261/*
2262** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
2263*/
2264
2265#ifndef NULL_INTPTR_T
2266#  define NULL_INTPTR_T ((intptr_t)(0))
2267#endif
2268
2269#ifndef BAD_INTPTR_T
2270#  define BAD_INTPTR_T ((intptr_t)(-1))
2271#endif
2272
2273/*
2274** We need to provide the necessary structures and related types.
2275*/
2276
2277#ifndef DIRENT_DEFINED
2278#define DIRENT_DEFINED
2279typedef struct DIRENT DIRENT;
2280typedef DIRENT *LPDIRENT;
2281struct DIRENT {
2282  ino_t d_ino;               /* Sequence number, do not use. */
2283  unsigned d_attributes;     /* Win32 file attributes. */
2284  char d_name[NAME_MAX + 1]; /* Name within the directory. */
2285};
2286#endif
2287
2288#ifndef DIR_DEFINED
2289#define DIR_DEFINED
2290typedef struct DIR DIR;
2291typedef DIR *LPDIR;
2292struct DIR {
2293  intptr_t d_handle; /* Value returned by "_findfirst". */
2294  DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
2295  DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
2296};
2297#endif
2298
2299/*
2300** Provide a macro, for use by the implementation, to determine if a
2301** particular directory entry should be skipped over when searching for
2302** the next directory entry that should be returned by the readdir() or
2303** readdir_r() functions.
2304*/
2305
2306#ifndef is_filtered
2307#  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
2308#endif
2309
2310/*
2311** Provide the function prototype for the POSIX compatible getenv()
2312** function.  This function is not thread-safe.
2313*/
2314
2315extern const char *windirent_getenv(const char *name);
2316
2317/*
2318** Finally, we can provide the function prototypes for the opendir(),
2319** readdir(), readdir_r(), and closedir() POSIX functions.
2320*/
2321
2322extern LPDIR opendir(const char *dirname);
2323extern LPDIRENT readdir(LPDIR dirp);
2324extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
2325extern INT closedir(LPDIR dirp);
2326
2327#endif /* defined(WIN32) && defined(_MSC_VER) */
2328
2329/************************* End test_windirent.h ********************/
2330/************************* Begin test_windirent.c ******************/
2331/*
2332** 2015 November 30
2333**
2334** The author disclaims copyright to this source code.  In place of
2335** a legal notice, here is a blessing:
2336**
2337**    May you do good and not evil.
2338**    May you find forgiveness for yourself and forgive others.
2339**    May you share freely, never taking more than you give.
2340**
2341*************************************************************************
2342** This file contains code to implement most of the opendir() family of
2343** POSIX functions on Win32 using the MSVCRT.
2344*/
2345
2346#if defined(_WIN32) && defined(_MSC_VER)
2347/* #include "test_windirent.h" */
2348
2349/*
2350** Implementation of the POSIX getenv() function using the Win32 API.
2351** This function is not thread-safe.
2352*/
2353const char *windirent_getenv(
2354  const char *name
2355){
2356  static char value[32768]; /* Maximum length, per MSDN */
2357  DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
2358  DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
2359
2360  memset(value, 0, sizeof(value));
2361  dwRet = GetEnvironmentVariableA(name, value, dwSize);
2362  if( dwRet==0 || dwRet>dwSize ){
2363    /*
2364    ** The function call to GetEnvironmentVariableA() failed -OR-
2365    ** the buffer is not large enough.  Either way, return NULL.
2366    */
2367    return 0;
2368  }else{
2369    /*
2370    ** The function call to GetEnvironmentVariableA() succeeded
2371    ** -AND- the buffer contains the entire value.
2372    */
2373    return value;
2374  }
2375}
2376
2377/*
2378** Implementation of the POSIX opendir() function using the MSVCRT.
2379*/
2380LPDIR opendir(
2381  const char *dirname
2382){
2383  struct _finddata_t data;
2384  LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
2385  SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
2386
2387  if( dirp==NULL ) return NULL;
2388  memset(dirp, 0, sizeof(DIR));
2389
2390  /* TODO: Remove this if Unix-style root paths are not used. */
2391  if( sqlite3_stricmp(dirname, "/")==0 ){
2392    dirname = windirent_getenv("SystemDrive");
2393  }
2394
2395  memset(&data, 0, sizeof(struct _finddata_t));
2396  _snprintf(data.name, namesize, "%s\\*", dirname);
2397  dirp->d_handle = _findfirst(data.name, &data);
2398
2399  if( dirp->d_handle==BAD_INTPTR_T ){
2400    closedir(dirp);
2401    return NULL;
2402  }
2403
2404  /* TODO: Remove this block to allow hidden and/or system files. */
2405  if( is_filtered(data) ){
2406next:
2407
2408    memset(&data, 0, sizeof(struct _finddata_t));
2409    if( _findnext(dirp->d_handle, &data)==-1 ){
2410      closedir(dirp);
2411      return NULL;
2412    }
2413
2414    /* TODO: Remove this block to allow hidden and/or system files. */
2415    if( is_filtered(data) ) goto next;
2416  }
2417
2418  dirp->d_first.d_attributes = data.attrib;
2419  strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
2420  dirp->d_first.d_name[NAME_MAX] = '\0';
2421
2422  return dirp;
2423}
2424
2425/*
2426** Implementation of the POSIX readdir() function using the MSVCRT.
2427*/
2428LPDIRENT readdir(
2429  LPDIR dirp
2430){
2431  struct _finddata_t data;
2432
2433  if( dirp==NULL ) return NULL;
2434
2435  if( dirp->d_first.d_ino==0 ){
2436    dirp->d_first.d_ino++;
2437    dirp->d_next.d_ino++;
2438
2439    return &dirp->d_first;
2440  }
2441
2442next:
2443
2444  memset(&data, 0, sizeof(struct _finddata_t));
2445  if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
2446
2447  /* TODO: Remove this block to allow hidden and/or system files. */
2448  if( is_filtered(data) ) goto next;
2449
2450  dirp->d_next.d_ino++;
2451  dirp->d_next.d_attributes = data.attrib;
2452  strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
2453  dirp->d_next.d_name[NAME_MAX] = '\0';
2454
2455  return &dirp->d_next;
2456}
2457
2458/*
2459** Implementation of the POSIX readdir_r() function using the MSVCRT.
2460*/
2461INT readdir_r(
2462  LPDIR dirp,
2463  LPDIRENT entry,
2464  LPDIRENT *result
2465){
2466  struct _finddata_t data;
2467
2468  if( dirp==NULL ) return EBADF;
2469
2470  if( dirp->d_first.d_ino==0 ){
2471    dirp->d_first.d_ino++;
2472    dirp->d_next.d_ino++;
2473
2474    entry->d_ino = dirp->d_first.d_ino;
2475    entry->d_attributes = dirp->d_first.d_attributes;
2476    strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
2477    entry->d_name[NAME_MAX] = '\0';
2478
2479    *result = entry;
2480    return 0;
2481  }
2482
2483next:
2484
2485  memset(&data, 0, sizeof(struct _finddata_t));
2486  if( _findnext(dirp->d_handle, &data)==-1 ){
2487    *result = NULL;
2488    return ENOENT;
2489  }
2490
2491  /* TODO: Remove this block to allow hidden and/or system files. */
2492  if( is_filtered(data) ) goto next;
2493
2494  entry->d_ino = (ino_t)-1; /* not available */
2495  entry->d_attributes = data.attrib;
2496  strncpy(entry->d_name, data.name, NAME_MAX);
2497  entry->d_name[NAME_MAX] = '\0';
2498
2499  *result = entry;
2500  return 0;
2501}
2502
2503/*
2504** Implementation of the POSIX closedir() function using the MSVCRT.
2505*/
2506INT closedir(
2507  LPDIR dirp
2508){
2509  INT result = 0;
2510
2511  if( dirp==NULL ) return EINVAL;
2512
2513  if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
2514    result = _findclose(dirp->d_handle);
2515  }
2516
2517  sqlite3_free(dirp);
2518  return result;
2519}
2520
2521#endif /* defined(WIN32) && defined(_MSC_VER) */
2522
2523/************************* End test_windirent.c ********************/
2524#define dirent DIRENT
2525#endif
2526/************************* Begin ../ext/misc/memtrace.c ******************/
2527/*
2528** 2019-01-21
2529**
2530** The author disclaims copyright to this source code.  In place of
2531** a legal notice, here is a blessing:
2532**
2533**    May you do good and not evil.
2534**    May you find forgiveness for yourself and forgive others.
2535**    May you share freely, never taking more than you give.
2536**
2537*************************************************************************
2538**
2539** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
2540** mechanism to add a tracing layer on top of SQLite.  If this extension
2541** is registered prior to sqlite3_initialize(), it will cause all memory
2542** allocation activities to be logged on standard output, or to some other
2543** FILE specified by the initializer.
2544**
2545** This file needs to be compiled into the application that uses it.
2546**
2547** This extension is used to implement the --memtrace option of the
2548** command-line shell.
2549*/
2550#include <assert.h>
2551#include <string.h>
2552#include <stdio.h>
2553
2554/* The original memory allocation routines */
2555static sqlite3_mem_methods memtraceBase;
2556static FILE *memtraceOut;
2557
2558/* Methods that trace memory allocations */
2559static void *memtraceMalloc(int n){
2560  if( memtraceOut ){
2561    fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
2562            memtraceBase.xRoundup(n));
2563  }
2564  return memtraceBase.xMalloc(n);
2565}
2566static void memtraceFree(void *p){
2567  if( p==0 ) return;
2568  if( memtraceOut ){
2569    fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
2570  }
2571  memtraceBase.xFree(p);
2572}
2573static void *memtraceRealloc(void *p, int n){
2574  if( p==0 ) return memtraceMalloc(n);
2575  if( n==0 ){
2576    memtraceFree(p);
2577    return 0;
2578  }
2579  if( memtraceOut ){
2580    fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
2581            memtraceBase.xSize(p), memtraceBase.xRoundup(n));
2582  }
2583  return memtraceBase.xRealloc(p, n);
2584}
2585static int memtraceSize(void *p){
2586  return memtraceBase.xSize(p);
2587}
2588static int memtraceRoundup(int n){
2589  return memtraceBase.xRoundup(n);
2590}
2591static int memtraceInit(void *p){
2592  return memtraceBase.xInit(p);
2593}
2594static void memtraceShutdown(void *p){
2595  memtraceBase.xShutdown(p);
2596}
2597
2598/* The substitute memory allocator */
2599static sqlite3_mem_methods ersaztMethods = {
2600  memtraceMalloc,
2601  memtraceFree,
2602  memtraceRealloc,
2603  memtraceSize,
2604  memtraceRoundup,
2605  memtraceInit,
2606  memtraceShutdown,
2607  0
2608};
2609
2610/* Begin tracing memory allocations to out. */
2611static int sqlite3MemTraceActivate(FILE *out){
2612  int rc = SQLITE_OK;
2613  if( memtraceBase.xMalloc==0 ){
2614    rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
2615    if( rc==SQLITE_OK ){
2616      rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
2617    }
2618  }
2619  memtraceOut = out;
2620  return rc;
2621}
2622
2623/* Deactivate memory tracing */
2624static int sqlite3MemTraceDeactivate(void){
2625  int rc = SQLITE_OK;
2626  if( memtraceBase.xMalloc!=0 ){
2627    rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
2628    if( rc==SQLITE_OK ){
2629      memset(&memtraceBase, 0, sizeof(memtraceBase));
2630    }
2631  }
2632  memtraceOut = 0;
2633  return rc;
2634}
2635
2636/************************* End ../ext/misc/memtrace.c ********************/
2637/************************* Begin ../ext/misc/pcachetrace.c ******************/
2638/*
2639** 2023-06-21
2640**
2641** The author disclaims copyright to this source code.  In place of
2642** a legal notice, here is a blessing:
2643**
2644**    May you do good and not evil.
2645**    May you find forgiveness for yourself and forgive others.
2646**    May you share freely, never taking more than you give.
2647**
2648*************************************************************************
2649**
2650** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
2651** mechanism to add a tracing layer on top of pluggable page cache of
2652** SQLite.  If this extension is registered prior to sqlite3_initialize(),
2653** it will cause all page cache activities to be logged on standard output,
2654** or to some other FILE specified by the initializer.
2655**
2656** This file needs to be compiled into the application that uses it.
2657**
2658** This extension is used to implement the --pcachetrace option of the
2659** command-line shell.
2660*/
2661#include <assert.h>
2662#include <string.h>
2663#include <stdio.h>
2664
2665/* The original page cache routines */
2666static sqlite3_pcache_methods2 pcacheBase;
2667static FILE *pcachetraceOut;
2668
2669/* Methods that trace pcache activity */
2670static int pcachetraceInit(void *pArg){
2671  int nRes;
2672  if( pcachetraceOut ){
2673    fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
2674  }
2675  nRes = pcacheBase.xInit(pArg);
2676  if( pcachetraceOut ){
2677    fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
2678  }
2679  return nRes;
2680}
2681static void pcachetraceShutdown(void *pArg){
2682  if( pcachetraceOut ){
2683    fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
2684  }
2685  pcacheBase.xShutdown(pArg);
2686}
2687static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
2688  sqlite3_pcache *pRes;
2689  if( pcachetraceOut ){
2690    fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
2691            szPage, szExtra, bPurge);
2692  }
2693  pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
2694  if( pcachetraceOut ){
2695    fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
2696            szPage, szExtra, bPurge, pRes);
2697  }
2698  return pRes;
2699}
2700static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
2701  if( pcachetraceOut ){
2702    fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
2703  }
2704  pcacheBase.xCachesize(p, nCachesize);
2705}
2706static int pcachetracePagecount(sqlite3_pcache *p){
2707  int nRes;
2708  if( pcachetraceOut ){
2709    fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
2710  }
2711  nRes = pcacheBase.xPagecount(p);
2712  if( pcachetraceOut ){
2713    fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
2714  }
2715  return nRes;
2716}
2717static sqlite3_pcache_page *pcachetraceFetch(
2718  sqlite3_pcache *p,
2719  unsigned key,
2720  int crFg
2721){
2722  sqlite3_pcache_page *pRes;
2723  if( pcachetraceOut ){
2724    fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
2725  }
2726  pRes = pcacheBase.xFetch(p, key, crFg);
2727  if( pcachetraceOut ){
2728    fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
2729            p, key, crFg, pRes);
2730  }
2731  return pRes;
2732}
2733static void pcachetraceUnpin(
2734  sqlite3_pcache *p,
2735  sqlite3_pcache_page *pPg,
2736  int bDiscard
2737){
2738  if( pcachetraceOut ){
2739    fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
2740            p, pPg, bDiscard);
2741  }
2742  pcacheBase.xUnpin(p, pPg, bDiscard);
2743}
2744static void pcachetraceRekey(
2745  sqlite3_pcache *p,
2746  sqlite3_pcache_page *pPg,
2747  unsigned oldKey,
2748  unsigned newKey
2749){
2750  if( pcachetraceOut ){
2751    fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
2752        p, pPg, oldKey, newKey);
2753  }
2754  pcacheBase.xRekey(p, pPg, oldKey, newKey);
2755}
2756static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
2757  if( pcachetraceOut ){
2758    fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
2759  }
2760  pcacheBase.xTruncate(p, n);
2761}
2762static void pcachetraceDestroy(sqlite3_pcache *p){
2763  if( pcachetraceOut ){
2764    fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
2765  }
2766  pcacheBase.xDestroy(p);
2767}
2768static void pcachetraceShrink(sqlite3_pcache *p){
2769  if( pcachetraceOut ){
2770    fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
2771  }
2772  pcacheBase.xShrink(p);
2773}
2774
2775/* The substitute pcache methods */
2776static sqlite3_pcache_methods2 ersaztPcacheMethods = {
2777  0,
2778  0,
2779  pcachetraceInit,
2780  pcachetraceShutdown,
2781  pcachetraceCreate,
2782  pcachetraceCachesize,
2783  pcachetracePagecount,
2784  pcachetraceFetch,
2785  pcachetraceUnpin,
2786  pcachetraceRekey,
2787  pcachetraceTruncate,
2788  pcachetraceDestroy,
2789  pcachetraceShrink
2790};
2791
2792/* Begin tracing memory allocations to out. */
2793static int sqlite3PcacheTraceActivate(FILE *out){
2794  int rc = SQLITE_OK;
2795  if( pcacheBase.xFetch==0 ){
2796    rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
2797    if( rc==SQLITE_OK ){
2798      rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
2799    }
2800  }
2801  pcachetraceOut = out;
2802  return rc;
2803}
2804
2805/* Deactivate memory tracing */
2806static int sqlite3PcacheTraceDeactivate(void){
2807  int rc = SQLITE_OK;
2808  if( pcacheBase.xFetch!=0 ){
2809    rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
2810    if( rc==SQLITE_OK ){
2811      memset(&pcacheBase, 0, sizeof(pcacheBase));
2812    }
2813  }
2814  pcachetraceOut = 0;
2815  return rc;
2816}
2817
2818/************************* End ../ext/misc/pcachetrace.c ********************/
2819/************************* Begin ../ext/misc/shathree.c ******************/
2820/*
2821** 2017-03-08
2822**
2823** The author disclaims copyright to this source code.  In place of
2824** a legal notice, here is a blessing:
2825**
2826**    May you do good and not evil.
2827**    May you find forgiveness for yourself and forgive others.
2828**    May you share freely, never taking more than you give.
2829**
2830******************************************************************************
2831**
2832** This SQLite extension implements functions that compute SHA3 hashes
2833** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2834** Two SQL functions are implemented:
2835**
2836**     sha3(X,SIZE)
2837**     sha3_query(Y,SIZE)
2838**
2839** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
2840** X is NULL.
2841**
2842** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
2843** and returns a hash of their results.
2844**
2845** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
2846** is used.  If SIZE is included it must be one of the integers 224, 256,
2847** 384, or 512, to determine SHA3 hash variant that is computed.
2848*/
2849/* #include "sqlite3ext.h" */
2850SQLITE_EXTENSION_INIT1
2851#include <assert.h>
2852#include <string.h>
2853#include <stdarg.h>
2854
2855#ifndef SQLITE_AMALGAMATION
2856/* typedef sqlite3_uint64 u64; */
2857#endif /* SQLITE_AMALGAMATION */
2858
2859/******************************************************************************
2860** The Hash Engine
2861*/
2862/*
2863** Macros to determine whether the machine is big or little endian,
2864** and whether or not that determination is run-time or compile-time.
2865**
2866** For best performance, an attempt is made to guess at the byte-order
2867** using C-preprocessor macros.  If that is unsuccessful, or if
2868** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2869** at run-time.
2870*/
2871#ifndef SHA3_BYTEORDER
2872# if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
2873     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
2874     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
2875     defined(__arm__)
2876#   define SHA3_BYTEORDER    1234
2877# elif defined(sparc)    || defined(__ppc__)
2878#   define SHA3_BYTEORDER    4321
2879# else
2880#   define SHA3_BYTEORDER 0
2881# endif
2882#endif
2883
2884
2885/*
2886** State structure for a SHA3 hash in progress
2887*/
2888typedef struct SHA3Context SHA3Context;
2889struct SHA3Context {
2890  union {
2891    u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
2892    unsigned char x[1600];    /* ... or 1600 bytes */
2893  } u;
2894  unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
2895  unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
2896  unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
2897};
2898
2899/*
2900** A single step of the Keccak mixing function for a 1600-bit state
2901*/
2902static void KeccakF1600Step(SHA3Context *p){
2903  int i;
2904  u64 b0, b1, b2, b3, b4;
2905  u64 c0, c1, c2, c3, c4;
2906  u64 d0, d1, d2, d3, d4;
2907  static const u64 RC[] = {
2908    0x0000000000000001ULL,  0x0000000000008082ULL,
2909    0x800000000000808aULL,  0x8000000080008000ULL,
2910    0x000000000000808bULL,  0x0000000080000001ULL,
2911    0x8000000080008081ULL,  0x8000000000008009ULL,
2912    0x000000000000008aULL,  0x0000000000000088ULL,
2913    0x0000000080008009ULL,  0x000000008000000aULL,
2914    0x000000008000808bULL,  0x800000000000008bULL,
2915    0x8000000000008089ULL,  0x8000000000008003ULL,
2916    0x8000000000008002ULL,  0x8000000000000080ULL,
2917    0x000000000000800aULL,  0x800000008000000aULL,
2918    0x8000000080008081ULL,  0x8000000000008080ULL,
2919    0x0000000080000001ULL,  0x8000000080008008ULL
2920  };
2921# define a00 (p->u.s[0])
2922# define a01 (p->u.s[1])
2923# define a02 (p->u.s[2])
2924# define a03 (p->u.s[3])
2925# define a04 (p->u.s[4])
2926# define a10 (p->u.s[5])
2927# define a11 (p->u.s[6])
2928# define a12 (p->u.s[7])
2929# define a13 (p->u.s[8])
2930# define a14 (p->u.s[9])
2931# define a20 (p->u.s[10])
2932# define a21 (p->u.s[11])
2933# define a22 (p->u.s[12])
2934# define a23 (p->u.s[13])
2935# define a24 (p->u.s[14])
2936# define a30 (p->u.s[15])
2937# define a31 (p->u.s[16])
2938# define a32 (p->u.s[17])
2939# define a33 (p->u.s[18])
2940# define a34 (p->u.s[19])
2941# define a40 (p->u.s[20])
2942# define a41 (p->u.s[21])
2943# define a42 (p->u.s[22])
2944# define a43 (p->u.s[23])
2945# define a44 (p->u.s[24])
2946# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
2947
2948  for(i=0; i<24; i+=4){
2949    c0 = a00^a10^a20^a30^a40;
2950    c1 = a01^a11^a21^a31^a41;
2951    c2 = a02^a12^a22^a32^a42;
2952    c3 = a03^a13^a23^a33^a43;
2953    c4 = a04^a14^a24^a34^a44;
2954    d0 = c4^ROL64(c1, 1);
2955    d1 = c0^ROL64(c2, 1);
2956    d2 = c1^ROL64(c3, 1);
2957    d3 = c2^ROL64(c4, 1);
2958    d4 = c3^ROL64(c0, 1);
2959
2960    b0 = (a00^d0);
2961    b1 = ROL64((a11^d1), 44);
2962    b2 = ROL64((a22^d2), 43);
2963    b3 = ROL64((a33^d3), 21);
2964    b4 = ROL64((a44^d4), 14);
2965    a00 =   b0 ^((~b1)&  b2 );
2966    a00 ^= RC[i];
2967    a11 =   b1 ^((~b2)&  b3 );
2968    a22 =   b2 ^((~b3)&  b4 );
2969    a33 =   b3 ^((~b4)&  b0 );
2970    a44 =   b4 ^((~b0)&  b1 );
2971
2972    b2 = ROL64((a20^d0), 3);
2973    b3 = ROL64((a31^d1), 45);
2974    b4 = ROL64((a42^d2), 61);
2975    b0 = ROL64((a03^d3), 28);
2976    b1 = ROL64((a14^d4), 20);
2977    a20 =   b0 ^((~b1)&  b2 );
2978    a31 =   b1 ^((~b2)&  b3 );
2979    a42 =   b2 ^((~b3)&  b4 );
2980    a03 =   b3 ^((~b4)&  b0 );
2981    a14 =   b4 ^((~b0)&  b1 );
2982
2983    b4 = ROL64((a40^d0), 18);
2984    b0 = ROL64((a01^d1), 1);
2985    b1 = ROL64((a12^d2), 6);
2986    b2 = ROL64((a23^d3), 25);
2987    b3 = ROL64((a34^d4), 8);
2988    a40 =   b0 ^((~b1)&  b2 );
2989    a01 =   b1 ^((~b2)&  b3 );
2990    a12 =   b2 ^((~b3)&  b4 );
2991    a23 =   b3 ^((~b4)&  b0 );
2992    a34 =   b4 ^((~b0)&  b1 );
2993
2994    b1 = ROL64((a10^d0), 36);
2995    b2 = ROL64((a21^d1), 10);
2996    b3 = ROL64((a32^d2), 15);
2997    b4 = ROL64((a43^d3), 56);
2998    b0 = ROL64((a04^d4), 27);
2999    a10 =   b0 ^((~b1)&  b2 );
3000    a21 =   b1 ^((~b2)&  b3 );
3001    a32 =   b2 ^((~b3)&  b4 );
3002    a43 =   b3 ^((~b4)&  b0 );
3003    a04 =   b4 ^((~b0)&  b1 );
3004
3005    b3 = ROL64((a30^d0), 41);
3006    b4 = ROL64((a41^d1), 2);
3007    b0 = ROL64((a02^d2), 62);
3008    b1 = ROL64((a13^d3), 55);
3009    b2 = ROL64((a24^d4), 39);
3010    a30 =   b0 ^((~b1)&  b2 );
3011    a41 =   b1 ^((~b2)&  b3 );
3012    a02 =   b2 ^((~b3)&  b4 );
3013    a13 =   b3 ^((~b4)&  b0 );
3014    a24 =   b4 ^((~b0)&  b1 );
3015
3016    c0 = a00^a20^a40^a10^a30;
3017    c1 = a11^a31^a01^a21^a41;
3018    c2 = a22^a42^a12^a32^a02;
3019    c3 = a33^a03^a23^a43^a13;
3020    c4 = a44^a14^a34^a04^a24;
3021    d0 = c4^ROL64(c1, 1);
3022    d1 = c0^ROL64(c2, 1);
3023    d2 = c1^ROL64(c3, 1);
3024    d3 = c2^ROL64(c4, 1);
3025    d4 = c3^ROL64(c0, 1);
3026
3027    b0 = (a00^d0);
3028    b1 = ROL64((a31^d1), 44);
3029    b2 = ROL64((a12^d2), 43);
3030    b3 = ROL64((a43^d3), 21);
3031    b4 = ROL64((a24^d4), 14);
3032    a00 =   b0 ^((~b1)&  b2 );
3033    a00 ^= RC[i+1];
3034    a31 =   b1 ^((~b2)&  b3 );
3035    a12 =   b2 ^((~b3)&  b4 );
3036    a43 =   b3 ^((~b4)&  b0 );
3037    a24 =   b4 ^((~b0)&  b1 );
3038
3039    b2 = ROL64((a40^d0), 3);
3040    b3 = ROL64((a21^d1), 45);
3041    b4 = ROL64((a02^d2), 61);
3042    b0 = ROL64((a33^d3), 28);
3043    b1 = ROL64((a14^d4), 20);
3044    a40 =   b0 ^((~b1)&  b2 );
3045    a21 =   b1 ^((~b2)&  b3 );
3046    a02 =   b2 ^((~b3)&  b4 );
3047    a33 =   b3 ^((~b4)&  b0 );
3048    a14 =   b4 ^((~b0)&  b1 );
3049
3050    b4 = ROL64((a30^d0), 18);
3051    b0 = ROL64((a11^d1), 1);
3052    b1 = ROL64((a42^d2), 6);
3053    b2 = ROL64((a23^d3), 25);
3054    b3 = ROL64((a04^d4), 8);
3055    a30 =   b0 ^((~b1)&  b2 );
3056    a11 =   b1 ^((~b2)&  b3 );
3057    a42 =   b2 ^((~b3)&  b4 );
3058    a23 =   b3 ^((~b4)&  b0 );
3059    a04 =   b4 ^((~b0)&  b1 );
3060
3061    b1 = ROL64((a20^d0), 36);
3062    b2 = ROL64((a01^d1), 10);
3063    b3 = ROL64((a32^d2), 15);
3064    b4 = ROL64((a13^d3), 56);
3065    b0 = ROL64((a44^d4), 27);
3066    a20 =   b0 ^((~b1)&  b2 );
3067    a01 =   b1 ^((~b2)&  b3 );
3068    a32 =   b2 ^((~b3)&  b4 );
3069    a13 =   b3 ^((~b4)&  b0 );
3070    a44 =   b4 ^((~b0)&  b1 );
3071
3072    b3 = ROL64((a10^d0), 41);
3073    b4 = ROL64((a41^d1), 2);
3074    b0 = ROL64((a22^d2), 62);
3075    b1 = ROL64((a03^d3), 55);
3076    b2 = ROL64((a34^d4), 39);
3077    a10 =   b0 ^((~b1)&  b2 );
3078    a41 =   b1 ^((~b2)&  b3 );
3079    a22 =   b2 ^((~b3)&  b4 );
3080    a03 =   b3 ^((~b4)&  b0 );
3081    a34 =   b4 ^((~b0)&  b1 );
3082
3083    c0 = a00^a40^a30^a20^a10;
3084    c1 = a31^a21^a11^a01^a41;
3085    c2 = a12^a02^a42^a32^a22;
3086    c3 = a43^a33^a23^a13^a03;
3087    c4 = a24^a14^a04^a44^a34;
3088    d0 = c4^ROL64(c1, 1);
3089    d1 = c0^ROL64(c2, 1);
3090    d2 = c1^ROL64(c3, 1);
3091    d3 = c2^ROL64(c4, 1);
3092    d4 = c3^ROL64(c0, 1);
3093
3094    b0 = (a00^d0);
3095    b1 = ROL64((a21^d1), 44);
3096    b2 = ROL64((a42^d2), 43);
3097    b3 = ROL64((a13^d3), 21);
3098    b4 = ROL64((a34^d4), 14);
3099    a00 =   b0 ^((~b1)&  b2 );
3100    a00 ^= RC[i+2];
3101    a21 =   b1 ^((~b2)&  b3 );
3102    a42 =   b2 ^((~b3)&  b4 );
3103    a13 =   b3 ^((~b4)&  b0 );
3104    a34 =   b4 ^((~b0)&  b1 );
3105
3106    b2 = ROL64((a30^d0), 3);
3107    b3 = ROL64((a01^d1), 45);
3108    b4 = ROL64((a22^d2), 61);
3109    b0 = ROL64((a43^d3), 28);
3110    b1 = ROL64((a14^d4), 20);
3111    a30 =   b0 ^((~b1)&  b2 );
3112    a01 =   b1 ^((~b2)&  b3 );
3113    a22 =   b2 ^((~b3)&  b4 );
3114    a43 =   b3 ^((~b4)&  b0 );
3115    a14 =   b4 ^((~b0)&  b1 );
3116
3117    b4 = ROL64((a10^d0), 18);
3118    b0 = ROL64((a31^d1), 1);
3119    b1 = ROL64((a02^d2), 6);
3120    b2 = ROL64((a23^d3), 25);
3121    b3 = ROL64((a44^d4), 8);
3122    a10 =   b0 ^((~b1)&  b2 );
3123    a31 =   b1 ^((~b2)&  b3 );
3124    a02 =   b2 ^((~b3)&  b4 );
3125    a23 =   b3 ^((~b4)&  b0 );
3126    a44 =   b4 ^((~b0)&  b1 );
3127
3128    b1 = ROL64((a40^d0), 36);
3129    b2 = ROL64((a11^d1), 10);
3130    b3 = ROL64((a32^d2), 15);
3131    b4 = ROL64((a03^d3), 56);
3132    b0 = ROL64((a24^d4), 27);
3133    a40 =   b0 ^((~b1)&  b2 );
3134    a11 =   b1 ^((~b2)&  b3 );
3135    a32 =   b2 ^((~b3)&  b4 );
3136    a03 =   b3 ^((~b4)&  b0 );
3137    a24 =   b4 ^((~b0)&  b1 );
3138
3139    b3 = ROL64((a20^d0), 41);
3140    b4 = ROL64((a41^d1), 2);
3141    b0 = ROL64((a12^d2), 62);
3142    b1 = ROL64((a33^d3), 55);
3143    b2 = ROL64((a04^d4), 39);
3144    a20 =   b0 ^((~b1)&  b2 );
3145    a41 =   b1 ^((~b2)&  b3 );
3146    a12 =   b2 ^((~b3)&  b4 );
3147    a33 =   b3 ^((~b4)&  b0 );
3148    a04 =   b4 ^((~b0)&  b1 );
3149
3150    c0 = a00^a30^a10^a40^a20;
3151    c1 = a21^a01^a31^a11^a41;
3152    c2 = a42^a22^a02^a32^a12;
3153    c3 = a13^a43^a23^a03^a33;
3154    c4 = a34^a14^a44^a24^a04;
3155    d0 = c4^ROL64(c1, 1);
3156    d1 = c0^ROL64(c2, 1);
3157    d2 = c1^ROL64(c3, 1);
3158    d3 = c2^ROL64(c4, 1);
3159    d4 = c3^ROL64(c0, 1);
3160
3161    b0 = (a00^d0);
3162    b1 = ROL64((a01^d1), 44);
3163    b2 = ROL64((a02^d2), 43);
3164    b3 = ROL64((a03^d3), 21);
3165    b4 = ROL64((a04^d4), 14);
3166    a00 =   b0 ^((~b1)&  b2 );
3167    a00 ^= RC[i+3];
3168    a01 =   b1 ^((~b2)&  b3 );
3169    a02 =   b2 ^((~b3)&  b4 );
3170    a03 =   b3 ^((~b4)&  b0 );
3171    a04 =   b4 ^((~b0)&  b1 );
3172
3173    b2 = ROL64((a10^d0), 3);
3174    b3 = ROL64((a11^d1), 45);
3175    b4 = ROL64((a12^d2), 61);
3176    b0 = ROL64((a13^d3), 28);
3177    b1 = ROL64((a14^d4), 20);
3178    a10 =   b0 ^((~b1)&  b2 );
3179    a11 =   b1 ^((~b2)&  b3 );
3180    a12 =   b2 ^((~b3)&  b4 );
3181    a13 =   b3 ^((~b4)&  b0 );
3182    a14 =   b4 ^((~b0)&  b1 );
3183
3184    b4 = ROL64((a20^d0), 18);
3185    b0 = ROL64((a21^d1), 1);
3186    b1 = ROL64((a22^d2), 6);
3187    b2 = ROL64((a23^d3), 25);
3188    b3 = ROL64((a24^d4), 8);
3189    a20 =   b0 ^((~b1)&  b2 );
3190    a21 =   b1 ^((~b2)&  b3 );
3191    a22 =   b2 ^((~b3)&  b4 );
3192    a23 =   b3 ^((~b4)&  b0 );
3193    a24 =   b4 ^((~b0)&  b1 );
3194
3195    b1 = ROL64((a30^d0), 36);
3196    b2 = ROL64((a31^d1), 10);
3197    b3 = ROL64((a32^d2), 15);
3198    b4 = ROL64((a33^d3), 56);
3199    b0 = ROL64((a34^d4), 27);
3200    a30 =   b0 ^((~b1)&  b2 );
3201    a31 =   b1 ^((~b2)&  b3 );
3202    a32 =   b2 ^((~b3)&  b4 );
3203    a33 =   b3 ^((~b4)&  b0 );
3204    a34 =   b4 ^((~b0)&  b1 );
3205
3206    b3 = ROL64((a40^d0), 41);
3207    b4 = ROL64((a41^d1), 2);
3208    b0 = ROL64((a42^d2), 62);
3209    b1 = ROL64((a43^d3), 55);
3210    b2 = ROL64((a44^d4), 39);
3211    a40 =   b0 ^((~b1)&  b2 );
3212    a41 =   b1 ^((~b2)&  b3 );
3213    a42 =   b2 ^((~b3)&  b4 );
3214    a43 =   b3 ^((~b4)&  b0 );
3215    a44 =   b4 ^((~b0)&  b1 );
3216  }
3217}
3218
3219/*
3220** Initialize a new hash.  iSize determines the size of the hash
3221** in bits and should be one of 224, 256, 384, or 512.  Or iSize
3222** can be zero to use the default hash size of 256 bits.
3223*/
3224static void SHA3Init(SHA3Context *p, int iSize){
3225  memset(p, 0, sizeof(*p));
3226  if( iSize>=128 && iSize<=512 ){
3227    p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
3228  }else{
3229    p->nRate = (1600 - 2*256)/8;
3230  }
3231#if SHA3_BYTEORDER==1234
3232  /* Known to be little-endian at compile-time. No-op */
3233#elif SHA3_BYTEORDER==4321
3234  p->ixMask = 7;  /* Big-endian */
3235#else
3236  {
3237    static unsigned int one = 1;
3238    if( 1==*(unsigned char*)&one ){
3239      /* Little endian.  No byte swapping. */
3240      p->ixMask = 0;
3241    }else{
3242      /* Big endian.  Byte swap. */
3243      p->ixMask = 7;
3244    }
3245  }
3246#endif
3247}
3248
3249/*
3250** Make consecutive calls to the SHA3Update function to add new content
3251** to the hash
3252*/
3253static void SHA3Update(
3254  SHA3Context *p,
3255  const unsigned char *aData,
3256  unsigned int nData
3257){
3258  unsigned int i = 0;
3259  if( aData==0 ) return;
3260#if SHA3_BYTEORDER==1234
3261  if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
3262    for(; i+7<nData; i+=8){
3263      p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
3264      p->nLoaded += 8;
3265      if( p->nLoaded>=p->nRate ){
3266        KeccakF1600Step(p);
3267        p->nLoaded = 0;
3268      }
3269    }
3270  }
3271#endif
3272  for(; i<nData; i++){
3273#if SHA3_BYTEORDER==1234
3274    p->u.x[p->nLoaded] ^= aData[i];
3275#elif SHA3_BYTEORDER==4321
3276    p->u.x[p->nLoaded^0x07] ^= aData[i];
3277#else
3278    p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
3279#endif
3280    p->nLoaded++;
3281    if( p->nLoaded==p->nRate ){
3282      KeccakF1600Step(p);
3283      p->nLoaded = 0;
3284    }
3285  }
3286}
3287
3288/*
3289** After all content has been added, invoke SHA3Final() to compute
3290** the final hash.  The function returns a pointer to the binary
3291** hash value.
3292*/
3293static unsigned char *SHA3Final(SHA3Context *p){
3294  unsigned int i;
3295  if( p->nLoaded==p->nRate-1 ){
3296    const unsigned char c1 = 0x86;
3297    SHA3Update(p, &c1, 1);
3298  }else{
3299    const unsigned char c2 = 0x06;
3300    const unsigned char c3 = 0x80;
3301    SHA3Update(p, &c2, 1);
3302    p->nLoaded = p->nRate - 1;
3303    SHA3Update(p, &c3, 1);
3304  }
3305  for(i=0; i<p->nRate; i++){
3306    p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
3307  }
3308  return &p->u.x[p->nRate];
3309}
3310/* End of the hashing logic
3311*****************************************************************************/
3312
3313/*
3314** Implementation of the sha3(X,SIZE) function.
3315**
3316** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
3317** size is 256.  If X is a BLOB, it is hashed as is.
3318** For all other non-NULL types of input, X is converted into a UTF-8 string
3319** and the string is hashed without the trailing 0x00 terminator.  The hash
3320** of a NULL value is NULL.
3321*/
3322static void sha3Func(
3323  sqlite3_context *context,
3324  int argc,
3325  sqlite3_value **argv
3326){
3327  SHA3Context cx;
3328  int eType = sqlite3_value_type(argv[0]);
3329  int nByte = sqlite3_value_bytes(argv[0]);
3330  int iSize;
3331  if( argc==1 ){
3332    iSize = 256;
3333  }else{
3334    iSize = sqlite3_value_int(argv[1]);
3335    if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3336      sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3337                                    "384 512", -1);
3338      return;
3339    }
3340  }
3341  if( eType==SQLITE_NULL ) return;
3342  SHA3Init(&cx, iSize);
3343  if( eType==SQLITE_BLOB ){
3344    SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
3345  }else{
3346    SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
3347  }
3348  sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3349}
3350
3351/* Compute a string using sqlite3_vsnprintf() with a maximum length
3352** of 50 bytes and add it to the hash.
3353*/
3354static void sha3_step_vformat(
3355  SHA3Context *p,                 /* Add content to this context */
3356  const char *zFormat,
3357  ...
3358){
3359  va_list ap;
3360  int n;
3361  char zBuf[50];
3362  va_start(ap, zFormat);
3363  sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
3364  va_end(ap);
3365  n = (int)strlen(zBuf);
3366  SHA3Update(p, (unsigned char*)zBuf, n);
3367}
3368
3369/*
3370** Implementation of the sha3_query(SQL,SIZE) function.
3371**
3372** This function compiles and runs the SQL statement(s) given in the
3373** argument. The results are hashed using a SIZE-bit SHA3.  The default
3374** size is 256.
3375**
3376** The format of the byte stream that is hashed is summarized as follows:
3377**
3378**       S<n>:<sql>
3379**       R
3380**       N
3381**       I<int>
3382**       F<ieee-float>
3383**       B<size>:<bytes>
3384**       T<size>:<text>
3385**
3386** <sql> is the original SQL text for each statement run and <n> is
3387** the size of that text.  The SQL text is UTF-8.  A single R character
3388** occurs before the start of each row.  N means a NULL value.
3389** I mean an 8-byte little-endian integer <int>.  F is a floating point
3390** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3391** B means blobs of <size> bytes.  T means text rendered as <size>
3392** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
3393** text integers.
3394**
3395** For each SQL statement in the X input, there is one S segment.  Each
3396** S segment is followed by zero or more R segments, one for each row in the
3397** result set.  After each R, there are one or more N, I, F, B, or T segments,
3398** one for each column in the result set.  Segments are concatentated directly
3399** with no delimiters of any kind.
3400*/
3401static void sha3QueryFunc(
3402  sqlite3_context *context,
3403  int argc,
3404  sqlite3_value **argv
3405){
3406  sqlite3 *db = sqlite3_context_db_handle(context);
3407  const char *zSql = (const char*)sqlite3_value_text(argv[0]);
3408  sqlite3_stmt *pStmt = 0;
3409  int nCol;                   /* Number of columns in the result set */
3410  int i;                      /* Loop counter */
3411  int rc;
3412  int n;
3413  const char *z;
3414  SHA3Context cx;
3415  int iSize;
3416
3417  if( argc==1 ){
3418    iSize = 256;
3419  }else{
3420    iSize = sqlite3_value_int(argv[1]);
3421    if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3422      sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3423                                    "384 512", -1);
3424      return;
3425    }
3426  }
3427  if( zSql==0 ) return;
3428  SHA3Init(&cx, iSize);
3429  while( zSql[0] ){
3430    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
3431    if( rc ){
3432      char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
3433                                   zSql, sqlite3_errmsg(db));
3434      sqlite3_finalize(pStmt);
3435      sqlite3_result_error(context, zMsg, -1);
3436      sqlite3_free(zMsg);
3437      return;
3438    }
3439    if( !sqlite3_stmt_readonly(pStmt) ){
3440      char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
3441      sqlite3_finalize(pStmt);
3442      sqlite3_result_error(context, zMsg, -1);
3443      sqlite3_free(zMsg);
3444      return;
3445    }
3446    nCol = sqlite3_column_count(pStmt);
3447    z = sqlite3_sql(pStmt);
3448    if( z ){
3449      n = (int)strlen(z);
3450      sha3_step_vformat(&cx,"S%d:",n);
3451      SHA3Update(&cx,(unsigned char*)z,n);
3452    }
3453
3454    /* Compute a hash over the result of the query */
3455    while( SQLITE_ROW==sqlite3_step(pStmt) ){
3456      SHA3Update(&cx,(const unsigned char*)"R",1);
3457      for(i=0; i<nCol; i++){
3458        switch( sqlite3_column_type(pStmt,i) ){
3459          case SQLITE_NULL: {
3460            SHA3Update(&cx, (const unsigned char*)"N",1);
3461            break;
3462          }
3463          case SQLITE_INTEGER: {
3464            sqlite3_uint64 u;
3465            int j;
3466            unsigned char x[9];
3467            sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
3468            memcpy(&u, &v, 8);
3469            for(j=8; j>=1; j--){
3470              x[j] = u & 0xff;
3471              u >>= 8;
3472            }
3473            x[0] = 'I';
3474            SHA3Update(&cx, x, 9);
3475            break;
3476          }
3477          case SQLITE_FLOAT: {
3478            sqlite3_uint64 u;
3479            int j;
3480            unsigned char x[9];
3481            double r = sqlite3_column_double(pStmt,i);
3482            memcpy(&u, &r, 8);
3483            for(j=8; j>=1; j--){
3484              x[j] = u & 0xff;
3485              u >>= 8;
3486            }
3487            x[0] = 'F';
3488            SHA3Update(&cx,x,9);
3489            break;
3490          }
3491          case SQLITE_TEXT: {
3492            int n2 = sqlite3_column_bytes(pStmt, i);
3493            const unsigned char *z2 = sqlite3_column_text(pStmt, i);
3494            sha3_step_vformat(&cx,"T%d:",n2);
3495            SHA3Update(&cx, z2, n2);
3496            break;
3497          }
3498          case SQLITE_BLOB: {
3499            int n2 = sqlite3_column_bytes(pStmt, i);
3500            const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
3501            sha3_step_vformat(&cx,"B%d:",n2);
3502            SHA3Update(&cx, z2, n2);
3503            break;
3504          }
3505        }
3506      }
3507    }
3508    sqlite3_finalize(pStmt);
3509  }
3510  sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3511}
3512
3513
3514#ifdef _WIN32
3515
3516#endif
3517static int sqlite3_shathree_init(
3518  sqlite3 *db,
3519  char **pzErrMsg,
3520  const sqlite3_api_routines *pApi
3521){
3522  int rc = SQLITE_OK;
3523  SQLITE_EXTENSION_INIT2(pApi);
3524  (void)pzErrMsg;  /* Unused parameter */
3525  rc = sqlite3_create_function(db, "sha3", 1,
3526                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3527                      0, sha3Func, 0, 0);
3528  if( rc==SQLITE_OK ){
3529    rc = sqlite3_create_function(db, "sha3", 2,
3530                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3531                      0, sha3Func, 0, 0);
3532  }
3533  if( rc==SQLITE_OK ){
3534    rc = sqlite3_create_function(db, "sha3_query", 1,
3535                      SQLITE_UTF8 | SQLITE_DIRECTONLY,
3536                      0, sha3QueryFunc, 0, 0);
3537  }
3538  if( rc==SQLITE_OK ){
3539    rc = sqlite3_create_function(db, "sha3_query", 2,
3540                      SQLITE_UTF8 | SQLITE_DIRECTONLY,
3541                      0, sha3QueryFunc, 0, 0);
3542  }
3543  return rc;
3544}
3545
3546/************************* End ../ext/misc/shathree.c ********************/
3547/************************* Begin ../ext/misc/uint.c ******************/
3548/*
3549** 2020-04-14
3550**
3551** The author disclaims copyright to this source code.  In place of
3552** a legal notice, here is a blessing:
3553**
3554**    May you do good and not evil.
3555**    May you find forgiveness for yourself and forgive others.
3556**    May you share freely, never taking more than you give.
3557**
3558******************************************************************************
3559**
3560** This SQLite extension implements the UINT collating sequence.
3561**
3562** UINT works like BINARY for text, except that embedded strings
3563** of digits compare in numeric order.
3564**
3565**     *   Leading zeros are handled properly, in the sense that
3566**         they do not mess of the maginitude comparison of embedded
3567**         strings of digits.  "x00123y" is equal to "x123y".
3568**
3569**     *   Only unsigned integers are recognized.  Plus and minus
3570**         signs are ignored.  Decimal points and exponential notation
3571**         are ignored.
3572**
3573**     *   Embedded integers can be of arbitrary length.  Comparison
3574**         is *not* limited integers that can be expressed as a
3575**         64-bit machine integer.
3576*/
3577/* #include "sqlite3ext.h" */
3578SQLITE_EXTENSION_INIT1
3579#include <assert.h>
3580#include <string.h>
3581#include <ctype.h>
3582
3583/*
3584** Compare text in lexicographic order, except strings of digits
3585** compare in numeric order.
3586*/
3587static int uintCollFunc(
3588  void *notUsed,
3589  int nKey1, const void *pKey1,
3590  int nKey2, const void *pKey2
3591){
3592  const unsigned char *zA = (const unsigned char*)pKey1;
3593  const unsigned char *zB = (const unsigned char*)pKey2;
3594  int i=0, j=0, x;
3595  (void)notUsed;
3596  while( i<nKey1 && j<nKey2 ){
3597    x = zA[i] - zB[j];
3598    if( isdigit(zA[i]) ){
3599      int k;
3600      if( !isdigit(zB[j]) ) return x;
3601      while( i<nKey1 && zA[i]=='0' ){ i++; }
3602      while( j<nKey2 && zB[j]=='0' ){ j++; }
3603      k = 0;
3604      while( i+k<nKey1 && isdigit(zA[i+k])
3605             && j+k<nKey2 && isdigit(zB[j+k]) ){
3606        k++;
3607      }
3608      if( i+k<nKey1 && isdigit(zA[i+k]) ){
3609        return +1;
3610      }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
3611        return -1;
3612      }else{
3613        x = memcmp(zA+i, zB+j, k);
3614        if( x ) return x;
3615        i += k;
3616        j += k;
3617      }
3618    }else if( x ){
3619      return x;
3620    }else{
3621      i++;
3622      j++;
3623    }
3624  }
3625  return (nKey1 - i) - (nKey2 - j);
3626}
3627
3628#ifdef _WIN32
3629
3630#endif
3631static int sqlite3_uint_init(
3632  sqlite3 *db,
3633  char **pzErrMsg,
3634  const sqlite3_api_routines *pApi
3635){
3636  SQLITE_EXTENSION_INIT2(pApi);
3637  (void)pzErrMsg;  /* Unused parameter */
3638  return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
3639}
3640
3641/************************* End ../ext/misc/uint.c ********************/
3642/************************* Begin ../ext/misc/decimal.c ******************/
3643/*
3644** 2020-06-22
3645**
3646** The author disclaims copyright to this source code.  In place of
3647** a legal notice, here is a blessing:
3648**
3649**    May you do good and not evil.
3650**    May you find forgiveness for yourself and forgive others.
3651**    May you share freely, never taking more than you give.
3652**
3653******************************************************************************
3654**
3655** Routines to implement arbitrary-precision decimal math.
3656**
3657** The focus here is on simplicity and correctness, not performance.
3658*/
3659/* #include "sqlite3ext.h" */
3660SQLITE_EXTENSION_INIT1
3661#include <assert.h>
3662#include <string.h>
3663#include <ctype.h>
3664#include <stdlib.h>
3665
3666/* Mark a function parameter as unused, to suppress nuisance compiler
3667** warnings. */
3668#ifndef UNUSED_PARAMETER
3669# define UNUSED_PARAMETER(X)  (void)(X)
3670#endif
3671
3672
3673/* A decimal object */
3674typedef struct Decimal Decimal;
3675struct Decimal {
3676  char sign;        /* 0 for positive, 1 for negative */
3677  char oom;         /* True if an OOM is encountered */
3678  char isNull;      /* True if holds a NULL rather than a number */
3679  char isInit;      /* True upon initialization */
3680  int nDigit;       /* Total number of digits */
3681  int nFrac;        /* Number of digits to the right of the decimal point */
3682  signed char *a;   /* Array of digits.  Most significant first. */
3683};
3684
3685/*
3686** Release memory held by a Decimal, but do not free the object itself.
3687*/
3688static void decimal_clear(Decimal *p){
3689  sqlite3_free(p->a);
3690}
3691
3692/*
3693** Destroy a Decimal object
3694*/
3695static void decimal_free(Decimal *p){
3696  if( p ){
3697    decimal_clear(p);
3698    sqlite3_free(p);
3699  }
3700}
3701
3702/*
3703** Allocate a new Decimal object initialized to the text in zIn[].
3704** Return NULL if any kind of error occurs.
3705*/
3706static Decimal *decimalNewFromText(const char *zIn, int n){
3707  Decimal *p = 0;
3708  int i;
3709  int iExp = 0;
3710
3711  p = sqlite3_malloc( sizeof(*p) );
3712  if( p==0 ) goto new_from_text_failed;
3713  p->sign = 0;
3714  p->oom = 0;
3715  p->isInit = 1;
3716  p->isNull = 0;
3717  p->nDigit = 0;
3718  p->nFrac = 0;
3719  p->a = sqlite3_malloc64( n+1 );
3720  if( p->a==0 ) goto new_from_text_failed;
3721  for(i=0; isspace((unsigned char)zIn[i]); i++){}
3722  if( zIn[i]=='-' ){
3723    p->sign = 1;
3724    i++;
3725  }else if( zIn[i]=='+' ){
3726    i++;
3727  }
3728  while( i<n && zIn[i]=='0' ) i++;
3729  while( i<n ){
3730    char c = zIn[i];
3731    if( c>='0' && c<='9' ){
3732      p->a[p->nDigit++] = c - '0';
3733    }else if( c=='.' ){
3734      p->nFrac = p->nDigit + 1;
3735    }else if( c=='e' || c=='E' ){
3736      int j = i+1;
3737      int neg = 0;
3738      if( j>=n ) break;
3739      if( zIn[j]=='-' ){
3740        neg = 1;
3741        j++;
3742      }else if( zIn[j]=='+' ){
3743        j++;
3744      }
3745      while( j<n && iExp<1000000 ){
3746        if( zIn[j]>='0' && zIn[j]<='9' ){
3747          iExp = iExp*10 + zIn[j] - '0';
3748        }
3749        j++;
3750      }
3751      if( neg ) iExp = -iExp;
3752      break;
3753    }
3754    i++;
3755  }
3756  if( p->nFrac ){
3757    p->nFrac = p->nDigit - (p->nFrac - 1);
3758  }
3759  if( iExp>0 ){
3760    if( p->nFrac>0 ){
3761      if( iExp<=p->nFrac ){
3762        p->nFrac -= iExp;
3763        iExp = 0;
3764      }else{
3765        iExp -= p->nFrac;
3766        p->nFrac = 0;
3767      }
3768    }
3769    if( iExp>0 ){
3770      p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3771      if( p->a==0 ) goto new_from_text_failed;
3772      memset(p->a+p->nDigit, 0, iExp);
3773      p->nDigit += iExp;
3774    }
3775  }else if( iExp<0 ){
3776    int nExtra;
3777    iExp = -iExp;
3778    nExtra = p->nDigit - p->nFrac - 1;
3779    if( nExtra ){
3780      if( nExtra>=iExp ){
3781        p->nFrac += iExp;
3782        iExp  = 0;
3783      }else{
3784        iExp -= nExtra;
3785        p->nFrac = p->nDigit - 1;
3786      }
3787    }
3788    if( iExp>0 ){
3789      p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3790      if( p->a==0 ) goto new_from_text_failed;
3791      memmove(p->a+iExp, p->a, p->nDigit);
3792      memset(p->a, 0, iExp);
3793      p->nDigit += iExp;
3794      p->nFrac += iExp;
3795    }
3796  }
3797  return p;
3798
3799new_from_text_failed:
3800  if( p ){
3801    if( p->a ) sqlite3_free(p->a);
3802    sqlite3_free(p);
3803  }
3804  return 0;
3805}
3806
3807/* Forward reference */
3808static Decimal *decimalFromDouble(double);
3809
3810/*
3811** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
3812** to the new object, or NULL if there is an error.  If the pCtx argument
3813** is not NULL, then errors are reported on it as well.
3814**
3815** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3816** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
3817** 8 bytes, the resulting double value is expanded into its decimal equivalent.
3818** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3819** then NULL is returned.
3820*/
3821static Decimal *decimal_new(
3822  sqlite3_context *pCtx,       /* Report error here, if not null */
3823  sqlite3_value *pIn,          /* Construct the decimal object from this */
3824  int bTextOnly                /* Always interpret pIn as text if true */
3825){
3826  Decimal *p = 0;
3827  int eType = sqlite3_value_type(pIn);
3828  if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
3829    eType = SQLITE_TEXT;
3830  }
3831  switch( eType ){
3832    case SQLITE_TEXT:
3833    case SQLITE_INTEGER: {
3834      const char *zIn = (const char*)sqlite3_value_text(pIn);
3835      int n = sqlite3_value_bytes(pIn);
3836      p = decimalNewFromText(zIn, n);
3837      if( p==0 ) goto new_failed;
3838      break;
3839    }
3840
3841    case SQLITE_FLOAT: {
3842      p = decimalFromDouble(sqlite3_value_double(pIn));
3843      break;
3844    }
3845
3846    case SQLITE_BLOB: {
3847      const unsigned char *x;
3848      unsigned int i;
3849      sqlite3_uint64 v = 0;
3850      double r;
3851
3852      if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
3853      x = sqlite3_value_blob(pIn);
3854      for(i=0; i<sizeof(r); i++){
3855        v = (v<<8) | x[i];
3856      }
3857      memcpy(&r, &v, sizeof(r));
3858      p = decimalFromDouble(r);
3859      break;
3860    }
3861
3862    case SQLITE_NULL: {
3863      break;
3864    }
3865  }
3866  return p;
3867
3868new_failed:
3869  if( pCtx ) sqlite3_result_error_nomem(pCtx);
3870  sqlite3_free(p);
3871  return 0;
3872}
3873
3874/*
3875** Make the given Decimal the result.
3876*/
3877static void decimal_result(sqlite3_context *pCtx, Decimal *p){
3878  char *z;
3879  int i, j;
3880  int n;
3881  if( p==0 || p->oom ){
3882    sqlite3_result_error_nomem(pCtx);
3883    return;
3884  }
3885  if( p->isNull ){
3886    sqlite3_result_null(pCtx);
3887    return;
3888  }
3889  z = sqlite3_malloc( p->nDigit+4 );
3890  if( z==0 ){
3891    sqlite3_result_error_nomem(pCtx);
3892    return;
3893  }
3894  i = 0;
3895  if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
3896    p->sign = 0;
3897  }
3898  if( p->sign ){
3899    z[0] = '-';
3900    i = 1;
3901  }
3902  n = p->nDigit - p->nFrac;
3903  if( n<=0 ){
3904    z[i++] = '0';
3905  }
3906  j = 0;
3907  while( n>1 && p->a[j]==0 ){
3908    j++;
3909    n--;
3910  }
3911  while( n>0  ){
3912    z[i++] = p->a[j] + '0';
3913    j++;
3914    n--;
3915  }
3916  if( p->nFrac ){
3917    z[i++] = '.';
3918    do{
3919      z[i++] = p->a[j] + '0';
3920      j++;
3921    }while( j<p->nDigit );
3922  }
3923  z[i] = 0;
3924  sqlite3_result_text(pCtx, z, i, sqlite3_free);
3925}
3926
3927/*
3928** Make the given Decimal the result in an format similar to  '%+#e'.
3929** In other words, show exponential notation with leading and trailing
3930** zeros omitted.
3931*/
3932static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){
3933  char *z;       /* The output buffer */
3934  int i;         /* Loop counter */
3935  int nZero;     /* Number of leading zeros */
3936  int nDigit;    /* Number of digits not counting trailing zeros */
3937  int nFrac;     /* Digits to the right of the decimal point */
3938  int exp;       /* Exponent value */
3939  signed char zero;     /* Zero value */
3940  signed char *a;       /* Array of digits */
3941
3942  if( p==0 || p->oom ){
3943    sqlite3_result_error_nomem(pCtx);
3944    return;
3945  }
3946  if( p->isNull ){
3947    sqlite3_result_null(pCtx);
3948    return;
3949  }
3950  for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){}
3951  for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
3952  nFrac = p->nFrac + (nDigit - p->nDigit);
3953  nDigit -= nZero;
3954  z = sqlite3_malloc( nDigit+20 );
3955  if( z==0 ){
3956    sqlite3_result_error_nomem(pCtx);
3957    return;
3958  }
3959  if( nDigit==0 ){
3960    zero = 0;
3961    a = &zero;
3962    nDigit = 1;
3963    nFrac = 0;
3964  }else{
3965    a = &p->a[nZero];
3966  }
3967  if( p->sign && nDigit>0 ){
3968    z[0] = '-';
3969  }else{
3970    z[0] = '+';
3971  }
3972  z[1] = a[0]+'0';
3973  z[2] = '.';
3974  if( nDigit==1 ){
3975    z[3] = '0';
3976    i = 4;
3977  }else{
3978    for(i=1; i<nDigit; i++){
3979      z[2+i] = a[i]+'0';
3980    }
3981    i = nDigit+2;
3982  }
3983  exp = nDigit - nFrac - 1;
3984  sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
3985  sqlite3_result_text(pCtx, z, -1, sqlite3_free);
3986}
3987
3988/*
3989** Compare to Decimal objects.  Return negative, 0, or positive if the
3990** first object is less than, equal to, or greater than the second.
3991**
3992** Preconditions for this routine:
3993**
3994**    pA!=0
3995**    pA->isNull==0
3996**    pB!=0
3997**    pB->isNull==0
3998*/
3999static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4000  int nASig, nBSig, rc, n;
4001  if( pA->sign!=pB->sign ){
4002    return pA->sign ? -1 : +1;
4003  }
4004  if( pA->sign ){
4005    const Decimal *pTemp = pA;
4006    pA = pB;
4007    pB = pTemp;
4008  }
4009  nASig = pA->nDigit - pA->nFrac;
4010  nBSig = pB->nDigit - pB->nFrac;
4011  if( nASig!=nBSig ){
4012    return nASig - nBSig;
4013  }
4014  n = pA->nDigit;
4015  if( n>pB->nDigit ) n = pB->nDigit;
4016  rc = memcmp(pA->a, pB->a, n);
4017  if( rc==0 ){
4018    rc = pA->nDigit - pB->nDigit;
4019  }
4020  return rc;
4021}
4022
4023/*
4024** SQL Function:   decimal_cmp(X, Y)
4025**
4026** Return negative, zero, or positive if X is less then, equal to, or
4027** greater than Y.
4028*/
4029static void decimalCmpFunc(
4030  sqlite3_context *context,
4031  int argc,
4032  sqlite3_value **argv
4033){
4034  Decimal *pA = 0, *pB = 0;
4035  int rc;
4036
4037  UNUSED_PARAMETER(argc);
4038  pA = decimal_new(context, argv[0], 1);
4039  if( pA==0 || pA->isNull ) goto cmp_done;
4040  pB = decimal_new(context, argv[1], 1);
4041  if( pB==0 || pB->isNull ) goto cmp_done;
4042  rc = decimal_cmp(pA, pB);
4043  if( rc<0 ) rc = -1;
4044  else if( rc>0 ) rc = +1;
4045  sqlite3_result_int(context, rc);
4046cmp_done:
4047  decimal_free(pA);
4048  decimal_free(pB);
4049}
4050
4051/*
4052** Expand the Decimal so that it has a least nDigit digits and nFrac
4053** digits to the right of the decimal point.
4054*/
4055static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4056  int nAddSig;
4057  int nAddFrac;
4058  if( p==0 ) return;
4059  nAddFrac = nFrac - p->nFrac;
4060  nAddSig = (nDigit - p->nDigit) - nAddFrac;
4061  if( nAddFrac==0 && nAddSig==0 ) return;
4062  p->a = sqlite3_realloc64(p->a, nDigit+1);
4063  if( p->a==0 ){
4064    p->oom = 1;
4065    return;
4066  }
4067  if( nAddSig ){
4068    memmove(p->a+nAddSig, p->a, p->nDigit);
4069    memset(p->a, 0, nAddSig);
4070    p->nDigit += nAddSig;
4071  }
4072  if( nAddFrac ){
4073    memset(p->a+p->nDigit, 0, nAddFrac);
4074    p->nDigit += nAddFrac;
4075    p->nFrac += nAddFrac;
4076  }
4077}
4078
4079/*
4080** Add the value pB into pA.   A := A + B.
4081**
4082** Both pA and pB might become denormalized by this routine.
4083*/
4084static void decimal_add(Decimal *pA, Decimal *pB){
4085  int nSig, nFrac, nDigit;
4086  int i, rc;
4087  if( pA==0 ){
4088    return;
4089  }
4090  if( pA->oom || pB==0 || pB->oom ){
4091    pA->oom = 1;
4092    return;
4093  }
4094  if( pA->isNull || pB->isNull ){
4095    pA->isNull = 1;
4096    return;
4097  }
4098  nSig = pA->nDigit - pA->nFrac;
4099  if( nSig && pA->a[0]==0 ) nSig--;
4100  if( nSig<pB->nDigit-pB->nFrac ){
4101    nSig = pB->nDigit - pB->nFrac;
4102  }
4103  nFrac = pA->nFrac;
4104  if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4105  nDigit = nSig + nFrac + 1;
4106  decimal_expand(pA, nDigit, nFrac);
4107  decimal_expand(pB, nDigit, nFrac);
4108  if( pA->oom || pB->oom ){
4109    pA->oom = 1;
4110  }else{
4111    if( pA->sign==pB->sign ){
4112      int carry = 0;
4113      for(i=nDigit-1; i>=0; i--){
4114        int x = pA->a[i] + pB->a[i] + carry;
4115        if( x>=10 ){
4116          carry = 1;
4117          pA->a[i] = x - 10;
4118        }else{
4119          carry = 0;
4120          pA->a[i] = x;
4121        }
4122      }
4123    }else{
4124      signed char *aA, *aB;
4125      int borrow = 0;
4126      rc = memcmp(pA->a, pB->a, nDigit);
4127      if( rc<0 ){
4128        aA = pB->a;
4129        aB = pA->a;
4130        pA->sign = !pA->sign;
4131      }else{
4132        aA = pA->a;
4133        aB = pB->a;
4134      }
4135      for(i=nDigit-1; i>=0; i--){
4136        int x = aA[i] - aB[i] - borrow;
4137        if( x<0 ){
4138          pA->a[i] = x+10;
4139          borrow = 1;
4140        }else{
4141          pA->a[i] = x;
4142          borrow = 0;
4143        }
4144      }
4145    }
4146  }
4147}
4148
4149/*
4150** Multiply A by B.   A := A * B
4151**
4152** All significant digits after the decimal point are retained.
4153** Trailing zeros after the decimal point are omitted as long as
4154** the number of digits after the decimal point is no less than
4155** either the number of digits in either input.
4156*/
4157static void decimalMul(Decimal *pA, Decimal *pB){
4158  signed char *acc = 0;
4159  int i, j, k;
4160  int minFrac;
4161
4162  if( pA==0 || pA->oom || pA->isNull
4163   || pB==0 || pB->oom || pB->isNull
4164  ){
4165    goto mul_end;
4166  }
4167  acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
4168  if( acc==0 ){
4169    pA->oom = 1;
4170    goto mul_end;
4171  }
4172  memset(acc, 0, pA->nDigit + pB->nDigit + 2);
4173  minFrac = pA->nFrac;
4174  if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
4175  for(i=pA->nDigit-1; i>=0; i--){
4176    signed char f = pA->a[i];
4177    int carry = 0, x;
4178    for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
4179      x = acc[k] + f*pB->a[j] + carry;
4180      acc[k] = x%10;
4181      carry = x/10;
4182    }
4183    x = acc[k] + carry;
4184    acc[k] = x%10;
4185    acc[k-1] += x/10;
4186  }
4187  sqlite3_free(pA->a);
4188  pA->a = acc;
4189  acc = 0;
4190  pA->nDigit += pB->nDigit + 2;
4191  pA->nFrac += pB->nFrac;
4192  pA->sign ^= pB->sign;
4193  while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
4194    pA->nFrac--;
4195    pA->nDigit--;
4196  }
4197
4198mul_end:
4199  sqlite3_free(acc);
4200}
4201
4202/*
4203** Create a new Decimal object that contains an integer power of 2.
4204*/
4205static Decimal *decimalPow2(int N){
4206  Decimal *pA = 0;      /* The result to be returned */
4207  Decimal *pX = 0;      /* Multiplier */
4208  if( N<-20000 || N>20000 ) goto pow2_fault;
4209  pA = decimalNewFromText("1.0", 3);
4210  if( pA==0 || pA->oom ) goto pow2_fault;
4211  if( N==0 ) return pA;
4212  if( N>0 ){
4213    pX = decimalNewFromText("2.0", 3);
4214  }else{
4215    N = -N;
4216    pX = decimalNewFromText("0.5", 3);
4217  }
4218  if( pX==0 || pX->oom ) goto pow2_fault;
4219  while( 1 /* Exit by break */ ){
4220    if( N & 1 ){
4221      decimalMul(pA, pX);
4222      if( pA->oom ) goto pow2_fault;
4223    }
4224    N >>= 1;
4225    if( N==0 ) break;
4226    decimalMul(pX, pX);
4227  }
4228  decimal_free(pX);
4229  return pA;
4230
4231pow2_fault:
4232  decimal_free(pA);
4233  decimal_free(pX);
4234  return 0;
4235}
4236
4237/*
4238** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
4239*/
4240static Decimal *decimalFromDouble(double r){
4241  sqlite3_int64 m, a;
4242  int e;
4243  int isNeg;
4244  Decimal *pA;
4245  Decimal *pX;
4246  char zNum[100];
4247  if( r<0.0 ){
4248    isNeg = 1;
4249    r = -r;
4250  }else{
4251    isNeg = 0;
4252  }
4253  memcpy(&a,&r,sizeof(a));
4254  if( a==0 ){
4255    e = 0;
4256    m = 0;
4257  }else{
4258    e = a>>52;
4259    m = a & ((((sqlite3_int64)1)<<52)-1);
4260    if( e==0 ){
4261      m <<= 1;
4262    }else{
4263      m |= ((sqlite3_int64)1)<<52;
4264    }
4265    while( e<1075 && m>0 && (m&1)==0 ){
4266      m >>= 1;
4267      e++;
4268    }
4269    if( isNeg ) m = -m;
4270    e = e - 1075;
4271    if( e>971 ){
4272      return 0;  /* A NaN or an Infinity */
4273    }
4274  }
4275
4276  /* At this point m is the integer significand and e is the exponent */
4277  sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
4278  pA = decimalNewFromText(zNum, (int)strlen(zNum));
4279  pX = decimalPow2(e);
4280  decimalMul(pA, pX);
4281  decimal_free(pX);
4282  return pA;
4283}
4284
4285/*
4286** SQL Function:   decimal(X)
4287** OR:             decimal_exp(X)
4288**
4289** Convert input X into decimal and then back into text.
4290**
4291** If X is originally a float, then a full decimal expansion of that floating
4292** point value is done.  Or if X is an 8-byte blob, it is interpreted
4293** as a float and similarly expanded.
4294**
4295** The decimal_exp(X) function returns the result in exponential notation.
4296** decimal(X) returns a complete decimal, without the e+NNN at the end.
4297*/
4298static void decimalFunc(
4299  sqlite3_context *context,
4300  int argc,
4301  sqlite3_value **argv
4302){
4303  Decimal *p =  decimal_new(context, argv[0], 0);
4304  UNUSED_PARAMETER(argc);
4305  if( p ){
4306    if( sqlite3_user_data(context)!=0 ){
4307      decimal_result_sci(context, p);
4308    }else{
4309      decimal_result(context, p);
4310    }
4311    decimal_free(p);
4312  }
4313}
4314
4315/*
4316** Compare text in decimal order.
4317*/
4318static int decimalCollFunc(
4319  void *notUsed,
4320  int nKey1, const void *pKey1,
4321  int nKey2, const void *pKey2
4322){
4323  const unsigned char *zA = (const unsigned char*)pKey1;
4324  const unsigned char *zB = (const unsigned char*)pKey2;
4325  Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
4326  Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
4327  int rc;
4328  UNUSED_PARAMETER(notUsed);
4329  if( pA==0 || pB==0 ){
4330    rc = 0;
4331  }else{
4332    rc = decimal_cmp(pA, pB);
4333  }
4334  decimal_free(pA);
4335  decimal_free(pB);
4336  return rc;
4337}
4338
4339
4340/*
4341** SQL Function:   decimal_add(X, Y)
4342**                 decimal_sub(X, Y)
4343**
4344** Return the sum or difference of X and Y.
4345*/
4346static void decimalAddFunc(
4347  sqlite3_context *context,
4348  int argc,
4349  sqlite3_value **argv
4350){
4351  Decimal *pA = decimal_new(context, argv[0], 1);
4352  Decimal *pB = decimal_new(context, argv[1], 1);
4353  UNUSED_PARAMETER(argc);
4354  decimal_add(pA, pB);
4355  decimal_result(context, pA);
4356  decimal_free(pA);
4357  decimal_free(pB);
4358}
4359static void decimalSubFunc(
4360  sqlite3_context *context,
4361  int argc,
4362  sqlite3_value **argv
4363){
4364  Decimal *pA = decimal_new(context, argv[0], 1);
4365  Decimal *pB = decimal_new(context, argv[1], 1);
4366  UNUSED_PARAMETER(argc);
4367  if( pB ){
4368    pB->sign = !pB->sign;
4369    decimal_add(pA, pB);
4370    decimal_result(context, pA);
4371  }
4372  decimal_free(pA);
4373  decimal_free(pB);
4374}
4375
4376/* Aggregate funcion:   decimal_sum(X)
4377**
4378** Works like sum() except that it uses decimal arithmetic for unlimited
4379** precision.
4380*/
4381static void decimalSumStep(
4382  sqlite3_context *context,
4383  int argc,
4384  sqlite3_value **argv
4385){
4386  Decimal *p;
4387  Decimal *pArg;
4388  UNUSED_PARAMETER(argc);
4389  p = sqlite3_aggregate_context(context, sizeof(*p));
4390  if( p==0 ) return;
4391  if( !p->isInit ){
4392    p->isInit = 1;
4393    p->a = sqlite3_malloc(2);
4394    if( p->a==0 ){
4395      p->oom = 1;
4396    }else{
4397      p->a[0] = 0;
4398    }
4399    p->nDigit = 1;
4400    p->nFrac = 0;
4401  }
4402  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4403  pArg = decimal_new(context, argv[0], 1);
4404  decimal_add(p, pArg);
4405  decimal_free(pArg);
4406}
4407static void decimalSumInverse(
4408  sqlite3_context *context,
4409  int argc,
4410  sqlite3_value **argv
4411){
4412  Decimal *p;
4413  Decimal *pArg;
4414  UNUSED_PARAMETER(argc);
4415  p = sqlite3_aggregate_context(context, sizeof(*p));
4416  if( p==0 ) return;
4417  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4418  pArg = decimal_new(context, argv[0], 1);
4419  if( pArg ) pArg->sign = !pArg->sign;
4420  decimal_add(p, pArg);
4421  decimal_free(pArg);
4422}
4423static void decimalSumValue(sqlite3_context *context){
4424  Decimal *p = sqlite3_aggregate_context(context, 0);
4425  if( p==0 ) return;
4426  decimal_result(context, p);
4427}
4428static void decimalSumFinalize(sqlite3_context *context){
4429  Decimal *p = sqlite3_aggregate_context(context, 0);
4430  if( p==0 ) return;
4431  decimal_result(context, p);
4432  decimal_clear(p);
4433}
4434
4435/*
4436** SQL Function:   decimal_mul(X, Y)
4437**
4438** Return the product of X and Y.
4439*/
4440static void decimalMulFunc(
4441  sqlite3_context *context,
4442  int argc,
4443  sqlite3_value **argv
4444){
4445  Decimal *pA = decimal_new(context, argv[0], 1);
4446  Decimal *pB = decimal_new(context, argv[1], 1);
4447  UNUSED_PARAMETER(argc);
4448  if( pA==0 || pA->oom || pA->isNull
4449   || pB==0 || pB->oom || pB->isNull
4450  ){
4451    goto mul_end;
4452  }
4453  decimalMul(pA, pB);
4454  if( pA->oom ){
4455    goto mul_end;
4456  }
4457  decimal_result(context, pA);
4458
4459mul_end:
4460  decimal_free(pA);
4461  decimal_free(pB);
4462}
4463
4464/*
4465** SQL Function:   decimal_pow2(N)
4466**
4467** Return the N-th power of 2.  N must be an integer.
4468*/
4469static void decimalPow2Func(
4470  sqlite3_context *context,
4471  int argc,
4472  sqlite3_value **argv
4473){
4474  UNUSED_PARAMETER(argc);
4475  if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
4476    Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
4477    decimal_result_sci(context, pA);
4478    decimal_free(pA);
4479  }
4480}
4481
4482#ifdef _WIN32
4483
4484#endif
4485static int sqlite3_decimal_init(
4486  sqlite3 *db,
4487  char **pzErrMsg,
4488  const sqlite3_api_routines *pApi
4489){
4490  int rc = SQLITE_OK;
4491  static const struct {
4492    const char *zFuncName;
4493    int nArg;
4494    int iArg;
4495    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4496  } aFunc[] = {
4497    { "decimal",       1, 0,  decimalFunc        },
4498    { "decimal_exp",   1, 1,  decimalFunc        },
4499    { "decimal_cmp",   2, 0,  decimalCmpFunc     },
4500    { "decimal_add",   2, 0,  decimalAddFunc     },
4501    { "decimal_sub",   2, 0,  decimalSubFunc     },
4502    { "decimal_mul",   2, 0,  decimalMulFunc     },
4503    { "decimal_pow2",  1, 0,  decimalPow2Func    },
4504  };
4505  unsigned int i;
4506  (void)pzErrMsg;  /* Unused parameter */
4507
4508  SQLITE_EXTENSION_INIT2(pApi);
4509
4510  for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
4511    rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
4512                   SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4513                   aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
4514  }
4515  if( rc==SQLITE_OK ){
4516    rc = sqlite3_create_window_function(db, "decimal_sum", 1,
4517                   SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
4518                   decimalSumStep, decimalSumFinalize,
4519                   decimalSumValue, decimalSumInverse, 0);
4520  }
4521  if( rc==SQLITE_OK ){
4522    rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
4523                                  0, decimalCollFunc);
4524  }
4525  return rc;
4526}
4527
4528/************************* End ../ext/misc/decimal.c ********************/
4529#undef sqlite3_base_init
4530#define sqlite3_base_init sqlite3_base64_init
4531/************************* Begin ../ext/misc/base64.c ******************/
4532/*
4533** 2022-11-18
4534**
4535** The author disclaims copyright to this source code.  In place of
4536** a legal notice, here is a blessing:
4537**
4538**    May you do good and not evil.
4539**    May you find forgiveness for yourself and forgive others.
4540**    May you share freely, never taking more than you give.
4541**
4542*************************************************************************
4543**
4544** This is a SQLite extension for converting in either direction
4545** between a (binary) blob and base64 text. Base64 can transit a
4546** sane USASCII channel unmolested. It also plays nicely in CSV or
4547** written as TCL brace-enclosed literals or SQL string literals,
4548** and can be used unmodified in XML-like documents.
4549**
4550** This is an independent implementation of conversions specified in
4551** RFC 4648, done on the above date by the author (Larry Brasfield)
4552** who thereby has the right to put this into the public domain.
4553**
4554** The conversions meet RFC 4648 requirements, provided that this
4555** C source specifies that line-feeds are included in the encoded
4556** data to limit visible line lengths to 72 characters and to
4557** terminate any encoded blob having non-zero length.
4558**
4559** Length limitations are not imposed except that the runtime
4560** SQLite string or blob length limits are respected. Otherwise,
4561** any length binary sequence can be represented and recovered.
4562** Generated base64 sequences, with their line-feeds included,
4563** can be concatenated; the result converted back to binary will
4564** be the concatenation of the represented binary sequences.
4565**
4566** This SQLite3 extension creates a function, base64(x), which
4567** either: converts text x containing base64 to a returned blob;
4568** or converts a blob x to returned text containing base64. An
4569** error will be thrown for other input argument types.
4570**
4571** This code relies on UTF-8 encoding only with respect to the
4572** meaning of the first 128 (7-bit) codes matching that of USASCII.
4573** It will fail miserably if somehow made to try to convert EBCDIC.
4574** Because it is table-driven, it could be enhanced to handle that,
4575** but the world and SQLite have moved on from that anachronism.
4576**
4577** To build the extension:
4578** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4579** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
4580** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
4581** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
4582** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
4583*/
4584
4585#include <assert.h>
4586
4587/* #include "sqlite3ext.h" */
4588
4589#ifndef deliberate_fall_through
4590/* Quiet some compilers about some of our intentional code. */
4591# if GCC_VERSION>=7000000
4592#  define deliberate_fall_through __attribute__((fallthrough));
4593# else
4594#  define deliberate_fall_through
4595# endif
4596#endif
4597
4598SQLITE_EXTENSION_INIT1;
4599
4600#define PC 0x80 /* pad character */
4601#define WS 0x81 /* whitespace */
4602#define ND 0x82 /* Not above or digit-value */
4603#define PAD_CHAR '='
4604
4605#ifndef U8_TYPEDEF
4606/* typedef unsigned char u8; */
4607#define U8_TYPEDEF
4608#endif
4609
4610/* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
4611static const u8 b64DigitValues[128] = {
4612  /*                             HT LF VT  FF CR       */
4613    ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
4614  /*                                                US */
4615    ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
4616  /*sp                                  +            / */
4617    WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
4618  /* 0  1            5            9            =       */
4619    52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
4620  /*    A                                            O */
4621    ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
4622  /* P                               Z                 */
4623    15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
4624  /*    a                                            o */
4625    ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
4626  /* p                               z                 */
4627    41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
4628};
4629
4630static const char b64Numerals[64+1]
4631= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4632
4633#define BX_DV_PROTO(c) \
4634  ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
4635#define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
4636#define IS_BX_WS(bdp) ((bdp)==WS)
4637#define IS_BX_PAD(bdp) ((bdp)==PC)
4638#define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
4639/* Width of base64 lines. Should be an integer multiple of 4. */
4640#define B64_DARK_MAX 72
4641
4642/* Encode a byte buffer into base64 text with linefeeds appended to limit
4643** encoded group lengths to B64_DARK_MAX or to terminate the last group.
4644*/
4645static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
4646  int nCol = 0;
4647  while( nbIn >= 3 ){
4648    /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
4649    pOut[0] = BX_NUMERAL(pIn[0]>>2);
4650    pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
4651    pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
4652    pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
4653    pOut += 4;
4654    nbIn -= 3;
4655    pIn += 3;
4656    if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
4657      *pOut++ = '\n';
4658      nCol = 0;
4659    }
4660  }
4661  if( nbIn > 0 ){
4662    signed char nco = nbIn+1;
4663    int nbe;
4664    unsigned long qv = *pIn++;
4665    for( nbe=1; nbe<3; ++nbe ){
4666      qv <<= 8;
4667      if( nbe<nbIn ) qv |= *pIn++;
4668    }
4669    for( nbe=3; nbe>=0; --nbe ){
4670      char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
4671      qv >>= 6;
4672      pOut[nbe] = ce;
4673    }
4674    pOut += 4;
4675    *pOut++ = '\n';
4676  }
4677  *pOut = 0;
4678  return pOut;
4679}
4680
4681/* Skip over text which is not base64 numeral(s). */
4682static char * skipNonB64( char *s, int nc ){
4683  char c;
4684  while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
4685  return s;
4686}
4687
4688/* Decode base64 text into a byte buffer. */
4689static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
4690  if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
4691  while( ncIn>0 && *pIn!=PAD_CHAR ){
4692    static signed char nboi[] = { 0, 0, 1, 2, 3 };
4693    char *pUse = skipNonB64(pIn, ncIn);
4694    unsigned long qv = 0L;
4695    int nti, nbo, nac;
4696    ncIn -= (pUse - pIn);
4697    pIn = pUse;
4698    nti = (ncIn>4)? 4 : ncIn;
4699    ncIn -= nti;
4700    nbo = nboi[nti];
4701    if( nbo==0 ) break;
4702    for( nac=0; nac<4; ++nac ){
4703      char c = (nac<nti)? *pIn++ : b64Numerals[0];
4704      u8 bdp = BX_DV_PROTO(c);
4705      switch( bdp ){
4706      case ND:
4707        /*  Treat dark non-digits as pad, but they terminate decode too. */
4708        ncIn = 0;
4709        deliberate_fall_through;
4710      case WS:
4711        /* Treat whitespace as pad and terminate this group.*/
4712        nti = nac;
4713        deliberate_fall_through;
4714      case PC:
4715        bdp = 0;
4716        --nbo;
4717        deliberate_fall_through;
4718      default: /* bdp is the digit value. */
4719        qv = qv<<6 | bdp;
4720        break;
4721      }
4722    }
4723    switch( nbo ){
4724    case 3:
4725      pOut[2] = (qv) & 0xff;
4726    case 2:
4727      pOut[1] = (qv>>8) & 0xff;
4728    case 1:
4729      pOut[0] = (qv>>16) & 0xff;
4730    }
4731    pOut += nbo;
4732  }
4733  return pOut;
4734}
4735
4736/* This function does the work for the SQLite base64(x) UDF. */
4737static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
4738  int nb, nc, nv = sqlite3_value_bytes(av[0]);
4739  int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
4740                            SQLITE_LIMIT_LENGTH, -1);
4741  char *cBuf;
4742  u8 *bBuf;
4743  assert(na==1);
4744  switch( sqlite3_value_type(av[0]) ){
4745  case SQLITE_BLOB:
4746    nb = nv;
4747    nc = 4*(nv+2/3); /* quads needed */
4748    nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
4749    if( nvMax < nc ){
4750      sqlite3_result_error(context, "blob expanded to base64 too big", -1);
4751      return;
4752    }
4753    bBuf = (u8*)sqlite3_value_blob(av[0]);
4754    if( !bBuf ){
4755      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4756        goto memFail;
4757      }
4758      sqlite3_result_text(context,"",-1,SQLITE_STATIC);
4759      break;
4760    }
4761    cBuf = sqlite3_malloc(nc);
4762    if( !cBuf ) goto memFail;
4763    nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
4764    sqlite3_result_text(context, cBuf, nc, sqlite3_free);
4765    break;
4766  case SQLITE_TEXT:
4767    nc = nv;
4768    nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
4769    if( nvMax < nb ){
4770      sqlite3_result_error(context, "blob from base64 may be too big", -1);
4771      return;
4772    }else if( nb<1 ){
4773      nb = 1;
4774    }
4775    cBuf = (char *)sqlite3_value_text(av[0]);
4776    if( !cBuf ){
4777      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4778        goto memFail;
4779      }
4780      sqlite3_result_zeroblob(context, 0);
4781      break;
4782    }
4783    bBuf = sqlite3_malloc(nb);
4784    if( !bBuf ) goto memFail;
4785    nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
4786    sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
4787    break;
4788  default:
4789    sqlite3_result_error(context, "base64 accepts only blob or text", -1);
4790    return;
4791  }
4792  return;
4793 memFail:
4794  sqlite3_result_error(context, "base64 OOM", -1);
4795}
4796
4797/*
4798** Establish linkage to running SQLite library.
4799*/
4800#ifndef SQLITE_SHELL_EXTFUNCS
4801#ifdef _WIN32
4802
4803#endif
4804static int sqlite3_base_init
4805#else
4806static int sqlite3_base64_init
4807#endif
4808(sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
4809  SQLITE_EXTENSION_INIT2(pApi);
4810  (void)pzErr;
4811  return sqlite3_create_function
4812    (db, "base64", 1,
4813     SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
4814     0, base64, 0, 0);
4815}
4816
4817/*
4818** Define some macros to allow this extension to be built into the shell
4819** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
4820** allows shell.c, as distributed, to have this extension built in.
4821*/
4822#define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
4823#define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
4824
4825/************************* End ../ext/misc/base64.c ********************/
4826#undef sqlite3_base_init
4827#define sqlite3_base_init sqlite3_base85_init
4828#define OMIT_BASE85_CHECKER
4829/************************* Begin ../ext/misc/base85.c ******************/
4830/*
4831** 2022-11-16
4832**
4833** The author disclaims copyright to this source code.  In place of
4834** a legal notice, here is a blessing:
4835**
4836**    May you do good and not evil.
4837**    May you find forgiveness for yourself and forgive others.
4838**    May you share freely, never taking more than you give.
4839**
4840*************************************************************************
4841**
4842** This is a utility for converting binary to base85 or vice-versa.
4843** It can be built as a standalone program or an SQLite3 extension.
4844**
4845** Much like base64 representations, base85 can be sent through a
4846** sane USASCII channel unmolested. It also plays nicely in CSV or
4847** written as TCL brace-enclosed literals or SQL string literals.
4848** It is not suited for unmodified use in XML-like documents.
4849**
4850** The encoding used resembles Ascii85, but was devised by the author
4851** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
4852** variant sources existed, in the 1984 timeframe on a VAX mainframe.
4853** Further, this is an independent implementation of a base85 system.
4854** Hence, the author has rightfully put this into the public domain.
4855**
4856** Base85 numerals are taken from the set of 7-bit USASCII codes,
4857** excluding control characters and Space ! " ' ( ) { | } ~ Del
4858** in code order representing digit values 0 to 84 (base 10.)
4859**
4860** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4861** are represented as 5-digit base85 numbers with MS to LS digit
4862** order. Groups of 1-3 bytes are represented with 2-4 digits,
4863** still big-endian but 8-24 bit values. (Using big-endian yields
4864** the simplest transition to byte groups smaller than 4 bytes.
4865** These byte groups can also be considered base-256 numbers.)
4866** Groups of 0 bytes are represented with 0 digits and vice-versa.
4867** No pad characters are used; Encoded base85 numeral sequence
4868** (aka "group") length maps 1-to-1 to the decoded binary length.
4869**
4870** Any character not in the base85 numeral set delimits groups.
4871** When base85 is streamed or stored in containers of indefinite
4872** size, newline is used to separate it into sub-sequences of no
4873** more than 80 digits so that fgets() can be used to read it.
4874**
4875** Length limitations are not imposed except that the runtime
4876** SQLite string or blob length limits are respected. Otherwise,
4877** any length binary sequence can be represented and recovered.
4878** Base85 sequences can be concatenated by separating them with
4879** a non-base85 character; the conversion to binary will then
4880** be the concatenation of the represented binary sequences.
4881
4882** The standalone program either converts base85 on stdin to create
4883** a binary file or converts a binary file to base85 on stdout.
4884** Read or make it blurt its help for invocation details.
4885**
4886** The SQLite3 extension creates a function, base85(x), which will
4887** either convert text base85 to a blob or a blob to text base85
4888** and return the result (or throw an error for other types.)
4889** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
4890** function, is_base85(t), which returns 1 iff the text t contains
4891** nothing other than base85 numerals and whitespace, or 0 otherwise.
4892**
4893** To build the extension:
4894** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4895** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4896** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4897** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4898** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4899** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4900**
4901** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
4902** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4903** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4904** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4905*/
4906
4907#include <stdio.h>
4908#include <memory.h>
4909#include <string.h>
4910#include <assert.h>
4911#ifndef OMIT_BASE85_CHECKER
4912# include <ctype.h>
4913#endif
4914
4915#ifndef BASE85_STANDALONE
4916
4917/* # include "sqlite3ext.h" */
4918
4919SQLITE_EXTENSION_INIT1;
4920
4921#else
4922
4923# ifdef _WIN32
4924#  include <io.h>
4925#  include <fcntl.h>
4926# else
4927#  define setmode(fd,m)
4928# endif
4929
4930static char *zHelp =
4931  "Usage: base85 <dirFlag> <binFile>\n"
4932  " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4933  "   content to be converted to/from base85 on stdout/stdin.\n"
4934  " <binFile> names a binary file to be rendered or created.\n"
4935  "   Or, the name '-' refers to the stdin or stdout stream.\n"
4936  ;
4937
4938static void sayHelp(){
4939  printf("%s", zHelp);
4940}
4941#endif
4942
4943#ifndef U8_TYPEDEF
4944/* typedef unsigned char u8; */
4945#define U8_TYPEDEF
4946#endif
4947
4948/* Classify c according to interval within USASCII set w.r.t. base85
4949 * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
4950 */
4951#define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
4952
4953/* Provide digitValue to b85Numeral offset as a function of above class. */
4954static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4955#define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
4956
4957/* Say whether c is a base85 numeral. */
4958#define IS_B85( c ) (B85_CLASS(c) & 1)
4959
4960#if 0 /* Not used, */
4961static u8 base85DigitValue( char c ){
4962  u8 dv = (u8)(c - '#');
4963  if( dv>87 ) return 0xff;
4964  return (dv > 3)? dv-3 : dv;
4965}
4966#endif
4967
4968/* Width of base64 lines. Should be an integer multiple of 5. */
4969#define B85_DARK_MAX 80
4970
4971
4972static char * skipNonB85( char *s, int nc ){
4973  char c;
4974  while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
4975  return s;
4976}
4977
4978/* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
4979 * Do not use the macro form with argument expression having a side-effect.*/
4980#if 0
4981static char base85Numeral( u8 b ){
4982  return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
4983}
4984#else
4985# define base85Numeral( dn )\
4986  ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
4987#endif
4988
4989static char *putcs(char *pc, char *s){
4990  char c;
4991  while( (c = *s++)!=0 ) *pc++ = c;
4992  return pc;
4993}
4994
4995/* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
4996** to be appended to encoded groups to limit their length to B85_DARK_MAX
4997** or to terminate the last group (to aid concatenation.)
4998*/
4999static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
5000  int nCol = 0;
5001  while( nbIn >= 4 ){
5002    int nco = 5;
5003    unsigned long qbv = (((unsigned long)pIn[0])<<24) |
5004                        (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
5005    while( nco > 0 ){
5006      unsigned nqv = (unsigned)(qbv/85UL);
5007      unsigned char dv = qbv - 85UL*nqv;
5008      qbv = nqv;
5009      pOut[--nco] = base85Numeral(dv);
5010    }
5011    nbIn -= 4;
5012    pIn += 4;
5013    pOut += 5;
5014    if( pSep && (nCol += 5)>=B85_DARK_MAX ){
5015      pOut = putcs(pOut, pSep);
5016      nCol = 0;
5017    }
5018  }
5019  if( nbIn > 0 ){
5020    int nco = nbIn + 1;
5021    unsigned long qv = *pIn++;
5022    int nbe = 1;
5023    while( nbe++ < nbIn ){
5024      qv = (qv<<8) | *pIn++;
5025    }
5026    nCol += nco;
5027    while( nco > 0 ){
5028      u8 dv = (u8)(qv % 85);
5029      qv /= 85;
5030      pOut[--nco] = base85Numeral(dv);
5031    }
5032    pOut += (nbIn+1);
5033  }
5034  if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
5035  *pOut = 0;
5036  return pOut;
5037}
5038
5039/* Decode base85 text into a byte buffer. */
5040static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
5041  if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
5042  while( ncIn>0 ){
5043    static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
5044    char *pUse = skipNonB85(pIn, ncIn);
5045    unsigned long qv = 0L;
5046    int nti, nbo;
5047    ncIn -= (pUse - pIn);
5048    pIn = pUse;
5049    nti = (ncIn>5)? 5 : ncIn;
5050    nbo = nboi[nti];
5051    if( nbo==0 ) break;
5052    while( nti>0 ){
5053      char c = *pIn++;
5054      u8 cdo = B85_DNOS(c);
5055      --ncIn;
5056      if( cdo==0 ) break;
5057      qv = 85 * qv + (c - cdo);
5058      --nti;
5059    }
5060    nbo -= nti; /* Adjust for early (non-digit) end of group. */
5061    switch( nbo ){
5062    case 4:
5063      *pOut++ = (qv >> 24)&0xff;
5064    case 3:
5065      *pOut++ = (qv >> 16)&0xff;
5066    case 2:
5067      *pOut++ = (qv >> 8)&0xff;
5068    case 1:
5069      *pOut++ = qv&0xff;
5070    case 0:
5071      break;
5072    }
5073  }
5074  return pOut;
5075}
5076
5077#ifndef OMIT_BASE85_CHECKER
5078/* Say whether input char sequence is all (base85 and/or whitespace).*/
5079static int allBase85( char *p, int len ){
5080  char c;
5081  while( len-- > 0 && (c = *p++) != 0 ){
5082    if( !IS_B85(c) && !isspace(c) ) return 0;
5083  }
5084  return 1;
5085}
5086#endif
5087
5088#ifndef BASE85_STANDALONE
5089
5090# ifndef OMIT_BASE85_CHECKER
5091/* This function does the work for the SQLite is_base85(t) UDF. */
5092static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5093  assert(na==1);
5094  switch( sqlite3_value_type(av[0]) ){
5095  case SQLITE_TEXT:
5096    {
5097      int rv = allBase85( (char *)sqlite3_value_text(av[0]),
5098                          sqlite3_value_bytes(av[0]) );
5099      sqlite3_result_int(context, rv);
5100    }
5101    break;
5102  case SQLITE_NULL:
5103    sqlite3_result_null(context);
5104    break;
5105  default:
5106    sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
5107    return;
5108  }
5109}
5110# endif
5111
5112/* This function does the work for the SQLite base85(x) UDF. */
5113static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5114  int nb, nc, nv = sqlite3_value_bytes(av[0]);
5115  int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
5116                            SQLITE_LIMIT_LENGTH, -1);
5117  char *cBuf;
5118  u8 *bBuf;
5119  assert(na==1);
5120  switch( sqlite3_value_type(av[0]) ){
5121  case SQLITE_BLOB:
5122    nb = nv;
5123    /*    ulongs    tail   newlines  tailenc+nul*/
5124    nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
5125    if( nvMax < nc ){
5126      sqlite3_result_error(context, "blob expanded to base85 too big", -1);
5127      return;
5128    }
5129    bBuf = (u8*)sqlite3_value_blob(av[0]);
5130    if( !bBuf ){
5131      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5132        goto memFail;
5133      }
5134      sqlite3_result_text(context,"",-1,SQLITE_STATIC);
5135      break;
5136    }
5137    cBuf = sqlite3_malloc(nc);
5138    if( !cBuf ) goto memFail;
5139    nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
5140    sqlite3_result_text(context, cBuf, nc, sqlite3_free);
5141    break;
5142  case SQLITE_TEXT:
5143    nc = nv;
5144    nb = 4*(nv/5) + nv%5; /* may overestimate */
5145    if( nvMax < nb ){
5146      sqlite3_result_error(context, "blob from base85 may be too big", -1);
5147      return;
5148    }else if( nb<1 ){
5149      nb = 1;
5150    }
5151    cBuf = (char *)sqlite3_value_text(av[0]);
5152    if( !cBuf ){
5153      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5154        goto memFail;
5155      }
5156      sqlite3_result_zeroblob(context, 0);
5157      break;
5158    }
5159    bBuf = sqlite3_malloc(nb);
5160    if( !bBuf ) goto memFail;
5161    nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
5162    sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
5163    break;
5164  default:
5165    sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
5166    return;
5167  }
5168  return;
5169 memFail:
5170  sqlite3_result_error(context, "base85 OOM", -1);
5171}
5172
5173/*
5174** Establish linkage to running SQLite library.
5175*/
5176#ifndef SQLITE_SHELL_EXTFUNCS
5177#ifdef _WIN32
5178
5179#endif
5180static int sqlite3_base_init
5181#else
5182static int sqlite3_base85_init
5183#endif
5184(sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
5185  SQLITE_EXTENSION_INIT2(pApi);
5186  (void)pzErr;
5187# ifndef OMIT_BASE85_CHECKER
5188  {
5189    int rc = sqlite3_create_function
5190      (db, "is_base85", 1,
5191       SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
5192       0, is_base85, 0, 0);
5193    if( rc!=SQLITE_OK ) return rc;
5194  }
5195# endif
5196  return sqlite3_create_function
5197    (db, "base85", 1,
5198     SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
5199     0, base85, 0, 0);
5200}
5201
5202/*
5203** Define some macros to allow this extension to be built into the shell
5204** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
5205** allows shell.c, as distributed, to have this extension built in.
5206*/
5207# define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
5208# define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
5209
5210#else /* standalone program */
5211
5212int main(int na, char *av[]){
5213  int cin;
5214  int rc = 0;
5215  u8 bBuf[4*(B85_DARK_MAX/5)];
5216  char cBuf[5*(sizeof(bBuf)/4)+2];
5217  size_t nio;
5218# ifndef OMIT_BASE85_CHECKER
5219  int b85Clean = 1;
5220# endif
5221  char rw;
5222  FILE *fb = 0, *foc = 0;
5223  char fmode[3] = "xb";
5224  if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
5225    sayHelp();
5226    return 0;
5227  }
5228  fmode[0] = rw;
5229  if( av[2][0]=='-' && av[2][1]==0 ){
5230    switch( rw ){
5231    case 'r':
5232      fb = stdin;
5233      setmode(fileno(stdin), O_BINARY);
5234      break;
5235    case 'w':
5236      fb = stdout;
5237      setmode(fileno(stdout), O_BINARY);
5238      break;
5239    }
5240  }else{
5241    fb = fopen(av[2], fmode);
5242    foc = fb;
5243  }
5244  if( !fb ){
5245    fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
5246    rc = 1;
5247  }else{
5248    switch( rw ){
5249    case 'r':
5250      while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
5251        toBase85( bBuf, (int)nio, cBuf, 0 );
5252        fprintf(stdout, "%s\n", cBuf);
5253      }
5254      break;
5255    case 'w':
5256      while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
5257        int nc = strlen(cBuf);
5258        size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
5259        if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
5260# ifndef OMIT_BASE85_CHECKER
5261        b85Clean &= allBase85( cBuf, nc );
5262# endif
5263      }
5264      break;
5265    default:
5266      sayHelp();
5267      rc = 1;
5268    }
5269    if( foc ) fclose(foc);
5270  }
5271# ifndef OMIT_BASE85_CHECKER
5272  if( !b85Clean ){
5273    fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
5274  }
5275# endif
5276  return rc;
5277}
5278
5279#endif
5280
5281/************************* End ../ext/misc/base85.c ********************/
5282/************************* Begin ../ext/misc/ieee754.c ******************/
5283/*
5284** 2013-04-17
5285**
5286** The author disclaims copyright to this source code.  In place of
5287** a legal notice, here is a blessing:
5288**
5289**    May you do good and not evil.
5290**    May you find forgiveness for yourself and forgive others.
5291**    May you share freely, never taking more than you give.
5292**
5293******************************************************************************
5294**
5295** This SQLite extension implements functions for the exact display
5296** and input of IEEE754 Binary64 floating-point numbers.
5297**
5298**   ieee754(X)
5299**   ieee754(Y,Z)
5300**
5301** In the first form, the value X should be a floating-point number.
5302** The function will return a string of the form 'ieee754(Y,Z)' where
5303** Y and Z are integers such that X==Y*pow(2,Z).
5304**
5305** In the second form, Y and Z are integers which are the mantissa and
5306** base-2 exponent of a new floating point number.  The function returns
5307** a floating-point value equal to Y*pow(2,Z).
5308**
5309** Examples:
5310**
5311**     ieee754(2.0)             ->     'ieee754(2,0)'
5312**     ieee754(45.25)           ->     'ieee754(181,-2)'
5313**     ieee754(2, 0)            ->     2.0
5314**     ieee754(181, -2)         ->     45.25
5315**
5316** Two additional functions break apart the one-argument ieee754()
5317** result into separate integer values:
5318**
5319**     ieee754_mantissa(45.25)  ->     181
5320**     ieee754_exponent(45.25)  ->     -2
5321**
5322** These functions convert binary64 numbers into blobs and back again.
5323**
5324**     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5325**     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5326**
5327** In all single-argument functions, if the argument is an 8-byte blob
5328** then that blob is interpreted as a big-endian binary64 value.
5329**
5330**
5331** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5332** -----------------------------------------------
5333**
5334** This extension in combination with the separate 'decimal' extension
5335** can be used to compute the exact decimal representation of binary64
5336** values.  To begin, first compute a table of exponent values:
5337**
5338**    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5339**    WITH RECURSIVE c(x,v) AS (
5340**      VALUES(0,'1')
5341**      UNION ALL
5342**      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5343**    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5344**    WITH RECURSIVE c(x,v) AS (
5345**      VALUES(-1,'0.5')
5346**      UNION ALL
5347**      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5348**    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5349**
5350** Then, to compute the exact decimal representation of a floating
5351** point value (the value 47.49 is used in the example) do:
5352**
5353**    WITH c(n) AS (VALUES(47.49))
5354**          ---------------^^^^^---- Replace with whatever you want
5355**    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5356**      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5357**
5358** Here is a query to show various boundry values for the binary64
5359** number format:
5360**
5361**    WITH c(name,bin) AS (VALUES
5362**       ('minimum positive value',        x'0000000000000001'),
5363**       ('maximum subnormal value',       x'000fffffffffffff'),
5364**       ('mininum positive nornal value', x'0010000000000000'),
5365**       ('maximum value',                 x'7fefffffffffffff'))
5366**    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5367**      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5368**
5369*/
5370/* #include "sqlite3ext.h" */
5371SQLITE_EXTENSION_INIT1
5372#include <assert.h>
5373#include <string.h>
5374
5375/* Mark a function parameter as unused, to suppress nuisance compiler
5376** warnings. */
5377#ifndef UNUSED_PARAMETER
5378# define UNUSED_PARAMETER(X)  (void)(X)
5379#endif
5380
5381/*
5382** Implementation of the ieee754() function
5383*/
5384static void ieee754func(
5385  sqlite3_context *context,
5386  int argc,
5387  sqlite3_value **argv
5388){
5389  if( argc==1 ){
5390    sqlite3_int64 m, a;
5391    double r;
5392    int e;
5393    int isNeg;
5394    char zResult[100];
5395    assert( sizeof(m)==sizeof(r) );
5396    if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5397     && sqlite3_value_bytes(argv[0])==sizeof(r)
5398    ){
5399      const unsigned char *x = sqlite3_value_blob(argv[0]);
5400      unsigned int i;
5401      sqlite3_uint64 v = 0;
5402      for(i=0; i<sizeof(r); i++){
5403        v = (v<<8) | x[i];
5404      }
5405      memcpy(&r, &v, sizeof(r));
5406    }else{
5407      r = sqlite3_value_double(argv[0]);
5408    }
5409    if( r<0.0 ){
5410      isNeg = 1;
5411      r = -r;
5412    }else{
5413      isNeg = 0;
5414    }
5415    memcpy(&a,&r,sizeof(a));
5416    if( a==0 ){
5417      e = 0;
5418      m = 0;
5419    }else{
5420      e = a>>52;
5421      m = a & ((((sqlite3_int64)1)<<52)-1);
5422      if( e==0 ){
5423        m <<= 1;
5424      }else{
5425        m |= ((sqlite3_int64)1)<<52;
5426      }
5427      while( e<1075 && m>0 && (m&1)==0 ){
5428        m >>= 1;
5429        e++;
5430      }
5431      if( isNeg ) m = -m;
5432    }
5433    switch( *(int*)sqlite3_user_data(context) ){
5434      case 0:
5435        sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5436                         m, e-1075);
5437        sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5438        break;
5439      case 1:
5440        sqlite3_result_int64(context, m);
5441        break;
5442      case 2:
5443        sqlite3_result_int(context, e-1075);
5444        break;
5445    }
5446  }else{
5447    sqlite3_int64 m, e, a;
5448    double r;
5449    int isNeg = 0;
5450    m = sqlite3_value_int64(argv[0]);
5451    e = sqlite3_value_int64(argv[1]);
5452
5453    /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
5454    if( e>10000 ){
5455      e = 10000;
5456    }else if( e<-10000 ){
5457      e = -10000;
5458    }
5459
5460    if( m<0 ){
5461      isNeg = 1;
5462      m = -m;
5463      if( m<0 ) return;
5464    }else if( m==0 && e>-1000 && e<1000 ){
5465      sqlite3_result_double(context, 0.0);
5466      return;
5467    }
5468    while( (m>>32)&0xffe00000 ){
5469      m >>= 1;
5470      e++;
5471    }
5472    while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5473      m <<= 1;
5474      e--;
5475    }
5476    e += 1075;
5477    if( e<=0 ){
5478      /* Subnormal */
5479      if( 1-e >= 64 ){
5480        m = 0;
5481      }else{
5482        m >>= 1-e;
5483      }
5484      e = 0;
5485    }else if( e>0x7ff ){
5486      e = 0x7ff;
5487    }
5488    a = m & ((((sqlite3_int64)1)<<52)-1);
5489    a |= e<<52;
5490    if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5491    memcpy(&r, &a, sizeof(r));
5492    sqlite3_result_double(context, r);
5493  }
5494}
5495
5496/*
5497** Functions to convert between blobs and floats.
5498*/
5499static void ieee754func_from_blob(
5500  sqlite3_context *context,
5501  int argc,
5502  sqlite3_value **argv
5503){
5504  UNUSED_PARAMETER(argc);
5505  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5506   && sqlite3_value_bytes(argv[0])==sizeof(double)
5507  ){
5508    double r;
5509    const unsigned char *x = sqlite3_value_blob(argv[0]);
5510    unsigned int i;
5511    sqlite3_uint64 v = 0;
5512    for(i=0; i<sizeof(r); i++){
5513      v = (v<<8) | x[i];
5514    }
5515    memcpy(&r, &v, sizeof(r));
5516    sqlite3_result_double(context, r);
5517  }
5518}
5519static void ieee754func_to_blob(
5520  sqlite3_context *context,
5521  int argc,
5522  sqlite3_value **argv
5523){
5524  UNUSED_PARAMETER(argc);
5525  if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5526   || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5527  ){
5528    double r = sqlite3_value_double(argv[0]);
5529    sqlite3_uint64 v;
5530    unsigned char a[sizeof(r)];
5531    unsigned int i;
5532    memcpy(&v, &r, sizeof(r));
5533    for(i=1; i<=sizeof(r); i++){
5534      a[sizeof(r)-i] = v&0xff;
5535      v >>= 8;
5536    }
5537    sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5538  }
5539}
5540
5541/*
5542** SQL Function:   ieee754_inc(r,N)
5543**
5544** Move the floating point value r by N quantums and return the new
5545** values.
5546**
5547** Behind the scenes: this routine merely casts r into a 64-bit unsigned
5548** integer, adds N, then casts the value back into float.
5549**
5550** Example:  To find the smallest positive number:
5551**
5552**     SELECT ieee754_inc(0.0,+1);
5553*/
5554static void ieee754inc(
5555  sqlite3_context *context,
5556  int argc,
5557  sqlite3_value **argv
5558){
5559  double r;
5560  sqlite3_int64 N;
5561  sqlite3_uint64 m1, m2;
5562  double r2;
5563  UNUSED_PARAMETER(argc);
5564  r = sqlite3_value_double(argv[0]);
5565  N = sqlite3_value_int64(argv[1]);
5566  memcpy(&m1, &r, 8);
5567  m2 = m1 + N;
5568  memcpy(&r2, &m2, 8);
5569  sqlite3_result_double(context, r2);
5570}
5571
5572
5573#ifdef _WIN32
5574
5575#endif
5576static int sqlite3_ieee_init(
5577  sqlite3 *db,
5578  char **pzErrMsg,
5579  const sqlite3_api_routines *pApi
5580){
5581  static const struct {
5582    char *zFName;
5583    int nArg;
5584    int iAux;
5585    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5586  } aFunc[] = {
5587    { "ieee754",           1,   0, ieee754func },
5588    { "ieee754",           2,   0, ieee754func },
5589    { "ieee754_mantissa",  1,   1, ieee754func },
5590    { "ieee754_exponent",  1,   2, ieee754func },
5591    { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5592    { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5593    { "ieee754_inc",       2,   0, ieee754inc  },
5594  };
5595  unsigned int i;
5596  int rc = SQLITE_OK;
5597  SQLITE_EXTENSION_INIT2(pApi);
5598  (void)pzErrMsg;  /* Unused parameter */
5599  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5600    rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
5601                               SQLITE_UTF8|SQLITE_INNOCUOUS,
5602                               (void*)&aFunc[i].iAux,
5603                               aFunc[i].xFunc, 0, 0);
5604  }
5605  return rc;
5606}
5607
5608/************************* End ../ext/misc/ieee754.c ********************/
5609/************************* Begin ../ext/misc/series.c ******************/
5610/*
5611** 2015-08-18, 2023-04-28
5612**
5613** The author disclaims copyright to this source code.  In place of
5614** a legal notice, here is a blessing:
5615**
5616**    May you do good and not evil.
5617**    May you find forgiveness for yourself and forgive others.
5618**    May you share freely, never taking more than you give.
5619**
5620*************************************************************************
5621**
5622** This file demonstrates how to create a table-valued-function using
5623** a virtual table.  This demo implements the generate_series() function
5624** which gives the same results as the eponymous function in PostgreSQL,
5625** within the limitation that its arguments are signed 64-bit integers.
5626**
5627** Considering its equivalents to generate_series(start,stop,step): A
5628** value V[n] sequence is produced for integer n ascending from 0 where
5629**  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
5630** for each produced value (independent of production time ordering.)
5631**
5632** All parameters must be either integer or convertable to integer.
5633** The start parameter is required.
5634** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
5635** The step parameter defaults to 1 and 0 is treated as 1.
5636**
5637** Examples:
5638**
5639**      SELECT * FROM generate_series(0,100,5);
5640**
5641** The query above returns integers from 0 through 100 counting by steps
5642** of 5.
5643**
5644**      SELECT * FROM generate_series(0,100);
5645**
5646** Integers from 0 through 100 with a step size of 1.
5647**
5648**      SELECT * FROM generate_series(20) LIMIT 10;
5649**
5650** Integers 20 through 29.
5651**
5652**      SELECT * FROM generate_series(0,-100,-5);
5653**
5654** Integers 0 -5 -10 ... -100.
5655**
5656**      SELECT * FROM generate_series(0,-1);
5657**
5658** Empty sequence.
5659**
5660** HOW IT WORKS
5661**
5662** The generate_series "function" is really a virtual table with the
5663** following schema:
5664**
5665**     CREATE TABLE generate_series(
5666**       value,
5667**       start HIDDEN,
5668**       stop HIDDEN,
5669**       step HIDDEN
5670**     );
5671**
5672** The virtual table also has a rowid, logically equivalent to n+1 where
5673** "n" is the ascending integer in the aforesaid production definition.
5674**
5675** Function arguments in queries against this virtual table are translated
5676** into equality constraints against successive hidden columns.  In other
5677** words, the following pairs of queries are equivalent to each other:
5678**
5679**    SELECT * FROM generate_series(0,100,5);
5680**    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5681**
5682**    SELECT * FROM generate_series(0,100);
5683**    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5684**
5685**    SELECT * FROM generate_series(20) LIMIT 10;
5686**    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5687**
5688** The generate_series virtual table implementation leaves the xCreate method
5689** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5690** TABLE command with "generate_series" as the USING argument.  Instead, there
5691** is a single generate_series virtual table that is always available without
5692** having to be created first.
5693**
5694** The xBestIndex method looks for equality constraints against the hidden
5695** start, stop, and step columns, and if present, it uses those constraints
5696** to bound the sequence of generated values.  If the equality constraints
5697** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5698** xBestIndex returns a small cost when both start and stop are available,
5699** and a very large cost if either start or stop are unavailable.  This
5700** encourages the query planner to order joins such that the bounds of the
5701** series are well-defined.
5702*/
5703/* #include "sqlite3ext.h" */
5704SQLITE_EXTENSION_INIT1
5705#include <assert.h>
5706#include <string.h>
5707#include <limits.h>
5708
5709#ifndef SQLITE_OMIT_VIRTUALTABLE
5710/*
5711** Return that member of a generate_series(...) sequence whose 0-based
5712** index is ix. The 0th member is given by smBase. The sequence members
5713** progress per ix increment by smStep.
5714*/
5715static sqlite3_int64 genSeqMember(sqlite3_int64 smBase,
5716                                  sqlite3_int64 smStep,
5717                                  sqlite3_uint64 ix){
5718  if( ix>=(sqlite3_uint64)LLONG_MAX ){
5719    /* Get ix into signed i64 range. */
5720    ix -= (sqlite3_uint64)LLONG_MAX;
5721    /* With 2's complement ALU, this next can be 1 step, but is split into
5722     * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
5723    smBase += (LLONG_MAX/2) * smStep;
5724    smBase += (LLONG_MAX - LLONG_MAX/2) * smStep;
5725  }
5726  /* Under UBSAN (or on 1's complement machines), must do this last term
5727   * in steps to avoid the dreaded (and harmless) signed multiply overlow. */
5728  if( ix>=2 ){
5729    sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
5730    smBase += ix2*smStep;
5731    ix -= ix2;
5732  }
5733  return smBase + ((sqlite3_int64)ix)*smStep;
5734}
5735
5736/* typedef unsigned char u8; */
5737
5738typedef struct SequenceSpec {
5739  sqlite3_int64 iBase;         /* Starting value ("start") */
5740  sqlite3_int64 iTerm;         /* Given terminal value ("stop") */
5741  sqlite3_int64 iStep;         /* Increment ("step") */
5742  sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
5743  sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
5744  sqlite3_int64 iValueNow;     /* Current value during generation */
5745  u8 isNotEOF;                 /* Sequence generation not exhausted */
5746  u8 isReversing;              /* Sequence is being reverse generated */
5747} SequenceSpec;
5748
5749/*
5750** Prepare a SequenceSpec for use in generating an integer series
5751** given initialized iBase, iTerm and iStep values. Sequence is
5752** initialized per given isReversing. Other members are computed.
5753*/
5754static void setupSequence( SequenceSpec *pss ){
5755  int bSameSigns;
5756  pss->uSeqIndexMax = 0;
5757  pss->isNotEOF = 0;
5758  bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
5759  if( pss->iTerm < pss->iBase ){
5760    sqlite3_uint64 nuspan = 0;
5761    if( bSameSigns ){
5762      nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
5763    }else{
5764      /* Under UBSAN (or on 1's complement machines), must do this in steps.
5765       * In this clause, iBase>=0 and iTerm<0 . */
5766      nuspan = 1;
5767      nuspan += pss->iBase;
5768      nuspan += -(pss->iTerm+1);
5769    }
5770    if( pss->iStep<0 ){
5771      pss->isNotEOF = 1;
5772      if( nuspan==ULONG_MAX ){
5773        pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
5774      }else if( pss->iStep>LLONG_MIN ){
5775        pss->uSeqIndexMax = nuspan/-pss->iStep;
5776      }
5777    }
5778  }else if( pss->iTerm > pss->iBase ){
5779    sqlite3_uint64 puspan = 0;
5780    if( bSameSigns ){
5781      puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
5782    }else{
5783      /* Under UBSAN (or on 1's complement machines), must do this in steps.
5784       * In this clause, iTerm>=0 and iBase<0 . */
5785      puspan = 1;
5786      puspan += pss->iTerm;
5787      puspan += -(pss->iBase+1);
5788    }
5789    if( pss->iStep>0 ){
5790      pss->isNotEOF = 1;
5791      pss->uSeqIndexMax = puspan/pss->iStep;
5792    }
5793  }else if( pss->iTerm == pss->iBase ){
5794      pss->isNotEOF = 1;
5795      pss->uSeqIndexMax = 0;
5796  }
5797  pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
5798  pss->iValueNow = (pss->isReversing)
5799    ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
5800    : pss->iBase;
5801}
5802
5803/*
5804** Progress sequence generator to yield next value, if any.
5805** Leave its state to either yield next value or be at EOF.
5806** Return whether there is a next value, or 0 at EOF.
5807*/
5808static int progressSequence( SequenceSpec *pss ){
5809  if( !pss->isNotEOF ) return 0;
5810  if( pss->isReversing ){
5811    if( pss->uSeqIndexNow > 0 ){
5812      pss->uSeqIndexNow--;
5813      pss->iValueNow -= pss->iStep;
5814    }else{
5815      pss->isNotEOF = 0;
5816    }
5817  }else{
5818    if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
5819      pss->uSeqIndexNow++;
5820      pss->iValueNow += pss->iStep;
5821    }else{
5822      pss->isNotEOF = 0;
5823    }
5824  }
5825  return pss->isNotEOF;
5826}
5827
5828/* series_cursor is a subclass of sqlite3_vtab_cursor which will
5829** serve as the underlying representation of a cursor that scans
5830** over rows of the result
5831*/
5832typedef struct series_cursor series_cursor;
5833struct series_cursor {
5834  sqlite3_vtab_cursor base;  /* Base class - must be first */
5835  SequenceSpec ss;           /* (this) Derived class data */
5836};
5837
5838/*
5839** The seriesConnect() method is invoked to create a new
5840** series_vtab that describes the generate_series virtual table.
5841**
5842** Think of this routine as the constructor for series_vtab objects.
5843**
5844** All this routine needs to do is:
5845**
5846**    (1) Allocate the series_vtab object and initialize all fields.
5847**
5848**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5849**        result set of queries against generate_series will look like.
5850*/
5851static int seriesConnect(
5852  sqlite3 *db,
5853  void *pUnused,
5854  int argcUnused, const char *const*argvUnused,
5855  sqlite3_vtab **ppVtab,
5856  char **pzErrUnused
5857){
5858  sqlite3_vtab *pNew;
5859  int rc;
5860
5861/* Column numbers */
5862#define SERIES_COLUMN_VALUE 0
5863#define SERIES_COLUMN_START 1
5864#define SERIES_COLUMN_STOP  2
5865#define SERIES_COLUMN_STEP  3
5866
5867  (void)pUnused;
5868  (void)argcUnused;
5869  (void)argvUnused;
5870  (void)pzErrUnused;
5871  rc = sqlite3_declare_vtab(db,
5872     "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5873  if( rc==SQLITE_OK ){
5874    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5875    if( pNew==0 ) return SQLITE_NOMEM;
5876    memset(pNew, 0, sizeof(*pNew));
5877    sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5878  }
5879  return rc;
5880}
5881
5882/*
5883** This method is the destructor for series_cursor objects.
5884*/
5885static int seriesDisconnect(sqlite3_vtab *pVtab){
5886  sqlite3_free(pVtab);
5887  return SQLITE_OK;
5888}
5889
5890/*
5891** Constructor for a new series_cursor object.
5892*/
5893static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5894  series_cursor *pCur;
5895  (void)pUnused;
5896  pCur = sqlite3_malloc( sizeof(*pCur) );
5897  if( pCur==0 ) return SQLITE_NOMEM;
5898  memset(pCur, 0, sizeof(*pCur));
5899  *ppCursor = &pCur->base;
5900  return SQLITE_OK;
5901}
5902
5903/*
5904** Destructor for a series_cursor.
5905*/
5906static int seriesClose(sqlite3_vtab_cursor *cur){
5907  sqlite3_free(cur);
5908  return SQLITE_OK;
5909}
5910
5911
5912/*
5913** Advance a series_cursor to its next row of output.
5914*/
5915static int seriesNext(sqlite3_vtab_cursor *cur){
5916  series_cursor *pCur = (series_cursor*)cur;
5917  progressSequence( & pCur->ss );
5918  return SQLITE_OK;
5919}
5920
5921/*
5922** Return values of columns for the row at which the series_cursor
5923** is currently pointing.
5924*/
5925static int seriesColumn(
5926  sqlite3_vtab_cursor *cur,   /* The cursor */
5927  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5928  int i                       /* Which column to return */
5929){
5930  series_cursor *pCur = (series_cursor*)cur;
5931  sqlite3_int64 x = 0;
5932  switch( i ){
5933    case SERIES_COLUMN_START:  x = pCur->ss.iBase; break;
5934    case SERIES_COLUMN_STOP:   x = pCur->ss.iTerm; break;
5935    case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;   break;
5936    default:                   x = pCur->ss.iValueNow;  break;
5937  }
5938  sqlite3_result_int64(ctx, x);
5939  return SQLITE_OK;
5940}
5941
5942#ifndef LARGEST_UINT64
5943#define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32))
5944#endif
5945
5946/*
5947** Return the rowid for the current row, logically equivalent to n+1 where
5948** "n" is the ascending integer in the aforesaid production definition.
5949*/
5950static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5951  series_cursor *pCur = (series_cursor*)cur;
5952  sqlite3_uint64 n = pCur->ss.uSeqIndexNow;
5953  *pRowid = (sqlite3_int64)((n<LARGEST_UINT64)? n+1 : 0);
5954  return SQLITE_OK;
5955}
5956
5957/*
5958** Return TRUE if the cursor has been moved off of the last
5959** row of output.
5960*/
5961static int seriesEof(sqlite3_vtab_cursor *cur){
5962  series_cursor *pCur = (series_cursor*)cur;
5963  return !pCur->ss.isNotEOF;
5964}
5965
5966/* True to cause run-time checking of the start=, stop=, and/or step=
5967** parameters.  The only reason to do this is for testing the
5968** constraint checking logic for virtual tables in the SQLite core.
5969*/
5970#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5971# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5972#endif
5973
5974/*
5975** This method is called to "rewind" the series_cursor object back
5976** to the first row of output.  This method is always called at least
5977** once prior to any call to seriesColumn() or seriesRowid() or
5978** seriesEof().
5979**
5980** The query plan selected by seriesBestIndex is passed in the idxNum
5981** parameter.  (idxStr is not used in this implementation.)  idxNum
5982** is a bitmask showing which constraints are available:
5983**
5984**    1:    start=VALUE
5985**    2:    stop=VALUE
5986**    4:    step=VALUE
5987**
5988** Also, if bit 8 is set, that means that the series should be output
5989** in descending order rather than in ascending order.  If bit 16 is
5990** set, then output must appear in ascending order.
5991**
5992** This routine should initialize the cursor and position it so that it
5993** is pointing at the first row, or pointing off the end of the table
5994** (so that seriesEof() will return true) if the table is empty.
5995*/
5996static int seriesFilter(
5997  sqlite3_vtab_cursor *pVtabCursor,
5998  int idxNum, const char *idxStrUnused,
5999  int argc, sqlite3_value **argv
6000){
6001  series_cursor *pCur = (series_cursor *)pVtabCursor;
6002  int i = 0;
6003  (void)idxStrUnused;
6004  if( idxNum & 1 ){
6005    pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
6006  }else{
6007    pCur->ss.iBase = 0;
6008  }
6009  if( idxNum & 2 ){
6010    pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
6011  }else{
6012    pCur->ss.iTerm = 0xffffffff;
6013  }
6014  if( idxNum & 4 ){
6015    pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
6016    if( pCur->ss.iStep==0 ){
6017      pCur->ss.iStep = 1;
6018    }else if( pCur->ss.iStep<0 ){
6019      if( (idxNum & 16)==0 ) idxNum |= 8;
6020    }
6021  }else{
6022    pCur->ss.iStep = 1;
6023  }
6024  for(i=0; i<argc; i++){
6025    if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
6026      /* If any of the constraints have a NULL value, then return no rows.
6027      ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
6028      pCur->ss.iBase = 1;
6029      pCur->ss.iTerm = 0;
6030      pCur->ss.iStep = 1;
6031      break;
6032    }
6033  }
6034  if( idxNum & 8 ){
6035    pCur->ss.isReversing = pCur->ss.iStep > 0;
6036  }else{
6037    pCur->ss.isReversing = pCur->ss.iStep < 0;
6038  }
6039  setupSequence( &pCur->ss );
6040  return SQLITE_OK;
6041}
6042
6043/*
6044** SQLite will invoke this method one or more times while planning a query
6045** that uses the generate_series virtual table.  This routine needs to create
6046** a query plan for each invocation and compute an estimated cost for that
6047** plan.
6048**
6049** In this implementation idxNum is used to represent the
6050** query plan.  idxStr is unused.
6051**
6052** The query plan is represented by bits in idxNum:
6053**
6054**  (1)  start = $value  -- constraint exists
6055**  (2)  stop = $value   -- constraint exists
6056**  (4)  step = $value   -- constraint exists
6057**  (8)  output in descending order
6058*/
6059static int seriesBestIndex(
6060  sqlite3_vtab *pVTab,
6061  sqlite3_index_info *pIdxInfo
6062){
6063  int i, j;              /* Loop over constraints */
6064  int idxNum = 0;        /* The query plan bitmask */
6065  int bStartSeen = 0;    /* EQ constraint seen on the START column */
6066  int unusableMask = 0;  /* Mask of unusable constraints */
6067  int nArg = 0;          /* Number of arguments that seriesFilter() expects */
6068  int aIdx[3];           /* Constraints on start, stop, and step */
6069  const struct sqlite3_index_constraint *pConstraint;
6070
6071  /* This implementation assumes that the start, stop, and step columns
6072  ** are the last three columns in the virtual table. */
6073  assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
6074  assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
6075
6076  aIdx[0] = aIdx[1] = aIdx[2] = -1;
6077  pConstraint = pIdxInfo->aConstraint;
6078  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6079    int iCol;    /* 0 for start, 1 for stop, 2 for step */
6080    int iMask;   /* bitmask for those column */
6081    if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
6082    iCol = pConstraint->iColumn - SERIES_COLUMN_START;
6083    assert( iCol>=0 && iCol<=2 );
6084    iMask = 1 << iCol;
6085    if( iCol==0 ) bStartSeen = 1;
6086    if( pConstraint->usable==0 ){
6087      unusableMask |=  iMask;
6088      continue;
6089    }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
6090      idxNum |= iMask;
6091      aIdx[iCol] = i;
6092    }
6093  }
6094  for(i=0; i<3; i++){
6095    if( (j = aIdx[i])>=0 ){
6096      pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
6097      pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
6098    }
6099  }
6100  /* The current generate_column() implementation requires at least one
6101  ** argument (the START value).  Legacy versions assumed START=0 if the
6102  ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
6103  ** to obtain the legacy behavior */
6104#ifndef ZERO_ARGUMENT_GENERATE_SERIES
6105  if( !bStartSeen ){
6106    sqlite3_free(pVTab->zErrMsg);
6107    pVTab->zErrMsg = sqlite3_mprintf(
6108        "first argument to \"generate_series()\" missing or unusable");
6109    return SQLITE_ERROR;
6110  }
6111#endif
6112  if( (unusableMask & ~idxNum)!=0 ){
6113    /* The start, stop, and step columns are inputs.  Therefore if there
6114    ** are unusable constraints on any of start, stop, or step then
6115    ** this plan is unusable */
6116    return SQLITE_CONSTRAINT;
6117  }
6118  if( (idxNum & 3)==3 ){
6119    /* Both start= and stop= boundaries are available.  This is the
6120    ** the preferred case */
6121    pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
6122    pIdxInfo->estimatedRows = 1000;
6123    if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
6124      if( pIdxInfo->aOrderBy[0].desc ){
6125        idxNum |= 8;
6126      }else{
6127        idxNum |= 16;
6128      }
6129      pIdxInfo->orderByConsumed = 1;
6130    }
6131  }else{
6132    /* If either boundary is missing, we have to generate a huge span
6133    ** of numbers.  Make this case very expensive so that the query
6134    ** planner will work hard to avoid it. */
6135    pIdxInfo->estimatedRows = 2147483647;
6136  }
6137  pIdxInfo->idxNum = idxNum;
6138  return SQLITE_OK;
6139}
6140
6141/*
6142** This following structure defines all the methods for the
6143** generate_series virtual table.
6144*/
6145static sqlite3_module seriesModule = {
6146  0,                         /* iVersion */
6147  0,                         /* xCreate */
6148  seriesConnect,             /* xConnect */
6149  seriesBestIndex,           /* xBestIndex */
6150  seriesDisconnect,          /* xDisconnect */
6151  0,                         /* xDestroy */
6152  seriesOpen,                /* xOpen - open a cursor */
6153  seriesClose,               /* xClose - close a cursor */
6154  seriesFilter,              /* xFilter - configure scan constraints */
6155  seriesNext,                /* xNext - advance a cursor */
6156  seriesEof,                 /* xEof - check for end of scan */
6157  seriesColumn,              /* xColumn - read data */
6158  seriesRowid,               /* xRowid - read data */
6159  0,                         /* xUpdate */
6160  0,                         /* xBegin */
6161  0,                         /* xSync */
6162  0,                         /* xCommit */
6163  0,                         /* xRollback */
6164  0,                         /* xFindMethod */
6165  0,                         /* xRename */
6166  0,                         /* xSavepoint */
6167  0,                         /* xRelease */
6168  0,                         /* xRollbackTo */
6169  0,                         /* xShadowName */
6170  0                          /* xIntegrity */
6171};
6172
6173#endif /* SQLITE_OMIT_VIRTUALTABLE */
6174
6175#ifdef _WIN32
6176
6177#endif
6178static int sqlite3_series_init(
6179  sqlite3 *db,
6180  char **pzErrMsg,
6181  const sqlite3_api_routines *pApi
6182){
6183  int rc = SQLITE_OK;
6184  SQLITE_EXTENSION_INIT2(pApi);
6185#ifndef SQLITE_OMIT_VIRTUALTABLE
6186  if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
6187    *pzErrMsg = sqlite3_mprintf(
6188        "generate_series() requires SQLite 3.8.12 or later");
6189    return SQLITE_ERROR;
6190  }
6191  rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
6192#endif
6193  return rc;
6194}
6195
6196/************************* End ../ext/misc/series.c ********************/
6197/************************* Begin ../ext/misc/regexp.c ******************/
6198/*
6199** 2012-11-13
6200**
6201** The author disclaims copyright to this source code.  In place of
6202** a legal notice, here is a blessing:
6203**
6204**    May you do good and not evil.
6205**    May you find forgiveness for yourself and forgive others.
6206**    May you share freely, never taking more than you give.
6207**
6208******************************************************************************
6209**
6210** The code in this file implements a compact but reasonably
6211** efficient regular-expression matcher for posix extended regular
6212** expressions against UTF8 text.
6213**
6214** This file is an SQLite extension.  It registers a single function
6215** named "regexp(A,B)" where A is the regular expression and B is the
6216** string to be matched.  By registering this function, SQLite will also
6217** then implement the "B regexp A" operator.  Note that with the function
6218** the regular expression comes first, but with the operator it comes
6219** second.
6220**
6221**  The following regular expression syntax is supported:
6222**
6223**     X*      zero or more occurrences of X
6224**     X+      one or more occurrences of X
6225**     X?      zero or one occurrences of X
6226**     X{p,q}  between p and q occurrences of X
6227**     (X)     match X
6228**     X|Y     X or Y
6229**     ^X      X occurring at the beginning of the string
6230**     X$      X occurring at the end of the string
6231**     .       Match any single character
6232**     \c      Character c where c is one of \{}()[]|*+?.
6233**     \c      C-language escapes for c in afnrtv.  ex: \t or \n
6234**     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
6235**     \xXX    Where XX is exactly 2 hex digits, unicode value XX
6236**     [abc]   Any single character from the set abc
6237**     [^abc]  Any single character not in the set abc
6238**     [a-z]   Any single character in the range a-z
6239**     [^a-z]  Any single character not in the range a-z
6240**     \b      Word boundary
6241**     \w      Word character.  [A-Za-z0-9_]
6242**     \W      Non-word character
6243**     \d      Digit
6244**     \D      Non-digit
6245**     \s      Whitespace character
6246**     \S      Non-whitespace character
6247**
6248** A nondeterministic finite automaton (NFA) is used for matching, so the
6249** performance is bounded by O(N*M) where N is the size of the regular
6250** expression and M is the size of the input string.  The matcher never
6251** exhibits exponential behavior.  Note that the X{p,q} operator expands
6252** to p copies of X following by q-p copies of X? and that the size of the
6253** regular expression in the O(N*M) performance bound is computed after
6254** this expansion.
6255*/
6256#include <string.h>
6257#include <stdlib.h>
6258/* #include "sqlite3ext.h" */
6259SQLITE_EXTENSION_INIT1
6260
6261/*
6262** The following #defines change the names of some functions implemented in
6263** this file to prevent name collisions with C-library functions of the
6264** same name.
6265*/
6266#define re_match   sqlite3re_match
6267#define re_compile sqlite3re_compile
6268#define re_free    sqlite3re_free
6269
6270/* The end-of-input character */
6271#define RE_EOF            0    /* End of input */
6272#define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
6273
6274/* The NFA is implemented as sequence of opcodes taken from the following
6275** set.  Each opcode has a single integer argument.
6276*/
6277#define RE_OP_MATCH       1    /* Match the one character in the argument */
6278#define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
6279#define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
6280#define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
6281#define RE_OP_GOTO        5    /* Jump to opcode at iArg */
6282#define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
6283#define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
6284#define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
6285#define RE_OP_CC_VALUE    9    /* Single value in a character class */
6286#define RE_OP_CC_RANGE   10    /* Range of values in a character class */
6287#define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
6288#define RE_OP_NOTWORD    12    /* Not a perl word character */
6289#define RE_OP_DIGIT      13    /* digit:  [0-9] */
6290#define RE_OP_NOTDIGIT   14    /* Not a digit */
6291#define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
6292#define RE_OP_NOTSPACE   16    /* Not a digit */
6293#define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
6294#define RE_OP_ATSTART    18    /* Currently at the start of the string */
6295
6296#if defined(SQLITE_DEBUG)
6297/* Opcode names used for symbolic debugging */
6298static const char *ReOpName[] = {
6299  "EOF",
6300  "MATCH",
6301  "ANY",
6302  "ANYSTAR",
6303  "FORK",
6304  "GOTO",
6305  "ACCEPT",
6306  "CC_INC",
6307  "CC_EXC",
6308  "CC_VALUE",
6309  "CC_RANGE",
6310  "WORD",
6311  "NOTWORD",
6312  "DIGIT",
6313  "NOTDIGIT",
6314  "SPACE",
6315  "NOTSPACE",
6316  "BOUNDARY",
6317  "ATSTART",
6318};
6319#endif /* SQLITE_DEBUG */
6320
6321
6322/* Each opcode is a "state" in the NFA */
6323typedef unsigned short ReStateNumber;
6324
6325/* Because this is an NFA and not a DFA, multiple states can be active at
6326** once.  An instance of the following object records all active states in
6327** the NFA.  The implementation is optimized for the common case where the
6328** number of actives states is small.
6329*/
6330typedef struct ReStateSet {
6331  unsigned nState;            /* Number of current states */
6332  ReStateNumber *aState;      /* Current states */
6333} ReStateSet;
6334
6335/* An input string read one character at a time.
6336*/
6337typedef struct ReInput ReInput;
6338struct ReInput {
6339  const unsigned char *z;  /* All text */
6340  int i;                   /* Next byte to read */
6341  int mx;                  /* EOF when i>=mx */
6342};
6343
6344/* A compiled NFA (or an NFA that is in the process of being compiled) is
6345** an instance of the following object.
6346*/
6347typedef struct ReCompiled ReCompiled;
6348struct ReCompiled {
6349  ReInput sIn;                /* Regular expression text */
6350  const char *zErr;           /* Error message to return */
6351  char *aOp;                  /* Operators for the virtual machine */
6352  int *aArg;                  /* Arguments to each operator */
6353  unsigned (*xNextChar)(ReInput*);  /* Next character function */
6354  unsigned char zInit[12];    /* Initial text to match */
6355  int nInit;                  /* Number of bytes in zInit */
6356  unsigned nState;            /* Number of entries in aOp[] and aArg[] */
6357  unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
6358};
6359
6360/* Add a state to the given state set if it is not already there */
6361static void re_add_state(ReStateSet *pSet, int newState){
6362  unsigned i;
6363  for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
6364  pSet->aState[pSet->nState++] = (ReStateNumber)newState;
6365}
6366
6367/* Extract the next unicode character from *pzIn and return it.  Advance
6368** *pzIn to the first byte past the end of the character returned.  To
6369** be clear:  this routine converts utf8 to unicode.  This routine is
6370** optimized for the common case where the next character is a single byte.
6371*/
6372static unsigned re_next_char(ReInput *p){
6373  unsigned c;
6374  if( p->i>=p->mx ) return 0;
6375  c = p->z[p->i++];
6376  if( c>=0x80 ){
6377    if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
6378      c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
6379      if( c<0x80 ) c = 0xfffd;
6380    }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
6381           && (p->z[p->i+1]&0xc0)==0x80 ){
6382      c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
6383      p->i += 2;
6384      if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
6385    }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
6386           && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
6387      c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
6388                       | (p->z[p->i+2]&0x3f);
6389      p->i += 3;
6390      if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
6391    }else{
6392      c = 0xfffd;
6393    }
6394  }
6395  return c;
6396}
6397static unsigned re_next_char_nocase(ReInput *p){
6398  unsigned c = re_next_char(p);
6399  if( c>='A' && c<='Z' ) c += 'a' - 'A';
6400  return c;
6401}
6402
6403/* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
6404static int re_word_char(int c){
6405  return (c>='0' && c<='9') || (c>='a' && c<='z')
6406      || (c>='A' && c<='Z') || c=='_';
6407}
6408
6409/* Return true if c is a "digit" character:  [0-9] */
6410static int re_digit_char(int c){
6411  return (c>='0' && c<='9');
6412}
6413
6414/* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
6415static int re_space_char(int c){
6416  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
6417}
6418
6419/* Run a compiled regular expression on the zero-terminated input
6420** string zIn[].  Return true on a match and false if there is no match.
6421*/
6422static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
6423  ReStateSet aStateSet[2], *pThis, *pNext;
6424  ReStateNumber aSpace[100];
6425  ReStateNumber *pToFree;
6426  unsigned int i = 0;
6427  unsigned int iSwap = 0;
6428  int c = RE_START;
6429  int cPrev = 0;
6430  int rc = 0;
6431  ReInput in;
6432
6433  in.z = zIn;
6434  in.i = 0;
6435  in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
6436
6437  /* Look for the initial prefix match, if there is one. */
6438  if( pRe->nInit ){
6439    unsigned char x = pRe->zInit[0];
6440    while( in.i+pRe->nInit<=in.mx
6441     && (zIn[in.i]!=x ||
6442         strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
6443    ){
6444      in.i++;
6445    }
6446    if( in.i+pRe->nInit>in.mx ) return 0;
6447    c = RE_START-1;
6448  }
6449
6450  if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
6451    pToFree = 0;
6452    aStateSet[0].aState = aSpace;
6453  }else{
6454    pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
6455    if( pToFree==0 ) return -1;
6456    aStateSet[0].aState = pToFree;
6457  }
6458  aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
6459  pNext = &aStateSet[1];
6460  pNext->nState = 0;
6461  re_add_state(pNext, 0);
6462  while( c!=RE_EOF && pNext->nState>0 ){
6463    cPrev = c;
6464    c = pRe->xNextChar(&in);
6465    pThis = pNext;
6466    pNext = &aStateSet[iSwap];
6467    iSwap = 1 - iSwap;
6468    pNext->nState = 0;
6469    for(i=0; i<pThis->nState; i++){
6470      int x = pThis->aState[i];
6471      switch( pRe->aOp[x] ){
6472        case RE_OP_MATCH: {
6473          if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
6474          break;
6475        }
6476        case RE_OP_ATSTART: {
6477          if( cPrev==RE_START ) re_add_state(pThis, x+1);
6478          break;
6479        }
6480        case RE_OP_ANY: {
6481          if( c!=0 ) re_add_state(pNext, x+1);
6482          break;
6483        }
6484        case RE_OP_WORD: {
6485          if( re_word_char(c) ) re_add_state(pNext, x+1);
6486          break;
6487        }
6488        case RE_OP_NOTWORD: {
6489          if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
6490          break;
6491        }
6492        case RE_OP_DIGIT: {
6493          if( re_digit_char(c) ) re_add_state(pNext, x+1);
6494          break;
6495        }
6496        case RE_OP_NOTDIGIT: {
6497          if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
6498          break;
6499        }
6500        case RE_OP_SPACE: {
6501          if( re_space_char(c) ) re_add_state(pNext, x+1);
6502          break;
6503        }
6504        case RE_OP_NOTSPACE: {
6505          if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
6506          break;
6507        }
6508        case RE_OP_BOUNDARY: {
6509          if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
6510          break;
6511        }
6512        case RE_OP_ANYSTAR: {
6513          re_add_state(pNext, x);
6514          re_add_state(pThis, x+1);
6515          break;
6516        }
6517        case RE_OP_FORK: {
6518          re_add_state(pThis, x+pRe->aArg[x]);
6519          re_add_state(pThis, x+1);
6520          break;
6521        }
6522        case RE_OP_GOTO: {
6523          re_add_state(pThis, x+pRe->aArg[x]);
6524          break;
6525        }
6526        case RE_OP_ACCEPT: {
6527          rc = 1;
6528          goto re_match_end;
6529        }
6530        case RE_OP_CC_EXC: {
6531          if( c==0 ) break;
6532          /* fall-through */ goto re_op_cc_inc;
6533        }
6534        case RE_OP_CC_INC: re_op_cc_inc: {
6535          int j = 1;
6536          int n = pRe->aArg[x];
6537          int hit = 0;
6538          for(j=1; j>0 && j<n; j++){
6539            if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
6540              if( pRe->aArg[x+j]==c ){
6541                hit = 1;
6542                j = -1;
6543              }
6544            }else{
6545              if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
6546                hit = 1;
6547                j = -1;
6548              }else{
6549                j++;
6550              }
6551            }
6552          }
6553          if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
6554          if( hit ) re_add_state(pNext, x+n);
6555          break;
6556        }
6557      }
6558    }
6559  }
6560  for(i=0; i<pNext->nState; i++){
6561    int x = pNext->aState[i];
6562    while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
6563    if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
6564  }
6565re_match_end:
6566  sqlite3_free(pToFree);
6567  return rc;
6568}
6569
6570/* Resize the opcode and argument arrays for an RE under construction.
6571*/
6572static int re_resize(ReCompiled *p, int N){
6573  char *aOp;
6574  int *aArg;
6575  aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
6576  if( aOp==0 ) return 1;
6577  p->aOp = aOp;
6578  aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
6579  if( aArg==0 ) return 1;
6580  p->aArg = aArg;
6581  p->nAlloc = N;
6582  return 0;
6583}
6584
6585/* Insert a new opcode and argument into an RE under construction.  The
6586** insertion point is just prior to existing opcode iBefore.
6587*/
6588static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
6589  int i;
6590  if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
6591  for(i=p->nState; i>iBefore; i--){
6592    p->aOp[i] = p->aOp[i-1];
6593    p->aArg[i] = p->aArg[i-1];
6594  }
6595  p->nState++;
6596  p->aOp[iBefore] = (char)op;
6597  p->aArg[iBefore] = arg;
6598  return iBefore;
6599}
6600
6601/* Append a new opcode and argument to the end of the RE under construction.
6602*/
6603static int re_append(ReCompiled *p, int op, int arg){
6604  return re_insert(p, p->nState, op, arg);
6605}
6606
6607/* Make a copy of N opcodes starting at iStart onto the end of the RE
6608** under construction.
6609*/
6610static void re_copy(ReCompiled *p, int iStart, int N){
6611  if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
6612  memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
6613  memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
6614  p->nState += N;
6615}
6616
6617/* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
6618** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
6619** c is not a hex digit *pV is unchanged.
6620*/
6621static int re_hex(int c, int *pV){
6622  if( c>='0' && c<='9' ){
6623    c -= '0';
6624  }else if( c>='a' && c<='f' ){
6625    c -= 'a' - 10;
6626  }else if( c>='A' && c<='F' ){
6627    c -= 'A' - 10;
6628  }else{
6629    return 0;
6630  }
6631  *pV = (*pV)*16 + (c & 0xff);
6632  return 1;
6633}
6634
6635/* A backslash character has been seen, read the next character and
6636** return its interpretation.
6637*/
6638static unsigned re_esc_char(ReCompiled *p){
6639  static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
6640  static const char zTrans[] = "\a\f\n\r\t\v";
6641  int i, v = 0;
6642  char c;
6643  if( p->sIn.i>=p->sIn.mx ) return 0;
6644  c = p->sIn.z[p->sIn.i];
6645  if( c=='u' && p->sIn.i+4<p->sIn.mx ){
6646    const unsigned char *zIn = p->sIn.z + p->sIn.i;
6647    if( re_hex(zIn[1],&v)
6648     && re_hex(zIn[2],&v)
6649     && re_hex(zIn[3],&v)
6650     && re_hex(zIn[4],&v)
6651    ){
6652      p->sIn.i += 5;
6653      return v;
6654    }
6655  }
6656  if( c=='x' && p->sIn.i+2<p->sIn.mx ){
6657    const unsigned char *zIn = p->sIn.z + p->sIn.i;
6658    if( re_hex(zIn[1],&v)
6659     && re_hex(zIn[2],&v)
6660    ){
6661      p->sIn.i += 3;
6662      return v;
6663    }
6664  }
6665  for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
6666  if( zEsc[i] ){
6667    if( i<6 ) c = zTrans[i];
6668    p->sIn.i++;
6669  }else{
6670    p->zErr = "unknown \\ escape";
6671  }
6672  return c;
6673}
6674
6675/* Forward declaration */
6676static const char *re_subcompile_string(ReCompiled*);
6677
6678/* Peek at the next byte of input */
6679static unsigned char rePeek(ReCompiled *p){
6680  return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
6681}
6682
6683/* Compile RE text into a sequence of opcodes.  Continue up to the
6684** first unmatched ")" character, then return.  If an error is found,
6685** return a pointer to the error message string.
6686*/
6687static const char *re_subcompile_re(ReCompiled *p){
6688  const char *zErr;
6689  int iStart, iEnd, iGoto;
6690  iStart = p->nState;
6691  zErr = re_subcompile_string(p);
6692  if( zErr ) return zErr;
6693  while( rePeek(p)=='|' ){
6694    iEnd = p->nState;
6695    re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
6696    iGoto = re_append(p, RE_OP_GOTO, 0);
6697    p->sIn.i++;
6698    zErr = re_subcompile_string(p);
6699    if( zErr ) return zErr;
6700    p->aArg[iGoto] = p->nState - iGoto;
6701  }
6702  return 0;
6703}
6704
6705/* Compile an element of regular expression text (anything that can be
6706** an operand to the "|" operator).  Return NULL on success or a pointer
6707** to the error message if there is a problem.
6708*/
6709static const char *re_subcompile_string(ReCompiled *p){
6710  int iPrev = -1;
6711  int iStart;
6712  unsigned c;
6713  const char *zErr;
6714  while( (c = p->xNextChar(&p->sIn))!=0 ){
6715    iStart = p->nState;
6716    switch( c ){
6717      case '|':
6718      case ')': {
6719        p->sIn.i--;
6720        return 0;
6721      }
6722      case '(': {
6723        zErr = re_subcompile_re(p);
6724        if( zErr ) return zErr;
6725        if( rePeek(p)!=')' ) return "unmatched '('";
6726        p->sIn.i++;
6727        break;
6728      }
6729      case '.': {
6730        if( rePeek(p)=='*' ){
6731          re_append(p, RE_OP_ANYSTAR, 0);
6732          p->sIn.i++;
6733        }else{
6734          re_append(p, RE_OP_ANY, 0);
6735        }
6736        break;
6737      }
6738      case '*': {
6739        if( iPrev<0 ) return "'*' without operand";
6740        re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
6741        re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
6742        break;
6743      }
6744      case '+': {
6745        if( iPrev<0 ) return "'+' without operand";
6746        re_append(p, RE_OP_FORK, iPrev - p->nState);
6747        break;
6748      }
6749      case '?': {
6750        if( iPrev<0 ) return "'?' without operand";
6751        re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
6752        break;
6753      }
6754      case '$': {
6755        re_append(p, RE_OP_MATCH, RE_EOF);
6756        break;
6757      }
6758      case '^': {
6759        re_append(p, RE_OP_ATSTART, 0);
6760        break;
6761      }
6762      case '{': {
6763        int m = 0, n = 0;
6764        int sz, j;
6765        if( iPrev<0 ) return "'{m,n}' without operand";
6766        while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
6767        n = m;
6768        if( c==',' ){
6769          p->sIn.i++;
6770          n = 0;
6771          while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
6772        }
6773        if( c!='}' ) return "unmatched '{'";
6774        if( n>0 && n<m ) return "n less than m in '{m,n}'";
6775        p->sIn.i++;
6776        sz = p->nState - iPrev;
6777        if( m==0 ){
6778          if( n==0 ) return "both m and n are zero in '{m,n}'";
6779          re_insert(p, iPrev, RE_OP_FORK, sz+1);
6780          iPrev++;
6781          n--;
6782        }else{
6783          for(j=1; j<m; j++) re_copy(p, iPrev, sz);
6784        }
6785        for(j=m; j<n; j++){
6786          re_append(p, RE_OP_FORK, sz+1);
6787          re_copy(p, iPrev, sz);
6788        }
6789        if( n==0 && m>0 ){
6790          re_append(p, RE_OP_FORK, -sz);
6791        }
6792        break;
6793      }
6794      case '[': {
6795        unsigned int iFirst = p->nState;
6796        if( rePeek(p)=='^' ){
6797          re_append(p, RE_OP_CC_EXC, 0);
6798          p->sIn.i++;
6799        }else{
6800          re_append(p, RE_OP_CC_INC, 0);
6801        }
6802        while( (c = p->xNextChar(&p->sIn))!=0 ){
6803          if( c=='[' && rePeek(p)==':' ){
6804            return "POSIX character classes not supported";
6805          }
6806          if( c=='\\' ) c = re_esc_char(p);
6807          if( rePeek(p)=='-' ){
6808            re_append(p, RE_OP_CC_RANGE, c);
6809            p->sIn.i++;
6810            c = p->xNextChar(&p->sIn);
6811            if( c=='\\' ) c = re_esc_char(p);
6812            re_append(p, RE_OP_CC_RANGE, c);
6813          }else{
6814            re_append(p, RE_OP_CC_VALUE, c);
6815          }
6816          if( rePeek(p)==']' ){ p->sIn.i++; break; }
6817        }
6818        if( c==0 ) return "unclosed '['";
6819        if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
6820        break;
6821      }
6822      case '\\': {
6823        int specialOp = 0;
6824        switch( rePeek(p) ){
6825          case 'b': specialOp = RE_OP_BOUNDARY;   break;
6826          case 'd': specialOp = RE_OP_DIGIT;      break;
6827          case 'D': specialOp = RE_OP_NOTDIGIT;   break;
6828          case 's': specialOp = RE_OP_SPACE;      break;
6829          case 'S': specialOp = RE_OP_NOTSPACE;   break;
6830          case 'w': specialOp = RE_OP_WORD;       break;
6831          case 'W': specialOp = RE_OP_NOTWORD;    break;
6832        }
6833        if( specialOp ){
6834          p->sIn.i++;
6835          re_append(p, specialOp, 0);
6836        }else{
6837          c = re_esc_char(p);
6838          re_append(p, RE_OP_MATCH, c);
6839        }
6840        break;
6841      }
6842      default: {
6843        re_append(p, RE_OP_MATCH, c);
6844        break;
6845      }
6846    }
6847    iPrev = iStart;
6848  }
6849  return 0;
6850}
6851
6852/* Free and reclaim all the memory used by a previously compiled
6853** regular expression.  Applications should invoke this routine once
6854** for every call to re_compile() to avoid memory leaks.
6855*/
6856static void re_free(ReCompiled *pRe){
6857  if( pRe ){
6858    sqlite3_free(pRe->aOp);
6859    sqlite3_free(pRe->aArg);
6860    sqlite3_free(pRe);
6861  }
6862}
6863
6864/*
6865** Compile a textual regular expression in zIn[] into a compiled regular
6866** expression suitable for us by re_match() and return a pointer to the
6867** compiled regular expression in *ppRe.  Return NULL on success or an
6868** error message if something goes wrong.
6869*/
6870static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
6871  ReCompiled *pRe;
6872  const char *zErr;
6873  int i, j;
6874
6875  *ppRe = 0;
6876  pRe = sqlite3_malloc( sizeof(*pRe) );
6877  if( pRe==0 ){
6878    return "out of memory";
6879  }
6880  memset(pRe, 0, sizeof(*pRe));
6881  pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
6882  if( re_resize(pRe, 30) ){
6883    re_free(pRe);
6884    return "out of memory";
6885  }
6886  if( zIn[0]=='^' ){
6887    zIn++;
6888  }else{
6889    re_append(pRe, RE_OP_ANYSTAR, 0);
6890  }
6891  pRe->sIn.z = (unsigned char*)zIn;
6892  pRe->sIn.i = 0;
6893  pRe->sIn.mx = (int)strlen(zIn);
6894  zErr = re_subcompile_re(pRe);
6895  if( zErr ){
6896    re_free(pRe);
6897    return zErr;
6898  }
6899  if( pRe->sIn.i>=pRe->sIn.mx ){
6900    re_append(pRe, RE_OP_ACCEPT, 0);
6901    *ppRe = pRe;
6902  }else{
6903    re_free(pRe);
6904    return "unrecognized character";
6905  }
6906
6907  /* The following is a performance optimization.  If the regex begins with
6908  ** ".*" (if the input regex lacks an initial "^") and afterwards there are
6909  ** one or more matching characters, enter those matching characters into
6910  ** zInit[].  The re_match() routine can then search ahead in the input
6911  ** string looking for the initial match without having to run the whole
6912  ** regex engine over the string.  Do not worry about trying to match
6913  ** unicode characters beyond plane 0 - those are very rare and this is
6914  ** just an optimization. */
6915  if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
6916    for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
6917      unsigned x = pRe->aArg[i];
6918      if( x<=0x7f ){
6919        pRe->zInit[j++] = (unsigned char)x;
6920      }else if( x<=0x7ff ){
6921        pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
6922        pRe->zInit[j++] = 0x80 | (x&0x3f);
6923      }else if( x<=0xffff ){
6924        pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
6925        pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
6926        pRe->zInit[j++] = 0x80 | (x&0x3f);
6927      }else{
6928        break;
6929      }
6930    }
6931    if( j>0 && pRe->zInit[j-1]==0 ) j--;
6932    pRe->nInit = j;
6933  }
6934  return pRe->zErr;
6935}
6936
6937/*
6938** Implementation of the regexp() SQL function.  This function implements
6939** the build-in REGEXP operator.  The first argument to the function is the
6940** pattern and the second argument is the string.  So, the SQL statements:
6941**
6942**       A REGEXP B
6943**
6944** is implemented as regexp(B,A).
6945*/
6946static void re_sql_func(
6947  sqlite3_context *context,
6948  int argc,
6949  sqlite3_value **argv
6950){
6951  ReCompiled *pRe;          /* Compiled regular expression */
6952  const char *zPattern;     /* The regular expression */
6953  const unsigned char *zStr;/* String being searched */
6954  const char *zErr;         /* Compile error message */
6955  int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
6956
6957  (void)argc;  /* Unused */
6958  pRe = sqlite3_get_auxdata(context, 0);
6959  if( pRe==0 ){
6960    zPattern = (const char*)sqlite3_value_text(argv[0]);
6961    if( zPattern==0 ) return;
6962    zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
6963    if( zErr ){
6964      re_free(pRe);
6965      sqlite3_result_error(context, zErr, -1);
6966      return;
6967    }
6968    if( pRe==0 ){
6969      sqlite3_result_error_nomem(context);
6970      return;
6971    }
6972    setAux = 1;
6973  }
6974  zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
6975  if( zStr!=0 ){
6976    sqlite3_result_int(context, re_match(pRe, zStr, -1));
6977  }
6978  if( setAux ){
6979    sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
6980  }
6981}
6982
6983#if defined(SQLITE_DEBUG)
6984/*
6985** This function is used for testing and debugging only.  It is only available
6986** if the SQLITE_DEBUG compile-time option is used.
6987**
6988** Compile a regular expression and then convert the compiled expression into
6989** text and return that text.
6990*/
6991static void re_bytecode_func(
6992  sqlite3_context *context,
6993  int argc,
6994  sqlite3_value **argv
6995){
6996  const char *zPattern;
6997  const char *zErr;
6998  ReCompiled *pRe;
6999  sqlite3_str *pStr;
7000  int i;
7001  int n;
7002  char *z;
7003  (void)argc;
7004
7005  zPattern = (const char*)sqlite3_value_text(argv[0]);
7006  if( zPattern==0 ) return;
7007  zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7008  if( zErr ){
7009    re_free(pRe);
7010    sqlite3_result_error(context, zErr, -1);
7011    return;
7012  }
7013  if( pRe==0 ){
7014    sqlite3_result_error_nomem(context);
7015    return;
7016  }
7017  pStr = sqlite3_str_new(0);
7018  if( pStr==0 ) goto re_bytecode_func_err;
7019  if( pRe->nInit>0 ){
7020    sqlite3_str_appendf(pStr, "INIT     ");
7021    for(i=0; i<pRe->nInit; i++){
7022      sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
7023    }
7024    sqlite3_str_appendf(pStr, "\n");
7025  }
7026  for(i=0; (unsigned)i<pRe->nState; i++){
7027    sqlite3_str_appendf(pStr, "%-8s %4d\n",
7028         ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
7029  }
7030  n = sqlite3_str_length(pStr);
7031  z = sqlite3_str_finish(pStr);
7032  if( n==0 ){
7033    sqlite3_free(z);
7034  }else{
7035    sqlite3_result_text(context, z, n-1, sqlite3_free);
7036  }
7037
7038re_bytecode_func_err:
7039  re_free(pRe);
7040}
7041
7042#endif /* SQLITE_DEBUG */
7043
7044
7045/*
7046** Invoke this routine to register the regexp() function with the
7047** SQLite database connection.
7048*/
7049#ifdef _WIN32
7050
7051#endif
7052static int sqlite3_regexp_init(
7053  sqlite3 *db,
7054  char **pzErrMsg,
7055  const sqlite3_api_routines *pApi
7056){
7057  int rc = SQLITE_OK;
7058  SQLITE_EXTENSION_INIT2(pApi);
7059  (void)pzErrMsg;  /* Unused */
7060  rc = sqlite3_create_function(db, "regexp", 2,
7061                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7062                            0, re_sql_func, 0, 0);
7063  if( rc==SQLITE_OK ){
7064    /* The regexpi(PATTERN,STRING) function is a case-insensitive version
7065    ** of regexp(PATTERN,STRING). */
7066    rc = sqlite3_create_function(db, "regexpi", 2,
7067                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7068                            (void*)db, re_sql_func, 0, 0);
7069#if defined(SQLITE_DEBUG)
7070    if( rc==SQLITE_OK ){
7071      rc = sqlite3_create_function(db, "regexp_bytecode", 1,
7072                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7073                            0, re_bytecode_func, 0, 0);
7074    }
7075#endif /* SQLITE_DEBUG */
7076  }
7077  return rc;
7078}
7079
7080/************************* End ../ext/misc/regexp.c ********************/
7081#ifndef SQLITE_SHELL_FIDDLE
7082/************************* Begin ../ext/misc/fileio.c ******************/
7083/*
7084** 2014-06-13
7085**
7086** The author disclaims copyright to this source code.  In place of
7087** a legal notice, here is a blessing:
7088**
7089**    May you do good and not evil.
7090**    May you find forgiveness for yourself and forgive others.
7091**    May you share freely, never taking more than you give.
7092**
7093******************************************************************************
7094**
7095** This SQLite extension implements SQL functions readfile() and
7096** writefile(), and eponymous virtual type "fsdir".
7097**
7098** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
7099**
7100**   If neither of the optional arguments is present, then this UDF
7101**   function writes blob DATA to file FILE. If successful, the number
7102**   of bytes written is returned. If an error occurs, NULL is returned.
7103**
7104**   If the first option argument - MODE - is present, then it must
7105**   be passed an integer value that corresponds to a POSIX mode
7106**   value (file type + permissions, as returned in the stat.st_mode
7107**   field by the stat() system call). Three types of files may
7108**   be written/created:
7109**
7110**     regular files:  (mode & 0170000)==0100000
7111**     symbolic links: (mode & 0170000)==0120000
7112**     directories:    (mode & 0170000)==0040000
7113**
7114**   For a directory, the DATA is ignored. For a symbolic link, it is
7115**   interpreted as text and used as the target of the link. For a
7116**   regular file, it is interpreted as a blob and written into the
7117**   named file. Regardless of the type of file, its permissions are
7118**   set to (mode & 0777) before returning.
7119**
7120**   If the optional MTIME argument is present, then it is interpreted
7121**   as an integer - the number of seconds since the unix epoch. The
7122**   modification-time of the target file is set to this value before
7123**   returning.
7124**
7125**   If three or more arguments are passed to this function and an
7126**   error is encountered, an exception is raised.
7127**
7128** READFILE(FILE):
7129**
7130**   Read and return the contents of file FILE (type blob) from disk.
7131**
7132** FSDIR:
7133**
7134**   Used as follows:
7135**
7136**     SELECT * FROM fsdir($path [, $dir]);
7137**
7138**   Parameter $path is an absolute or relative pathname. If the file that it
7139**   refers to does not exist, it is an error. If the path refers to a regular
7140**   file or symbolic link, it returns a single row. Or, if the path refers
7141**   to a directory, it returns one row for the directory, and one row for each
7142**   file within the hierarchy rooted at $path.
7143**
7144**   Each row has the following columns:
7145**
7146**     name:  Path to file or directory (text value).
7147**     mode:  Value of stat.st_mode for directory entry (an integer).
7148**     mtime: Value of stat.st_mtime for directory entry (an integer).
7149**     data:  For a regular file, a blob containing the file data. For a
7150**            symlink, a text value containing the text of the link. For a
7151**            directory, NULL.
7152**
7153**   If a non-NULL value is specified for the optional $dir parameter and
7154**   $path is a relative path, then $path is interpreted relative to $dir.
7155**   And the paths returned in the "name" column of the table are also
7156**   relative to directory $dir.
7157**
7158** Notes on building this extension for Windows:
7159**   Unless linked statically with the SQLite library, a preprocessor
7160**   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
7161**   DLL form of this extension for WIN32. See its use below for details.
7162*/
7163/* #include "sqlite3ext.h" */
7164SQLITE_EXTENSION_INIT1
7165#include <stdio.h>
7166#include <string.h>
7167#include <assert.h>
7168
7169#include <sys/types.h>
7170#include <sys/stat.h>
7171#include <fcntl.h>
7172#if !defined(_WIN32) && !defined(WIN32)
7173#  include <unistd.h>
7174#  include <dirent.h>
7175#  include <utime.h>
7176#  include <sys/time.h>
7177#else
7178#  include "windows.h"
7179#  include <io.h>
7180#  include <direct.h>
7181/* #  include "test_windirent.h" */
7182#  define dirent DIRENT
7183#  ifndef chmod
7184#    define chmod _chmod
7185#  endif
7186#  ifndef stat
7187#    define stat _stat
7188#  endif
7189#  define mkdir(path,mode) _mkdir(path)
7190#  define lstat(path,buf) stat(path,buf)
7191#endif
7192#include <time.h>
7193#include <errno.h>
7194
7195
7196/*
7197** Structure of the fsdir() table-valued function
7198*/
7199                 /*    0    1    2     3    4           5             */
7200#define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
7201#define FSDIR_COLUMN_NAME     0     /* Name of the file */
7202#define FSDIR_COLUMN_MODE     1     /* Access mode */
7203#define FSDIR_COLUMN_MTIME    2     /* Last modification time */
7204#define FSDIR_COLUMN_DATA     3     /* File content */
7205#define FSDIR_COLUMN_PATH     4     /* Path to top of search */
7206#define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
7207
7208
7209/*
7210** Set the result stored by context ctx to a blob containing the
7211** contents of file zName.  Or, leave the result unchanged (NULL)
7212** if the file does not exist or is unreadable.
7213**
7214** If the file exceeds the SQLite blob size limit, through an
7215** SQLITE_TOOBIG error.
7216**
7217** Throw an SQLITE_IOERR if there are difficulties pulling the file
7218** off of disk.
7219*/
7220static void readFileContents(sqlite3_context *ctx, const char *zName){
7221  FILE *in;
7222  sqlite3_int64 nIn;
7223  void *pBuf;
7224  sqlite3 *db;
7225  int mxBlob;
7226
7227  in = fopen(zName, "rb");
7228  if( in==0 ){
7229    /* File does not exist or is unreadable. Leave the result set to NULL. */
7230    return;
7231  }
7232  fseek(in, 0, SEEK_END);
7233  nIn = ftell(in);
7234  rewind(in);
7235  db = sqlite3_context_db_handle(ctx);
7236  mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
7237  if( nIn>mxBlob ){
7238    sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
7239    fclose(in);
7240    return;
7241  }
7242  pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
7243  if( pBuf==0 ){
7244    sqlite3_result_error_nomem(ctx);
7245    fclose(in);
7246    return;
7247  }
7248  if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
7249    sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
7250  }else{
7251    sqlite3_result_error_code(ctx, SQLITE_IOERR);
7252    sqlite3_free(pBuf);
7253  }
7254  fclose(in);
7255}
7256
7257/*
7258** Implementation of the "readfile(X)" SQL function.  The entire content
7259** of the file named X is read and returned as a BLOB.  NULL is returned
7260** if the file does not exist or is unreadable.
7261*/
7262static void readfileFunc(
7263  sqlite3_context *context,
7264  int argc,
7265  sqlite3_value **argv
7266){
7267  const char *zName;
7268  (void)(argc);  /* Unused parameter */
7269  zName = (const char*)sqlite3_value_text(argv[0]);
7270  if( zName==0 ) return;
7271  readFileContents(context, zName);
7272}
7273
7274/*
7275** Set the error message contained in context ctx to the results of
7276** vprintf(zFmt, ...).
7277*/
7278static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7279  char *zMsg = 0;
7280  va_list ap;
7281  va_start(ap, zFmt);
7282  zMsg = sqlite3_vmprintf(zFmt, ap);
7283  sqlite3_result_error(ctx, zMsg, -1);
7284  sqlite3_free(zMsg);
7285  va_end(ap);
7286}
7287
7288#if defined(_WIN32)
7289/*
7290** This function is designed to convert a Win32 FILETIME structure into the
7291** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
7292*/
7293static sqlite3_uint64 fileTimeToUnixTime(
7294  LPFILETIME pFileTime
7295){
7296  SYSTEMTIME epochSystemTime;
7297  ULARGE_INTEGER epochIntervals;
7298  FILETIME epochFileTime;
7299  ULARGE_INTEGER fileIntervals;
7300
7301  memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
7302  epochSystemTime.wYear = 1970;
7303  epochSystemTime.wMonth = 1;
7304  epochSystemTime.wDay = 1;
7305  SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
7306  epochIntervals.LowPart = epochFileTime.dwLowDateTime;
7307  epochIntervals.HighPart = epochFileTime.dwHighDateTime;
7308
7309  fileIntervals.LowPart = pFileTime->dwLowDateTime;
7310  fileIntervals.HighPart = pFileTime->dwHighDateTime;
7311
7312  return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
7313}
7314
7315
7316#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
7317#  /* To allow a standalone DLL, use this next replacement function: */
7318#  undef sqlite3_win32_utf8_to_unicode
7319#  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
7320#
7321LPWSTR utf8_to_utf16(const char *z){
7322  int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
7323  LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
7324  if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
7325    return rv;
7326  sqlite3_free(rv);
7327  return 0;
7328}
7329#endif
7330
7331/*
7332** This function attempts to normalize the time values found in the stat()
7333** buffer to UTC.  This is necessary on Win32, where the runtime library
7334** appears to return these values as local times.
7335*/
7336static void statTimesToUtc(
7337  const char *zPath,
7338  struct stat *pStatBuf
7339){
7340  HANDLE hFindFile;
7341  WIN32_FIND_DATAW fd;
7342  LPWSTR zUnicodeName;
7343  extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7344  zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
7345  if( zUnicodeName ){
7346    memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
7347    hFindFile = FindFirstFileW(zUnicodeName, &fd);
7348    if( hFindFile!=NULL ){
7349      pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
7350      pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
7351      pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
7352      FindClose(hFindFile);
7353    }
7354    sqlite3_free(zUnicodeName);
7355  }
7356}
7357#endif
7358
7359/*
7360** This function is used in place of stat().  On Windows, special handling
7361** is required in order for the included time to be returned as UTC.  On all
7362** other systems, this function simply calls stat().
7363*/
7364static int fileStat(
7365  const char *zPath,
7366  struct stat *pStatBuf
7367){
7368#if defined(_WIN32)
7369  int rc = stat(zPath, pStatBuf);
7370  if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7371  return rc;
7372#else
7373  return stat(zPath, pStatBuf);
7374#endif
7375}
7376
7377/*
7378** This function is used in place of lstat().  On Windows, special handling
7379** is required in order for the included time to be returned as UTC.  On all
7380** other systems, this function simply calls lstat().
7381*/
7382static int fileLinkStat(
7383  const char *zPath,
7384  struct stat *pStatBuf
7385){
7386#if defined(_WIN32)
7387  int rc = lstat(zPath, pStatBuf);
7388  if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7389  return rc;
7390#else
7391  return lstat(zPath, pStatBuf);
7392#endif
7393}
7394
7395/*
7396** Argument zFile is the name of a file that will be created and/or written
7397** by SQL function writefile(). This function ensures that the directory
7398** zFile will be written to exists, creating it if required. The permissions
7399** for any path components created by this function are set in accordance
7400** with the current umask.
7401**
7402** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
7403** SQLITE_OK is returned if the directory is successfully created, or
7404** SQLITE_ERROR otherwise.
7405*/
7406static int makeDirectory(
7407  const char *zFile
7408){
7409  char *zCopy = sqlite3_mprintf("%s", zFile);
7410  int rc = SQLITE_OK;
7411
7412  if( zCopy==0 ){
7413    rc = SQLITE_NOMEM;
7414  }else{
7415    int nCopy = (int)strlen(zCopy);
7416    int i = 1;
7417
7418    while( rc==SQLITE_OK ){
7419      struct stat sStat;
7420      int rc2;
7421
7422      for(; zCopy[i]!='/' && i<nCopy; i++);
7423      if( i==nCopy ) break;
7424      zCopy[i] = '\0';
7425
7426      rc2 = fileStat(zCopy, &sStat);
7427      if( rc2!=0 ){
7428        if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
7429      }else{
7430        if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
7431      }
7432      zCopy[i] = '/';
7433      i++;
7434    }
7435
7436    sqlite3_free(zCopy);
7437  }
7438
7439  return rc;
7440}
7441
7442/*
7443** This function does the work for the writefile() UDF. Refer to
7444** header comments at the top of this file for details.
7445*/
7446static int writeFile(
7447  sqlite3_context *pCtx,          /* Context to return bytes written in */
7448  const char *zFile,              /* File to write */
7449  sqlite3_value *pData,           /* Data to write */
7450  mode_t mode,                    /* MODE parameter passed to writefile() */
7451  sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
7452){
7453  if( zFile==0 ) return 1;
7454#if !defined(_WIN32) && !defined(WIN32)
7455  if( S_ISLNK(mode) ){
7456    const char *zTo = (const char*)sqlite3_value_text(pData);
7457    if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
7458  }else
7459#endif
7460  {
7461    if( S_ISDIR(mode) ){
7462      if( mkdir(zFile, mode) ){
7463        /* The mkdir() call to create the directory failed. This might not
7464        ** be an error though - if there is already a directory at the same
7465        ** path and either the permissions already match or can be changed
7466        ** to do so using chmod(), it is not an error.  */
7467        struct stat sStat;
7468        if( errno!=EEXIST
7469         || 0!=fileStat(zFile, &sStat)
7470         || !S_ISDIR(sStat.st_mode)
7471         || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
7472        ){
7473          return 1;
7474        }
7475      }
7476    }else{
7477      sqlite3_int64 nWrite = 0;
7478      const char *z;
7479      int rc = 0;
7480      FILE *out = fopen(zFile, "wb");
7481      if( out==0 ) return 1;
7482      z = (const char*)sqlite3_value_blob(pData);
7483      if( z ){
7484        sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
7485        nWrite = sqlite3_value_bytes(pData);
7486        if( nWrite!=n ){
7487          rc = 1;
7488        }
7489      }
7490      fclose(out);
7491      if( rc==0 && mode && chmod(zFile, mode & 0777) ){
7492        rc = 1;
7493      }
7494      if( rc ) return 2;
7495      sqlite3_result_int64(pCtx, nWrite);
7496    }
7497  }
7498
7499  if( mtime>=0 ){
7500#if defined(_WIN32)
7501#if !SQLITE_OS_WINRT
7502    /* Windows */
7503    FILETIME lastAccess;
7504    FILETIME lastWrite;
7505    SYSTEMTIME currentTime;
7506    LONGLONG intervals;
7507    HANDLE hFile;
7508    LPWSTR zUnicodeName;
7509    extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7510
7511    GetSystemTime(&currentTime);
7512    SystemTimeToFileTime(&currentTime, &lastAccess);
7513    intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
7514    lastWrite.dwLowDateTime = (DWORD)intervals;
7515    lastWrite.dwHighDateTime = intervals >> 32;
7516    zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
7517    if( zUnicodeName==0 ){
7518      return 1;
7519    }
7520    hFile = CreateFileW(
7521      zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
7522      FILE_FLAG_BACKUP_SEMANTICS, NULL
7523    );
7524    sqlite3_free(zUnicodeName);
7525    if( hFile!=INVALID_HANDLE_VALUE ){
7526      BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
7527      CloseHandle(hFile);
7528      return !bResult;
7529    }else{
7530      return 1;
7531    }
7532#endif
7533#elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
7534    /* Recent unix */
7535    struct timespec times[2];
7536    times[0].tv_nsec = times[1].tv_nsec = 0;
7537    times[0].tv_sec = time(0);
7538    times[1].tv_sec = mtime;
7539    if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
7540      return 1;
7541    }
7542#else
7543    /* Legacy unix */
7544    struct timeval times[2];
7545    times[0].tv_usec = times[1].tv_usec = 0;
7546    times[0].tv_sec = time(0);
7547    times[1].tv_sec = mtime;
7548    if( utimes(zFile, times) ){
7549      return 1;
7550    }
7551#endif
7552  }
7553
7554  return 0;
7555}
7556
7557/*
7558** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
7559** Refer to header comments at the top of this file for details.
7560*/
7561static void writefileFunc(
7562  sqlite3_context *context,
7563  int argc,
7564  sqlite3_value **argv
7565){
7566  const char *zFile;
7567  mode_t mode = 0;
7568  int res;
7569  sqlite3_int64 mtime = -1;
7570
7571  if( argc<2 || argc>4 ){
7572    sqlite3_result_error(context,
7573        "wrong number of arguments to function writefile()", -1
7574    );
7575    return;
7576  }
7577
7578  zFile = (const char*)sqlite3_value_text(argv[0]);
7579  if( zFile==0 ) return;
7580  if( argc>=3 ){
7581    mode = (mode_t)sqlite3_value_int(argv[2]);
7582  }
7583  if( argc==4 ){
7584    mtime = sqlite3_value_int64(argv[3]);
7585  }
7586
7587  res = writeFile(context, zFile, argv[1], mode, mtime);
7588  if( res==1 && errno==ENOENT ){
7589    if( makeDirectory(zFile)==SQLITE_OK ){
7590      res = writeFile(context, zFile, argv[1], mode, mtime);
7591    }
7592  }
7593
7594  if( argc>2 && res!=0 ){
7595    if( S_ISLNK(mode) ){
7596      ctxErrorMsg(context, "failed to create symlink: %s", zFile);
7597    }else if( S_ISDIR(mode) ){
7598      ctxErrorMsg(context, "failed to create directory: %s", zFile);
7599    }else{
7600      ctxErrorMsg(context, "failed to write file: %s", zFile);
7601    }
7602  }
7603}
7604
7605/*
7606** SQL function:   lsmode(MODE)
7607**
7608** Given a numberic st_mode from stat(), convert it into a human-readable
7609** text string in the style of "ls -l".
7610*/
7611static void lsModeFunc(
7612  sqlite3_context *context,
7613  int argc,
7614  sqlite3_value **argv
7615){
7616  int i;
7617  int iMode = sqlite3_value_int(argv[0]);
7618  char z[16];
7619  (void)argc;
7620  if( S_ISLNK(iMode) ){
7621    z[0] = 'l';
7622  }else if( S_ISREG(iMode) ){
7623    z[0] = '-';
7624  }else if( S_ISDIR(iMode) ){
7625    z[0] = 'd';
7626  }else{
7627    z[0] = '?';
7628  }
7629  for(i=0; i<3; i++){
7630    int m = (iMode >> ((2-i)*3));
7631    char *a = &z[1 + i*3];
7632    a[0] = (m & 0x4) ? 'r' : '-';
7633    a[1] = (m & 0x2) ? 'w' : '-';
7634    a[2] = (m & 0x1) ? 'x' : '-';
7635  }
7636  z[10] = '\0';
7637  sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
7638}
7639
7640#ifndef SQLITE_OMIT_VIRTUALTABLE
7641
7642/*
7643** Cursor type for recursively iterating through a directory structure.
7644*/
7645typedef struct fsdir_cursor fsdir_cursor;
7646typedef struct FsdirLevel FsdirLevel;
7647
7648struct FsdirLevel {
7649  DIR *pDir;                 /* From opendir() */
7650  char *zDir;                /* Name of directory (nul-terminated) */
7651};
7652
7653struct fsdir_cursor {
7654  sqlite3_vtab_cursor base;  /* Base class - must be first */
7655
7656  int nLvl;                  /* Number of entries in aLvl[] array */
7657  int iLvl;                  /* Index of current entry */
7658  FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
7659
7660  const char *zBase;
7661  int nBase;
7662
7663  struct stat sStat;         /* Current lstat() results */
7664  char *zPath;               /* Path to current entry */
7665  sqlite3_int64 iRowid;      /* Current rowid */
7666};
7667
7668typedef struct fsdir_tab fsdir_tab;
7669struct fsdir_tab {
7670  sqlite3_vtab base;         /* Base class - must be first */
7671};
7672
7673/*
7674** Construct a new fsdir virtual table object.
7675*/
7676static int fsdirConnect(
7677  sqlite3 *db,
7678  void *pAux,
7679  int argc, const char *const*argv,
7680  sqlite3_vtab **ppVtab,
7681  char **pzErr
7682){
7683  fsdir_tab *pNew = 0;
7684  int rc;
7685  (void)pAux;
7686  (void)argc;
7687  (void)argv;
7688  (void)pzErr;
7689  rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
7690  if( rc==SQLITE_OK ){
7691    pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
7692    if( pNew==0 ) return SQLITE_NOMEM;
7693    memset(pNew, 0, sizeof(*pNew));
7694    sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
7695  }
7696  *ppVtab = (sqlite3_vtab*)pNew;
7697  return rc;
7698}
7699
7700/*
7701** This method is the destructor for fsdir vtab objects.
7702*/
7703static int fsdirDisconnect(sqlite3_vtab *pVtab){
7704  sqlite3_free(pVtab);
7705  return SQLITE_OK;
7706}
7707
7708/*
7709** Constructor for a new fsdir_cursor object.
7710*/
7711static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
7712  fsdir_cursor *pCur;
7713  (void)p;
7714  pCur = sqlite3_malloc( sizeof(*pCur) );
7715  if( pCur==0 ) return SQLITE_NOMEM;
7716  memset(pCur, 0, sizeof(*pCur));
7717  pCur->iLvl = -1;
7718  *ppCursor = &pCur->base;
7719  return SQLITE_OK;
7720}
7721
7722/*
7723** Reset a cursor back to the state it was in when first returned
7724** by fsdirOpen().
7725*/
7726static void fsdirResetCursor(fsdir_cursor *pCur){
7727  int i;
7728  for(i=0; i<=pCur->iLvl; i++){
7729    FsdirLevel *pLvl = &pCur->aLvl[i];
7730    if( pLvl->pDir ) closedir(pLvl->pDir);
7731    sqlite3_free(pLvl->zDir);
7732  }
7733  sqlite3_free(pCur->zPath);
7734  sqlite3_free(pCur->aLvl);
7735  pCur->aLvl = 0;
7736  pCur->zPath = 0;
7737  pCur->zBase = 0;
7738  pCur->nBase = 0;
7739  pCur->nLvl = 0;
7740  pCur->iLvl = -1;
7741  pCur->iRowid = 1;
7742}
7743
7744/*
7745** Destructor for an fsdir_cursor.
7746*/
7747static int fsdirClose(sqlite3_vtab_cursor *cur){
7748  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7749
7750  fsdirResetCursor(pCur);
7751  sqlite3_free(pCur);
7752  return SQLITE_OK;
7753}
7754
7755/*
7756** Set the error message for the virtual table associated with cursor
7757** pCur to the results of vprintf(zFmt, ...).
7758*/
7759static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
7760  va_list ap;
7761  va_start(ap, zFmt);
7762  pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7763  va_end(ap);
7764}
7765
7766
7767/*
7768** Advance an fsdir_cursor to its next row of output.
7769*/
7770static int fsdirNext(sqlite3_vtab_cursor *cur){
7771  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7772  mode_t m = pCur->sStat.st_mode;
7773
7774  pCur->iRowid++;
7775  if( S_ISDIR(m) ){
7776    /* Descend into this directory */
7777    int iNew = pCur->iLvl + 1;
7778    FsdirLevel *pLvl;
7779    if( iNew>=pCur->nLvl ){
7780      int nNew = iNew+1;
7781      sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
7782      FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
7783      if( aNew==0 ) return SQLITE_NOMEM;
7784      memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
7785      pCur->aLvl = aNew;
7786      pCur->nLvl = nNew;
7787    }
7788    pCur->iLvl = iNew;
7789    pLvl = &pCur->aLvl[iNew];
7790
7791    pLvl->zDir = pCur->zPath;
7792    pCur->zPath = 0;
7793    pLvl->pDir = opendir(pLvl->zDir);
7794    if( pLvl->pDir==0 ){
7795      fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
7796      return SQLITE_ERROR;
7797    }
7798  }
7799
7800  while( pCur->iLvl>=0 ){
7801    FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
7802    struct dirent *pEntry = readdir(pLvl->pDir);
7803    if( pEntry ){
7804      if( pEntry->d_name[0]=='.' ){
7805       if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
7806       if( pEntry->d_name[1]=='\0' ) continue;
7807      }
7808      sqlite3_free(pCur->zPath);
7809      pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
7810      if( pCur->zPath==0 ) return SQLITE_NOMEM;
7811      if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7812        fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7813        return SQLITE_ERROR;
7814      }
7815      return SQLITE_OK;
7816    }
7817    closedir(pLvl->pDir);
7818    sqlite3_free(pLvl->zDir);
7819    pLvl->pDir = 0;
7820    pLvl->zDir = 0;
7821    pCur->iLvl--;
7822  }
7823
7824  /* EOF */
7825  sqlite3_free(pCur->zPath);
7826  pCur->zPath = 0;
7827  return SQLITE_OK;
7828}
7829
7830/*
7831** Return values of columns for the row at which the series_cursor
7832** is currently pointing.
7833*/
7834static int fsdirColumn(
7835  sqlite3_vtab_cursor *cur,   /* The cursor */
7836  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7837  int i                       /* Which column to return */
7838){
7839  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7840  switch( i ){
7841    case FSDIR_COLUMN_NAME: {
7842      sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
7843      break;
7844    }
7845
7846    case FSDIR_COLUMN_MODE:
7847      sqlite3_result_int64(ctx, pCur->sStat.st_mode);
7848      break;
7849
7850    case FSDIR_COLUMN_MTIME:
7851      sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
7852      break;
7853
7854    case FSDIR_COLUMN_DATA: {
7855      mode_t m = pCur->sStat.st_mode;
7856      if( S_ISDIR(m) ){
7857        sqlite3_result_null(ctx);
7858#if !defined(_WIN32) && !defined(WIN32)
7859      }else if( S_ISLNK(m) ){
7860        char aStatic[64];
7861        char *aBuf = aStatic;
7862        sqlite3_int64 nBuf = 64;
7863        int n;
7864
7865        while( 1 ){
7866          n = readlink(pCur->zPath, aBuf, nBuf);
7867          if( n<nBuf ) break;
7868          if( aBuf!=aStatic ) sqlite3_free(aBuf);
7869          nBuf = nBuf*2;
7870          aBuf = sqlite3_malloc64(nBuf);
7871          if( aBuf==0 ){
7872            sqlite3_result_error_nomem(ctx);
7873            return SQLITE_NOMEM;
7874          }
7875        }
7876
7877        sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
7878        if( aBuf!=aStatic ) sqlite3_free(aBuf);
7879#endif
7880      }else{
7881        readFileContents(ctx, pCur->zPath);
7882      }
7883    }
7884    case FSDIR_COLUMN_PATH:
7885    default: {
7886      /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
7887      ** always return their values as NULL */
7888      break;
7889    }
7890  }
7891  return SQLITE_OK;
7892}
7893
7894/*
7895** Return the rowid for the current row. In this implementation, the
7896** first row returned is assigned rowid value 1, and each subsequent
7897** row a value 1 more than that of the previous.
7898*/
7899static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7900  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7901  *pRowid = pCur->iRowid;
7902  return SQLITE_OK;
7903}
7904
7905/*
7906** Return TRUE if the cursor has been moved off of the last
7907** row of output.
7908*/
7909static int fsdirEof(sqlite3_vtab_cursor *cur){
7910  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7911  return (pCur->zPath==0);
7912}
7913
7914/*
7915** xFilter callback.
7916**
7917** idxNum==1   PATH parameter only
7918** idxNum==2   Both PATH and DIR supplied
7919*/
7920static int fsdirFilter(
7921  sqlite3_vtab_cursor *cur,
7922  int idxNum, const char *idxStr,
7923  int argc, sqlite3_value **argv
7924){
7925  const char *zDir = 0;
7926  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7927  (void)idxStr;
7928  fsdirResetCursor(pCur);
7929
7930  if( idxNum==0 ){
7931    fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
7932    return SQLITE_ERROR;
7933  }
7934
7935  assert( argc==idxNum && (argc==1 || argc==2) );
7936  zDir = (const char*)sqlite3_value_text(argv[0]);
7937  if( zDir==0 ){
7938    fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
7939    return SQLITE_ERROR;
7940  }
7941  if( argc==2 ){
7942    pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
7943  }
7944  if( pCur->zBase ){
7945    pCur->nBase = (int)strlen(pCur->zBase)+1;
7946    pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
7947  }else{
7948    pCur->zPath = sqlite3_mprintf("%s", zDir);
7949  }
7950
7951  if( pCur->zPath==0 ){
7952    return SQLITE_NOMEM;
7953  }
7954  if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7955    fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7956    return SQLITE_ERROR;
7957  }
7958
7959  return SQLITE_OK;
7960}
7961
7962/*
7963** SQLite will invoke this method one or more times while planning a query
7964** that uses the generate_series virtual table.  This routine needs to create
7965** a query plan for each invocation and compute an estimated cost for that
7966** plan.
7967**
7968** In this implementation idxNum is used to represent the
7969** query plan.  idxStr is unused.
7970**
7971** The query plan is represented by values of idxNum:
7972**
7973**  (1)  The path value is supplied by argv[0]
7974**  (2)  Path is in argv[0] and dir is in argv[1]
7975*/
7976static int fsdirBestIndex(
7977  sqlite3_vtab *tab,
7978  sqlite3_index_info *pIdxInfo
7979){
7980  int i;                 /* Loop over constraints */
7981  int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
7982  int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
7983  int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
7984  int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
7985  const struct sqlite3_index_constraint *pConstraint;
7986
7987  (void)tab;
7988  pConstraint = pIdxInfo->aConstraint;
7989  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
7990    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
7991    switch( pConstraint->iColumn ){
7992      case FSDIR_COLUMN_PATH: {
7993        if( pConstraint->usable ){
7994          idxPath = i;
7995          seenPath = 0;
7996        }else if( idxPath<0 ){
7997          seenPath = 1;
7998        }
7999        break;
8000      }
8001      case FSDIR_COLUMN_DIR: {
8002        if( pConstraint->usable ){
8003          idxDir = i;
8004          seenDir = 0;
8005        }else if( idxDir<0 ){
8006          seenDir = 1;
8007        }
8008        break;
8009      }
8010    }
8011  }
8012  if( seenPath || seenDir ){
8013    /* If input parameters are unusable, disallow this plan */
8014    return SQLITE_CONSTRAINT;
8015  }
8016
8017  if( idxPath<0 ){
8018    pIdxInfo->idxNum = 0;
8019    /* The pIdxInfo->estimatedCost should have been initialized to a huge
8020    ** number.  Leave it unchanged. */
8021    pIdxInfo->estimatedRows = 0x7fffffff;
8022  }else{
8023    pIdxInfo->aConstraintUsage[idxPath].omit = 1;
8024    pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
8025    if( idxDir>=0 ){
8026      pIdxInfo->aConstraintUsage[idxDir].omit = 1;
8027      pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
8028      pIdxInfo->idxNum = 2;
8029      pIdxInfo->estimatedCost = 10.0;
8030    }else{
8031      pIdxInfo->idxNum = 1;
8032      pIdxInfo->estimatedCost = 100.0;
8033    }
8034  }
8035
8036  return SQLITE_OK;
8037}
8038
8039/*
8040** Register the "fsdir" virtual table.
8041*/
8042static int fsdirRegister(sqlite3 *db){
8043  static sqlite3_module fsdirModule = {
8044    0,                         /* iVersion */
8045    0,                         /* xCreate */
8046    fsdirConnect,              /* xConnect */
8047    fsdirBestIndex,            /* xBestIndex */
8048    fsdirDisconnect,           /* xDisconnect */
8049    0,                         /* xDestroy */
8050    fsdirOpen,                 /* xOpen - open a cursor */
8051    fsdirClose,                /* xClose - close a cursor */
8052    fsdirFilter,               /* xFilter - configure scan constraints */
8053    fsdirNext,                 /* xNext - advance a cursor */
8054    fsdirEof,                  /* xEof - check for end of scan */
8055    fsdirColumn,               /* xColumn - read data */
8056    fsdirRowid,                /* xRowid - read data */
8057    0,                         /* xUpdate */
8058    0,                         /* xBegin */
8059    0,                         /* xSync */
8060    0,                         /* xCommit */
8061    0,                         /* xRollback */
8062    0,                         /* xFindMethod */
8063    0,                         /* xRename */
8064    0,                         /* xSavepoint */
8065    0,                         /* xRelease */
8066    0,                         /* xRollbackTo */
8067    0,                         /* xShadowName */
8068    0                          /* xIntegrity */
8069  };
8070
8071  int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
8072  return rc;
8073}
8074#else         /* SQLITE_OMIT_VIRTUALTABLE */
8075# define fsdirRegister(x) SQLITE_OK
8076#endif
8077
8078#ifdef _WIN32
8079
8080#endif
8081static int sqlite3_fileio_init(
8082  sqlite3 *db,
8083  char **pzErrMsg,
8084  const sqlite3_api_routines *pApi
8085){
8086  int rc = SQLITE_OK;
8087  SQLITE_EXTENSION_INIT2(pApi);
8088  (void)pzErrMsg;  /* Unused parameter */
8089  rc = sqlite3_create_function(db, "readfile", 1,
8090                               SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8091                               readfileFunc, 0, 0);
8092  if( rc==SQLITE_OK ){
8093    rc = sqlite3_create_function(db, "writefile", -1,
8094                                 SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8095                                 writefileFunc, 0, 0);
8096  }
8097  if( rc==SQLITE_OK ){
8098    rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
8099                                 lsModeFunc, 0, 0);
8100  }
8101  if( rc==SQLITE_OK ){
8102    rc = fsdirRegister(db);
8103  }
8104  return rc;
8105}
8106
8107#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
8108/* To allow a standalone DLL, make test_windirent.c use the same
8109 * redefined SQLite API calls as the above extension code does.
8110 * Just pull in this .c to accomplish this. As a beneficial side
8111 * effect, this extension becomes a single translation unit. */
8112#  include "test_windirent.c"
8113#endif
8114
8115/************************* End ../ext/misc/fileio.c ********************/
8116/************************* Begin ../ext/misc/completion.c ******************/
8117/*
8118** 2017-07-10
8119**
8120** The author disclaims copyright to this source code.  In place of
8121** a legal notice, here is a blessing:
8122**
8123**    May you do good and not evil.
8124**    May you find forgiveness for yourself and forgive others.
8125**    May you share freely, never taking more than you give.
8126**
8127*************************************************************************
8128**
8129** This file implements an eponymous virtual table that returns suggested
8130** completions for a partial SQL input.
8131**
8132** Suggested usage:
8133**
8134**     SELECT DISTINCT candidate COLLATE nocase
8135**       FROM completion($prefix,$wholeline)
8136**      ORDER BY 1;
8137**
8138** The two query parameters are optional.  $prefix is the text of the
8139** current word being typed and that is to be completed.  $wholeline is
8140** the complete input line, used for context.
8141**
8142** The raw completion() table might return the same candidate multiple
8143** times, for example if the same column name is used to two or more
8144** tables.  And the candidates are returned in an arbitrary order.  Hence,
8145** the DISTINCT and ORDER BY are recommended.
8146**
8147** This virtual table operates at the speed of human typing, and so there
8148** is no attempt to make it fast.  Even a slow implementation will be much
8149** faster than any human can type.
8150**
8151*/
8152/* #include "sqlite3ext.h" */
8153SQLITE_EXTENSION_INIT1
8154#include <assert.h>
8155#include <string.h>
8156#include <ctype.h>
8157
8158#ifndef SQLITE_OMIT_VIRTUALTABLE
8159
8160/* completion_vtab is a subclass of sqlite3_vtab which will
8161** serve as the underlying representation of a completion virtual table
8162*/
8163typedef struct completion_vtab completion_vtab;
8164struct completion_vtab {
8165  sqlite3_vtab base;  /* Base class - must be first */
8166  sqlite3 *db;        /* Database connection for this completion vtab */
8167};
8168
8169/* completion_cursor is a subclass of sqlite3_vtab_cursor which will
8170** serve as the underlying representation of a cursor that scans
8171** over rows of the result
8172*/
8173typedef struct completion_cursor completion_cursor;
8174struct completion_cursor {
8175  sqlite3_vtab_cursor base;  /* Base class - must be first */
8176  sqlite3 *db;               /* Database connection for this cursor */
8177  int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
8178  char *zPrefix;             /* The prefix for the word we want to complete */
8179  char *zLine;               /* The whole that we want to complete */
8180  const char *zCurrentRow;   /* Current output row */
8181  int szRow;                 /* Length of the zCurrentRow string */
8182  sqlite3_stmt *pStmt;       /* Current statement */
8183  sqlite3_int64 iRowid;      /* The rowid */
8184  int ePhase;                /* Current phase */
8185  int j;                     /* inter-phase counter */
8186};
8187
8188/* Values for ePhase:
8189*/
8190#define COMPLETION_FIRST_PHASE   1
8191#define COMPLETION_KEYWORDS      1
8192#define COMPLETION_PRAGMAS       2
8193#define COMPLETION_FUNCTIONS     3
8194#define COMPLETION_COLLATIONS    4
8195#define COMPLETION_INDEXES       5
8196#define COMPLETION_TRIGGERS      6
8197#define COMPLETION_DATABASES     7
8198#define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
8199#define COMPLETION_COLUMNS       9
8200#define COMPLETION_MODULES       10
8201#define COMPLETION_EOF           11
8202
8203/*
8204** The completionConnect() method is invoked to create a new
8205** completion_vtab that describes the completion virtual table.
8206**
8207** Think of this routine as the constructor for completion_vtab objects.
8208**
8209** All this routine needs to do is:
8210**
8211**    (1) Allocate the completion_vtab object and initialize all fields.
8212**
8213**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
8214**        result set of queries against completion will look like.
8215*/
8216static int completionConnect(
8217  sqlite3 *db,
8218  void *pAux,
8219  int argc, const char *const*argv,
8220  sqlite3_vtab **ppVtab,
8221  char **pzErr
8222){
8223  completion_vtab *pNew;
8224  int rc;
8225
8226  (void)(pAux);    /* Unused parameter */
8227  (void)(argc);    /* Unused parameter */
8228  (void)(argv);    /* Unused parameter */
8229  (void)(pzErr);   /* Unused parameter */
8230
8231/* Column numbers */
8232#define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
8233#define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
8234#define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
8235#define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
8236
8237  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
8238  rc = sqlite3_declare_vtab(db,
8239      "CREATE TABLE x("
8240      "  candidate TEXT,"
8241      "  prefix TEXT HIDDEN,"
8242      "  wholeline TEXT HIDDEN,"
8243      "  phase INT HIDDEN"        /* Used for debugging only */
8244      ")");
8245  if( rc==SQLITE_OK ){
8246    pNew = sqlite3_malloc( sizeof(*pNew) );
8247    *ppVtab = (sqlite3_vtab*)pNew;
8248    if( pNew==0 ) return SQLITE_NOMEM;
8249    memset(pNew, 0, sizeof(*pNew));
8250    pNew->db = db;
8251  }
8252  return rc;
8253}
8254
8255/*
8256** This method is the destructor for completion_cursor objects.
8257*/
8258static int completionDisconnect(sqlite3_vtab *pVtab){
8259  sqlite3_free(pVtab);
8260  return SQLITE_OK;
8261}
8262
8263/*
8264** Constructor for a new completion_cursor object.
8265*/
8266static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
8267  completion_cursor *pCur;
8268  pCur = sqlite3_malloc( sizeof(*pCur) );
8269  if( pCur==0 ) return SQLITE_NOMEM;
8270  memset(pCur, 0, sizeof(*pCur));
8271  pCur->db = ((completion_vtab*)p)->db;
8272  *ppCursor = &pCur->base;
8273  return SQLITE_OK;
8274}
8275
8276/*
8277** Reset the completion_cursor.
8278*/
8279static void completionCursorReset(completion_cursor *pCur){
8280  sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
8281  sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
8282  sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
8283  pCur->j = 0;
8284}
8285
8286/*
8287** Destructor for a completion_cursor.
8288*/
8289static int completionClose(sqlite3_vtab_cursor *cur){
8290  completionCursorReset((completion_cursor*)cur);
8291  sqlite3_free(cur);
8292  return SQLITE_OK;
8293}
8294
8295/*
8296** Advance a completion_cursor to its next row of output.
8297**
8298** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
8299** record the current state of the scan.  This routine sets ->zCurrentRow
8300** to the current row of output and then returns.  If no more rows remain,
8301** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
8302** table that has reached the end of its scan.
8303**
8304** The current implementation just lists potential identifiers and
8305** keywords and filters them by zPrefix.  Future enhancements should
8306** take zLine into account to try to restrict the set of identifiers and
8307** keywords based on what would be legal at the current point of input.
8308*/
8309static int completionNext(sqlite3_vtab_cursor *cur){
8310  completion_cursor *pCur = (completion_cursor*)cur;
8311  int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
8312  int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
8313  pCur->iRowid++;
8314  while( pCur->ePhase!=COMPLETION_EOF ){
8315    switch( pCur->ePhase ){
8316      case COMPLETION_KEYWORDS: {
8317        if( pCur->j >= sqlite3_keyword_count() ){
8318          pCur->zCurrentRow = 0;
8319          pCur->ePhase = COMPLETION_DATABASES;
8320        }else{
8321          sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
8322        }
8323        iCol = -1;
8324        break;
8325      }
8326      case COMPLETION_DATABASES: {
8327        if( pCur->pStmt==0 ){
8328          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
8329                             &pCur->pStmt, 0);
8330        }
8331        iCol = 1;
8332        eNextPhase = COMPLETION_TABLES;
8333        break;
8334      }
8335      case COMPLETION_TABLES: {
8336        if( pCur->pStmt==0 ){
8337          sqlite3_stmt *pS2;
8338          char *zSql = 0;
8339          const char *zSep = "";
8340          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8341          while( sqlite3_step(pS2)==SQLITE_ROW ){
8342            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8343            zSql = sqlite3_mprintf(
8344               "%z%s"
8345               "SELECT name FROM \"%w\".sqlite_schema",
8346               zSql, zSep, zDb
8347            );
8348            if( zSql==0 ) return SQLITE_NOMEM;
8349            zSep = " UNION ";
8350          }
8351          sqlite3_finalize(pS2);
8352          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8353          sqlite3_free(zSql);
8354        }
8355        iCol = 0;
8356        eNextPhase = COMPLETION_COLUMNS;
8357        break;
8358      }
8359      case COMPLETION_COLUMNS: {
8360        if( pCur->pStmt==0 ){
8361          sqlite3_stmt *pS2;
8362          char *zSql = 0;
8363          const char *zSep = "";
8364          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8365          while( sqlite3_step(pS2)==SQLITE_ROW ){
8366            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8367            zSql = sqlite3_mprintf(
8368               "%z%s"
8369               "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
8370                       " JOIN pragma_table_info(sm.name,%Q) AS pti"
8371               " WHERE sm.type='table'",
8372               zSql, zSep, zDb, zDb
8373            );
8374            if( zSql==0 ) return SQLITE_NOMEM;
8375            zSep = " UNION ";
8376          }
8377          sqlite3_finalize(pS2);
8378          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8379          sqlite3_free(zSql);
8380        }
8381        iCol = 0;
8382        eNextPhase = COMPLETION_EOF;
8383        break;
8384      }
8385    }
8386    if( iCol<0 ){
8387      /* This case is when the phase presets zCurrentRow */
8388      if( pCur->zCurrentRow==0 ) continue;
8389    }else{
8390      if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
8391        /* Extract the next row of content */
8392        pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
8393        pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
8394      }else{
8395        /* When all rows are finished, advance to the next phase */
8396        sqlite3_finalize(pCur->pStmt);
8397        pCur->pStmt = 0;
8398        pCur->ePhase = eNextPhase;
8399        continue;
8400      }
8401    }
8402    if( pCur->nPrefix==0 ) break;
8403    if( pCur->nPrefix<=pCur->szRow
8404     && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
8405    ){
8406      break;
8407    }
8408  }
8409
8410  return SQLITE_OK;
8411}
8412
8413/*
8414** Return values of columns for the row at which the completion_cursor
8415** is currently pointing.
8416*/
8417static int completionColumn(
8418  sqlite3_vtab_cursor *cur,   /* The cursor */
8419  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8420  int i                       /* Which column to return */
8421){
8422  completion_cursor *pCur = (completion_cursor*)cur;
8423  switch( i ){
8424    case COMPLETION_COLUMN_CANDIDATE: {
8425      sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
8426      break;
8427    }
8428    case COMPLETION_COLUMN_PREFIX: {
8429      sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
8430      break;
8431    }
8432    case COMPLETION_COLUMN_WHOLELINE: {
8433      sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
8434      break;
8435    }
8436    case COMPLETION_COLUMN_PHASE: {
8437      sqlite3_result_int(ctx, pCur->ePhase);
8438      break;
8439    }
8440  }
8441  return SQLITE_OK;
8442}
8443
8444/*
8445** Return the rowid for the current row.  In this implementation, the
8446** rowid is the same as the output value.
8447*/
8448static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8449  completion_cursor *pCur = (completion_cursor*)cur;
8450  *pRowid = pCur->iRowid;
8451  return SQLITE_OK;
8452}
8453
8454/*
8455** Return TRUE if the cursor has been moved off of the last
8456** row of output.
8457*/
8458static int completionEof(sqlite3_vtab_cursor *cur){
8459  completion_cursor *pCur = (completion_cursor*)cur;
8460  return pCur->ePhase >= COMPLETION_EOF;
8461}
8462
8463/*
8464** This method is called to "rewind" the completion_cursor object back
8465** to the first row of output.  This method is always called at least
8466** once prior to any call to completionColumn() or completionRowid() or
8467** completionEof().
8468*/
8469static int completionFilter(
8470  sqlite3_vtab_cursor *pVtabCursor,
8471  int idxNum, const char *idxStr,
8472  int argc, sqlite3_value **argv
8473){
8474  completion_cursor *pCur = (completion_cursor *)pVtabCursor;
8475  int iArg = 0;
8476  (void)(idxStr);   /* Unused parameter */
8477  (void)(argc);     /* Unused parameter */
8478  completionCursorReset(pCur);
8479  if( idxNum & 1 ){
8480    pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
8481    if( pCur->nPrefix>0 ){
8482      pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8483      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8484    }
8485    iArg = 1;
8486  }
8487  if( idxNum & 2 ){
8488    pCur->nLine = sqlite3_value_bytes(argv[iArg]);
8489    if( pCur->nLine>0 ){
8490      pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8491      if( pCur->zLine==0 ) return SQLITE_NOMEM;
8492    }
8493  }
8494  if( pCur->zLine!=0 && pCur->zPrefix==0 ){
8495    int i = pCur->nLine;
8496    while( i>0 && (isalnum((unsigned char)pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
8497      i--;
8498    }
8499    pCur->nPrefix = pCur->nLine - i;
8500    if( pCur->nPrefix>0 ){
8501      pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
8502      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8503    }
8504  }
8505  pCur->iRowid = 0;
8506  pCur->ePhase = COMPLETION_FIRST_PHASE;
8507  return completionNext(pVtabCursor);
8508}
8509
8510/*
8511** SQLite will invoke this method one or more times while planning a query
8512** that uses the completion virtual table.  This routine needs to create
8513** a query plan for each invocation and compute an estimated cost for that
8514** plan.
8515**
8516** There are two hidden parameters that act as arguments to the table-valued
8517** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
8518** is available and bit 1 is set if "wholeline" is available.
8519*/
8520static int completionBestIndex(
8521  sqlite3_vtab *tab,
8522  sqlite3_index_info *pIdxInfo
8523){
8524  int i;                 /* Loop over constraints */
8525  int idxNum = 0;        /* The query plan bitmask */
8526  int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
8527  int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
8528  int nArg = 0;          /* Number of arguments that completeFilter() expects */
8529  const struct sqlite3_index_constraint *pConstraint;
8530
8531  (void)(tab);    /* Unused parameter */
8532  pConstraint = pIdxInfo->aConstraint;
8533  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8534    if( pConstraint->usable==0 ) continue;
8535    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8536    switch( pConstraint->iColumn ){
8537      case COMPLETION_COLUMN_PREFIX:
8538        prefixIdx = i;
8539        idxNum |= 1;
8540        break;
8541      case COMPLETION_COLUMN_WHOLELINE:
8542        wholelineIdx = i;
8543        idxNum |= 2;
8544        break;
8545    }
8546  }
8547  if( prefixIdx>=0 ){
8548    pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
8549    pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
8550  }
8551  if( wholelineIdx>=0 ){
8552    pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
8553    pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
8554  }
8555  pIdxInfo->idxNum = idxNum;
8556  pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
8557  pIdxInfo->estimatedRows = 500 - 100*nArg;
8558  return SQLITE_OK;
8559}
8560
8561/*
8562** This following structure defines all the methods for the
8563** completion virtual table.
8564*/
8565static sqlite3_module completionModule = {
8566  0,                         /* iVersion */
8567  0,                         /* xCreate */
8568  completionConnect,         /* xConnect */
8569  completionBestIndex,       /* xBestIndex */
8570  completionDisconnect,      /* xDisconnect */
8571  0,                         /* xDestroy */
8572  completionOpen,            /* xOpen - open a cursor */
8573  completionClose,           /* xClose - close a cursor */
8574  completionFilter,          /* xFilter - configure scan constraints */
8575  completionNext,            /* xNext - advance a cursor */
8576  completionEof,             /* xEof - check for end of scan */
8577  completionColumn,          /* xColumn - read data */
8578  completionRowid,           /* xRowid - read data */
8579  0,                         /* xUpdate */
8580  0,                         /* xBegin */
8581  0,                         /* xSync */
8582  0,                         /* xCommit */
8583  0,                         /* xRollback */
8584  0,                         /* xFindMethod */
8585  0,                         /* xRename */
8586  0,                         /* xSavepoint */
8587  0,                         /* xRelease */
8588  0,                         /* xRollbackTo */
8589  0,                         /* xShadowName */
8590  0                          /* xIntegrity */
8591};
8592
8593#endif /* SQLITE_OMIT_VIRTUALTABLE */
8594
8595static int sqlite3CompletionVtabInit(sqlite3 *db){
8596  int rc = SQLITE_OK;
8597#ifndef SQLITE_OMIT_VIRTUALTABLE
8598  rc = sqlite3_create_module(db, "completion", &completionModule, 0);
8599#endif
8600  return rc;
8601}
8602
8603#ifdef _WIN32
8604
8605#endif
8606static int sqlite3_completion_init(
8607  sqlite3 *db,
8608  char **pzErrMsg,
8609  const sqlite3_api_routines *pApi
8610){
8611  int rc = SQLITE_OK;
8612  SQLITE_EXTENSION_INIT2(pApi);
8613  (void)(pzErrMsg);  /* Unused parameter */
8614#ifndef SQLITE_OMIT_VIRTUALTABLE
8615  rc = sqlite3CompletionVtabInit(db);
8616#endif
8617  return rc;
8618}
8619
8620/************************* End ../ext/misc/completion.c ********************/
8621/************************* Begin ../ext/misc/appendvfs.c ******************/
8622/*
8623** 2017-10-20
8624**
8625** The author disclaims copyright to this source code.  In place of
8626** a legal notice, here is a blessing:
8627**
8628**    May you do good and not evil.
8629**    May you find forgiveness for yourself and forgive others.
8630**    May you share freely, never taking more than you give.
8631**
8632******************************************************************************
8633**
8634** This file implements a VFS shim that allows an SQLite database to be
8635** appended onto the end of some other file, such as an executable.
8636**
8637** A special record must appear at the end of the file that identifies the
8638** file as an appended database and provides the offset to the first page
8639** of the exposed content. (Or, it is the length of the content prefix.)
8640** For best performance page 1 should be located at a disk page boundary,
8641** though that is not required.
8642**
8643** When opening a database using this VFS, the connection might treat
8644** the file as an ordinary SQLite database, or it might treat it as a
8645** database appended onto some other file.  The decision is made by
8646** applying the following rules in order:
8647**
8648**  (1)  An empty file is an ordinary database.
8649**
8650**  (2)  If the file ends with the appendvfs trailer string
8651**       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
8652**
8653**  (3)  If the file begins with the standard SQLite prefix string
8654**       "SQLite format 3", that file is an ordinary database.
8655**
8656**  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
8657**       set, then a new database is appended to the already existing file.
8658**
8659**  (5)  Otherwise, SQLITE_CANTOPEN is returned.
8660**
8661** To avoid unnecessary complications with the PENDING_BYTE, the size of
8662** the file containing the database is limited to 1GiB. (1073741824 bytes)
8663** This VFS will not read or write past the 1GiB mark.  This restriction
8664** might be lifted in future versions.  For now, if you need a larger
8665** database, then keep it in a separate file.
8666**
8667** If the file being opened is a plain database (not an appended one), then
8668** this shim is a pass-through into the default underlying VFS. (rule 3)
8669**/
8670/* #include "sqlite3ext.h" */
8671SQLITE_EXTENSION_INIT1
8672#include <string.h>
8673#include <assert.h>
8674
8675/* The append mark at the end of the database is:
8676**
8677**     Start-Of-SQLite3-NNNNNNNN
8678**     123456789 123456789 12345
8679**
8680** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
8681** the offset to page 1, and also the length of the prefix content.
8682*/
8683#define APND_MARK_PREFIX     "Start-Of-SQLite3-"
8684#define APND_MARK_PREFIX_SZ  17
8685#define APND_MARK_FOS_SZ      8
8686#define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
8687
8688/*
8689** Maximum size of the combined prefix + database + append-mark.  This
8690** must be less than 0x40000000 to avoid locking issues on Windows.
8691*/
8692#define APND_MAX_SIZE  (0x40000000)
8693
8694/*
8695** Try to align the database to an even multiple of APND_ROUNDUP bytes.
8696*/
8697#ifndef APND_ROUNDUP
8698#define APND_ROUNDUP 4096
8699#endif
8700#define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
8701#define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
8702
8703/*
8704** Forward declaration of objects used by this utility
8705*/
8706typedef struct sqlite3_vfs ApndVfs;
8707typedef struct ApndFile ApndFile;
8708
8709/* Access to a lower-level VFS that (might) implement dynamic loading,
8710** access to randomness, etc.
8711*/
8712#define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
8713#define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
8714
8715/* An open appendvfs file
8716**
8717** An instance of this structure describes the appended database file.
8718** A separate sqlite3_file object is always appended. The appended
8719** sqlite3_file object (which can be accessed using ORIGFILE()) describes
8720** the entire file, including the prefix, the database, and the
8721** append-mark.
8722**
8723** The structure of an AppendVFS database is like this:
8724**
8725**   +-------------+---------+----------+-------------+
8726**   | prefix-file | padding | database | append-mark |
8727**   +-------------+---------+----------+-------------+
8728**                           ^          ^
8729**                           |          |
8730**                         iPgOne      iMark
8731**
8732**
8733** "prefix file" -  file onto which the database has been appended.
8734** "padding"     -  zero or more bytes inserted so that "database"
8735**                  starts on an APND_ROUNDUP boundary
8736** "database"    -  The SQLite database file
8737** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8738**                  the offset from the start of prefix-file to the start
8739**                  of "database".
8740**
8741** The size of the database is iMark - iPgOne.
8742**
8743** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8744** of iPgOne stored as a big-ending 64-bit integer.
8745**
8746** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
8747** Or, iMark is -1 to indicate that it has not yet been written.
8748*/
8749struct ApndFile {
8750  sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
8751  sqlite3_int64 iPgOne;     /* Offset to the start of the database */
8752  sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
8753  /* Always followed by another sqlite3_file that describes the whole file */
8754};
8755
8756/*
8757** Methods for ApndFile
8758*/
8759static int apndClose(sqlite3_file*);
8760static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
8761static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
8762static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
8763static int apndSync(sqlite3_file*, int flags);
8764static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
8765static int apndLock(sqlite3_file*, int);
8766static int apndUnlock(sqlite3_file*, int);
8767static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
8768static int apndFileControl(sqlite3_file*, int op, void *pArg);
8769static int apndSectorSize(sqlite3_file*);
8770static int apndDeviceCharacteristics(sqlite3_file*);
8771static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
8772static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
8773static void apndShmBarrier(sqlite3_file*);
8774static int apndShmUnmap(sqlite3_file*, int deleteFlag);
8775static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
8776static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
8777
8778/*
8779** Methods for ApndVfs
8780*/
8781static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
8782static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
8783static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
8784static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
8785static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
8786static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
8787static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
8788static void apndDlClose(sqlite3_vfs*, void*);
8789static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
8790static int apndSleep(sqlite3_vfs*, int microseconds);
8791static int apndCurrentTime(sqlite3_vfs*, double*);
8792static int apndGetLastError(sqlite3_vfs*, int, char *);
8793static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
8794static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
8795static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
8796static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
8797
8798static sqlite3_vfs apnd_vfs = {
8799  3,                            /* iVersion (set when registered) */
8800  0,                            /* szOsFile (set when registered) */
8801  1024,                         /* mxPathname */
8802  0,                            /* pNext */
8803  "apndvfs",                    /* zName */
8804  0,                            /* pAppData (set when registered) */
8805  apndOpen,                     /* xOpen */
8806  apndDelete,                   /* xDelete */
8807  apndAccess,                   /* xAccess */
8808  apndFullPathname,             /* xFullPathname */
8809  apndDlOpen,                   /* xDlOpen */
8810  apndDlError,                  /* xDlError */
8811  apndDlSym,                    /* xDlSym */
8812  apndDlClose,                  /* xDlClose */
8813  apndRandomness,               /* xRandomness */
8814  apndSleep,                    /* xSleep */
8815  apndCurrentTime,              /* xCurrentTime */
8816  apndGetLastError,             /* xGetLastError */
8817  apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
8818  apndSetSystemCall,            /* xSetSystemCall */
8819  apndGetSystemCall,            /* xGetSystemCall */
8820  apndNextSystemCall            /* xNextSystemCall */
8821};
8822
8823static const sqlite3_io_methods apnd_io_methods = {
8824  3,                              /* iVersion */
8825  apndClose,                      /* xClose */
8826  apndRead,                       /* xRead */
8827  apndWrite,                      /* xWrite */
8828  apndTruncate,                   /* xTruncate */
8829  apndSync,                       /* xSync */
8830  apndFileSize,                   /* xFileSize */
8831  apndLock,                       /* xLock */
8832  apndUnlock,                     /* xUnlock */
8833  apndCheckReservedLock,          /* xCheckReservedLock */
8834  apndFileControl,                /* xFileControl */
8835  apndSectorSize,                 /* xSectorSize */
8836  apndDeviceCharacteristics,      /* xDeviceCharacteristics */
8837  apndShmMap,                     /* xShmMap */
8838  apndShmLock,                    /* xShmLock */
8839  apndShmBarrier,                 /* xShmBarrier */
8840  apndShmUnmap,                   /* xShmUnmap */
8841  apndFetch,                      /* xFetch */
8842  apndUnfetch                     /* xUnfetch */
8843};
8844
8845/*
8846** Close an apnd-file.
8847*/
8848static int apndClose(sqlite3_file *pFile){
8849  pFile = ORIGFILE(pFile);
8850  return pFile->pMethods->xClose(pFile);
8851}
8852
8853/*
8854** Read data from an apnd-file.
8855*/
8856static int apndRead(
8857  sqlite3_file *pFile,
8858  void *zBuf,
8859  int iAmt,
8860  sqlite_int64 iOfst
8861){
8862  ApndFile *paf = (ApndFile *)pFile;
8863  pFile = ORIGFILE(pFile);
8864  return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8865}
8866
8867/*
8868** Add the append-mark onto what should become the end of the file.
8869*  If and only if this succeeds, internal ApndFile.iMark is updated.
8870*  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8871*/
8872static int apndWriteMark(
8873  ApndFile *paf,
8874  sqlite3_file *pFile,
8875  sqlite_int64 iWriteEnd
8876){
8877  sqlite_int64 iPgOne = paf->iPgOne;
8878  unsigned char a[APND_MARK_SIZE];
8879  int i = APND_MARK_FOS_SZ;
8880  int rc;
8881  assert(pFile == ORIGFILE(paf));
8882  memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
8883  while( --i >= 0 ){
8884    a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
8885    iPgOne >>= 8;
8886  }
8887  iWriteEnd += paf->iPgOne;
8888  if( SQLITE_OK==(rc = pFile->pMethods->xWrite
8889                  (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
8890    paf->iMark = iWriteEnd;
8891  }
8892  return rc;
8893}
8894
8895/*
8896** Write data to an apnd-file.
8897*/
8898static int apndWrite(
8899  sqlite3_file *pFile,
8900  const void *zBuf,
8901  int iAmt,
8902  sqlite_int64 iOfst
8903){
8904  ApndFile *paf = (ApndFile *)pFile;
8905  sqlite_int64 iWriteEnd = iOfst + iAmt;
8906  if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
8907  pFile = ORIGFILE(pFile);
8908  /* If append-mark is absent or will be overwritten, write it. */
8909  if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
8910    int rc = apndWriteMark(paf, pFile, iWriteEnd);
8911    if( SQLITE_OK!=rc ) return rc;
8912  }
8913  return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8914}
8915
8916/*
8917** Truncate an apnd-file.
8918*/
8919static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
8920  ApndFile *paf = (ApndFile *)pFile;
8921  pFile = ORIGFILE(pFile);
8922  /* The append mark goes out first so truncate failure does not lose it. */
8923  if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
8924  /* Truncate underlying file just past append mark */
8925  return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
8926}
8927
8928/*
8929** Sync an apnd-file.
8930*/
8931static int apndSync(sqlite3_file *pFile, int flags){
8932  pFile = ORIGFILE(pFile);
8933  return pFile->pMethods->xSync(pFile, flags);
8934}
8935
8936/*
8937** Return the current file-size of an apnd-file.
8938** If the append mark is not yet there, the file-size is 0.
8939*/
8940static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
8941  ApndFile *paf = (ApndFile *)pFile;
8942  *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
8943  return SQLITE_OK;
8944}
8945
8946/*
8947** Lock an apnd-file.
8948*/
8949static int apndLock(sqlite3_file *pFile, int eLock){
8950  pFile = ORIGFILE(pFile);
8951  return pFile->pMethods->xLock(pFile, eLock);
8952}
8953
8954/*
8955** Unlock an apnd-file.
8956*/
8957static int apndUnlock(sqlite3_file *pFile, int eLock){
8958  pFile = ORIGFILE(pFile);
8959  return pFile->pMethods->xUnlock(pFile, eLock);
8960}
8961
8962/*
8963** Check if another file-handle holds a RESERVED lock on an apnd-file.
8964*/
8965static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
8966  pFile = ORIGFILE(pFile);
8967  return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
8968}
8969
8970/*
8971** File control method. For custom operations on an apnd-file.
8972*/
8973static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
8974  ApndFile *paf = (ApndFile *)pFile;
8975  int rc;
8976  pFile = ORIGFILE(pFile);
8977  if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
8978  rc = pFile->pMethods->xFileControl(pFile, op, pArg);
8979  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
8980    *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
8981  }
8982  return rc;
8983}
8984
8985/*
8986** Return the sector-size in bytes for an apnd-file.
8987*/
8988static int apndSectorSize(sqlite3_file *pFile){
8989  pFile = ORIGFILE(pFile);
8990  return pFile->pMethods->xSectorSize(pFile);
8991}
8992
8993/*
8994** Return the device characteristic flags supported by an apnd-file.
8995*/
8996static int apndDeviceCharacteristics(sqlite3_file *pFile){
8997  pFile = ORIGFILE(pFile);
8998  return pFile->pMethods->xDeviceCharacteristics(pFile);
8999}
9000
9001/* Create a shared memory file mapping */
9002static int apndShmMap(
9003  sqlite3_file *pFile,
9004  int iPg,
9005  int pgsz,
9006  int bExtend,
9007  void volatile **pp
9008){
9009  pFile = ORIGFILE(pFile);
9010  return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
9011}
9012
9013/* Perform locking on a shared-memory segment */
9014static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
9015  pFile = ORIGFILE(pFile);
9016  return pFile->pMethods->xShmLock(pFile,offset,n,flags);
9017}
9018
9019/* Memory barrier operation on shared memory */
9020static void apndShmBarrier(sqlite3_file *pFile){
9021  pFile = ORIGFILE(pFile);
9022  pFile->pMethods->xShmBarrier(pFile);
9023}
9024
9025/* Unmap a shared memory segment */
9026static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
9027  pFile = ORIGFILE(pFile);
9028  return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
9029}
9030
9031/* Fetch a page of a memory-mapped file */
9032static int apndFetch(
9033  sqlite3_file *pFile,
9034  sqlite3_int64 iOfst,
9035  int iAmt,
9036  void **pp
9037){
9038  ApndFile *p = (ApndFile *)pFile;
9039  if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
9040    return SQLITE_IOERR; /* Cannot read what is not yet there. */
9041  }
9042  pFile = ORIGFILE(pFile);
9043  return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
9044}
9045
9046/* Release a memory-mapped page */
9047static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
9048  ApndFile *p = (ApndFile *)pFile;
9049  pFile = ORIGFILE(pFile);
9050  return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
9051}
9052
9053/*
9054** Try to read the append-mark off the end of a file.  Return the
9055** start of the appended database if the append-mark is present.
9056** If there is no valid append-mark, return -1;
9057**
9058** An append-mark is only valid if the NNNNNNNN start-of-database offset
9059** indicates that the appended database contains at least one page.  The
9060** start-of-database value must be a multiple of 512.
9061*/
9062static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
9063  int rc, i;
9064  sqlite3_int64 iMark;
9065  int msbs = 8 * (APND_MARK_FOS_SZ-1);
9066  unsigned char a[APND_MARK_SIZE];
9067
9068  if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
9069  rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
9070  if( rc ) return -1;
9071  if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
9072  iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
9073  for(i=1; i<8; i++){
9074    msbs -= 8;
9075    iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
9076  }
9077  if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
9078  if( iMark & 0x1ff ) return -1;
9079  return iMark;
9080}
9081
9082static const char apvfsSqliteHdr[] = "SQLite format 3";
9083/*
9084** Check to see if the file is an appendvfs SQLite database file.
9085** Return true iff it is such. Parameter sz is the file's size.
9086*/
9087static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
9088  int rc;
9089  char zHdr[16];
9090  sqlite3_int64 iMark = apndReadMark(sz, pFile);
9091  if( iMark>=0 ){
9092    /* If file has the correct end-marker, the expected odd size, and the
9093    ** SQLite DB type marker where the end-marker puts it, then it
9094    ** is an appendvfs database.
9095    */
9096    rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
9097    if( SQLITE_OK==rc
9098     && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
9099     && (sz & 0x1ff) == APND_MARK_SIZE
9100     && sz>=512+APND_MARK_SIZE
9101    ){
9102      return 1; /* It's an appendvfs database */
9103    }
9104  }
9105  return 0;
9106}
9107
9108/*
9109** Check to see if the file is an ordinary SQLite database file.
9110** Return true iff so. Parameter sz is the file's size.
9111*/
9112static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
9113  char zHdr[16];
9114  if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
9115   || (sz & 0x1ff) != 0
9116   || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
9117   || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
9118  ){
9119    return 0;
9120  }else{
9121    return 1;
9122  }
9123}
9124
9125/*
9126** Open an apnd file handle.
9127*/
9128static int apndOpen(
9129  sqlite3_vfs *pApndVfs,
9130  const char *zName,
9131  sqlite3_file *pFile,
9132  int flags,
9133  int *pOutFlags
9134){
9135  ApndFile *pApndFile = (ApndFile*)pFile;
9136  sqlite3_file *pBaseFile = ORIGFILE(pFile);
9137  sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
9138  int rc;
9139  sqlite3_int64 sz = 0;
9140  if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
9141    /* The appendvfs is not to be used for transient or temporary databases.
9142    ** Just use the base VFS open to initialize the given file object and
9143    ** open the underlying file. (Appendvfs is then unused for this file.)
9144    */
9145    return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
9146  }
9147  memset(pApndFile, 0, sizeof(ApndFile));
9148  pFile->pMethods = &apnd_io_methods;
9149  pApndFile->iMark = -1;    /* Append mark not yet written */
9150
9151  rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
9152  if( rc==SQLITE_OK ){
9153    rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
9154    if( rc ){
9155      pBaseFile->pMethods->xClose(pBaseFile);
9156    }
9157  }
9158  if( rc ){
9159    pFile->pMethods = 0;
9160    return rc;
9161  }
9162  if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
9163    /* The file being opened appears to be just an ordinary DB. Copy
9164    ** the base dispatch-table so this instance mimics the base VFS.
9165    */
9166    memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
9167    return SQLITE_OK;
9168  }
9169  pApndFile->iPgOne = apndReadMark(sz, pFile);
9170  if( pApndFile->iPgOne>=0 ){
9171    pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
9172    return SQLITE_OK;
9173  }
9174  if( (flags & SQLITE_OPEN_CREATE)==0 ){
9175    pBaseFile->pMethods->xClose(pBaseFile);
9176    rc = SQLITE_CANTOPEN;
9177    pFile->pMethods = 0;
9178  }else{
9179    /* Round newly added appendvfs location to #define'd page boundary.
9180    ** Note that nothing has yet been written to the underlying file.
9181    ** The append mark will be written along with first content write.
9182    ** Until then, paf->iMark value indicates it is not yet written.
9183    */
9184    pApndFile->iPgOne = APND_START_ROUNDUP(sz);
9185  }
9186  return rc;
9187}
9188
9189/*
9190** Delete an apnd file.
9191** For an appendvfs, this could mean delete the appendvfs portion,
9192** leaving the appendee as it was before it gained an appendvfs.
9193** For now, this code deletes the underlying file too.
9194*/
9195static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
9196  return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
9197}
9198
9199/*
9200** All other VFS methods are pass-thrus.
9201*/
9202static int apndAccess(
9203  sqlite3_vfs *pVfs,
9204  const char *zPath,
9205  int flags,
9206  int *pResOut
9207){
9208  return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
9209}
9210static int apndFullPathname(
9211  sqlite3_vfs *pVfs,
9212  const char *zPath,
9213  int nOut,
9214  char *zOut
9215){
9216  return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
9217}
9218static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
9219  return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
9220}
9221static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
9222  ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
9223}
9224static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
9225  return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
9226}
9227static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
9228  ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
9229}
9230static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
9231  return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
9232}
9233static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
9234  return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
9235}
9236static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
9237  return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
9238}
9239static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
9240  return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
9241}
9242static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
9243  return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
9244}
9245static int apndSetSystemCall(
9246  sqlite3_vfs *pVfs,
9247  const char *zName,
9248  sqlite3_syscall_ptr pCall
9249){
9250  return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
9251}
9252static sqlite3_syscall_ptr apndGetSystemCall(
9253  sqlite3_vfs *pVfs,
9254  const char *zName
9255){
9256  return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
9257}
9258static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
9259  return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
9260}
9261
9262
9263#ifdef _WIN32
9264
9265#endif
9266/*
9267** This routine is called when the extension is loaded.
9268** Register the new VFS.
9269*/
9270static int sqlite3_appendvfs_init(
9271  sqlite3 *db,
9272  char **pzErrMsg,
9273  const sqlite3_api_routines *pApi
9274){
9275  int rc = SQLITE_OK;
9276  sqlite3_vfs *pOrig;
9277  SQLITE_EXTENSION_INIT2(pApi);
9278  (void)pzErrMsg;
9279  (void)db;
9280  pOrig = sqlite3_vfs_find(0);
9281  if( pOrig==0 ) return SQLITE_ERROR;
9282  apnd_vfs.iVersion = pOrig->iVersion;
9283  apnd_vfs.pAppData = pOrig;
9284  apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
9285  rc = sqlite3_vfs_register(&apnd_vfs, 0);
9286#ifdef APPENDVFS_TEST
9287  if( rc==SQLITE_OK ){
9288    rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
9289  }
9290#endif
9291  if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
9292  return rc;
9293}
9294
9295/************************* End ../ext/misc/appendvfs.c ********************/
9296#endif
9297#ifdef SQLITE_HAVE_ZLIB
9298/************************* Begin ../ext/misc/zipfile.c ******************/
9299/*
9300** 2017-12-26
9301**
9302** The author disclaims copyright to this source code.  In place of
9303** a legal notice, here is a blessing:
9304**
9305**    May you do good and not evil.
9306**    May you find forgiveness for yourself and forgive others.
9307**    May you share freely, never taking more than you give.
9308**
9309******************************************************************************
9310**
9311** This file implements a virtual table for reading and writing ZIP archive
9312** files.
9313**
9314** Usage example:
9315**
9316**     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
9317**
9318** Current limitations:
9319**
9320**    *  No support for encryption
9321**    *  No support for ZIP archives spanning multiple files
9322**    *  No support for zip64 extensions
9323**    *  Only the "inflate/deflate" (zlib) compression method is supported
9324*/
9325/* #include "sqlite3ext.h" */
9326SQLITE_EXTENSION_INIT1
9327#include <stdio.h>
9328#include <string.h>
9329#include <assert.h>
9330#include <stdint.h>
9331
9332#include <zlib.h>
9333
9334#ifndef SQLITE_OMIT_VIRTUALTABLE
9335
9336#ifndef SQLITE_AMALGAMATION
9337
9338#ifndef UINT32_TYPE
9339# ifdef HAVE_UINT32_T
9340#  define UINT32_TYPE uint32_t
9341# else
9342#  define UINT32_TYPE unsigned int
9343# endif
9344#endif
9345#ifndef UINT16_TYPE
9346# ifdef HAVE_UINT16_T
9347#  define UINT16_TYPE uint16_t
9348# else
9349#  define UINT16_TYPE unsigned short int
9350# endif
9351#endif
9352/* typedef sqlite3_int64 i64; */
9353/* typedef unsigned char u8; */
9354/* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
9355/* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
9356#define MIN(a,b) ((a)<(b) ? (a) : (b))
9357
9358#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
9359# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
9360#endif
9361#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
9362# define ALWAYS(X)      (1)
9363# define NEVER(X)       (0)
9364#elif !defined(NDEBUG)
9365# define ALWAYS(X)      ((X)?1:(assert(0),0))
9366# define NEVER(X)       ((X)?(assert(0),1):0)
9367#else
9368# define ALWAYS(X)      (X)
9369# define NEVER(X)       (X)
9370#endif
9371
9372#endif   /* SQLITE_AMALGAMATION */
9373
9374/*
9375** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
9376**
9377** In some ways it would be better to obtain these values from system
9378** header files. But, the dependency is undesirable and (a) these
9379** have been stable for decades, (b) the values are part of POSIX and
9380** are also made explicit in [man stat], and (c) are part of the
9381** file format for zip archives.
9382*/
9383#ifndef S_IFDIR
9384# define S_IFDIR 0040000
9385#endif
9386#ifndef S_IFREG
9387# define S_IFREG 0100000
9388#endif
9389#ifndef S_IFLNK
9390# define S_IFLNK 0120000
9391#endif
9392
9393static const char ZIPFILE_SCHEMA[] =
9394  "CREATE TABLE y("
9395    "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
9396    "mode,"              /* 1: POSIX mode for file */
9397    "mtime,"             /* 2: Last modification time (secs since 1970)*/
9398    "sz,"                /* 3: Size of object */
9399    "rawdata,"           /* 4: Raw data */
9400    "data,"              /* 5: Uncompressed data */
9401    "method,"            /* 6: Compression method (integer) */
9402    "z HIDDEN"           /* 7: Name of zip file */
9403  ") WITHOUT ROWID;";
9404
9405#define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
9406#define ZIPFILE_BUFFER_SIZE (64*1024)
9407
9408
9409/*
9410** Magic numbers used to read and write zip files.
9411**
9412** ZIPFILE_NEWENTRY_MADEBY:
9413**   Use this value for the "version-made-by" field in new zip file
9414**   entries. The upper byte indicates "unix", and the lower byte
9415**   indicates that the zip file matches pkzip specification 3.0.
9416**   This is what info-zip seems to do.
9417**
9418** ZIPFILE_NEWENTRY_REQUIRED:
9419**   Value for "version-required-to-extract" field of new entries.
9420**   Version 2.0 is required to support folders and deflate compression.
9421**
9422** ZIPFILE_NEWENTRY_FLAGS:
9423**   Value for "general-purpose-bit-flags" field of new entries. Bit
9424**   11 means "utf-8 filename and comment".
9425**
9426** ZIPFILE_SIGNATURE_CDS:
9427**   First 4 bytes of a valid CDS record.
9428**
9429** ZIPFILE_SIGNATURE_LFH:
9430**   First 4 bytes of a valid LFH record.
9431**
9432** ZIPFILE_SIGNATURE_EOCD
9433**   First 4 bytes of a valid EOCD record.
9434*/
9435#define ZIPFILE_EXTRA_TIMESTAMP   0x5455
9436#define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
9437#define ZIPFILE_NEWENTRY_REQUIRED 20
9438#define ZIPFILE_NEWENTRY_FLAGS    0x800
9439#define ZIPFILE_SIGNATURE_CDS     0x02014b50
9440#define ZIPFILE_SIGNATURE_LFH     0x04034b50
9441#define ZIPFILE_SIGNATURE_EOCD    0x06054b50
9442
9443/*
9444** The sizes of the fixed-size part of each of the three main data
9445** structures in a zip archive.
9446*/
9447#define ZIPFILE_LFH_FIXED_SZ      30
9448#define ZIPFILE_EOCD_FIXED_SZ     22
9449#define ZIPFILE_CDS_FIXED_SZ      46
9450
9451/*
9452*** 4.3.16  End of central directory record:
9453***
9454***   end of central dir signature    4 bytes  (0x06054b50)
9455***   number of this disk             2 bytes
9456***   number of the disk with the
9457***   start of the central directory  2 bytes
9458***   total number of entries in the
9459***   central directory on this disk  2 bytes
9460***   total number of entries in
9461***   the central directory           2 bytes
9462***   size of the central directory   4 bytes
9463***   offset of start of central
9464***   directory with respect to
9465***   the starting disk number        4 bytes
9466***   .ZIP file comment length        2 bytes
9467***   .ZIP file comment       (variable size)
9468*/
9469typedef struct ZipfileEOCD ZipfileEOCD;
9470struct ZipfileEOCD {
9471  u16 iDisk;
9472  u16 iFirstDisk;
9473  u16 nEntry;
9474  u16 nEntryTotal;
9475  u32 nSize;
9476  u32 iOffset;
9477};
9478
9479/*
9480*** 4.3.12  Central directory structure:
9481***
9482*** ...
9483***
9484***   central file header signature   4 bytes  (0x02014b50)
9485***   version made by                 2 bytes
9486***   version needed to extract       2 bytes
9487***   general purpose bit flag        2 bytes
9488***   compression method              2 bytes
9489***   last mod file time              2 bytes
9490***   last mod file date              2 bytes
9491***   crc-32                          4 bytes
9492***   compressed size                 4 bytes
9493***   uncompressed size               4 bytes
9494***   file name length                2 bytes
9495***   extra field length              2 bytes
9496***   file comment length             2 bytes
9497***   disk number start               2 bytes
9498***   internal file attributes        2 bytes
9499***   external file attributes        4 bytes
9500***   relative offset of local header 4 bytes
9501*/
9502typedef struct ZipfileCDS ZipfileCDS;
9503struct ZipfileCDS {
9504  u16 iVersionMadeBy;
9505  u16 iVersionExtract;
9506  u16 flags;
9507  u16 iCompression;
9508  u16 mTime;
9509  u16 mDate;
9510  u32 crc32;
9511  u32 szCompressed;
9512  u32 szUncompressed;
9513  u16 nFile;
9514  u16 nExtra;
9515  u16 nComment;
9516  u16 iDiskStart;
9517  u16 iInternalAttr;
9518  u32 iExternalAttr;
9519  u32 iOffset;
9520  char *zFile;                    /* Filename (sqlite3_malloc()) */
9521};
9522
9523/*
9524*** 4.3.7  Local file header:
9525***
9526***   local file header signature     4 bytes  (0x04034b50)
9527***   version needed to extract       2 bytes
9528***   general purpose bit flag        2 bytes
9529***   compression method              2 bytes
9530***   last mod file time              2 bytes
9531***   last mod file date              2 bytes
9532***   crc-32                          4 bytes
9533***   compressed size                 4 bytes
9534***   uncompressed size               4 bytes
9535***   file name length                2 bytes
9536***   extra field length              2 bytes
9537***
9538*/
9539typedef struct ZipfileLFH ZipfileLFH;
9540struct ZipfileLFH {
9541  u16 iVersionExtract;
9542  u16 flags;
9543  u16 iCompression;
9544  u16 mTime;
9545  u16 mDate;
9546  u32 crc32;
9547  u32 szCompressed;
9548  u32 szUncompressed;
9549  u16 nFile;
9550  u16 nExtra;
9551};
9552
9553typedef struct ZipfileEntry ZipfileEntry;
9554struct ZipfileEntry {
9555  ZipfileCDS cds;            /* Parsed CDS record */
9556  u32 mUnixTime;             /* Modification time, in UNIX format */
9557  u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
9558  i64 iDataOff;              /* Offset to data in file (if aData==0) */
9559  u8 *aData;                 /* cds.szCompressed bytes of compressed data */
9560  ZipfileEntry *pNext;       /* Next element in in-memory CDS */
9561};
9562
9563/*
9564** Cursor type for zipfile tables.
9565*/
9566typedef struct ZipfileCsr ZipfileCsr;
9567struct ZipfileCsr {
9568  sqlite3_vtab_cursor base;  /* Base class - must be first */
9569  i64 iId;                   /* Cursor ID */
9570  u8 bEof;                   /* True when at EOF */
9571  u8 bNoop;                  /* If next xNext() call is no-op */
9572
9573  /* Used outside of write transactions */
9574  FILE *pFile;               /* Zip file */
9575  i64 iNextOff;              /* Offset of next record in central directory */
9576  ZipfileEOCD eocd;          /* Parse of central directory record */
9577
9578  ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
9579  ZipfileEntry *pCurrent;    /* Current entry */
9580  ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
9581};
9582
9583typedef struct ZipfileTab ZipfileTab;
9584struct ZipfileTab {
9585  sqlite3_vtab base;         /* Base class - must be first */
9586  char *zFile;               /* Zip file this table accesses (may be NULL) */
9587  sqlite3 *db;               /* Host database connection */
9588  u8 *aBuffer;               /* Temporary buffer used for various tasks */
9589
9590  ZipfileCsr *pCsrList;      /* List of cursors */
9591  i64 iNextCsrid;
9592
9593  /* The following are used by write transactions only */
9594  ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
9595  ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
9596  FILE *pWriteFd;            /* File handle open on zip archive */
9597  i64 szCurrent;             /* Current size of zip archive */
9598  i64 szOrig;                /* Size of archive at start of transaction */
9599};
9600
9601/*
9602** Set the error message contained in context ctx to the results of
9603** vprintf(zFmt, ...).
9604*/
9605static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
9606  char *zMsg = 0;
9607  va_list ap;
9608  va_start(ap, zFmt);
9609  zMsg = sqlite3_vmprintf(zFmt, ap);
9610  sqlite3_result_error(ctx, zMsg, -1);
9611  sqlite3_free(zMsg);
9612  va_end(ap);
9613}
9614
9615/*
9616** If string zIn is quoted, dequote it in place. Otherwise, if the string
9617** is not quoted, do nothing.
9618*/
9619static void zipfileDequote(char *zIn){
9620  char q = zIn[0];
9621  if( q=='"' || q=='\'' || q=='`' || q=='[' ){
9622    int iIn = 1;
9623    int iOut = 0;
9624    if( q=='[' ) q = ']';
9625    while( ALWAYS(zIn[iIn]) ){
9626      char c = zIn[iIn++];
9627      if( c==q && zIn[iIn++]!=q ) break;
9628      zIn[iOut++] = c;
9629    }
9630    zIn[iOut] = '\0';
9631  }
9632}
9633
9634/*
9635** Construct a new ZipfileTab virtual table object.
9636**
9637**   argv[0]   -> module name  ("zipfile")
9638**   argv[1]   -> database name
9639**   argv[2]   -> table name
9640**   argv[...] -> "column name" and other module argument fields.
9641*/
9642static int zipfileConnect(
9643  sqlite3 *db,
9644  void *pAux,
9645  int argc, const char *const*argv,
9646  sqlite3_vtab **ppVtab,
9647  char **pzErr
9648){
9649  int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
9650  int nFile = 0;
9651  const char *zFile = 0;
9652  ZipfileTab *pNew = 0;
9653  int rc;
9654  (void)pAux;
9655
9656  /* If the table name is not "zipfile", require that the argument be
9657  ** specified. This stops zipfile tables from being created as:
9658  **
9659  **   CREATE VIRTUAL TABLE zzz USING zipfile();
9660  **
9661  ** It does not prevent:
9662  **
9663  **   CREATE VIRTUAL TABLE zipfile USING zipfile();
9664  */
9665  assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
9666  if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
9667    *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
9668    return SQLITE_ERROR;
9669  }
9670
9671  if( argc>3 ){
9672    zFile = argv[3];
9673    nFile = (int)strlen(zFile)+1;
9674  }
9675
9676  rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
9677  if( rc==SQLITE_OK ){
9678    pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
9679    if( pNew==0 ) return SQLITE_NOMEM;
9680    memset(pNew, 0, nByte+nFile);
9681    pNew->db = db;
9682    pNew->aBuffer = (u8*)&pNew[1];
9683    if( zFile ){
9684      pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
9685      memcpy(pNew->zFile, zFile, nFile);
9686      zipfileDequote(pNew->zFile);
9687    }
9688  }
9689  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
9690  *ppVtab = (sqlite3_vtab*)pNew;
9691  return rc;
9692}
9693
9694/*
9695** Free the ZipfileEntry structure indicated by the only argument.
9696*/
9697static void zipfileEntryFree(ZipfileEntry *p){
9698  if( p ){
9699    sqlite3_free(p->cds.zFile);
9700    sqlite3_free(p);
9701  }
9702}
9703
9704/*
9705** Release resources that should be freed at the end of a write
9706** transaction.
9707*/
9708static void zipfileCleanupTransaction(ZipfileTab *pTab){
9709  ZipfileEntry *pEntry;
9710  ZipfileEntry *pNext;
9711
9712  if( pTab->pWriteFd ){
9713    fclose(pTab->pWriteFd);
9714    pTab->pWriteFd = 0;
9715  }
9716  for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
9717    pNext = pEntry->pNext;
9718    zipfileEntryFree(pEntry);
9719  }
9720  pTab->pFirstEntry = 0;
9721  pTab->pLastEntry = 0;
9722  pTab->szCurrent = 0;
9723  pTab->szOrig = 0;
9724}
9725
9726/*
9727** This method is the destructor for zipfile vtab objects.
9728*/
9729static int zipfileDisconnect(sqlite3_vtab *pVtab){
9730  zipfileCleanupTransaction((ZipfileTab*)pVtab);
9731  sqlite3_free(pVtab);
9732  return SQLITE_OK;
9733}
9734
9735/*
9736** Constructor for a new ZipfileCsr object.
9737*/
9738static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
9739  ZipfileTab *pTab = (ZipfileTab*)p;
9740  ZipfileCsr *pCsr;
9741  pCsr = sqlite3_malloc(sizeof(*pCsr));
9742  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
9743  if( pCsr==0 ){
9744    return SQLITE_NOMEM;
9745  }
9746  memset(pCsr, 0, sizeof(*pCsr));
9747  pCsr->iId = ++pTab->iNextCsrid;
9748  pCsr->pCsrNext = pTab->pCsrList;
9749  pTab->pCsrList = pCsr;
9750  return SQLITE_OK;
9751}
9752
9753/*
9754** Reset a cursor back to the state it was in when first returned
9755** by zipfileOpen().
9756*/
9757static void zipfileResetCursor(ZipfileCsr *pCsr){
9758  ZipfileEntry *p;
9759  ZipfileEntry *pNext;
9760
9761  pCsr->bEof = 0;
9762  if( pCsr->pFile ){
9763    fclose(pCsr->pFile);
9764    pCsr->pFile = 0;
9765    zipfileEntryFree(pCsr->pCurrent);
9766    pCsr->pCurrent = 0;
9767  }
9768
9769  for(p=pCsr->pFreeEntry; p; p=pNext){
9770    pNext = p->pNext;
9771    zipfileEntryFree(p);
9772  }
9773}
9774
9775/*
9776** Destructor for an ZipfileCsr.
9777*/
9778static int zipfileClose(sqlite3_vtab_cursor *cur){
9779  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9780  ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
9781  ZipfileCsr **pp;
9782  zipfileResetCursor(pCsr);
9783
9784  /* Remove this cursor from the ZipfileTab.pCsrList list. */
9785  for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
9786  *pp = pCsr->pCsrNext;
9787
9788  sqlite3_free(pCsr);
9789  return SQLITE_OK;
9790}
9791
9792/*
9793** Set the error message for the virtual table associated with cursor
9794** pCsr to the results of vprintf(zFmt, ...).
9795*/
9796static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
9797  va_list ap;
9798  va_start(ap, zFmt);
9799  sqlite3_free(pTab->base.zErrMsg);
9800  pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
9801  va_end(ap);
9802}
9803static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
9804  va_list ap;
9805  va_start(ap, zFmt);
9806  sqlite3_free(pCsr->base.pVtab->zErrMsg);
9807  pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
9808  va_end(ap);
9809}
9810
9811/*
9812** Read nRead bytes of data from offset iOff of file pFile into buffer
9813** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
9814** otherwise.
9815**
9816** If an error does occur, output variable (*pzErrmsg) may be set to point
9817** to an English language error message. It is the responsibility of the
9818** caller to eventually free this buffer using
9819** sqlite3_free().
9820*/
9821static int zipfileReadData(
9822  FILE *pFile,                    /* Read from this file */
9823  u8 *aRead,                      /* Read into this buffer */
9824  int nRead,                      /* Number of bytes to read */
9825  i64 iOff,                       /* Offset to read from */
9826  char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
9827){
9828  size_t n;
9829  fseek(pFile, (long)iOff, SEEK_SET);
9830  n = fread(aRead, 1, nRead, pFile);
9831  if( (int)n!=nRead ){
9832    *pzErrmsg = sqlite3_mprintf("error in fread()");
9833    return SQLITE_ERROR;
9834  }
9835  return SQLITE_OK;
9836}
9837
9838static int zipfileAppendData(
9839  ZipfileTab *pTab,
9840  const u8 *aWrite,
9841  int nWrite
9842){
9843  if( nWrite>0 ){
9844    size_t n = nWrite;
9845    fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
9846    n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
9847    if( (int)n!=nWrite ){
9848      pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
9849      return SQLITE_ERROR;
9850    }
9851    pTab->szCurrent += nWrite;
9852  }
9853  return SQLITE_OK;
9854}
9855
9856/*
9857** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9858*/
9859static u16 zipfileGetU16(const u8 *aBuf){
9860  return (aBuf[1] << 8) + aBuf[0];
9861}
9862
9863/*
9864** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9865*/
9866static u32 zipfileGetU32(const u8 *aBuf){
9867  if( aBuf==0 ) return 0;
9868  return ((u32)(aBuf[3]) << 24)
9869       + ((u32)(aBuf[2]) << 16)
9870       + ((u32)(aBuf[1]) <<  8)
9871       + ((u32)(aBuf[0]) <<  0);
9872}
9873
9874/*
9875** Write a 16-bit little endiate integer into buffer aBuf.
9876*/
9877static void zipfilePutU16(u8 *aBuf, u16 val){
9878  aBuf[0] = val & 0xFF;
9879  aBuf[1] = (val>>8) & 0xFF;
9880}
9881
9882/*
9883** Write a 32-bit little endiate integer into buffer aBuf.
9884*/
9885static void zipfilePutU32(u8 *aBuf, u32 val){
9886  aBuf[0] = val & 0xFF;
9887  aBuf[1] = (val>>8) & 0xFF;
9888  aBuf[2] = (val>>16) & 0xFF;
9889  aBuf[3] = (val>>24) & 0xFF;
9890}
9891
9892#define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9893#define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9894
9895#define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
9896#define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
9897
9898/*
9899** Magic numbers used to read CDS records.
9900*/
9901#define ZIPFILE_CDS_NFILE_OFF        28
9902#define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
9903
9904/*
9905** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
9906** if the record is not well-formed, or SQLITE_OK otherwise.
9907*/
9908static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
9909  u8 *aRead = aBuf;
9910  u32 sig = zipfileRead32(aRead);
9911  int rc = SQLITE_OK;
9912  if( sig!=ZIPFILE_SIGNATURE_CDS ){
9913    rc = SQLITE_ERROR;
9914  }else{
9915    pCDS->iVersionMadeBy = zipfileRead16(aRead);
9916    pCDS->iVersionExtract = zipfileRead16(aRead);
9917    pCDS->flags = zipfileRead16(aRead);
9918    pCDS->iCompression = zipfileRead16(aRead);
9919    pCDS->mTime = zipfileRead16(aRead);
9920    pCDS->mDate = zipfileRead16(aRead);
9921    pCDS->crc32 = zipfileRead32(aRead);
9922    pCDS->szCompressed = zipfileRead32(aRead);
9923    pCDS->szUncompressed = zipfileRead32(aRead);
9924    assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
9925    pCDS->nFile = zipfileRead16(aRead);
9926    pCDS->nExtra = zipfileRead16(aRead);
9927    pCDS->nComment = zipfileRead16(aRead);
9928    pCDS->iDiskStart = zipfileRead16(aRead);
9929    pCDS->iInternalAttr = zipfileRead16(aRead);
9930    pCDS->iExternalAttr = zipfileRead32(aRead);
9931    pCDS->iOffset = zipfileRead32(aRead);
9932    assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
9933  }
9934
9935  return rc;
9936}
9937
9938/*
9939** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
9940** if the record is not well-formed, or SQLITE_OK otherwise.
9941*/
9942static int zipfileReadLFH(
9943  u8 *aBuffer,
9944  ZipfileLFH *pLFH
9945){
9946  u8 *aRead = aBuffer;
9947  int rc = SQLITE_OK;
9948
9949  u32 sig = zipfileRead32(aRead);
9950  if( sig!=ZIPFILE_SIGNATURE_LFH ){
9951    rc = SQLITE_ERROR;
9952  }else{
9953    pLFH->iVersionExtract = zipfileRead16(aRead);
9954    pLFH->flags = zipfileRead16(aRead);
9955    pLFH->iCompression = zipfileRead16(aRead);
9956    pLFH->mTime = zipfileRead16(aRead);
9957    pLFH->mDate = zipfileRead16(aRead);
9958    pLFH->crc32 = zipfileRead32(aRead);
9959    pLFH->szCompressed = zipfileRead32(aRead);
9960    pLFH->szUncompressed = zipfileRead32(aRead);
9961    pLFH->nFile = zipfileRead16(aRead);
9962    pLFH->nExtra = zipfileRead16(aRead);
9963  }
9964  return rc;
9965}
9966
9967
9968/*
9969** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
9970** Scan through this buffer to find an "extra-timestamp" field. If one
9971** exists, extract the 32-bit modification-timestamp from it and store
9972** the value in output parameter *pmTime.
9973**
9974** Zero is returned if no extra-timestamp record could be found (and so
9975** *pmTime is left unchanged), or non-zero otherwise.
9976**
9977** The general format of an extra field is:
9978**
9979**   Header ID    2 bytes
9980**   Data Size    2 bytes
9981**   Data         N bytes
9982*/
9983static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
9984  int ret = 0;
9985  u8 *p = aExtra;
9986  u8 *pEnd = &aExtra[nExtra];
9987
9988  while( p<pEnd ){
9989    u16 id = zipfileRead16(p);
9990    u16 nByte = zipfileRead16(p);
9991
9992    switch( id ){
9993      case ZIPFILE_EXTRA_TIMESTAMP: {
9994        u8 b = p[0];
9995        if( b & 0x01 ){     /* 0x01 -> modtime is present */
9996          *pmTime = zipfileGetU32(&p[1]);
9997          ret = 1;
9998        }
9999        break;
10000      }
10001    }
10002
10003    p += nByte;
10004  }
10005  return ret;
10006}
10007
10008/*
10009** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10010** fields of the CDS structure passed as the only argument to a 32-bit
10011** UNIX seconds-since-the-epoch timestamp. Return the result.
10012**
10013** "Standard" MS-DOS time format:
10014**
10015**   File modification time:
10016**     Bits 00-04: seconds divided by 2
10017**     Bits 05-10: minute
10018**     Bits 11-15: hour
10019**   File modification date:
10020**     Bits 00-04: day
10021**     Bits 05-08: month (1-12)
10022**     Bits 09-15: years from 1980
10023**
10024** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10025*/
10026static u32 zipfileMtime(ZipfileCDS *pCDS){
10027  int Y,M,D,X1,X2,A,B,sec,min,hr;
10028  i64 JDsec;
10029  Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
10030  M = ((pCDS->mDate >> 5) & 0x0F);
10031  D = (pCDS->mDate & 0x1F);
10032  sec = (pCDS->mTime & 0x1F)*2;
10033  min = (pCDS->mTime >> 5) & 0x3F;
10034  hr = (pCDS->mTime >> 11) & 0x1F;
10035  if( M<=2 ){
10036    Y--;
10037    M += 12;
10038  }
10039  X1 = 36525*(Y+4716)/100;
10040  X2 = 306001*(M+1)/10000;
10041  A = Y/100;
10042  B = 2 - A + (A/4);
10043  JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
10044  return (u32)(JDsec - (i64)24405875*(i64)8640);
10045}
10046
10047/*
10048** The opposite of zipfileMtime(). This function populates the mTime and
10049** mDate fields of the CDS structure passed as the first argument according
10050** to the UNIX timestamp value passed as the second.
10051*/
10052static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
10053  /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
10054  i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
10055
10056  int A, B, C, D, E;
10057  int yr, mon, day;
10058  int hr, min, sec;
10059
10060  A = (int)((JD - 1867216.25)/36524.25);
10061  A = (int)(JD + 1 + A - (A/4));
10062  B = A + 1524;
10063  C = (int)((B - 122.1)/365.25);
10064  D = (36525*(C&32767))/100;
10065  E = (int)((B-D)/30.6001);
10066
10067  day = B - D - (int)(30.6001*E);
10068  mon = (E<14 ? E-1 : E-13);
10069  yr = mon>2 ? C-4716 : C-4715;
10070
10071  hr = (mUnixTime % (24*60*60)) / (60*60);
10072  min = (mUnixTime % (60*60)) / 60;
10073  sec = (mUnixTime % 60);
10074
10075  if( yr>=1980 ){
10076    pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
10077    pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
10078  }else{
10079    pCds->mDate = pCds->mTime = 0;
10080  }
10081
10082  assert( mUnixTime<315507600
10083       || mUnixTime==zipfileMtime(pCds)
10084       || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
10085       /* || (mUnixTime % 2) */
10086  );
10087}
10088
10089/*
10090** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
10091** size) containing an entire zip archive image. Or, if aBlob is NULL,
10092** then pFile is a file-handle open on a zip file. In either case, this
10093** function creates a ZipfileEntry object based on the zip archive entry
10094** for which the CDS record is at offset iOff.
10095**
10096** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
10097** the new object. Otherwise, an SQLite error code is returned and the
10098** final value of (*ppEntry) undefined.
10099*/
10100static int zipfileGetEntry(
10101  ZipfileTab *pTab,               /* Store any error message here */
10102  const u8 *aBlob,                /* Pointer to in-memory file image */
10103  int nBlob,                      /* Size of aBlob[] in bytes */
10104  FILE *pFile,                    /* If aBlob==0, read from this file */
10105  i64 iOff,                       /* Offset of CDS record */
10106  ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
10107){
10108  u8 *aRead;
10109  char **pzErr = &pTab->base.zErrMsg;
10110  int rc = SQLITE_OK;
10111  (void)nBlob;
10112
10113  if( aBlob==0 ){
10114    aRead = pTab->aBuffer;
10115    rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
10116  }else{
10117    aRead = (u8*)&aBlob[iOff];
10118  }
10119
10120  if( rc==SQLITE_OK ){
10121    sqlite3_int64 nAlloc;
10122    ZipfileEntry *pNew;
10123
10124    int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
10125    int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
10126    nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
10127
10128    nAlloc = sizeof(ZipfileEntry) + nExtra;
10129    if( aBlob ){
10130      nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
10131    }
10132
10133    pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
10134    if( pNew==0 ){
10135      rc = SQLITE_NOMEM;
10136    }else{
10137      memset(pNew, 0, sizeof(ZipfileEntry));
10138      rc = zipfileReadCDS(aRead, &pNew->cds);
10139      if( rc!=SQLITE_OK ){
10140        *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
10141      }else if( aBlob==0 ){
10142        rc = zipfileReadData(
10143            pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
10144        );
10145      }else{
10146        aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
10147      }
10148    }
10149
10150    if( rc==SQLITE_OK ){
10151      u32 *pt = &pNew->mUnixTime;
10152      pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
10153      pNew->aExtra = (u8*)&pNew[1];
10154      memcpy(pNew->aExtra, &aRead[nFile], nExtra);
10155      if( pNew->cds.zFile==0 ){
10156        rc = SQLITE_NOMEM;
10157      }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
10158        pNew->mUnixTime = zipfileMtime(&pNew->cds);
10159      }
10160    }
10161
10162    if( rc==SQLITE_OK ){
10163      static const int szFix = ZIPFILE_LFH_FIXED_SZ;
10164      ZipfileLFH lfh;
10165      if( pFile ){
10166        rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
10167      }else{
10168        aRead = (u8*)&aBlob[pNew->cds.iOffset];
10169      }
10170
10171      if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
10172      if( rc==SQLITE_OK ){
10173        pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
10174        pNew->iDataOff += lfh.nFile + lfh.nExtra;
10175        if( aBlob && pNew->cds.szCompressed ){
10176          pNew->aData = &pNew->aExtra[nExtra];
10177          memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
10178        }
10179      }else{
10180        *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
10181            (int)pNew->cds.iOffset
10182        );
10183      }
10184    }
10185
10186    if( rc!=SQLITE_OK ){
10187      zipfileEntryFree(pNew);
10188    }else{
10189      *ppEntry = pNew;
10190    }
10191  }
10192
10193  return rc;
10194}
10195
10196/*
10197** Advance an ZipfileCsr to its next row of output.
10198*/
10199static int zipfileNext(sqlite3_vtab_cursor *cur){
10200  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10201  int rc = SQLITE_OK;
10202
10203  if( pCsr->pFile ){
10204    i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
10205    zipfileEntryFree(pCsr->pCurrent);
10206    pCsr->pCurrent = 0;
10207    if( pCsr->iNextOff>=iEof ){
10208      pCsr->bEof = 1;
10209    }else{
10210      ZipfileEntry *p = 0;
10211      ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
10212      rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
10213      if( rc==SQLITE_OK ){
10214        pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
10215        pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
10216      }
10217      pCsr->pCurrent = p;
10218    }
10219  }else{
10220    if( !pCsr->bNoop ){
10221      pCsr->pCurrent = pCsr->pCurrent->pNext;
10222    }
10223    if( pCsr->pCurrent==0 ){
10224      pCsr->bEof = 1;
10225    }
10226  }
10227
10228  pCsr->bNoop = 0;
10229  return rc;
10230}
10231
10232static void zipfileFree(void *p) {
10233  sqlite3_free(p);
10234}
10235
10236/*
10237** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
10238** size is nOut bytes. This function uncompresses the data and sets the
10239** return value in context pCtx to the result (a blob).
10240**
10241** If an error occurs, an error code is left in pCtx instead.
10242*/
10243static void zipfileInflate(
10244  sqlite3_context *pCtx,          /* Store result here */
10245  const u8 *aIn,                  /* Compressed data */
10246  int nIn,                        /* Size of buffer aIn[] in bytes */
10247  int nOut                        /* Expected output size */
10248){
10249  u8 *aRes = sqlite3_malloc(nOut);
10250  if( aRes==0 ){
10251    sqlite3_result_error_nomem(pCtx);
10252  }else{
10253    int err;
10254    z_stream str;
10255    memset(&str, 0, sizeof(str));
10256
10257    str.next_in = (Byte*)aIn;
10258    str.avail_in = nIn;
10259    str.next_out = (Byte*)aRes;
10260    str.avail_out = nOut;
10261
10262    err = inflateInit2(&str, -15);
10263    if( err!=Z_OK ){
10264      zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
10265    }else{
10266      err = inflate(&str, Z_NO_FLUSH);
10267      if( err!=Z_STREAM_END ){
10268        zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
10269      }else{
10270        sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
10271        aRes = 0;
10272      }
10273    }
10274    sqlite3_free(aRes);
10275    inflateEnd(&str);
10276  }
10277}
10278
10279/*
10280** Buffer aIn (size nIn bytes) contains uncompressed data. This function
10281** compresses it and sets (*ppOut) to point to a buffer containing the
10282** compressed data. The caller is responsible for eventually calling
10283** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
10284** is set to the size of buffer (*ppOut) in bytes.
10285**
10286** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
10287** code is returned and an error message left in virtual-table handle
10288** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
10289** case.
10290*/
10291static int zipfileDeflate(
10292  const u8 *aIn, int nIn,         /* Input */
10293  u8 **ppOut, int *pnOut,         /* Output */
10294  char **pzErr                    /* OUT: Error message */
10295){
10296  int rc = SQLITE_OK;
10297  sqlite3_int64 nAlloc;
10298  z_stream str;
10299  u8 *aOut;
10300
10301  memset(&str, 0, sizeof(str));
10302  str.next_in = (Bytef*)aIn;
10303  str.avail_in = nIn;
10304  deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
10305
10306  nAlloc = deflateBound(&str, nIn);
10307  aOut = (u8*)sqlite3_malloc64(nAlloc);
10308  if( aOut==0 ){
10309    rc = SQLITE_NOMEM;
10310  }else{
10311    int res;
10312    str.next_out = aOut;
10313    str.avail_out = nAlloc;
10314    res = deflate(&str, Z_FINISH);
10315    if( res==Z_STREAM_END ){
10316      *ppOut = aOut;
10317      *pnOut = (int)str.total_out;
10318    }else{
10319      sqlite3_free(aOut);
10320      *pzErr = sqlite3_mprintf("zipfile: deflate() error");
10321      rc = SQLITE_ERROR;
10322    }
10323    deflateEnd(&str);
10324  }
10325
10326  return rc;
10327}
10328
10329
10330/*
10331** Return values of columns for the row at which the series_cursor
10332** is currently pointing.
10333*/
10334static int zipfileColumn(
10335  sqlite3_vtab_cursor *cur,   /* The cursor */
10336  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
10337  int i                       /* Which column to return */
10338){
10339  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10340  ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
10341  int rc = SQLITE_OK;
10342  switch( i ){
10343    case 0:   /* name */
10344      sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
10345      break;
10346    case 1:   /* mode */
10347      /* TODO: Whether or not the following is correct surely depends on
10348      ** the platform on which the archive was created.  */
10349      sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
10350      break;
10351    case 2: { /* mtime */
10352      sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
10353      break;
10354    }
10355    case 3: { /* sz */
10356      if( sqlite3_vtab_nochange(ctx)==0 ){
10357        sqlite3_result_int64(ctx, pCDS->szUncompressed);
10358      }
10359      break;
10360    }
10361    case 4:   /* rawdata */
10362      if( sqlite3_vtab_nochange(ctx) ) break;
10363    case 5: { /* data */
10364      if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
10365        int sz = pCDS->szCompressed;
10366        int szFinal = pCDS->szUncompressed;
10367        if( szFinal>0 ){
10368          u8 *aBuf;
10369          u8 *aFree = 0;
10370          if( pCsr->pCurrent->aData ){
10371            aBuf = pCsr->pCurrent->aData;
10372          }else{
10373            aBuf = aFree = sqlite3_malloc64(sz);
10374            if( aBuf==0 ){
10375              rc = SQLITE_NOMEM;
10376            }else{
10377              FILE *pFile = pCsr->pFile;
10378              if( pFile==0 ){
10379                pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
10380              }
10381              rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
10382                  &pCsr->base.pVtab->zErrMsg
10383              );
10384            }
10385          }
10386          if( rc==SQLITE_OK ){
10387            if( i==5 && pCDS->iCompression ){
10388              zipfileInflate(ctx, aBuf, sz, szFinal);
10389            }else{
10390              sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
10391            }
10392          }
10393          sqlite3_free(aFree);
10394        }else{
10395          /* Figure out if this is a directory or a zero-sized file. Consider
10396          ** it to be a directory either if the mode suggests so, or if
10397          ** the final character in the name is '/'.  */
10398          u32 mode = pCDS->iExternalAttr >> 16;
10399          if( !(mode & S_IFDIR)
10400           && pCDS->nFile>=1
10401           && pCDS->zFile[pCDS->nFile-1]!='/'
10402          ){
10403            sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
10404          }
10405        }
10406      }
10407      break;
10408    }
10409    case 6:   /* method */
10410      sqlite3_result_int(ctx, pCDS->iCompression);
10411      break;
10412    default:  /* z */
10413      assert( i==7 );
10414      sqlite3_result_int64(ctx, pCsr->iId);
10415      break;
10416  }
10417
10418  return rc;
10419}
10420
10421/*
10422** Return TRUE if the cursor is at EOF.
10423*/
10424static int zipfileEof(sqlite3_vtab_cursor *cur){
10425  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10426  return pCsr->bEof;
10427}
10428
10429/*
10430** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
10431** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
10432** is guaranteed to be a file-handle open on a zip file.
10433**
10434** This function attempts to locate the EOCD record within the zip archive
10435** and populate *pEOCD with the results of decoding it. SQLITE_OK is
10436** returned if successful. Otherwise, an SQLite error code is returned and
10437** an English language error message may be left in virtual-table pTab.
10438*/
10439static int zipfileReadEOCD(
10440  ZipfileTab *pTab,               /* Return errors here */
10441  const u8 *aBlob,                /* Pointer to in-memory file image */
10442  int nBlob,                      /* Size of aBlob[] in bytes */
10443  FILE *pFile,                    /* Read from this file if aBlob==0 */
10444  ZipfileEOCD *pEOCD              /* Object to populate */
10445){
10446  u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
10447  int nRead;                      /* Bytes to read from file */
10448  int rc = SQLITE_OK;
10449
10450  memset(pEOCD, 0, sizeof(ZipfileEOCD));
10451  if( aBlob==0 ){
10452    i64 iOff;                     /* Offset to read from */
10453    i64 szFile;                   /* Total size of file in bytes */
10454    fseek(pFile, 0, SEEK_END);
10455    szFile = (i64)ftell(pFile);
10456    if( szFile==0 ){
10457      return SQLITE_OK;
10458    }
10459    nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
10460    iOff = szFile - nRead;
10461    rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
10462  }else{
10463    nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
10464    aRead = (u8*)&aBlob[nBlob-nRead];
10465  }
10466
10467  if( rc==SQLITE_OK ){
10468    int i;
10469
10470    /* Scan backwards looking for the signature bytes */
10471    for(i=nRead-20; i>=0; i--){
10472      if( aRead[i]==0x50 && aRead[i+1]==0x4b
10473       && aRead[i+2]==0x05 && aRead[i+3]==0x06
10474      ){
10475        break;
10476      }
10477    }
10478    if( i<0 ){
10479      pTab->base.zErrMsg = sqlite3_mprintf(
10480          "cannot find end of central directory record"
10481      );
10482      return SQLITE_ERROR;
10483    }
10484
10485    aRead += i+4;
10486    pEOCD->iDisk = zipfileRead16(aRead);
10487    pEOCD->iFirstDisk = zipfileRead16(aRead);
10488    pEOCD->nEntry = zipfileRead16(aRead);
10489    pEOCD->nEntryTotal = zipfileRead16(aRead);
10490    pEOCD->nSize = zipfileRead32(aRead);
10491    pEOCD->iOffset = zipfileRead32(aRead);
10492  }
10493
10494  return rc;
10495}
10496
10497/*
10498** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
10499** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
10500** to the end of the list. Otherwise, it is added to the list immediately
10501** before pBefore (which is guaranteed to be a part of said list).
10502*/
10503static void zipfileAddEntry(
10504  ZipfileTab *pTab,
10505  ZipfileEntry *pBefore,
10506  ZipfileEntry *pNew
10507){
10508  assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
10509  assert( pNew->pNext==0 );
10510  if( pBefore==0 ){
10511    if( pTab->pFirstEntry==0 ){
10512      pTab->pFirstEntry = pTab->pLastEntry = pNew;
10513    }else{
10514      assert( pTab->pLastEntry->pNext==0 );
10515      pTab->pLastEntry->pNext = pNew;
10516      pTab->pLastEntry = pNew;
10517    }
10518  }else{
10519    ZipfileEntry **pp;
10520    for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
10521    pNew->pNext = pBefore;
10522    *pp = pNew;
10523  }
10524}
10525
10526static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
10527  ZipfileEOCD eocd;
10528  int rc;
10529  int i;
10530  i64 iOff;
10531
10532  rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
10533  iOff = eocd.iOffset;
10534  for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
10535    ZipfileEntry *pNew = 0;
10536    rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
10537
10538    if( rc==SQLITE_OK ){
10539      zipfileAddEntry(pTab, 0, pNew);
10540      iOff += ZIPFILE_CDS_FIXED_SZ;
10541      iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
10542    }
10543  }
10544  return rc;
10545}
10546
10547/*
10548** xFilter callback.
10549*/
10550static int zipfileFilter(
10551  sqlite3_vtab_cursor *cur,
10552  int idxNum, const char *idxStr,
10553  int argc, sqlite3_value **argv
10554){
10555  ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
10556  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10557  const char *zFile = 0;          /* Zip file to scan */
10558  int rc = SQLITE_OK;             /* Return Code */
10559  int bInMemory = 0;              /* True for an in-memory zipfile */
10560
10561  (void)idxStr;
10562  (void)argc;
10563
10564  zipfileResetCursor(pCsr);
10565
10566  if( pTab->zFile ){
10567    zFile = pTab->zFile;
10568  }else if( idxNum==0 ){
10569    zipfileCursorErr(pCsr, "zipfile() function requires an argument");
10570    return SQLITE_ERROR;
10571  }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
10572    static const u8 aEmptyBlob = 0;
10573    const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
10574    int nBlob = sqlite3_value_bytes(argv[0]);
10575    assert( pTab->pFirstEntry==0 );
10576    if( aBlob==0 ){
10577      aBlob = &aEmptyBlob;
10578      nBlob = 0;
10579    }
10580    rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
10581    pCsr->pFreeEntry = pTab->pFirstEntry;
10582    pTab->pFirstEntry = pTab->pLastEntry = 0;
10583    if( rc!=SQLITE_OK ) return rc;
10584    bInMemory = 1;
10585  }else{
10586    zFile = (const char*)sqlite3_value_text(argv[0]);
10587  }
10588
10589  if( 0==pTab->pWriteFd && 0==bInMemory ){
10590    pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
10591    if( pCsr->pFile==0 ){
10592      zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
10593      rc = SQLITE_ERROR;
10594    }else{
10595      rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
10596      if( rc==SQLITE_OK ){
10597        if( pCsr->eocd.nEntry==0 ){
10598          pCsr->bEof = 1;
10599        }else{
10600          pCsr->iNextOff = pCsr->eocd.iOffset;
10601          rc = zipfileNext(cur);
10602        }
10603      }
10604    }
10605  }else{
10606    pCsr->bNoop = 1;
10607    pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
10608    rc = zipfileNext(cur);
10609  }
10610
10611  return rc;
10612}
10613
10614/*
10615** xBestIndex callback.
10616*/
10617static int zipfileBestIndex(
10618  sqlite3_vtab *tab,
10619  sqlite3_index_info *pIdxInfo
10620){
10621  int i;
10622  int idx = -1;
10623  int unusable = 0;
10624  (void)tab;
10625
10626  for(i=0; i<pIdxInfo->nConstraint; i++){
10627    const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
10628    if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
10629    if( pCons->usable==0 ){
10630      unusable = 1;
10631    }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10632      idx = i;
10633    }
10634  }
10635  pIdxInfo->estimatedCost = 1000.0;
10636  if( idx>=0 ){
10637    pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
10638    pIdxInfo->aConstraintUsage[idx].omit = 1;
10639    pIdxInfo->idxNum = 1;
10640  }else if( unusable ){
10641    return SQLITE_CONSTRAINT;
10642  }
10643  return SQLITE_OK;
10644}
10645
10646static ZipfileEntry *zipfileNewEntry(const char *zPath){
10647  ZipfileEntry *pNew;
10648  pNew = sqlite3_malloc(sizeof(ZipfileEntry));
10649  if( pNew ){
10650    memset(pNew, 0, sizeof(ZipfileEntry));
10651    pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
10652    if( pNew->cds.zFile==0 ){
10653      sqlite3_free(pNew);
10654      pNew = 0;
10655    }
10656  }
10657  return pNew;
10658}
10659
10660static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
10661  ZipfileCDS *pCds = &pEntry->cds;
10662  u8 *a = aBuf;
10663
10664  pCds->nExtra = 9;
10665
10666  /* Write the LFH itself */
10667  zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
10668  zipfileWrite16(a, pCds->iVersionExtract);
10669  zipfileWrite16(a, pCds->flags);
10670  zipfileWrite16(a, pCds->iCompression);
10671  zipfileWrite16(a, pCds->mTime);
10672  zipfileWrite16(a, pCds->mDate);
10673  zipfileWrite32(a, pCds->crc32);
10674  zipfileWrite32(a, pCds->szCompressed);
10675  zipfileWrite32(a, pCds->szUncompressed);
10676  zipfileWrite16(a, (u16)pCds->nFile);
10677  zipfileWrite16(a, pCds->nExtra);
10678  assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
10679
10680  /* Add the file name */
10681  memcpy(a, pCds->zFile, (int)pCds->nFile);
10682  a += (int)pCds->nFile;
10683
10684  /* The "extra" data */
10685  zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
10686  zipfileWrite16(a, 5);
10687  *a++ = 0x01;
10688  zipfileWrite32(a, pEntry->mUnixTime);
10689
10690  return a-aBuf;
10691}
10692
10693static int zipfileAppendEntry(
10694  ZipfileTab *pTab,
10695  ZipfileEntry *pEntry,
10696  const u8 *pData,
10697  int nData
10698){
10699  u8 *aBuf = pTab->aBuffer;
10700  int nBuf;
10701  int rc;
10702
10703  nBuf = zipfileSerializeLFH(pEntry, aBuf);
10704  rc = zipfileAppendData(pTab, aBuf, nBuf);
10705  if( rc==SQLITE_OK ){
10706    pEntry->iDataOff = pTab->szCurrent;
10707    rc = zipfileAppendData(pTab, pData, nData);
10708  }
10709
10710  return rc;
10711}
10712
10713static int zipfileGetMode(
10714  sqlite3_value *pVal,
10715  int bIsDir,                     /* If true, default to directory */
10716  u32 *pMode,                     /* OUT: Mode value */
10717  char **pzErr                    /* OUT: Error message */
10718){
10719  const char *z = (const char*)sqlite3_value_text(pVal);
10720  u32 mode = 0;
10721  if( z==0 ){
10722    mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
10723  }else if( z[0]>='0' && z[0]<='9' ){
10724    mode = (unsigned int)sqlite3_value_int(pVal);
10725  }else{
10726    const char zTemplate[11] = "-rwxrwxrwx";
10727    int i;
10728    if( strlen(z)!=10 ) goto parse_error;
10729    switch( z[0] ){
10730      case '-': mode |= S_IFREG; break;
10731      case 'd': mode |= S_IFDIR; break;
10732      case 'l': mode |= S_IFLNK; break;
10733      default: goto parse_error;
10734    }
10735    for(i=1; i<10; i++){
10736      if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
10737      else if( z[i]!='-' ) goto parse_error;
10738    }
10739  }
10740  if( ((mode & S_IFDIR)==0)==bIsDir ){
10741    /* The "mode" attribute is a directory, but data has been specified.
10742    ** Or vice-versa - no data but "mode" is a file or symlink.  */
10743    *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
10744    return SQLITE_CONSTRAINT;
10745  }
10746  *pMode = mode;
10747  return SQLITE_OK;
10748
10749 parse_error:
10750  *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
10751  return SQLITE_ERROR;
10752}
10753
10754/*
10755** Both (const char*) arguments point to nul-terminated strings. Argument
10756** nB is the value of strlen(zB). This function returns 0 if the strings are
10757** identical, ignoring any trailing '/' character in either path.  */
10758static int zipfileComparePath(const char *zA, const char *zB, int nB){
10759  int nA = (int)strlen(zA);
10760  if( nA>0 && zA[nA-1]=='/' ) nA--;
10761  if( nB>0 && zB[nB-1]=='/' ) nB--;
10762  if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
10763  return 1;
10764}
10765
10766static int zipfileBegin(sqlite3_vtab *pVtab){
10767  ZipfileTab *pTab = (ZipfileTab*)pVtab;
10768  int rc = SQLITE_OK;
10769
10770  assert( pTab->pWriteFd==0 );
10771  if( pTab->zFile==0 || pTab->zFile[0]==0 ){
10772    pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
10773    return SQLITE_ERROR;
10774  }
10775
10776  /* Open a write fd on the file. Also load the entire central directory
10777  ** structure into memory. During the transaction any new file data is
10778  ** appended to the archive file, but the central directory is accumulated
10779  ** in main-memory until the transaction is committed.  */
10780  pTab->pWriteFd = fopen(pTab->zFile, "ab+");
10781  if( pTab->pWriteFd==0 ){
10782    pTab->base.zErrMsg = sqlite3_mprintf(
10783        "zipfile: failed to open file %s for writing", pTab->zFile
10784        );
10785    rc = SQLITE_ERROR;
10786  }else{
10787    fseek(pTab->pWriteFd, 0, SEEK_END);
10788    pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
10789    rc = zipfileLoadDirectory(pTab, 0, 0);
10790  }
10791
10792  if( rc!=SQLITE_OK ){
10793    zipfileCleanupTransaction(pTab);
10794  }
10795
10796  return rc;
10797}
10798
10799/*
10800** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10801** time(2)).
10802*/
10803static u32 zipfileTime(void){
10804  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
10805  u32 ret;
10806  if( pVfs==0 ) return 0;
10807  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
10808    i64 ms;
10809    pVfs->xCurrentTimeInt64(pVfs, &ms);
10810    ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
10811  }else{
10812    double day;
10813    pVfs->xCurrentTime(pVfs, &day);
10814    ret = (u32)((day - 2440587.5) * 86400);
10815  }
10816  return ret;
10817}
10818
10819/*
10820** Return a 32-bit timestamp in UNIX epoch format.
10821**
10822** If the value passed as the only argument is either NULL or an SQL NULL,
10823** return the current time. Otherwise, return the value stored in (*pVal)
10824** cast to a 32-bit unsigned integer.
10825*/
10826static u32 zipfileGetTime(sqlite3_value *pVal){
10827  if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
10828    return zipfileTime();
10829  }
10830  return (u32)sqlite3_value_int64(pVal);
10831}
10832
10833/*
10834** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10835** linked list.  Remove it from the list and free the object.
10836*/
10837static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
10838  if( pOld ){
10839    if( pTab->pFirstEntry==pOld ){
10840      pTab->pFirstEntry = pOld->pNext;
10841      if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
10842    }else{
10843      ZipfileEntry *p;
10844      for(p=pTab->pFirstEntry; p; p=p->pNext){
10845        if( p->pNext==pOld ){
10846          p->pNext = pOld->pNext;
10847          if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
10848          break;
10849        }
10850      }
10851    }
10852    zipfileEntryFree(pOld);
10853  }
10854}
10855
10856/*
10857** xUpdate method.
10858*/
10859static int zipfileUpdate(
10860  sqlite3_vtab *pVtab,
10861  int nVal,
10862  sqlite3_value **apVal,
10863  sqlite_int64 *pRowid
10864){
10865  ZipfileTab *pTab = (ZipfileTab*)pVtab;
10866  int rc = SQLITE_OK;             /* Return Code */
10867  ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
10868
10869  u32 mode = 0;                   /* Mode for new entry */
10870  u32 mTime = 0;                  /* Modification time for new entry */
10871  i64 sz = 0;                     /* Uncompressed size */
10872  const char *zPath = 0;          /* Path for new entry */
10873  int nPath = 0;                  /* strlen(zPath) */
10874  const u8 *pData = 0;            /* Pointer to buffer containing content */
10875  int nData = 0;                  /* Size of pData buffer in bytes */
10876  int iMethod = 0;                /* Compression method for new entry */
10877  u8 *pFree = 0;                  /* Free this */
10878  char *zFree = 0;                /* Also free this */
10879  ZipfileEntry *pOld = 0;
10880  ZipfileEntry *pOld2 = 0;
10881  int bUpdate = 0;                /* True for an update that modifies "name" */
10882  int bIsDir = 0;
10883  u32 iCrc32 = 0;
10884
10885  (void)pRowid;
10886
10887  if( pTab->pWriteFd==0 ){
10888    rc = zipfileBegin(pVtab);
10889    if( rc!=SQLITE_OK ) return rc;
10890  }
10891
10892  /* If this is a DELETE or UPDATE, find the archive entry to delete. */
10893  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
10894    const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
10895    int nDelete = (int)strlen(zDelete);
10896    if( nVal>1 ){
10897      const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
10898      if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
10899        bUpdate = 1;
10900      }
10901    }
10902    for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
10903      if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
10904        break;
10905      }
10906      assert( pOld->pNext );
10907    }
10908  }
10909
10910  if( nVal>1 ){
10911    /* Check that "sz" and "rawdata" are both NULL: */
10912    if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
10913      zipfileTableErr(pTab, "sz must be NULL");
10914      rc = SQLITE_CONSTRAINT;
10915    }
10916    if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
10917      zipfileTableErr(pTab, "rawdata must be NULL");
10918      rc = SQLITE_CONSTRAINT;
10919    }
10920
10921    if( rc==SQLITE_OK ){
10922      if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
10923        /* data=NULL. A directory */
10924        bIsDir = 1;
10925      }else{
10926        /* Value specified for "data", and possibly "method". This must be
10927        ** a regular file or a symlink. */
10928        const u8 *aIn = sqlite3_value_blob(apVal[7]);
10929        int nIn = sqlite3_value_bytes(apVal[7]);
10930        int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
10931
10932        iMethod = sqlite3_value_int(apVal[8]);
10933        sz = nIn;
10934        pData = aIn;
10935        nData = nIn;
10936        if( iMethod!=0 && iMethod!=8 ){
10937          zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
10938          rc = SQLITE_CONSTRAINT;
10939        }else{
10940          if( bAuto || iMethod ){
10941            int nCmp;
10942            rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
10943            if( rc==SQLITE_OK ){
10944              if( iMethod || nCmp<nIn ){
10945                iMethod = 8;
10946                pData = pFree;
10947                nData = nCmp;
10948              }
10949            }
10950          }
10951          iCrc32 = crc32(0, aIn, nIn);
10952        }
10953      }
10954    }
10955
10956    if( rc==SQLITE_OK ){
10957      rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
10958    }
10959
10960    if( rc==SQLITE_OK ){
10961      zPath = (const char*)sqlite3_value_text(apVal[2]);
10962      if( zPath==0 ) zPath = "";
10963      nPath = (int)strlen(zPath);
10964      mTime = zipfileGetTime(apVal[4]);
10965    }
10966
10967    if( rc==SQLITE_OK && bIsDir ){
10968      /* For a directory, check that the last character in the path is a
10969      ** '/'. This appears to be required for compatibility with info-zip
10970      ** (the unzip command on unix). It does not create directories
10971      ** otherwise.  */
10972      if( nPath<=0 || zPath[nPath-1]!='/' ){
10973        zFree = sqlite3_mprintf("%s/", zPath);
10974        zPath = (const char*)zFree;
10975        if( zFree==0 ){
10976          rc = SQLITE_NOMEM;
10977          nPath = 0;
10978        }else{
10979          nPath = (int)strlen(zPath);
10980        }
10981      }
10982    }
10983
10984    /* Check that we're not inserting a duplicate entry -OR- updating an
10985    ** entry with a path, thereby making it into a duplicate. */
10986    if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
10987      ZipfileEntry *p;
10988      for(p=pTab->pFirstEntry; p; p=p->pNext){
10989        if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
10990          switch( sqlite3_vtab_on_conflict(pTab->db) ){
10991            case SQLITE_IGNORE: {
10992              goto zipfile_update_done;
10993            }
10994            case SQLITE_REPLACE: {
10995              pOld2 = p;
10996              break;
10997            }
10998            default: {
10999              zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
11000              rc = SQLITE_CONSTRAINT;
11001              break;
11002            }
11003          }
11004          break;
11005        }
11006      }
11007    }
11008
11009    if( rc==SQLITE_OK ){
11010      /* Create the new CDS record. */
11011      pNew = zipfileNewEntry(zPath);
11012      if( pNew==0 ){
11013        rc = SQLITE_NOMEM;
11014      }else{
11015        pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11016        pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11017        pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11018        pNew->cds.iCompression = (u16)iMethod;
11019        zipfileMtimeToDos(&pNew->cds, mTime);
11020        pNew->cds.crc32 = iCrc32;
11021        pNew->cds.szCompressed = nData;
11022        pNew->cds.szUncompressed = (u32)sz;
11023        pNew->cds.iExternalAttr = (mode<<16);
11024        pNew->cds.iOffset = (u32)pTab->szCurrent;
11025        pNew->cds.nFile = (u16)nPath;
11026        pNew->mUnixTime = (u32)mTime;
11027        rc = zipfileAppendEntry(pTab, pNew, pData, nData);
11028        zipfileAddEntry(pTab, pOld, pNew);
11029      }
11030    }
11031  }
11032
11033  if( rc==SQLITE_OK && (pOld || pOld2) ){
11034    ZipfileCsr *pCsr;
11035    for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11036      if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
11037        pCsr->pCurrent = pCsr->pCurrent->pNext;
11038        pCsr->bNoop = 1;
11039      }
11040    }
11041
11042    zipfileRemoveEntryFromList(pTab, pOld);
11043    zipfileRemoveEntryFromList(pTab, pOld2);
11044  }
11045
11046zipfile_update_done:
11047  sqlite3_free(pFree);
11048  sqlite3_free(zFree);
11049  return rc;
11050}
11051
11052static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
11053  u8 *a = aBuf;
11054  zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
11055  zipfileWrite16(a, p->iDisk);
11056  zipfileWrite16(a, p->iFirstDisk);
11057  zipfileWrite16(a, p->nEntry);
11058  zipfileWrite16(a, p->nEntryTotal);
11059  zipfileWrite32(a, p->nSize);
11060  zipfileWrite32(a, p->iOffset);
11061  zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
11062
11063  return a-aBuf;
11064}
11065
11066static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
11067  int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
11068  assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
11069  return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
11070}
11071
11072/*
11073** Serialize the CDS structure into buffer aBuf[]. Return the number
11074** of bytes written.
11075*/
11076static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
11077  u8 *a = aBuf;
11078  ZipfileCDS *pCDS = &pEntry->cds;
11079
11080  if( pEntry->aExtra==0 ){
11081    pCDS->nExtra = 9;
11082  }
11083
11084  zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
11085  zipfileWrite16(a, pCDS->iVersionMadeBy);
11086  zipfileWrite16(a, pCDS->iVersionExtract);
11087  zipfileWrite16(a, pCDS->flags);
11088  zipfileWrite16(a, pCDS->iCompression);
11089  zipfileWrite16(a, pCDS->mTime);
11090  zipfileWrite16(a, pCDS->mDate);
11091  zipfileWrite32(a, pCDS->crc32);
11092  zipfileWrite32(a, pCDS->szCompressed);
11093  zipfileWrite32(a, pCDS->szUncompressed);
11094  assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
11095  zipfileWrite16(a, pCDS->nFile);
11096  zipfileWrite16(a, pCDS->nExtra);
11097  zipfileWrite16(a, pCDS->nComment);
11098  zipfileWrite16(a, pCDS->iDiskStart);
11099  zipfileWrite16(a, pCDS->iInternalAttr);
11100  zipfileWrite32(a, pCDS->iExternalAttr);
11101  zipfileWrite32(a, pCDS->iOffset);
11102
11103  memcpy(a, pCDS->zFile, pCDS->nFile);
11104  a += pCDS->nFile;
11105
11106  if( pEntry->aExtra ){
11107    int n = (int)pCDS->nExtra + (int)pCDS->nComment;
11108    memcpy(a, pEntry->aExtra, n);
11109    a += n;
11110  }else{
11111    assert( pCDS->nExtra==9 );
11112    zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
11113    zipfileWrite16(a, 5);
11114    *a++ = 0x01;
11115    zipfileWrite32(a, pEntry->mUnixTime);
11116  }
11117
11118  return a-aBuf;
11119}
11120
11121static int zipfileCommit(sqlite3_vtab *pVtab){
11122  ZipfileTab *pTab = (ZipfileTab*)pVtab;
11123  int rc = SQLITE_OK;
11124  if( pTab->pWriteFd ){
11125    i64 iOffset = pTab->szCurrent;
11126    ZipfileEntry *p;
11127    ZipfileEOCD eocd;
11128    int nEntry = 0;
11129
11130    /* Write out all entries */
11131    for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
11132      int n = zipfileSerializeCDS(p, pTab->aBuffer);
11133      rc = zipfileAppendData(pTab, pTab->aBuffer, n);
11134      nEntry++;
11135    }
11136
11137    /* Write out the EOCD record */
11138    eocd.iDisk = 0;
11139    eocd.iFirstDisk = 0;
11140    eocd.nEntry = (u16)nEntry;
11141    eocd.nEntryTotal = (u16)nEntry;
11142    eocd.nSize = (u32)(pTab->szCurrent - iOffset);
11143    eocd.iOffset = (u32)iOffset;
11144    rc = zipfileAppendEOCD(pTab, &eocd);
11145
11146    zipfileCleanupTransaction(pTab);
11147  }
11148  return rc;
11149}
11150
11151static int zipfileRollback(sqlite3_vtab *pVtab){
11152  return zipfileCommit(pVtab);
11153}
11154
11155static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
11156  ZipfileCsr *pCsr;
11157  for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11158    if( iId==pCsr->iId ) break;
11159  }
11160  return pCsr;
11161}
11162
11163static void zipfileFunctionCds(
11164  sqlite3_context *context,
11165  int argc,
11166  sqlite3_value **argv
11167){
11168  ZipfileCsr *pCsr;
11169  ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
11170  assert( argc>0 );
11171
11172  pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
11173  if( pCsr ){
11174    ZipfileCDS *p = &pCsr->pCurrent->cds;
11175    char *zRes = sqlite3_mprintf("{"
11176        "\"version-made-by\" : %u, "
11177        "\"version-to-extract\" : %u, "
11178        "\"flags\" : %u, "
11179        "\"compression\" : %u, "
11180        "\"time\" : %u, "
11181        "\"date\" : %u, "
11182        "\"crc32\" : %u, "
11183        "\"compressed-size\" : %u, "
11184        "\"uncompressed-size\" : %u, "
11185        "\"file-name-length\" : %u, "
11186        "\"extra-field-length\" : %u, "
11187        "\"file-comment-length\" : %u, "
11188        "\"disk-number-start\" : %u, "
11189        "\"internal-attr\" : %u, "
11190        "\"external-attr\" : %u, "
11191        "\"offset\" : %u }",
11192        (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
11193        (u32)p->flags, (u32)p->iCompression,
11194        (u32)p->mTime, (u32)p->mDate,
11195        (u32)p->crc32, (u32)p->szCompressed,
11196        (u32)p->szUncompressed, (u32)p->nFile,
11197        (u32)p->nExtra, (u32)p->nComment,
11198        (u32)p->iDiskStart, (u32)p->iInternalAttr,
11199        (u32)p->iExternalAttr, (u32)p->iOffset
11200    );
11201
11202    if( zRes==0 ){
11203      sqlite3_result_error_nomem(context);
11204    }else{
11205      sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
11206      sqlite3_free(zRes);
11207    }
11208  }
11209}
11210
11211/*
11212** xFindFunction method.
11213*/
11214static int zipfileFindFunction(
11215  sqlite3_vtab *pVtab,            /* Virtual table handle */
11216  int nArg,                       /* Number of SQL function arguments */
11217  const char *zName,              /* Name of SQL function */
11218  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
11219  void **ppArg                    /* OUT: User data for *pxFunc */
11220){
11221  (void)nArg;
11222  if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
11223    *pxFunc = zipfileFunctionCds;
11224    *ppArg = (void*)pVtab;
11225    return 1;
11226  }
11227  return 0;
11228}
11229
11230typedef struct ZipfileBuffer ZipfileBuffer;
11231struct ZipfileBuffer {
11232  u8 *a;                          /* Pointer to buffer */
11233  int n;                          /* Size of buffer in bytes */
11234  int nAlloc;                     /* Byte allocated at a[] */
11235};
11236
11237typedef struct ZipfileCtx ZipfileCtx;
11238struct ZipfileCtx {
11239  int nEntry;
11240  ZipfileBuffer body;
11241  ZipfileBuffer cds;
11242};
11243
11244static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
11245  if( pBuf->n+nByte>pBuf->nAlloc ){
11246    u8 *aNew;
11247    sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
11248    int nReq = pBuf->n + nByte;
11249
11250    while( nNew<nReq ) nNew = nNew*2;
11251    aNew = sqlite3_realloc64(pBuf->a, nNew);
11252    if( aNew==0 ) return SQLITE_NOMEM;
11253    pBuf->a = aNew;
11254    pBuf->nAlloc = (int)nNew;
11255  }
11256  return SQLITE_OK;
11257}
11258
11259/*
11260** xStep() callback for the zipfile() aggregate. This can be called in
11261** any of the following ways:
11262**
11263**   SELECT zipfile(name,data) ...
11264**   SELECT zipfile(name,mode,mtime,data) ...
11265**   SELECT zipfile(name,mode,mtime,data,method) ...
11266*/
11267static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
11268  ZipfileCtx *p;                  /* Aggregate function context */
11269  ZipfileEntry e;                 /* New entry to add to zip archive */
11270
11271  sqlite3_value *pName = 0;
11272  sqlite3_value *pMode = 0;
11273  sqlite3_value *pMtime = 0;
11274  sqlite3_value *pData = 0;
11275  sqlite3_value *pMethod = 0;
11276
11277  int bIsDir = 0;
11278  u32 mode;
11279  int rc = SQLITE_OK;
11280  char *zErr = 0;
11281
11282  int iMethod = -1;               /* Compression method to use (0 or 8) */
11283
11284  const u8 *aData = 0;            /* Possibly compressed data for new entry */
11285  int nData = 0;                  /* Size of aData[] in bytes */
11286  int szUncompressed = 0;         /* Size of data before compression */
11287  u8 *aFree = 0;                  /* Free this before returning */
11288  u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
11289
11290  char *zName = 0;                /* Path (name) of new entry */
11291  int nName = 0;                  /* Size of zName in bytes */
11292  char *zFree = 0;                /* Free this before returning */
11293  int nByte;
11294
11295  memset(&e, 0, sizeof(e));
11296  p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11297  if( p==0 ) return;
11298
11299  /* Martial the arguments into stack variables */
11300  if( nVal!=2 && nVal!=4 && nVal!=5 ){
11301    zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
11302    rc = SQLITE_ERROR;
11303    goto zipfile_step_out;
11304  }
11305  pName = apVal[0];
11306  if( nVal==2 ){
11307    pData = apVal[1];
11308  }else{
11309    pMode = apVal[1];
11310    pMtime = apVal[2];
11311    pData = apVal[3];
11312    if( nVal==5 ){
11313      pMethod = apVal[4];
11314    }
11315  }
11316
11317  /* Check that the 'name' parameter looks ok. */
11318  zName = (char*)sqlite3_value_text(pName);
11319  nName = sqlite3_value_bytes(pName);
11320  if( zName==0 ){
11321    zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
11322    rc = SQLITE_ERROR;
11323    goto zipfile_step_out;
11324  }
11325
11326  /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
11327  ** deflate compression) or NULL (choose automatically).  */
11328  if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
11329    iMethod = (int)sqlite3_value_int64(pMethod);
11330    if( iMethod!=0 && iMethod!=8 ){
11331      zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
11332      rc = SQLITE_ERROR;
11333      goto zipfile_step_out;
11334    }
11335  }
11336
11337  /* Now inspect the data. If this is NULL, then the new entry must be a
11338  ** directory.  Otherwise, figure out whether or not the data should
11339  ** be deflated or simply stored in the zip archive. */
11340  if( sqlite3_value_type(pData)==SQLITE_NULL ){
11341    bIsDir = 1;
11342    iMethod = 0;
11343  }else{
11344    aData = sqlite3_value_blob(pData);
11345    szUncompressed = nData = sqlite3_value_bytes(pData);
11346    iCrc32 = crc32(0, aData, nData);
11347    if( iMethod<0 || iMethod==8 ){
11348      int nOut = 0;
11349      rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
11350      if( rc!=SQLITE_OK ){
11351        goto zipfile_step_out;
11352      }
11353      if( iMethod==8 || nOut<nData ){
11354        aData = aFree;
11355        nData = nOut;
11356        iMethod = 8;
11357      }else{
11358        iMethod = 0;
11359      }
11360    }
11361  }
11362
11363  /* Decode the "mode" argument. */
11364  rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
11365  if( rc ) goto zipfile_step_out;
11366
11367  /* Decode the "mtime" argument. */
11368  e.mUnixTime = zipfileGetTime(pMtime);
11369
11370  /* If this is a directory entry, ensure that there is exactly one '/'
11371  ** at the end of the path. Or, if this is not a directory and the path
11372  ** ends in '/' it is an error. */
11373  if( bIsDir==0 ){
11374    if( nName>0 && zName[nName-1]=='/' ){
11375      zErr = sqlite3_mprintf("non-directory name must not end with /");
11376      rc = SQLITE_ERROR;
11377      goto zipfile_step_out;
11378    }
11379  }else{
11380    if( nName==0 || zName[nName-1]!='/' ){
11381      zName = zFree = sqlite3_mprintf("%s/", zName);
11382      if( zName==0 ){
11383        rc = SQLITE_NOMEM;
11384        goto zipfile_step_out;
11385      }
11386      nName = (int)strlen(zName);
11387    }else{
11388      while( nName>1 && zName[nName-2]=='/' ) nName--;
11389    }
11390  }
11391
11392  /* Assemble the ZipfileEntry object for the new zip archive entry */
11393  e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11394  e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11395  e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11396  e.cds.iCompression = (u16)iMethod;
11397  zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
11398  e.cds.crc32 = iCrc32;
11399  e.cds.szCompressed = nData;
11400  e.cds.szUncompressed = szUncompressed;
11401  e.cds.iExternalAttr = (mode<<16);
11402  e.cds.iOffset = p->body.n;
11403  e.cds.nFile = (u16)nName;
11404  e.cds.zFile = zName;
11405
11406  /* Append the LFH to the body of the new archive */
11407  nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
11408  if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
11409  p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
11410
11411  /* Append the data to the body of the new archive */
11412  if( nData>0 ){
11413    if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
11414    memcpy(&p->body.a[p->body.n], aData, nData);
11415    p->body.n += nData;
11416  }
11417
11418  /* Append the CDS record to the directory of the new archive */
11419  nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
11420  if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
11421  p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
11422
11423  /* Increment the count of entries in the archive */
11424  p->nEntry++;
11425
11426 zipfile_step_out:
11427  sqlite3_free(aFree);
11428  sqlite3_free(zFree);
11429  if( rc ){
11430    if( zErr ){
11431      sqlite3_result_error(pCtx, zErr, -1);
11432    }else{
11433      sqlite3_result_error_code(pCtx, rc);
11434    }
11435  }
11436  sqlite3_free(zErr);
11437}
11438
11439/*
11440** xFinalize() callback for zipfile aggregate function.
11441*/
11442static void zipfileFinal(sqlite3_context *pCtx){
11443  ZipfileCtx *p;
11444  ZipfileEOCD eocd;
11445  sqlite3_int64 nZip;
11446  u8 *aZip;
11447
11448  p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11449  if( p==0 ) return;
11450  if( p->nEntry>0 ){
11451    memset(&eocd, 0, sizeof(eocd));
11452    eocd.nEntry = (u16)p->nEntry;
11453    eocd.nEntryTotal = (u16)p->nEntry;
11454    eocd.nSize = p->cds.n;
11455    eocd.iOffset = p->body.n;
11456
11457    nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
11458    aZip = (u8*)sqlite3_malloc64(nZip);
11459    if( aZip==0 ){
11460      sqlite3_result_error_nomem(pCtx);
11461    }else{
11462      memcpy(aZip, p->body.a, p->body.n);
11463      memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
11464      zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
11465      sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
11466    }
11467  }
11468
11469  sqlite3_free(p->body.a);
11470  sqlite3_free(p->cds.a);
11471}
11472
11473
11474/*
11475** Register the "zipfile" virtual table.
11476*/
11477static int zipfileRegister(sqlite3 *db){
11478  static sqlite3_module zipfileModule = {
11479    1,                         /* iVersion */
11480    zipfileConnect,            /* xCreate */
11481    zipfileConnect,            /* xConnect */
11482    zipfileBestIndex,          /* xBestIndex */
11483    zipfileDisconnect,         /* xDisconnect */
11484    zipfileDisconnect,         /* xDestroy */
11485    zipfileOpen,               /* xOpen - open a cursor */
11486    zipfileClose,              /* xClose - close a cursor */
11487    zipfileFilter,             /* xFilter - configure scan constraints */
11488    zipfileNext,               /* xNext - advance a cursor */
11489    zipfileEof,                /* xEof - check for end of scan */
11490    zipfileColumn,             /* xColumn - read data */
11491    0,                         /* xRowid - read data */
11492    zipfileUpdate,             /* xUpdate */
11493    zipfileBegin,              /* xBegin */
11494    0,                         /* xSync */
11495    zipfileCommit,             /* xCommit */
11496    zipfileRollback,           /* xRollback */
11497    zipfileFindFunction,       /* xFindMethod */
11498    0,                         /* xRename */
11499    0,                         /* xSavepoint */
11500    0,                         /* xRelease */
11501    0,                         /* xRollback */
11502    0,                         /* xShadowName */
11503    0                          /* xIntegrity */
11504  };
11505
11506  int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
11507  if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
11508  if( rc==SQLITE_OK ){
11509    rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
11510        zipfileStep, zipfileFinal
11511    );
11512  }
11513  assert( sizeof(i64)==8 );
11514  assert( sizeof(u32)==4 );
11515  assert( sizeof(u16)==2 );
11516  assert( sizeof(u8)==1 );
11517  return rc;
11518}
11519#else         /* SQLITE_OMIT_VIRTUALTABLE */
11520# define zipfileRegister(x) SQLITE_OK
11521#endif
11522
11523#ifdef _WIN32
11524
11525#endif
11526int sqlite3_zipfile_init(
11527  sqlite3 *db,
11528  char **pzErrMsg,
11529  const sqlite3_api_routines *pApi
11530){
11531  SQLITE_EXTENSION_INIT2(pApi);
11532  (void)pzErrMsg;  /* Unused parameter */
11533  return zipfileRegister(db);
11534}
11535
11536/************************* End ../ext/misc/zipfile.c ********************/
11537/************************* Begin ../ext/misc/sqlar.c ******************/
11538/*
11539** 2017-12-17
11540**
11541** The author disclaims copyright to this source code.  In place of
11542** a legal notice, here is a blessing:
11543**
11544**    May you do good and not evil.
11545**    May you find forgiveness for yourself and forgive others.
11546**    May you share freely, never taking more than you give.
11547**
11548******************************************************************************
11549**
11550** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
11551** for working with sqlar archives and used by the shell tool's built-in
11552** sqlar support.
11553*/
11554/* #include "sqlite3ext.h" */
11555SQLITE_EXTENSION_INIT1
11556#include <zlib.h>
11557#include <assert.h>
11558
11559/*
11560** Implementation of the "sqlar_compress(X)" SQL function.
11561**
11562** If the type of X is SQLITE_BLOB, and compressing that blob using
11563** zlib utility function compress() yields a smaller blob, return the
11564** compressed blob. Otherwise, return a copy of X.
11565**
11566** SQLar uses the "zlib format" for compressed content.  The zlib format
11567** contains a two-byte identification header and a four-byte checksum at
11568** the end.  This is different from ZIP which uses the raw deflate format.
11569**
11570** Future enhancements to SQLar might add support for new compression formats.
11571** If so, those new formats will be identified by alternative headers in the
11572** compressed data.
11573*/
11574static void sqlarCompressFunc(
11575  sqlite3_context *context,
11576  int argc,
11577  sqlite3_value **argv
11578){
11579  assert( argc==1 );
11580  if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
11581    const Bytef *pData = sqlite3_value_blob(argv[0]);
11582    uLong nData = sqlite3_value_bytes(argv[0]);
11583    uLongf nOut = compressBound(nData);
11584    Bytef *pOut;
11585
11586    pOut = (Bytef*)sqlite3_malloc(nOut);
11587    if( pOut==0 ){
11588      sqlite3_result_error_nomem(context);
11589      return;
11590    }else{
11591      if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
11592        sqlite3_result_error(context, "error in compress()", -1);
11593      }else if( nOut<nData ){
11594        sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
11595      }else{
11596        sqlite3_result_value(context, argv[0]);
11597      }
11598      sqlite3_free(pOut);
11599    }
11600  }else{
11601    sqlite3_result_value(context, argv[0]);
11602  }
11603}
11604
11605/*
11606** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
11607**
11608** Parameter SZ is interpreted as an integer. If it is less than or
11609** equal to zero, then this function returns a copy of X. Or, if
11610** SZ is equal to the size of X when interpreted as a blob, also
11611** return a copy of X. Otherwise, decompress blob X using zlib
11612** utility function uncompress() and return the results (another
11613** blob).
11614*/
11615static void sqlarUncompressFunc(
11616  sqlite3_context *context,
11617  int argc,
11618  sqlite3_value **argv
11619){
11620  uLong nData;
11621  uLongf sz;
11622
11623  assert( argc==2 );
11624  sz = sqlite3_value_int(argv[1]);
11625
11626  if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
11627    sqlite3_result_value(context, argv[0]);
11628  }else{
11629    const Bytef *pData= sqlite3_value_blob(argv[0]);
11630    Bytef *pOut = sqlite3_malloc(sz);
11631    if( pOut==0 ){
11632      sqlite3_result_error_nomem(context);
11633    }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
11634      sqlite3_result_error(context, "error in uncompress()", -1);
11635    }else{
11636      sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
11637    }
11638    sqlite3_free(pOut);
11639  }
11640}
11641
11642#ifdef _WIN32
11643
11644#endif
11645int sqlite3_sqlar_init(
11646  sqlite3 *db,
11647  char **pzErrMsg,
11648  const sqlite3_api_routines *pApi
11649){
11650  int rc = SQLITE_OK;
11651  SQLITE_EXTENSION_INIT2(pApi);
11652  (void)pzErrMsg;  /* Unused parameter */
11653  rc = sqlite3_create_function(db, "sqlar_compress", 1,
11654                               SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11655                               sqlarCompressFunc, 0, 0);
11656  if( rc==SQLITE_OK ){
11657    rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
11658                                 SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11659                                 sqlarUncompressFunc, 0, 0);
11660  }
11661  return rc;
11662}
11663
11664/************************* End ../ext/misc/sqlar.c ********************/
11665#endif
11666/************************* Begin ../ext/expert/sqlite3expert.h ******************/
11667/*
11668** 2017 April 07
11669**
11670** The author disclaims copyright to this source code.  In place of
11671** a legal notice, here is a blessing:
11672**
11673**    May you do good and not evil.
11674**    May you find forgiveness for yourself and forgive others.
11675**    May you share freely, never taking more than you give.
11676**
11677*************************************************************************
11678*/
11679#if !defined(SQLITEEXPERT_H)
11680#define SQLITEEXPERT_H 1
11681/* #include "sqlite3.h" */
11682
11683typedef struct sqlite3expert sqlite3expert;
11684
11685/*
11686** Create a new sqlite3expert object.
11687**
11688** If successful, a pointer to the new object is returned and (*pzErr) set
11689** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
11690** an English-language error message. In this case it is the responsibility
11691** of the caller to eventually free the error message buffer using
11692** sqlite3_free().
11693*/
11694sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
11695
11696/*
11697** Configure an sqlite3expert object.
11698**
11699** EXPERT_CONFIG_SAMPLE:
11700**   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
11701**   each candidate index. This involves scanning and sorting the entire
11702**   contents of each user database table once for each candidate index
11703**   associated with the table. For large databases, this can be
11704**   prohibitively slow. This option allows the sqlite3expert object to
11705**   be configured so that sqlite_stat1 data is instead generated based on a
11706**   subset of each table, or so that no sqlite_stat1 data is used at all.
11707**
11708**   A single integer argument is passed to this option. If the value is less
11709**   than or equal to zero, then no sqlite_stat1 data is generated or used by
11710**   the analysis - indexes are recommended based on the database schema only.
11711**   Or, if the value is 100 or greater, complete sqlite_stat1 data is
11712**   generated for each candidate index (this is the default). Finally, if the
11713**   value falls between 0 and 100, then it represents the percentage of user
11714**   table rows that should be considered when generating sqlite_stat1 data.
11715**
11716**   Examples:
11717**
11718**     // Do not generate any sqlite_stat1 data
11719**     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
11720**
11721**     // Generate sqlite_stat1 data based on 10% of the rows in each table.
11722**     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
11723*/
11724int sqlite3_expert_config(sqlite3expert *p, int op, ...);
11725
11726#define EXPERT_CONFIG_SAMPLE 1    /* int */
11727
11728/*
11729** Specify zero or more SQL statements to be included in the analysis.
11730**
11731** Buffer zSql must contain zero or more complete SQL statements. This
11732** function parses all statements contained in the buffer and adds them
11733** to the internal list of statements to analyze. If successful, SQLITE_OK
11734** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11735** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11736** may be set to point to an English language error message. In this case
11737** the caller is responsible for eventually freeing the error message buffer
11738** using sqlite3_free().
11739**
11740** If an error does occur while processing one of the statements in the
11741** buffer passed as the second argument, none of the statements in the
11742** buffer are added to the analysis.
11743**
11744** This function must be called before sqlite3_expert_analyze(). If a call
11745** to this function is made on an sqlite3expert object that has already
11746** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
11747** immediately and no statements are added to the analysis.
11748*/
11749int sqlite3_expert_sql(
11750  sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
11751  const char *zSql,               /* SQL statement(s) to add */
11752  char **pzErr                    /* OUT: Error message (if any) */
11753);
11754
11755
11756/*
11757** This function is called after the sqlite3expert object has been configured
11758** with all SQL statements using sqlite3_expert_sql() to actually perform
11759** the analysis. Once this function has been called, it is not possible to
11760** add further SQL statements to the analysis.
11761**
11762** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
11763** an error occurs, an SQLite error code is returned and (*pzErr) set to
11764** point to a buffer containing an English language error message. In this
11765** case it is the responsibility of the caller to eventually free the buffer
11766** using sqlite3_free().
11767**
11768** If an error does occur within this function, the sqlite3expert object
11769** is no longer useful for any purpose. At that point it is no longer
11770** possible to add further SQL statements to the object or to re-attempt
11771** the analysis. The sqlite3expert object must still be freed using a call
11772** sqlite3_expert_destroy().
11773*/
11774int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
11775
11776/*
11777** Return the total number of statements loaded using sqlite3_expert_sql().
11778** The total number of SQL statements may be different from the total number
11779** to calls to sqlite3_expert_sql().
11780*/
11781int sqlite3_expert_count(sqlite3expert*);
11782
11783/*
11784** Return a component of the report.
11785**
11786** This function is called after sqlite3_expert_analyze() to extract the
11787** results of the analysis. Each call to this function returns either a
11788** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11789** The value passed as the third argument must be one of the EXPERT_REPORT_*
11790** #define constants defined below.
11791**
11792** For some EXPERT_REPORT_* parameters, the buffer returned contains
11793** information relating to a specific SQL statement. In these cases that
11794** SQL statement is identified by the value passed as the second argument.
11795** SQL statements are numbered from 0 in the order in which they are parsed.
11796** If an out-of-range value (less than zero or equal to or greater than the
11797** value returned by sqlite3_expert_count()) is passed as the second argument
11798** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
11799**
11800** EXPERT_REPORT_SQL:
11801**   Return the text of SQL statement iStmt.
11802**
11803** EXPERT_REPORT_INDEXES:
11804**   Return a buffer containing the CREATE INDEX statements for all recommended
11805**   indexes for statement iStmt. If there are no new recommeded indexes, NULL
11806**   is returned.
11807**
11808** EXPERT_REPORT_PLAN:
11809**   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
11810**   iStmt after the proposed indexes have been added to the database schema.
11811**
11812** EXPERT_REPORT_CANDIDATES:
11813**   Return a pointer to a buffer containing the CREATE INDEX statements
11814**   for all indexes that were tested (for all SQL statements). The iStmt
11815**   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
11816*/
11817const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
11818
11819/*
11820** Values for the third argument passed to sqlite3_expert_report().
11821*/
11822#define EXPERT_REPORT_SQL        1
11823#define EXPERT_REPORT_INDEXES    2
11824#define EXPERT_REPORT_PLAN       3
11825#define EXPERT_REPORT_CANDIDATES 4
11826
11827/*
11828** Free an (sqlite3expert*) handle and all associated resources. There
11829** should be one call to this function for each successful call to
11830** sqlite3-expert_new().
11831*/
11832void sqlite3_expert_destroy(sqlite3expert*);
11833
11834#endif  /* !defined(SQLITEEXPERT_H) */
11835
11836/************************* End ../ext/expert/sqlite3expert.h ********************/
11837/************************* Begin ../ext/expert/sqlite3expert.c ******************/
11838/*
11839** 2017 April 09
11840**
11841** The author disclaims copyright to this source code.  In place of
11842** a legal notice, here is a blessing:
11843**
11844**    May you do good and not evil.
11845**    May you find forgiveness for yourself and forgive others.
11846**    May you share freely, never taking more than you give.
11847**
11848*************************************************************************
11849*/
11850/* #include "sqlite3expert.h" */
11851#include <assert.h>
11852#include <string.h>
11853#include <stdio.h>
11854
11855#if !defined(SQLITE_AMALGAMATION)
11856#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11857# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
11858#endif
11859#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
11860# define ALWAYS(X)      (1)
11861# define NEVER(X)       (0)
11862#elif !defined(NDEBUG)
11863# define ALWAYS(X)      ((X)?1:(assert(0),0))
11864# define NEVER(X)       ((X)?(assert(0),1):0)
11865#else
11866# define ALWAYS(X)      (X)
11867# define NEVER(X)       (X)
11868#endif
11869#endif /* !defined(SQLITE_AMALGAMATION) */
11870
11871
11872#ifndef SQLITE_OMIT_VIRTUALTABLE
11873
11874/* typedef sqlite3_int64 i64; */
11875/* typedef sqlite3_uint64 u64; */
11876
11877typedef struct IdxColumn IdxColumn;
11878typedef struct IdxConstraint IdxConstraint;
11879typedef struct IdxScan IdxScan;
11880typedef struct IdxStatement IdxStatement;
11881typedef struct IdxTable IdxTable;
11882typedef struct IdxWrite IdxWrite;
11883
11884#define STRLEN  (int)strlen
11885
11886/*
11887** A temp table name that we assume no user database will actually use.
11888** If this assumption proves incorrect triggers on the table with the
11889** conflicting name will be ignored.
11890*/
11891#define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
11892
11893/*
11894** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
11895** any other type of single-ended range constraint on a column).
11896**
11897** pLink:
11898**   Used to temporarily link IdxConstraint objects into lists while
11899**   creating candidate indexes.
11900*/
11901struct IdxConstraint {
11902  char *zColl;                    /* Collation sequence */
11903  int bRange;                     /* True for range, false for eq */
11904  int iCol;                       /* Constrained table column */
11905  int bFlag;                      /* Used by idxFindCompatible() */
11906  int bDesc;                      /* True if ORDER BY <expr> DESC */
11907  IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
11908  IdxConstraint *pLink;           /* See above */
11909};
11910
11911/*
11912** A single scan of a single table.
11913*/
11914struct IdxScan {
11915  IdxTable *pTab;                 /* Associated table object */
11916  int iDb;                        /* Database containing table zTable */
11917  i64 covering;                   /* Mask of columns required for cov. index */
11918  IdxConstraint *pOrder;          /* ORDER BY columns */
11919  IdxConstraint *pEq;             /* List of == constraints */
11920  IdxConstraint *pRange;          /* List of < constraints */
11921  IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
11922};
11923
11924/*
11925** Information regarding a single database table. Extracted from
11926** "PRAGMA table_info" by function idxGetTableInfo().
11927*/
11928struct IdxColumn {
11929  char *zName;
11930  char *zColl;
11931  int iPk;
11932};
11933struct IdxTable {
11934  int nCol;
11935  char *zName;                    /* Table name */
11936  IdxColumn *aCol;
11937  IdxTable *pNext;                /* Next table in linked list of all tables */
11938};
11939
11940/*
11941** An object of the following type is created for each unique table/write-op
11942** seen. The objects are stored in a singly-linked list beginning at
11943** sqlite3expert.pWrite.
11944*/
11945struct IdxWrite {
11946  IdxTable *pTab;
11947  int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
11948  IdxWrite *pNext;
11949};
11950
11951/*
11952** Each statement being analyzed is represented by an instance of this
11953** structure.
11954*/
11955struct IdxStatement {
11956  int iId;                        /* Statement number */
11957  char *zSql;                     /* SQL statement */
11958  char *zIdx;                     /* Indexes */
11959  char *zEQP;                     /* Plan */
11960  IdxStatement *pNext;
11961};
11962
11963
11964/*
11965** A hash table for storing strings. With space for a payload string
11966** with each entry. Methods are:
11967**
11968**   idxHashInit()
11969**   idxHashClear()
11970**   idxHashAdd()
11971**   idxHashSearch()
11972*/
11973#define IDX_HASH_SIZE 1023
11974typedef struct IdxHashEntry IdxHashEntry;
11975typedef struct IdxHash IdxHash;
11976struct IdxHashEntry {
11977  char *zKey;                     /* nul-terminated key */
11978  char *zVal;                     /* nul-terminated value string */
11979  char *zVal2;                    /* nul-terminated value string 2 */
11980  IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
11981  IdxHashEntry *pNext;            /* Next entry in hash */
11982};
11983struct IdxHash {
11984  IdxHashEntry *pFirst;
11985  IdxHashEntry *aHash[IDX_HASH_SIZE];
11986};
11987
11988/*
11989** sqlite3expert object.
11990*/
11991struct sqlite3expert {
11992  int iSample;                    /* Percentage of tables to sample for stat1 */
11993  sqlite3 *db;                    /* User database */
11994  sqlite3 *dbm;                   /* In-memory db for this analysis */
11995  sqlite3 *dbv;                   /* Vtab schema for this analysis */
11996  IdxTable *pTable;               /* List of all IdxTable objects */
11997  IdxScan *pScan;                 /* List of scan objects */
11998  IdxWrite *pWrite;               /* List of write objects */
11999  IdxStatement *pStatement;       /* List of IdxStatement objects */
12000  int bRun;                       /* True once analysis has run */
12001  char **pzErrmsg;
12002  int rc;                         /* Error code from whereinfo hook */
12003  IdxHash hIdx;                   /* Hash containing all candidate indexes */
12004  char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
12005};
12006
12007
12008/*
12009** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
12010** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
12011*/
12012static void *idxMalloc(int *pRc, int nByte){
12013  void *pRet;
12014  assert( *pRc==SQLITE_OK );
12015  assert( nByte>0 );
12016  pRet = sqlite3_malloc(nByte);
12017  if( pRet ){
12018    memset(pRet, 0, nByte);
12019  }else{
12020    *pRc = SQLITE_NOMEM;
12021  }
12022  return pRet;
12023}
12024
12025/*
12026** Initialize an IdxHash hash table.
12027*/
12028static void idxHashInit(IdxHash *pHash){
12029  memset(pHash, 0, sizeof(IdxHash));
12030}
12031
12032/*
12033** Reset an IdxHash hash table.
12034*/
12035static void idxHashClear(IdxHash *pHash){
12036  int i;
12037  for(i=0; i<IDX_HASH_SIZE; i++){
12038    IdxHashEntry *pEntry;
12039    IdxHashEntry *pNext;
12040    for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
12041      pNext = pEntry->pHashNext;
12042      sqlite3_free(pEntry->zVal2);
12043      sqlite3_free(pEntry);
12044    }
12045  }
12046  memset(pHash, 0, sizeof(IdxHash));
12047}
12048
12049/*
12050** Return the index of the hash bucket that the string specified by the
12051** arguments to this function belongs.
12052*/
12053static int idxHashString(const char *z, int n){
12054  unsigned int ret = 0;
12055  int i;
12056  for(i=0; i<n; i++){
12057    ret += (ret<<3) + (unsigned char)(z[i]);
12058  }
12059  return (int)(ret % IDX_HASH_SIZE);
12060}
12061
12062/*
12063** If zKey is already present in the hash table, return non-zero and do
12064** nothing. Otherwise, add an entry with key zKey and payload string zVal to
12065** the hash table passed as the second argument.
12066*/
12067static int idxHashAdd(
12068  int *pRc,
12069  IdxHash *pHash,
12070  const char *zKey,
12071  const char *zVal
12072){
12073  int nKey = STRLEN(zKey);
12074  int iHash = idxHashString(zKey, nKey);
12075  int nVal = (zVal ? STRLEN(zVal) : 0);
12076  IdxHashEntry *pEntry;
12077  assert( iHash>=0 );
12078  for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12079    if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12080      return 1;
12081    }
12082  }
12083  pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
12084  if( pEntry ){
12085    pEntry->zKey = (char*)&pEntry[1];
12086    memcpy(pEntry->zKey, zKey, nKey);
12087    if( zVal ){
12088      pEntry->zVal = &pEntry->zKey[nKey+1];
12089      memcpy(pEntry->zVal, zVal, nVal);
12090    }
12091    pEntry->pHashNext = pHash->aHash[iHash];
12092    pHash->aHash[iHash] = pEntry;
12093
12094    pEntry->pNext = pHash->pFirst;
12095    pHash->pFirst = pEntry;
12096  }
12097  return 0;
12098}
12099
12100/*
12101** If zKey/nKey is present in the hash table, return a pointer to the
12102** hash-entry object.
12103*/
12104static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
12105  int iHash;
12106  IdxHashEntry *pEntry;
12107  if( nKey<0 ) nKey = STRLEN(zKey);
12108  iHash = idxHashString(zKey, nKey);
12109  assert( iHash>=0 );
12110  for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12111    if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12112      return pEntry;
12113    }
12114  }
12115  return 0;
12116}
12117
12118/*
12119** If the hash table contains an entry with a key equal to the string
12120** passed as the final two arguments to this function, return a pointer
12121** to the payload string. Otherwise, if zKey/nKey is not present in the
12122** hash table, return NULL.
12123*/
12124static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
12125  IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
12126  if( pEntry ) return pEntry->zVal;
12127  return 0;
12128}
12129
12130/*
12131** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
12132** variable to point to a copy of nul-terminated string zColl.
12133*/
12134static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
12135  IdxConstraint *pNew;
12136  int nColl = STRLEN(zColl);
12137
12138  assert( *pRc==SQLITE_OK );
12139  pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
12140  if( pNew ){
12141    pNew->zColl = (char*)&pNew[1];
12142    memcpy(pNew->zColl, zColl, nColl+1);
12143  }
12144  return pNew;
12145}
12146
12147/*
12148** An error associated with database handle db has just occurred. Pass
12149** the error message to callback function xOut.
12150*/
12151static void idxDatabaseError(
12152  sqlite3 *db,                    /* Database handle */
12153  char **pzErrmsg                 /* Write error here */
12154){
12155  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
12156}
12157
12158/*
12159** Prepare an SQL statement.
12160*/
12161static int idxPrepareStmt(
12162  sqlite3 *db,                    /* Database handle to compile against */
12163  sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12164  char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12165  const char *zSql                /* SQL statement to compile */
12166){
12167  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12168  if( rc!=SQLITE_OK ){
12169    *ppStmt = 0;
12170    idxDatabaseError(db, pzErrmsg);
12171  }
12172  return rc;
12173}
12174
12175/*
12176** Prepare an SQL statement using the results of a printf() formatting.
12177*/
12178static int idxPrintfPrepareStmt(
12179  sqlite3 *db,                    /* Database handle to compile against */
12180  sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12181  char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12182  const char *zFmt,               /* printf() format of SQL statement */
12183  ...                             /* Trailing printf() arguments */
12184){
12185  va_list ap;
12186  int rc;
12187  char *zSql;
12188  va_start(ap, zFmt);
12189  zSql = sqlite3_vmprintf(zFmt, ap);
12190  if( zSql==0 ){
12191    rc = SQLITE_NOMEM;
12192  }else{
12193    rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
12194    sqlite3_free(zSql);
12195  }
12196  va_end(ap);
12197  return rc;
12198}
12199
12200
12201/*************************************************************************
12202** Beginning of virtual table implementation.
12203*/
12204typedef struct ExpertVtab ExpertVtab;
12205struct ExpertVtab {
12206  sqlite3_vtab base;
12207  IdxTable *pTab;
12208  sqlite3expert *pExpert;
12209};
12210
12211typedef struct ExpertCsr ExpertCsr;
12212struct ExpertCsr {
12213  sqlite3_vtab_cursor base;
12214  sqlite3_stmt *pData;
12215};
12216
12217static char *expertDequote(const char *zIn){
12218  int n = STRLEN(zIn);
12219  char *zRet = sqlite3_malloc(n);
12220
12221  assert( zIn[0]=='\'' );
12222  assert( zIn[n-1]=='\'' );
12223
12224  if( zRet ){
12225    int iOut = 0;
12226    int iIn = 0;
12227    for(iIn=1; iIn<(n-1); iIn++){
12228      if( zIn[iIn]=='\'' ){
12229        assert( zIn[iIn+1]=='\'' );
12230        iIn++;
12231      }
12232      zRet[iOut++] = zIn[iIn];
12233    }
12234    zRet[iOut] = '\0';
12235  }
12236
12237  return zRet;
12238}
12239
12240/*
12241** This function is the implementation of both the xConnect and xCreate
12242** methods of the r-tree virtual table.
12243**
12244**   argv[0]   -> module name
12245**   argv[1]   -> database name
12246**   argv[2]   -> table name
12247**   argv[...] -> column names...
12248*/
12249static int expertConnect(
12250  sqlite3 *db,
12251  void *pAux,
12252  int argc, const char *const*argv,
12253  sqlite3_vtab **ppVtab,
12254  char **pzErr
12255){
12256  sqlite3expert *pExpert = (sqlite3expert*)pAux;
12257  ExpertVtab *p = 0;
12258  int rc;
12259
12260  if( argc!=4 ){
12261    *pzErr = sqlite3_mprintf("internal error!");
12262    rc = SQLITE_ERROR;
12263  }else{
12264    char *zCreateTable = expertDequote(argv[3]);
12265    if( zCreateTable ){
12266      rc = sqlite3_declare_vtab(db, zCreateTable);
12267      if( rc==SQLITE_OK ){
12268        p = idxMalloc(&rc, sizeof(ExpertVtab));
12269      }
12270      if( rc==SQLITE_OK ){
12271        p->pExpert = pExpert;
12272        p->pTab = pExpert->pTable;
12273        assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
12274      }
12275      sqlite3_free(zCreateTable);
12276    }else{
12277      rc = SQLITE_NOMEM;
12278    }
12279  }
12280
12281  *ppVtab = (sqlite3_vtab*)p;
12282  return rc;
12283}
12284
12285static int expertDisconnect(sqlite3_vtab *pVtab){
12286  ExpertVtab *p = (ExpertVtab*)pVtab;
12287  sqlite3_free(p);
12288  return SQLITE_OK;
12289}
12290
12291static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
12292  ExpertVtab *p = (ExpertVtab*)pVtab;
12293  int rc = SQLITE_OK;
12294  int n = 0;
12295  IdxScan *pScan;
12296  const int opmask =
12297    SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
12298    SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
12299    SQLITE_INDEX_CONSTRAINT_LE;
12300
12301  pScan = idxMalloc(&rc, sizeof(IdxScan));
12302  if( pScan ){
12303    int i;
12304
12305    /* Link the new scan object into the list */
12306    pScan->pTab = p->pTab;
12307    pScan->pNextScan = p->pExpert->pScan;
12308    p->pExpert->pScan = pScan;
12309
12310    /* Add the constraints to the IdxScan object */
12311    for(i=0; i<pIdxInfo->nConstraint; i++){
12312      struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
12313      if( pCons->usable
12314       && pCons->iColumn>=0
12315       && p->pTab->aCol[pCons->iColumn].iPk==0
12316       && (pCons->op & opmask)
12317      ){
12318        IdxConstraint *pNew;
12319        const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
12320        pNew = idxNewConstraint(&rc, zColl);
12321        if( pNew ){
12322          pNew->iCol = pCons->iColumn;
12323          if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
12324            pNew->pNext = pScan->pEq;
12325            pScan->pEq = pNew;
12326          }else{
12327            pNew->bRange = 1;
12328            pNew->pNext = pScan->pRange;
12329            pScan->pRange = pNew;
12330          }
12331        }
12332        n++;
12333        pIdxInfo->aConstraintUsage[i].argvIndex = n;
12334      }
12335    }
12336
12337    /* Add the ORDER BY to the IdxScan object */
12338    for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
12339      int iCol = pIdxInfo->aOrderBy[i].iColumn;
12340      if( iCol>=0 ){
12341        IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
12342        if( pNew ){
12343          pNew->iCol = iCol;
12344          pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
12345          pNew->pNext = pScan->pOrder;
12346          pNew->pLink = pScan->pOrder;
12347          pScan->pOrder = pNew;
12348          n++;
12349        }
12350      }
12351    }
12352  }
12353
12354  pIdxInfo->estimatedCost = 1000000.0 / (n+1);
12355  return rc;
12356}
12357
12358static int expertUpdate(
12359  sqlite3_vtab *pVtab,
12360  int nData,
12361  sqlite3_value **azData,
12362  sqlite_int64 *pRowid
12363){
12364  (void)pVtab;
12365  (void)nData;
12366  (void)azData;
12367  (void)pRowid;
12368  return SQLITE_OK;
12369}
12370
12371/*
12372** Virtual table module xOpen method.
12373*/
12374static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
12375  int rc = SQLITE_OK;
12376  ExpertCsr *pCsr;
12377  (void)pVTab;
12378  pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
12379  *ppCursor = (sqlite3_vtab_cursor*)pCsr;
12380  return rc;
12381}
12382
12383/*
12384** Virtual table module xClose method.
12385*/
12386static int expertClose(sqlite3_vtab_cursor *cur){
12387  ExpertCsr *pCsr = (ExpertCsr*)cur;
12388  sqlite3_finalize(pCsr->pData);
12389  sqlite3_free(pCsr);
12390  return SQLITE_OK;
12391}
12392
12393/*
12394** Virtual table module xEof method.
12395**
12396** Return non-zero if the cursor does not currently point to a valid
12397** record (i.e if the scan has finished), or zero otherwise.
12398*/
12399static int expertEof(sqlite3_vtab_cursor *cur){
12400  ExpertCsr *pCsr = (ExpertCsr*)cur;
12401  return pCsr->pData==0;
12402}
12403
12404/*
12405** Virtual table module xNext method.
12406*/
12407static int expertNext(sqlite3_vtab_cursor *cur){
12408  ExpertCsr *pCsr = (ExpertCsr*)cur;
12409  int rc = SQLITE_OK;
12410
12411  assert( pCsr->pData );
12412  rc = sqlite3_step(pCsr->pData);
12413  if( rc!=SQLITE_ROW ){
12414    rc = sqlite3_finalize(pCsr->pData);
12415    pCsr->pData = 0;
12416  }else{
12417    rc = SQLITE_OK;
12418  }
12419
12420  return rc;
12421}
12422
12423/*
12424** Virtual table module xRowid method.
12425*/
12426static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
12427  (void)cur;
12428  *pRowid = 0;
12429  return SQLITE_OK;
12430}
12431
12432/*
12433** Virtual table module xColumn method.
12434*/
12435static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
12436  ExpertCsr *pCsr = (ExpertCsr*)cur;
12437  sqlite3_value *pVal;
12438  pVal = sqlite3_column_value(pCsr->pData, i);
12439  if( pVal ){
12440    sqlite3_result_value(ctx, pVal);
12441  }
12442  return SQLITE_OK;
12443}
12444
12445/*
12446** Virtual table module xFilter method.
12447*/
12448static int expertFilter(
12449  sqlite3_vtab_cursor *cur,
12450  int idxNum, const char *idxStr,
12451  int argc, sqlite3_value **argv
12452){
12453  ExpertCsr *pCsr = (ExpertCsr*)cur;
12454  ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
12455  sqlite3expert *pExpert = pVtab->pExpert;
12456  int rc;
12457
12458  (void)idxNum;
12459  (void)idxStr;
12460  (void)argc;
12461  (void)argv;
12462  rc = sqlite3_finalize(pCsr->pData);
12463  pCsr->pData = 0;
12464  if( rc==SQLITE_OK ){
12465    rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
12466        "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
12467    );
12468  }
12469
12470  if( rc==SQLITE_OK ){
12471    rc = expertNext(cur);
12472  }
12473  return rc;
12474}
12475
12476static int idxRegisterVtab(sqlite3expert *p){
12477  static sqlite3_module expertModule = {
12478    2,                            /* iVersion */
12479    expertConnect,                /* xCreate - create a table */
12480    expertConnect,                /* xConnect - connect to an existing table */
12481    expertBestIndex,              /* xBestIndex - Determine search strategy */
12482    expertDisconnect,             /* xDisconnect - Disconnect from a table */
12483    expertDisconnect,             /* xDestroy - Drop a table */
12484    expertOpen,                   /* xOpen - open a cursor */
12485    expertClose,                  /* xClose - close a cursor */
12486    expertFilter,                 /* xFilter - configure scan constraints */
12487    expertNext,                   /* xNext - advance a cursor */
12488    expertEof,                    /* xEof */
12489    expertColumn,                 /* xColumn - read data */
12490    expertRowid,                  /* xRowid - read data */
12491    expertUpdate,                 /* xUpdate - write data */
12492    0,                            /* xBegin - begin transaction */
12493    0,                            /* xSync - sync transaction */
12494    0,                            /* xCommit - commit transaction */
12495    0,                            /* xRollback - rollback transaction */
12496    0,                            /* xFindFunction - function overloading */
12497    0,                            /* xRename - rename the table */
12498    0,                            /* xSavepoint */
12499    0,                            /* xRelease */
12500    0,                            /* xRollbackTo */
12501    0,                            /* xShadowName */
12502    0,                            /* xIntegrity */
12503  };
12504
12505  return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
12506}
12507/*
12508** End of virtual table implementation.
12509*************************************************************************/
12510/*
12511** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
12512** is called, set it to the return value of sqlite3_finalize() before
12513** returning. Otherwise, discard the sqlite3_finalize() return value.
12514*/
12515static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
12516  int rc = sqlite3_finalize(pStmt);
12517  if( *pRc==SQLITE_OK ) *pRc = rc;
12518}
12519
12520/*
12521** Attempt to allocate an IdxTable structure corresponding to table zTab
12522** in the main database of connection db. If successful, set (*ppOut) to
12523** point to the new object and return SQLITE_OK. Otherwise, return an
12524** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
12525** set to point to an error string.
12526**
12527** It is the responsibility of the caller to eventually free either the
12528** IdxTable object or error message using sqlite3_free().
12529*/
12530static int idxGetTableInfo(
12531  sqlite3 *db,                    /* Database connection to read details from */
12532  const char *zTab,               /* Table name */
12533  IdxTable **ppOut,               /* OUT: New object (if successful) */
12534  char **pzErrmsg                 /* OUT: Error message (if not) */
12535){
12536  sqlite3_stmt *p1 = 0;
12537  int nCol = 0;
12538  int nTab;
12539  int nByte;
12540  IdxTable *pNew = 0;
12541  int rc, rc2;
12542  char *pCsr = 0;
12543  int nPk = 0;
12544
12545  *ppOut = 0;
12546  if( zTab==0 ) return SQLITE_ERROR;
12547  nTab = STRLEN(zTab);
12548  nByte = sizeof(IdxTable) + nTab + 1;
12549  rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
12550  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12551    const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12552    const char *zColSeq = 0;
12553    if( zCol==0 ){
12554      rc = SQLITE_ERROR;
12555      break;
12556    }
12557    nByte += 1 + STRLEN(zCol);
12558    rc = sqlite3_table_column_metadata(
12559        db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12560    );
12561    if( zColSeq==0 ) zColSeq = "binary";
12562    nByte += 1 + STRLEN(zColSeq);
12563    nCol++;
12564    nPk += (sqlite3_column_int(p1, 5)>0);
12565  }
12566  rc2 = sqlite3_reset(p1);
12567  if( rc==SQLITE_OK ) rc = rc2;
12568
12569  nByte += sizeof(IdxColumn) * nCol;
12570  if( rc==SQLITE_OK ){
12571    pNew = idxMalloc(&rc, nByte);
12572  }
12573  if( rc==SQLITE_OK ){
12574    pNew->aCol = (IdxColumn*)&pNew[1];
12575    pNew->nCol = nCol;
12576    pCsr = (char*)&pNew->aCol[nCol];
12577  }
12578
12579  nCol = 0;
12580  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12581    const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12582    const char *zColSeq = 0;
12583    int nCopy;
12584    if( zCol==0 ) continue;
12585    nCopy = STRLEN(zCol) + 1;
12586    pNew->aCol[nCol].zName = pCsr;
12587    pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
12588    memcpy(pCsr, zCol, nCopy);
12589    pCsr += nCopy;
12590
12591    rc = sqlite3_table_column_metadata(
12592        db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12593    );
12594    if( rc==SQLITE_OK ){
12595      if( zColSeq==0 ) zColSeq = "binary";
12596      nCopy = STRLEN(zColSeq) + 1;
12597      pNew->aCol[nCol].zColl = pCsr;
12598      memcpy(pCsr, zColSeq, nCopy);
12599      pCsr += nCopy;
12600    }
12601
12602    nCol++;
12603  }
12604  idxFinalize(&rc, p1);
12605
12606  if( rc!=SQLITE_OK ){
12607    sqlite3_free(pNew);
12608    pNew = 0;
12609  }else if( ALWAYS(pNew!=0) ){
12610    pNew->zName = pCsr;
12611    if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
12612  }
12613
12614  *ppOut = pNew;
12615  return rc;
12616}
12617
12618/*
12619** This function is a no-op if *pRc is set to anything other than
12620** SQLITE_OK when it is called.
12621**
12622** If *pRc is initially set to SQLITE_OK, then the text specified by
12623** the printf() style arguments is appended to zIn and the result returned
12624** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
12625** zIn before returning.
12626*/
12627static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
12628  va_list ap;
12629  char *zAppend = 0;
12630  char *zRet = 0;
12631  int nIn = zIn ? STRLEN(zIn) : 0;
12632  int nAppend = 0;
12633  va_start(ap, zFmt);
12634  if( *pRc==SQLITE_OK ){
12635    zAppend = sqlite3_vmprintf(zFmt, ap);
12636    if( zAppend ){
12637      nAppend = STRLEN(zAppend);
12638      zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
12639    }
12640    if( zAppend && zRet ){
12641      if( nIn ) memcpy(zRet, zIn, nIn);
12642      memcpy(&zRet[nIn], zAppend, nAppend+1);
12643    }else{
12644      sqlite3_free(zRet);
12645      zRet = 0;
12646      *pRc = SQLITE_NOMEM;
12647    }
12648    sqlite3_free(zAppend);
12649    sqlite3_free(zIn);
12650  }
12651  va_end(ap);
12652  return zRet;
12653}
12654
12655/*
12656** Return true if zId must be quoted in order to use it as an SQL
12657** identifier, or false otherwise.
12658*/
12659static int idxIdentifierRequiresQuotes(const char *zId){
12660  int i;
12661  int nId = STRLEN(zId);
12662
12663  if( sqlite3_keyword_check(zId, nId) ) return 1;
12664
12665  for(i=0; zId[i]; i++){
12666    if( !(zId[i]=='_')
12667     && !(zId[i]>='0' && zId[i]<='9')
12668     && !(zId[i]>='a' && zId[i]<='z')
12669     && !(zId[i]>='A' && zId[i]<='Z')
12670    ){
12671      return 1;
12672    }
12673  }
12674  return 0;
12675}
12676
12677/*
12678** This function appends an index column definition suitable for constraint
12679** pCons to the string passed as zIn and returns the result.
12680*/
12681static char *idxAppendColDefn(
12682  int *pRc,                       /* IN/OUT: Error code */
12683  char *zIn,                      /* Column defn accumulated so far */
12684  IdxTable *pTab,                 /* Table index will be created on */
12685  IdxConstraint *pCons
12686){
12687  char *zRet = zIn;
12688  IdxColumn *p = &pTab->aCol[pCons->iCol];
12689  if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
12690
12691  if( idxIdentifierRequiresQuotes(p->zName) ){
12692    zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
12693  }else{
12694    zRet = idxAppendText(pRc, zRet, "%s", p->zName);
12695  }
12696
12697  if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
12698    if( idxIdentifierRequiresQuotes(pCons->zColl) ){
12699      zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
12700    }else{
12701      zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
12702    }
12703  }
12704
12705  if( pCons->bDesc ){
12706    zRet = idxAppendText(pRc, zRet, " DESC");
12707  }
12708  return zRet;
12709}
12710
12711/*
12712** Search database dbm for an index compatible with the one idxCreateFromCons()
12713** would create from arguments pScan, pEq and pTail. If no error occurs and
12714** such an index is found, return non-zero. Or, if no such index is found,
12715** return zero.
12716**
12717** If an error occurs, set *pRc to an SQLite error code and return zero.
12718*/
12719static int idxFindCompatible(
12720  int *pRc,                       /* OUT: Error code */
12721  sqlite3* dbm,                   /* Database to search */
12722  IdxScan *pScan,                 /* Scan for table to search for index on */
12723  IdxConstraint *pEq,             /* List of == constraints */
12724  IdxConstraint *pTail            /* List of range constraints */
12725){
12726  const char *zTbl = pScan->pTab->zName;
12727  sqlite3_stmt *pIdxList = 0;
12728  IdxConstraint *pIter;
12729  int nEq = 0;                    /* Number of elements in pEq */
12730  int rc;
12731
12732  /* Count the elements in list pEq */
12733  for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
12734
12735  rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
12736  while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
12737    int bMatch = 1;
12738    IdxConstraint *pT = pTail;
12739    sqlite3_stmt *pInfo = 0;
12740    const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
12741    if( zIdx==0 ) continue;
12742
12743    /* Zero the IdxConstraint.bFlag values in the pEq list */
12744    for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
12745
12746    rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
12747    while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
12748      int iIdx = sqlite3_column_int(pInfo, 0);
12749      int iCol = sqlite3_column_int(pInfo, 1);
12750      const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
12751
12752      if( iIdx<nEq ){
12753        for(pIter=pEq; pIter; pIter=pIter->pLink){
12754          if( pIter->bFlag ) continue;
12755          if( pIter->iCol!=iCol ) continue;
12756          if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
12757          pIter->bFlag = 1;
12758          break;
12759        }
12760        if( pIter==0 ){
12761          bMatch = 0;
12762          break;
12763        }
12764      }else{
12765        if( pT ){
12766          if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
12767            bMatch = 0;
12768            break;
12769          }
12770          pT = pT->pLink;
12771        }
12772      }
12773    }
12774    idxFinalize(&rc, pInfo);
12775
12776    if( rc==SQLITE_OK && bMatch ){
12777      sqlite3_finalize(pIdxList);
12778      return 1;
12779    }
12780  }
12781  idxFinalize(&rc, pIdxList);
12782
12783  *pRc = rc;
12784  return 0;
12785}
12786
12787/* Callback for sqlite3_exec() with query with leading count(*) column.
12788 * The first argument is expected to be an int*, referent to be incremented
12789 * if that leading column is not exactly '0'.
12790 */
12791static int countNonzeros(void* pCount, int nc,
12792                         char* azResults[], char* azColumns[]){
12793  (void)azColumns;  /* Suppress unused parameter warning */
12794  if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
12795    *((int *)pCount) += 1;
12796  }
12797  return 0;
12798}
12799
12800static int idxCreateFromCons(
12801  sqlite3expert *p,
12802  IdxScan *pScan,
12803  IdxConstraint *pEq,
12804  IdxConstraint *pTail
12805){
12806  sqlite3 *dbm = p->dbm;
12807  int rc = SQLITE_OK;
12808  if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
12809    IdxTable *pTab = pScan->pTab;
12810    char *zCols = 0;
12811    char *zIdx = 0;
12812    IdxConstraint *pCons;
12813    unsigned int h = 0;
12814    const char *zFmt;
12815
12816    for(pCons=pEq; pCons; pCons=pCons->pLink){
12817      zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12818    }
12819    for(pCons=pTail; pCons; pCons=pCons->pLink){
12820      zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12821    }
12822
12823    if( rc==SQLITE_OK ){
12824      /* Hash the list of columns to come up with a name for the index */
12825      const char *zTable = pScan->pTab->zName;
12826      int quoteTable = idxIdentifierRequiresQuotes(zTable);
12827      char *zName = 0;          /* Index name */
12828      int collisions = 0;
12829      do{
12830        int i;
12831        char *zFind;
12832        for(i=0; zCols[i]; i++){
12833          h += ((h<<3) + zCols[i]);
12834        }
12835        sqlite3_free(zName);
12836        zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
12837        if( zName==0 ) break;
12838        /* Is is unique among table, view and index names? */
12839        zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
12840          " AND type in ('index','table','view')";
12841        zFind = sqlite3_mprintf(zFmt, zName);
12842        i = 0;
12843        rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
12844        assert(rc==SQLITE_OK);
12845        sqlite3_free(zFind);
12846        if( i==0 ){
12847          collisions = 0;
12848          break;
12849        }
12850        ++collisions;
12851      }while( collisions<50 && zName!=0 );
12852      if( collisions ){
12853        /* This return means "Gave up trying to find a unique index name." */
12854        rc = SQLITE_BUSY_TIMEOUT;
12855      }else if( zName==0 ){
12856        rc = SQLITE_NOMEM;
12857      }else{
12858        if( quoteTable ){
12859          zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
12860        }else{
12861          zFmt = "CREATE INDEX %s ON %s(%s)";
12862        }
12863        zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
12864        if( !zIdx ){
12865          rc = SQLITE_NOMEM;
12866        }else{
12867          rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
12868          if( rc!=SQLITE_OK ){
12869            rc = SQLITE_BUSY_TIMEOUT;
12870          }else{
12871            idxHashAdd(&rc, &p->hIdx, zName, zIdx);
12872          }
12873        }
12874        sqlite3_free(zName);
12875        sqlite3_free(zIdx);
12876      }
12877    }
12878
12879    sqlite3_free(zCols);
12880  }
12881  return rc;
12882}
12883
12884/*
12885** Return true if list pList (linked by IdxConstraint.pLink) contains
12886** a constraint compatible with *p. Otherwise return false.
12887*/
12888static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
12889  IdxConstraint *pCmp;
12890  for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
12891    if( p->iCol==pCmp->iCol ) return 1;
12892  }
12893  return 0;
12894}
12895
12896static int idxCreateFromWhere(
12897  sqlite3expert *p,
12898  IdxScan *pScan,                 /* Create indexes for this scan */
12899  IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
12900){
12901  IdxConstraint *p1 = 0;
12902  IdxConstraint *pCon;
12903  int rc;
12904
12905  /* Gather up all the == constraints. */
12906  for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
12907    if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12908      pCon->pLink = p1;
12909      p1 = pCon;
12910    }
12911  }
12912
12913  /* Create an index using the == constraints collected above. And the
12914  ** range constraint/ORDER BY terms passed in by the caller, if any. */
12915  rc = idxCreateFromCons(p, pScan, p1, pTail);
12916
12917  /* If no range/ORDER BY passed by the caller, create a version of the
12918  ** index for each range constraint.  */
12919  if( pTail==0 ){
12920    for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
12921      assert( pCon->pLink==0 );
12922      if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12923        rc = idxCreateFromCons(p, pScan, p1, pCon);
12924      }
12925    }
12926  }
12927
12928  return rc;
12929}
12930
12931/*
12932** Create candidate indexes in database [dbm] based on the data in
12933** linked-list pScan.
12934*/
12935static int idxCreateCandidates(sqlite3expert *p){
12936  int rc = SQLITE_OK;
12937  IdxScan *pIter;
12938
12939  for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
12940    rc = idxCreateFromWhere(p, pIter, 0);
12941    if( rc==SQLITE_OK && pIter->pOrder ){
12942      rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
12943    }
12944  }
12945
12946  return rc;
12947}
12948
12949/*
12950** Free all elements of the linked list starting at pConstraint.
12951*/
12952static void idxConstraintFree(IdxConstraint *pConstraint){
12953  IdxConstraint *pNext;
12954  IdxConstraint *p;
12955
12956  for(p=pConstraint; p; p=pNext){
12957    pNext = p->pNext;
12958    sqlite3_free(p);
12959  }
12960}
12961
12962/*
12963** Free all elements of the linked list starting from pScan up until pLast
12964** (pLast is not freed).
12965*/
12966static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
12967  IdxScan *p;
12968  IdxScan *pNext;
12969  for(p=pScan; p!=pLast; p=pNext){
12970    pNext = p->pNextScan;
12971    idxConstraintFree(p->pOrder);
12972    idxConstraintFree(p->pEq);
12973    idxConstraintFree(p->pRange);
12974    sqlite3_free(p);
12975  }
12976}
12977
12978/*
12979** Free all elements of the linked list starting from pStatement up
12980** until pLast (pLast is not freed).
12981*/
12982static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
12983  IdxStatement *p;
12984  IdxStatement *pNext;
12985  for(p=pStatement; p!=pLast; p=pNext){
12986    pNext = p->pNext;
12987    sqlite3_free(p->zEQP);
12988    sqlite3_free(p->zIdx);
12989    sqlite3_free(p);
12990  }
12991}
12992
12993/*
12994** Free the linked list of IdxTable objects starting at pTab.
12995*/
12996static void idxTableFree(IdxTable *pTab){
12997  IdxTable *pIter;
12998  IdxTable *pNext;
12999  for(pIter=pTab; pIter; pIter=pNext){
13000    pNext = pIter->pNext;
13001    sqlite3_free(pIter);
13002  }
13003}
13004
13005/*
13006** Free the linked list of IdxWrite objects starting at pTab.
13007*/
13008static void idxWriteFree(IdxWrite *pTab){
13009  IdxWrite *pIter;
13010  IdxWrite *pNext;
13011  for(pIter=pTab; pIter; pIter=pNext){
13012    pNext = pIter->pNext;
13013    sqlite3_free(pIter);
13014  }
13015}
13016
13017
13018
13019/*
13020** This function is called after candidate indexes have been created. It
13021** runs all the queries to see which indexes they prefer, and populates
13022** IdxStatement.zIdx and IdxStatement.zEQP with the results.
13023*/
13024static int idxFindIndexes(
13025  sqlite3expert *p,
13026  char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
13027){
13028  IdxStatement *pStmt;
13029  sqlite3 *dbm = p->dbm;
13030  int rc = SQLITE_OK;
13031
13032  IdxHash hIdx;
13033  idxHashInit(&hIdx);
13034
13035  for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
13036    IdxHashEntry *pEntry;
13037    sqlite3_stmt *pExplain = 0;
13038    idxHashClear(&hIdx);
13039    rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
13040        "EXPLAIN QUERY PLAN %s", pStmt->zSql
13041    );
13042    while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
13043      /* int iId = sqlite3_column_int(pExplain, 0); */
13044      /* int iParent = sqlite3_column_int(pExplain, 1); */
13045      /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
13046      const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
13047      int nDetail;
13048      int i;
13049
13050      if( !zDetail ) continue;
13051      nDetail = STRLEN(zDetail);
13052
13053      for(i=0; i<nDetail; i++){
13054        const char *zIdx = 0;
13055        if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
13056          zIdx = &zDetail[i+13];
13057        }else if( i+22<nDetail
13058            && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
13059        ){
13060          zIdx = &zDetail[i+22];
13061        }
13062        if( zIdx ){
13063          const char *zSql;
13064          int nIdx = 0;
13065          while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
13066            nIdx++;
13067          }
13068          zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
13069          if( zSql ){
13070            idxHashAdd(&rc, &hIdx, zSql, 0);
13071            if( rc ) goto find_indexes_out;
13072          }
13073          break;
13074        }
13075      }
13076
13077      if( zDetail[0]!='-' ){
13078        pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
13079      }
13080    }
13081
13082    for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13083      pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
13084    }
13085
13086    idxFinalize(&rc, pExplain);
13087  }
13088
13089 find_indexes_out:
13090  idxHashClear(&hIdx);
13091  return rc;
13092}
13093
13094static int idxAuthCallback(
13095  void *pCtx,
13096  int eOp,
13097  const char *z3,
13098  const char *z4,
13099  const char *zDb,
13100  const char *zTrigger
13101){
13102  int rc = SQLITE_OK;
13103  (void)z4;
13104  (void)zTrigger;
13105  if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
13106    if( sqlite3_stricmp(zDb, "main")==0 ){
13107      sqlite3expert *p = (sqlite3expert*)pCtx;
13108      IdxTable *pTab;
13109      for(pTab=p->pTable; pTab; pTab=pTab->pNext){
13110        if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
13111      }
13112      if( pTab ){
13113        IdxWrite *pWrite;
13114        for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
13115          if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
13116        }
13117        if( pWrite==0 ){
13118          pWrite = idxMalloc(&rc, sizeof(IdxWrite));
13119          if( rc==SQLITE_OK ){
13120            pWrite->pTab = pTab;
13121            pWrite->eOp = eOp;
13122            pWrite->pNext = p->pWrite;
13123            p->pWrite = pWrite;
13124          }
13125        }
13126      }
13127    }
13128  }
13129  return rc;
13130}
13131
13132static int idxProcessOneTrigger(
13133  sqlite3expert *p,
13134  IdxWrite *pWrite,
13135  char **pzErr
13136){
13137  static const char *zInt = UNIQUE_TABLE_NAME;
13138  static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
13139  IdxTable *pTab = pWrite->pTab;
13140  const char *zTab = pTab->zName;
13141  const char *zSql =
13142    "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
13143    "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
13144    "ORDER BY type;";
13145  sqlite3_stmt *pSelect = 0;
13146  int rc = SQLITE_OK;
13147  char *zWrite = 0;
13148
13149  /* Create the table and its triggers in the temp schema */
13150  rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
13151  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
13152    const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
13153    if( zCreate==0 ) continue;
13154    rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
13155  }
13156  idxFinalize(&rc, pSelect);
13157
13158  /* Rename the table in the temp schema to zInt */
13159  if( rc==SQLITE_OK ){
13160    char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
13161    if( z==0 ){
13162      rc = SQLITE_NOMEM;
13163    }else{
13164      rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
13165      sqlite3_free(z);
13166    }
13167  }
13168
13169  switch( pWrite->eOp ){
13170    case SQLITE_INSERT: {
13171      int i;
13172      zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
13173      for(i=0; i<pTab->nCol; i++){
13174        zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
13175      }
13176      zWrite = idxAppendText(&rc, zWrite, ")");
13177      break;
13178    }
13179    case SQLITE_UPDATE: {
13180      int i;
13181      zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
13182      for(i=0; i<pTab->nCol; i++){
13183        zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
13184            pTab->aCol[i].zName
13185        );
13186      }
13187      break;
13188    }
13189    default: {
13190      assert( pWrite->eOp==SQLITE_DELETE );
13191      if( rc==SQLITE_OK ){
13192        zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
13193        if( zWrite==0 ) rc = SQLITE_NOMEM;
13194      }
13195    }
13196  }
13197
13198  if( rc==SQLITE_OK ){
13199    sqlite3_stmt *pX = 0;
13200    rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
13201    idxFinalize(&rc, pX);
13202    if( rc!=SQLITE_OK ){
13203      idxDatabaseError(p->dbv, pzErr);
13204    }
13205  }
13206  sqlite3_free(zWrite);
13207
13208  if( rc==SQLITE_OK ){
13209    rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
13210  }
13211
13212  return rc;
13213}
13214
13215static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
13216  int rc = SQLITE_OK;
13217  IdxWrite *pEnd = 0;
13218  IdxWrite *pFirst = p->pWrite;
13219
13220  while( rc==SQLITE_OK && pFirst!=pEnd ){
13221    IdxWrite *pIter;
13222    for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
13223      rc = idxProcessOneTrigger(p, pIter, pzErr);
13224    }
13225    pEnd = pFirst;
13226    pFirst = p->pWrite;
13227  }
13228
13229  return rc;
13230}
13231
13232
13233static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
13234  int rc = idxRegisterVtab(p);
13235  sqlite3_stmt *pSchema = 0;
13236
13237  /* For each table in the main db schema:
13238  **
13239  **   1) Add an entry to the p->pTable list, and
13240  **   2) Create the equivalent virtual table in dbv.
13241  */
13242  rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
13243      "SELECT type, name, sql, 1 FROM sqlite_schema "
13244      "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
13245      " UNION ALL "
13246      "SELECT type, name, sql, 2 FROM sqlite_schema "
13247      "WHERE type = 'trigger'"
13248      "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
13249      "ORDER BY 4, 1"
13250  );
13251  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
13252    const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
13253    const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
13254    const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
13255
13256    if( zType==0 || zName==0 ) continue;
13257    if( zType[0]=='v' || zType[1]=='r' ){
13258      if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
13259    }else{
13260      IdxTable *pTab;
13261      rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
13262      if( rc==SQLITE_OK ){
13263        int i;
13264        char *zInner = 0;
13265        char *zOuter = 0;
13266        pTab->pNext = p->pTable;
13267        p->pTable = pTab;
13268
13269        /* The statement the vtab will pass to sqlite3_declare_vtab() */
13270        zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
13271        for(i=0; i<pTab->nCol; i++){
13272          zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
13273              (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
13274          );
13275        }
13276        zInner = idxAppendText(&rc, zInner, ")");
13277
13278        /* The CVT statement to create the vtab */
13279        zOuter = idxAppendText(&rc, 0,
13280            "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
13281        );
13282        if( rc==SQLITE_OK ){
13283          rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
13284        }
13285        sqlite3_free(zInner);
13286        sqlite3_free(zOuter);
13287      }
13288    }
13289  }
13290  idxFinalize(&rc, pSchema);
13291  return rc;
13292}
13293
13294struct IdxSampleCtx {
13295  int iTarget;
13296  double target;                  /* Target nRet/nRow value */
13297  double nRow;                    /* Number of rows seen */
13298  double nRet;                    /* Number of rows returned */
13299};
13300
13301static void idxSampleFunc(
13302  sqlite3_context *pCtx,
13303  int argc,
13304  sqlite3_value **argv
13305){
13306  struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
13307  int bRet;
13308
13309  (void)argv;
13310  assert( argc==0 );
13311  if( p->nRow==0.0 ){
13312    bRet = 1;
13313  }else{
13314    bRet = (p->nRet / p->nRow) <= p->target;
13315    if( bRet==0 ){
13316      unsigned short rnd;
13317      sqlite3_randomness(2, (void*)&rnd);
13318      bRet = ((int)rnd % 100) <= p->iTarget;
13319    }
13320  }
13321
13322  sqlite3_result_int(pCtx, bRet);
13323  p->nRow += 1.0;
13324  p->nRet += (double)bRet;
13325}
13326
13327struct IdxRemCtx {
13328  int nSlot;
13329  struct IdxRemSlot {
13330    int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
13331    i64 iVal;                     /* SQLITE_INTEGER value */
13332    double rVal;                  /* SQLITE_FLOAT value */
13333    int nByte;                    /* Bytes of space allocated at z */
13334    int n;                        /* Size of buffer z */
13335    char *z;                      /* SQLITE_TEXT/BLOB value */
13336  } aSlot[1];
13337};
13338
13339/*
13340** Implementation of scalar function rem().
13341*/
13342static void idxRemFunc(
13343  sqlite3_context *pCtx,
13344  int argc,
13345  sqlite3_value **argv
13346){
13347  struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
13348  struct IdxRemSlot *pSlot;
13349  int iSlot;
13350  assert( argc==2 );
13351
13352  iSlot = sqlite3_value_int(argv[0]);
13353  assert( iSlot<=p->nSlot );
13354  pSlot = &p->aSlot[iSlot];
13355
13356  switch( pSlot->eType ){
13357    case SQLITE_NULL:
13358      /* no-op */
13359      break;
13360
13361    case SQLITE_INTEGER:
13362      sqlite3_result_int64(pCtx, pSlot->iVal);
13363      break;
13364
13365    case SQLITE_FLOAT:
13366      sqlite3_result_double(pCtx, pSlot->rVal);
13367      break;
13368
13369    case SQLITE_BLOB:
13370      sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13371      break;
13372
13373    case SQLITE_TEXT:
13374      sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13375      break;
13376  }
13377
13378  pSlot->eType = sqlite3_value_type(argv[1]);
13379  switch( pSlot->eType ){
13380    case SQLITE_NULL:
13381      /* no-op */
13382      break;
13383
13384    case SQLITE_INTEGER:
13385      pSlot->iVal = sqlite3_value_int64(argv[1]);
13386      break;
13387
13388    case SQLITE_FLOAT:
13389      pSlot->rVal = sqlite3_value_double(argv[1]);
13390      break;
13391
13392    case SQLITE_BLOB:
13393    case SQLITE_TEXT: {
13394      int nByte = sqlite3_value_bytes(argv[1]);
13395      const void *pData = 0;
13396      if( nByte>pSlot->nByte ){
13397        char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
13398        if( zNew==0 ){
13399          sqlite3_result_error_nomem(pCtx);
13400          return;
13401        }
13402        pSlot->nByte = nByte*2;
13403        pSlot->z = zNew;
13404      }
13405      pSlot->n = nByte;
13406      if( pSlot->eType==SQLITE_BLOB ){
13407        pData = sqlite3_value_blob(argv[1]);
13408        if( pData ) memcpy(pSlot->z, pData, nByte);
13409      }else{
13410        pData = sqlite3_value_text(argv[1]);
13411        memcpy(pSlot->z, pData, nByte);
13412      }
13413      break;
13414    }
13415  }
13416}
13417
13418static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
13419  int rc = SQLITE_OK;
13420  const char *zMax =
13421    "SELECT max(i.seqno) FROM "
13422    "  sqlite_schema AS s, "
13423    "  pragma_index_list(s.name) AS l, "
13424    "  pragma_index_info(l.name) AS i "
13425    "WHERE s.type = 'table'";
13426  sqlite3_stmt *pMax = 0;
13427
13428  *pnMax = 0;
13429  rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
13430  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
13431    *pnMax = sqlite3_column_int(pMax, 0) + 1;
13432  }
13433  idxFinalize(&rc, pMax);
13434
13435  return rc;
13436}
13437
13438static int idxPopulateOneStat1(
13439  sqlite3expert *p,
13440  sqlite3_stmt *pIndexXInfo,
13441  sqlite3_stmt *pWriteStat,
13442  const char *zTab,
13443  const char *zIdx,
13444  char **pzErr
13445){
13446  char *zCols = 0;
13447  char *zOrder = 0;
13448  char *zQuery = 0;
13449  int nCol = 0;
13450  int i;
13451  sqlite3_stmt *pQuery = 0;
13452  int *aStat = 0;
13453  int rc = SQLITE_OK;
13454
13455  assert( p->iSample>0 );
13456
13457  /* Formulate the query text */
13458  sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
13459  while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
13460    const char *zComma = zCols==0 ? "" : ", ";
13461    const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
13462    const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
13463    zCols = idxAppendText(&rc, zCols,
13464        "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
13465    );
13466    zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
13467  }
13468  sqlite3_reset(pIndexXInfo);
13469  if( rc==SQLITE_OK ){
13470    if( p->iSample==100 ){
13471      zQuery = sqlite3_mprintf(
13472          "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
13473      );
13474    }else{
13475      zQuery = sqlite3_mprintf(
13476          "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
13477      );
13478    }
13479  }
13480  sqlite3_free(zCols);
13481  sqlite3_free(zOrder);
13482
13483  /* Formulate the query text */
13484  if( rc==SQLITE_OK ){
13485    sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13486    rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
13487  }
13488  sqlite3_free(zQuery);
13489
13490  if( rc==SQLITE_OK ){
13491    aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
13492  }
13493  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13494    IdxHashEntry *pEntry;
13495    char *zStat = 0;
13496    for(i=0; i<=nCol; i++) aStat[i] = 1;
13497    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13498      aStat[0]++;
13499      for(i=0; i<nCol; i++){
13500        if( sqlite3_column_int(pQuery, i)==0 ) break;
13501      }
13502      for(/*no-op*/; i<nCol; i++){
13503        aStat[i+1]++;
13504      }
13505    }
13506
13507    if( rc==SQLITE_OK ){
13508      int s0 = aStat[0];
13509      zStat = sqlite3_mprintf("%d", s0);
13510      if( zStat==0 ) rc = SQLITE_NOMEM;
13511      for(i=1; rc==SQLITE_OK && i<=nCol; i++){
13512        zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
13513      }
13514    }
13515
13516    if( rc==SQLITE_OK ){
13517      sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
13518      sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
13519      sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
13520      sqlite3_step(pWriteStat);
13521      rc = sqlite3_reset(pWriteStat);
13522    }
13523
13524    pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
13525    if( pEntry ){
13526      assert( pEntry->zVal2==0 );
13527      pEntry->zVal2 = zStat;
13528    }else{
13529      sqlite3_free(zStat);
13530    }
13531  }
13532  sqlite3_free(aStat);
13533  idxFinalize(&rc, pQuery);
13534
13535  return rc;
13536}
13537
13538static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
13539  int rc;
13540  char *zSql;
13541
13542  rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13543  if( rc!=SQLITE_OK ) return rc;
13544
13545  zSql = sqlite3_mprintf(
13546      "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
13547  );
13548  if( zSql==0 ) return SQLITE_NOMEM;
13549  rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
13550  sqlite3_free(zSql);
13551
13552  return rc;
13553}
13554
13555/*
13556** This function is called as part of sqlite3_expert_analyze(). Candidate
13557** indexes have already been created in database sqlite3expert.dbm, this
13558** function populates sqlite_stat1 table in the same database.
13559**
13560** The stat1 data is generated by querying the
13561*/
13562static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
13563  int rc = SQLITE_OK;
13564  int nMax =0;
13565  struct IdxRemCtx *pCtx = 0;
13566  struct IdxSampleCtx samplectx;
13567  int i;
13568  i64 iPrev = -100000;
13569  sqlite3_stmt *pAllIndex = 0;
13570  sqlite3_stmt *pIndexXInfo = 0;
13571  sqlite3_stmt *pWrite = 0;
13572
13573  const char *zAllIndex =
13574    "SELECT s.rowid, s.name, l.name FROM "
13575    "  sqlite_schema AS s, "
13576    "  pragma_index_list(s.name) AS l "
13577    "WHERE s.type = 'table'";
13578  const char *zIndexXInfo =
13579    "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
13580  const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
13581
13582  /* If iSample==0, no sqlite_stat1 data is required. */
13583  if( p->iSample==0 ) return SQLITE_OK;
13584
13585  rc = idxLargestIndex(p->dbm, &nMax, pzErr);
13586  if( nMax<=0 || rc!=SQLITE_OK ) return rc;
13587
13588  rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
13589
13590  if( rc==SQLITE_OK ){
13591    int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
13592    pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
13593  }
13594
13595  if( rc==SQLITE_OK ){
13596    sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13597    rc = sqlite3_create_function(
13598        dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
13599    );
13600  }
13601  if( rc==SQLITE_OK ){
13602    rc = sqlite3_create_function(
13603        p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
13604    );
13605  }
13606
13607  if( rc==SQLITE_OK ){
13608    pCtx->nSlot = nMax+1;
13609    rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
13610  }
13611  if( rc==SQLITE_OK ){
13612    rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
13613  }
13614  if( rc==SQLITE_OK ){
13615    rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
13616  }
13617
13618  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
13619    i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
13620    const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
13621    const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
13622    if( zTab==0 || zIdx==0 ) continue;
13623    if( p->iSample<100 && iPrev!=iRowid ){
13624      samplectx.target = (double)p->iSample / 100.0;
13625      samplectx.iTarget = p->iSample;
13626      samplectx.nRow = 0.0;
13627      samplectx.nRet = 0.0;
13628      rc = idxBuildSampleTable(p, zTab);
13629      if( rc!=SQLITE_OK ) break;
13630    }
13631    rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
13632    iPrev = iRowid;
13633  }
13634  if( rc==SQLITE_OK && p->iSample<100 ){
13635    rc = sqlite3_exec(p->dbv,
13636        "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
13637    );
13638  }
13639
13640  idxFinalize(&rc, pAllIndex);
13641  idxFinalize(&rc, pIndexXInfo);
13642  idxFinalize(&rc, pWrite);
13643
13644  if( pCtx ){
13645    for(i=0; i<pCtx->nSlot; i++){
13646      sqlite3_free(pCtx->aSlot[i].z);
13647    }
13648    sqlite3_free(pCtx);
13649  }
13650
13651  if( rc==SQLITE_OK ){
13652    rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
13653  }
13654
13655  sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13656  return rc;
13657}
13658
13659/*
13660** Define and possibly pretend to use a useless collation sequence.
13661** This pretense allows expert to accept SQL using custom collations.
13662*/
13663static int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
13664  (void)up1;
13665  (void)up2;
13666  (void)up3;
13667  (void)up4;
13668  (void)up5;
13669  assert(0); /* VDBE should never be run. */
13670  return 0;
13671}
13672/* And a callback to register above upon actual need */
13673static void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
13674  (void)up1;
13675  sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
13676}
13677
13678#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13679  && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13680/*
13681** dummy functions for no-op implementation of UDFs during expert's work
13682*/
13683static void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
13684  (void)up1;
13685  (void)up2;
13686  (void)up3;
13687  assert(0); /* VDBE should never be run. */
13688}
13689static void dummyUDFvalue(sqlite3_context *up1){
13690  (void)up1;
13691  assert(0); /* VDBE should never be run. */
13692}
13693
13694/*
13695** Register UDFs from user database with another.
13696*/
13697static int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
13698  sqlite3_stmt *pStmt;
13699  int rc = sqlite3_prepare_v2(dbSrc,
13700            "SELECT name,type,enc,narg,flags "
13701            "FROM pragma_function_list() "
13702            "WHERE builtin==0", -1, &pStmt, 0);
13703  if( rc==SQLITE_OK ){
13704    while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
13705      int nargs = sqlite3_column_int(pStmt,3);
13706      int flags = sqlite3_column_int(pStmt,4);
13707      const char *name = (char*)sqlite3_column_text(pStmt,0);
13708      const char *type = (char*)sqlite3_column_text(pStmt,1);
13709      const char *enc = (char*)sqlite3_column_text(pStmt,2);
13710      if( name==0 || type==0 || enc==0 ){
13711        /* no-op.  Only happens on OOM */
13712      }else{
13713        int ienc = SQLITE_UTF8;
13714        int rcf = SQLITE_ERROR;
13715        if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
13716        else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
13717        ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
13718        if( strcmp(type,"w")==0 ){
13719          rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
13720                                               dummyUDF,dummyUDFvalue,0,0,0);
13721        }else if( strcmp(type,"a")==0 ){
13722          rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13723                                        0,dummyUDF,dummyUDFvalue);
13724        }else if( strcmp(type,"s")==0 ){
13725          rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13726                                        dummyUDF,0,0);
13727        }
13728        if( rcf!=SQLITE_OK ){
13729          rc = rcf;
13730          break;
13731        }
13732      }
13733    }
13734    sqlite3_finalize(pStmt);
13735    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
13736  }
13737  return rc;
13738}
13739#endif
13740
13741/*
13742** Allocate a new sqlite3expert object.
13743*/
13744sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
13745  int rc = SQLITE_OK;
13746  sqlite3expert *pNew;
13747
13748  pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
13749
13750  /* Open two in-memory databases to work with. The "vtab database" (dbv)
13751  ** will contain a virtual table corresponding to each real table in
13752  ** the user database schema, and a copy of each view. It is used to
13753  ** collect information regarding the WHERE, ORDER BY and other clauses
13754  ** of the user's query.
13755  */
13756  if( rc==SQLITE_OK ){
13757    pNew->db = db;
13758    pNew->iSample = 100;
13759    rc = sqlite3_open(":memory:", &pNew->dbv);
13760  }
13761  if( rc==SQLITE_OK ){
13762    rc = sqlite3_open(":memory:", &pNew->dbm);
13763    if( rc==SQLITE_OK ){
13764      sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
13765    }
13766  }
13767
13768  /* Allow custom collations to be dealt with through prepare. */
13769  if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
13770  if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
13771
13772#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13773  && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13774  /* Register UDFs from database [db] with [dbm] and [dbv]. */
13775  if( rc==SQLITE_OK ){
13776    rc = registerUDFs(pNew->db, pNew->dbm);
13777  }
13778  if( rc==SQLITE_OK ){
13779    rc = registerUDFs(pNew->db, pNew->dbv);
13780  }
13781#endif
13782
13783  /* Copy the entire schema of database [db] into [dbm]. */
13784  if( rc==SQLITE_OK ){
13785    sqlite3_stmt *pSql = 0;
13786    rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
13787        "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
13788        " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
13789    );
13790    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
13791      const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
13792      if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
13793    }
13794    idxFinalize(&rc, pSql);
13795  }
13796
13797  /* Create the vtab schema */
13798  if( rc==SQLITE_OK ){
13799    rc = idxCreateVtabSchema(pNew, pzErrmsg);
13800  }
13801
13802  /* Register the auth callback with dbv */
13803  if( rc==SQLITE_OK ){
13804    sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
13805  }
13806
13807  /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
13808  ** return the new sqlite3expert handle.  */
13809  if( rc!=SQLITE_OK ){
13810    sqlite3_expert_destroy(pNew);
13811    pNew = 0;
13812  }
13813  return pNew;
13814}
13815
13816/*
13817** Configure an sqlite3expert object.
13818*/
13819int sqlite3_expert_config(sqlite3expert *p, int op, ...){
13820  int rc = SQLITE_OK;
13821  va_list ap;
13822  va_start(ap, op);
13823  switch( op ){
13824    case EXPERT_CONFIG_SAMPLE: {
13825      int iVal = va_arg(ap, int);
13826      if( iVal<0 ) iVal = 0;
13827      if( iVal>100 ) iVal = 100;
13828      p->iSample = iVal;
13829      break;
13830    }
13831    default:
13832      rc = SQLITE_NOTFOUND;
13833      break;
13834  }
13835
13836  va_end(ap);
13837  return rc;
13838}
13839
13840/*
13841** Add an SQL statement to the analysis.
13842*/
13843int sqlite3_expert_sql(
13844  sqlite3expert *p,               /* From sqlite3_expert_new() */
13845  const char *zSql,               /* SQL statement to add */
13846  char **pzErr                    /* OUT: Error message (if any) */
13847){
13848  IdxScan *pScanOrig = p->pScan;
13849  IdxStatement *pStmtOrig = p->pStatement;
13850  int rc = SQLITE_OK;
13851  const char *zStmt = zSql;
13852
13853  if( p->bRun ) return SQLITE_MISUSE;
13854
13855  while( rc==SQLITE_OK && zStmt && zStmt[0] ){
13856    sqlite3_stmt *pStmt = 0;
13857    /* Ensure that the provided statement compiles against user's DB. */
13858    rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
13859    if( rc!=SQLITE_OK ) break;
13860    sqlite3_finalize(pStmt);
13861    rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
13862    if( rc==SQLITE_OK ){
13863      if( pStmt ){
13864        IdxStatement *pNew;
13865        const char *z = sqlite3_sql(pStmt);
13866        int n = STRLEN(z);
13867        pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
13868        if( rc==SQLITE_OK ){
13869          pNew->zSql = (char*)&pNew[1];
13870          memcpy(pNew->zSql, z, n+1);
13871          pNew->pNext = p->pStatement;
13872          if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
13873          p->pStatement = pNew;
13874        }
13875        sqlite3_finalize(pStmt);
13876      }
13877    }else{
13878      idxDatabaseError(p->dbv, pzErr);
13879    }
13880  }
13881
13882  if( rc!=SQLITE_OK ){
13883    idxScanFree(p->pScan, pScanOrig);
13884    idxStatementFree(p->pStatement, pStmtOrig);
13885    p->pScan = pScanOrig;
13886    p->pStatement = pStmtOrig;
13887  }
13888
13889  return rc;
13890}
13891
13892int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
13893  int rc;
13894  IdxHashEntry *pEntry;
13895
13896  /* Do trigger processing to collect any extra IdxScan structures */
13897  rc = idxProcessTriggers(p, pzErr);
13898
13899  /* Create candidate indexes within the in-memory database file */
13900  if( rc==SQLITE_OK ){
13901    rc = idxCreateCandidates(p);
13902  }else if ( rc==SQLITE_BUSY_TIMEOUT ){
13903    if( pzErr )
13904      *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
13905    return rc;
13906  }
13907
13908  /* Generate the stat1 data */
13909  if( rc==SQLITE_OK ){
13910    rc = idxPopulateStat1(p, pzErr);
13911  }
13912
13913  /* Formulate the EXPERT_REPORT_CANDIDATES text */
13914  for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13915    p->zCandidates = idxAppendText(&rc, p->zCandidates,
13916        "%s;%s%s\n", pEntry->zVal,
13917        pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
13918    );
13919  }
13920
13921  /* Figure out which of the candidate indexes are preferred by the query
13922  ** planner and report the results to the user.  */
13923  if( rc==SQLITE_OK ){
13924    rc = idxFindIndexes(p, pzErr);
13925  }
13926
13927  if( rc==SQLITE_OK ){
13928    p->bRun = 1;
13929  }
13930  return rc;
13931}
13932
13933/*
13934** Return the total number of statements that have been added to this
13935** sqlite3expert using sqlite3_expert_sql().
13936*/
13937int sqlite3_expert_count(sqlite3expert *p){
13938  int nRet = 0;
13939  if( p->pStatement ) nRet = p->pStatement->iId+1;
13940  return nRet;
13941}
13942
13943/*
13944** Return a component of the report.
13945*/
13946const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
13947  const char *zRet = 0;
13948  IdxStatement *pStmt;
13949
13950  if( p->bRun==0 ) return 0;
13951  for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
13952  switch( eReport ){
13953    case EXPERT_REPORT_SQL:
13954      if( pStmt ) zRet = pStmt->zSql;
13955      break;
13956    case EXPERT_REPORT_INDEXES:
13957      if( pStmt ) zRet = pStmt->zIdx;
13958      break;
13959    case EXPERT_REPORT_PLAN:
13960      if( pStmt ) zRet = pStmt->zEQP;
13961      break;
13962    case EXPERT_REPORT_CANDIDATES:
13963      zRet = p->zCandidates;
13964      break;
13965  }
13966  return zRet;
13967}
13968
13969/*
13970** Free an sqlite3expert object.
13971*/
13972void sqlite3_expert_destroy(sqlite3expert *p){
13973  if( p ){
13974    sqlite3_close(p->dbm);
13975    sqlite3_close(p->dbv);
13976    idxScanFree(p->pScan, 0);
13977    idxStatementFree(p->pStatement, 0);
13978    idxTableFree(p->pTable);
13979    idxWriteFree(p->pWrite);
13980    idxHashClear(&p->hIdx);
13981    sqlite3_free(p->zCandidates);
13982    sqlite3_free(p);
13983  }
13984}
13985
13986#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13987
13988/************************* End ../ext/expert/sqlite3expert.c ********************/
13989
13990#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
13991#define SQLITE_SHELL_HAVE_RECOVER 1
13992#else
13993#define SQLITE_SHELL_HAVE_RECOVER 0
13994#endif
13995#if SQLITE_SHELL_HAVE_RECOVER
13996/************************* Begin ../ext/recover/sqlite3recover.h ******************/
13997/*
13998** 2022-08-27
13999**
14000** The author disclaims copyright to this source code.  In place of
14001** a legal notice, here is a blessing:
14002**
14003**    May you do good and not evil.
14004**    May you find forgiveness for yourself and forgive others.
14005**    May you share freely, never taking more than you give.
14006**
14007*************************************************************************
14008**
14009** This file contains the public interface to the "recover" extension -
14010** an SQLite extension designed to recover data from corrupted database
14011** files.
14012*/
14013
14014/*
14015** OVERVIEW:
14016**
14017** To use the API to recover data from a corrupted database, an
14018** application:
14019**
14020**   1) Creates an sqlite3_recover handle by calling either
14021**      sqlite3_recover_init() or sqlite3_recover_init_sql().
14022**
14023**   2) Configures the new handle using one or more calls to
14024**      sqlite3_recover_config().
14025**
14026**   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
14027**      the handle until it returns something other than SQLITE_OK. If it
14028**      returns SQLITE_DONE, then the recovery operation completed without
14029**      error. If it returns some other non-SQLITE_OK value, then an error
14030**      has occurred.
14031**
14032**   4) Retrieves any error code and English language error message using the
14033**      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
14034**      respectively.
14035**
14036**   5) Destroys the sqlite3_recover handle and frees all resources
14037**      using sqlite3_recover_finish().
14038**
14039** The application may abandon the recovery operation at any point
14040** before it is finished by passing the sqlite3_recover handle to
14041** sqlite3_recover_finish(). This is not an error, but the final state
14042** of the output database, or the results of running the partial script
14043** delivered to the SQL callback, are undefined.
14044*/
14045
14046#ifndef _SQLITE_RECOVER_H
14047#define _SQLITE_RECOVER_H
14048
14049/* #include "sqlite3.h" */
14050
14051#ifdef __cplusplus
14052extern "C" {
14053#endif
14054
14055/*
14056** An instance of the sqlite3_recover object represents a recovery
14057** operation in progress.
14058**
14059** Constructors:
14060**
14061**    sqlite3_recover_init()
14062**    sqlite3_recover_init_sql()
14063**
14064** Destructor:
14065**
14066**    sqlite3_recover_finish()
14067**
14068** Methods:
14069**
14070**    sqlite3_recover_config()
14071**    sqlite3_recover_errcode()
14072**    sqlite3_recover_errmsg()
14073**    sqlite3_recover_run()
14074**    sqlite3_recover_step()
14075*/
14076typedef struct sqlite3_recover sqlite3_recover;
14077
14078/*
14079** These two APIs attempt to create and return a new sqlite3_recover object.
14080** In both cases the first two arguments identify the (possibly
14081** corrupt) database to recover data from. The first argument is an open
14082** database handle and the second the name of a database attached to that
14083** handle (i.e. "main", "temp" or the name of an attached database).
14084**
14085** If sqlite3_recover_init() is used to create the new sqlite3_recover
14086** handle, then data is recovered into a new database, identified by
14087** string parameter zUri. zUri may be an absolute or relative file path,
14088** or may be an SQLite URI. If the identified database file already exists,
14089** it is overwritten.
14090**
14091** If sqlite3_recover_init_sql() is invoked, then any recovered data will
14092** be returned to the user as a series of SQL statements. Executing these
14093** SQL statements results in the same database as would have been created
14094** had sqlite3_recover_init() been used. For each SQL statement in the
14095** output, the callback function passed as the third argument (xSql) is
14096** invoked once. The first parameter is a passed a copy of the fourth argument
14097** to this function (pCtx) as its first parameter, and a pointer to a
14098** nul-terminated buffer containing the SQL statement formated as UTF-8 as
14099** the second. If the xSql callback returns any value other than SQLITE_OK,
14100** then processing is immediately abandoned and the value returned used as
14101** the recover handle error code (see below).
14102**
14103** If an out-of-memory error occurs, NULL may be returned instead of
14104** a valid handle. In all other cases, it is the responsibility of the
14105** application to avoid resource leaks by ensuring that
14106** sqlite3_recover_finish() is called on all allocated handles.
14107*/
14108sqlite3_recover *sqlite3_recover_init(
14109  sqlite3* db,
14110  const char *zDb,
14111  const char *zUri
14112);
14113sqlite3_recover *sqlite3_recover_init_sql(
14114  sqlite3* db,
14115  const char *zDb,
14116  int (*xSql)(void*, const char*),
14117  void *pCtx
14118);
14119
14120/*
14121** Configure an sqlite3_recover object that has just been created using
14122** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
14123** may only be called before the first call to sqlite3_recover_step()
14124** or sqlite3_recover_run() on the object.
14125**
14126** The second argument passed to this function must be one of the
14127** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
14128** depend on the specific SQLITE_RECOVER_* symbol in use.
14129**
14130** SQLITE_OK is returned if the configuration operation was successful,
14131** or an SQLite error code otherwise.
14132*/
14133int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
14134
14135/*
14136** SQLITE_RECOVER_LOST_AND_FOUND:
14137**   The pArg argument points to a string buffer containing the name
14138**   of a "lost-and-found" table in the output database, or NULL. If
14139**   the argument is non-NULL and the database contains seemingly
14140**   valid pages that cannot be associated with any table in the
14141**   recovered part of the schema, data is extracted from these
14142**   pages to add to the lost-and-found table.
14143**
14144** SQLITE_RECOVER_FREELIST_CORRUPT:
14145**   The pArg value must actually be a pointer to a value of type
14146**   int containing value 0 or 1 cast as a (void*). If this option is set
14147**   (argument is 1) and a lost-and-found table has been configured using
14148**   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
14149**   corrupt and an attempt is made to recover records from pages that
14150**   appear to be linked into the freelist. Otherwise, pages on the freelist
14151**   are ignored. Setting this option can recover more data from the
14152**   database, but often ends up "recovering" deleted records. The default
14153**   value is 0 (clear).
14154**
14155** SQLITE_RECOVER_ROWIDS:
14156**   The pArg value must actually be a pointer to a value of type
14157**   int containing value 0 or 1 cast as a (void*). If this option is set
14158**   (argument is 1), then an attempt is made to recover rowid values
14159**   that are not also INTEGER PRIMARY KEY values. If this option is
14160**   clear, then new rowids are assigned to all recovered rows. The
14161**   default value is 1 (set).
14162**
14163** SQLITE_RECOVER_SLOWINDEXES:
14164**   The pArg value must actually be a pointer to a value of type
14165**   int containing value 0 or 1 cast as a (void*). If this option is clear
14166**   (argument is 0), then when creating an output database, the recover
14167**   module creates and populates non-UNIQUE indexes right at the end of the
14168**   recovery operation - after all recoverable data has been inserted
14169**   into the new database. This is faster overall, but means that the
14170**   final call to sqlite3_recover_step() for a recovery operation may
14171**   be need to create a large number of indexes, which may be very slow.
14172**
14173**   Or, if this option is set (argument is 1), then non-UNIQUE indexes
14174**   are created in the output database before it is populated with
14175**   recovered data. This is slower overall, but avoids the slow call
14176**   to sqlite3_recover_step() at the end of the recovery operation.
14177**
14178**   The default option value is 0.
14179*/
14180#define SQLITE_RECOVER_LOST_AND_FOUND   1
14181#define SQLITE_RECOVER_FREELIST_CORRUPT 2
14182#define SQLITE_RECOVER_ROWIDS           3
14183#define SQLITE_RECOVER_SLOWINDEXES      4
14184
14185/*
14186** Perform a unit of work towards the recovery operation. This function
14187** must normally be called multiple times to complete database recovery.
14188**
14189** If no error occurs but the recovery operation is not completed, this
14190** function returns SQLITE_OK. If recovery has been completed successfully
14191** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
14192** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
14193** considered an error if some or all of the data cannot be recovered
14194** due to database corruption.
14195**
14196** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
14197** all further such calls on the same recover handle are no-ops that return
14198** the same non-SQLITE_OK value.
14199*/
14200int sqlite3_recover_step(sqlite3_recover*);
14201
14202/*
14203** Run the recovery operation to completion. Return SQLITE_OK if successful,
14204** or an SQLite error code otherwise. Calling this function is the same
14205** as executing:
14206**
14207**     while( SQLITE_OK==sqlite3_recover_step(p) );
14208**     return sqlite3_recover_errcode(p);
14209*/
14210int sqlite3_recover_run(sqlite3_recover*);
14211
14212/*
14213** If an error has been encountered during a prior call to
14214** sqlite3_recover_step(), then this function attempts to return a
14215** pointer to a buffer containing an English language explanation of
14216** the error. If no error message is available, or if an out-of memory
14217** error occurs while attempting to allocate a buffer in which to format
14218** the error message, NULL is returned.
14219**
14220** The returned buffer remains valid until the sqlite3_recover handle is
14221** destroyed using sqlite3_recover_finish().
14222*/
14223const char *sqlite3_recover_errmsg(sqlite3_recover*);
14224
14225/*
14226** If this function is called on an sqlite3_recover handle after
14227** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
14228*/
14229int sqlite3_recover_errcode(sqlite3_recover*);
14230
14231/*
14232** Clean up a recovery object created by a call to sqlite3_recover_init().
14233** The results of using a recovery object with any API after it has been
14234** passed to this function are undefined.
14235**
14236** This function returns the same value as sqlite3_recover_errcode().
14237*/
14238int sqlite3_recover_finish(sqlite3_recover*);
14239
14240
14241#ifdef __cplusplus
14242}  /* end of the 'extern "C"' block */
14243#endif
14244
14245#endif /* ifndef _SQLITE_RECOVER_H */
14246
14247/************************* End ../ext/recover/sqlite3recover.h ********************/
14248# ifndef SQLITE_HAVE_SQLITE3R
14249/************************* Begin ../ext/recover/dbdata.c ******************/
14250/*
14251** 2019-04-17
14252**
14253** The author disclaims copyright to this source code.  In place of
14254** a legal notice, here is a blessing:
14255**
14256**    May you do good and not evil.
14257**    May you find forgiveness for yourself and forgive others.
14258**    May you share freely, never taking more than you give.
14259**
14260******************************************************************************
14261**
14262** This file contains an implementation of two eponymous virtual tables,
14263** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
14264** "sqlite_dbpage" eponymous virtual table be available.
14265**
14266** SQLITE_DBDATA:
14267**   sqlite_dbdata is used to extract data directly from a database b-tree
14268**   page and its associated overflow pages, bypassing the b-tree layer.
14269**   The table schema is equivalent to:
14270**
14271**     CREATE TABLE sqlite_dbdata(
14272**       pgno INTEGER,
14273**       cell INTEGER,
14274**       field INTEGER,
14275**       value ANY,
14276**       schema TEXT HIDDEN
14277**     );
14278**
14279**   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
14280**   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
14281**   "schema".
14282**
14283**   Each page of the database is inspected. If it cannot be interpreted as
14284**   a b-tree page, or if it is a b-tree page containing 0 entries, the
14285**   sqlite_dbdata table contains no rows for that page.  Otherwise, the
14286**   table contains one row for each field in the record associated with
14287**   each cell on the page. For intkey b-trees, the key value is stored in
14288**   field -1.
14289**
14290**   For example, for the database:
14291**
14292**     CREATE TABLE t1(a, b);     -- root page is page 2
14293**     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
14294**     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
14295**
14296**   the sqlite_dbdata table contains, as well as from entries related to
14297**   page 1, content equivalent to:
14298**
14299**     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
14300**         (2, 0, -1, 5     ),
14301**         (2, 0,  0, 'v'   ),
14302**         (2, 0,  1, 'five'),
14303**         (2, 1, -1, 10    ),
14304**         (2, 1,  0, 'x'   ),
14305**         (2, 1,  1, 'ten' );
14306**
14307**   If database corruption is encountered, this module does not report an
14308**   error. Instead, it attempts to extract as much data as possible and
14309**   ignores the corruption.
14310**
14311** SQLITE_DBPTR:
14312**   The sqlite_dbptr table has the following schema:
14313**
14314**     CREATE TABLE sqlite_dbptr(
14315**       pgno INTEGER,
14316**       child INTEGER,
14317**       schema TEXT HIDDEN
14318**     );
14319**
14320**   It contains one entry for each b-tree pointer between a parent and
14321**   child page in the database.
14322*/
14323
14324#if !defined(SQLITEINT_H)
14325/* #include "sqlite3.h" */
14326
14327/* typedef unsigned char u8; */
14328/* typedef unsigned int u32; */
14329
14330#endif
14331#include <string.h>
14332#include <assert.h>
14333
14334#ifndef SQLITE_OMIT_VIRTUALTABLE
14335
14336#define DBDATA_PADDING_BYTES 100
14337
14338typedef struct DbdataTable DbdataTable;
14339typedef struct DbdataCursor DbdataCursor;
14340
14341/* Cursor object */
14342struct DbdataCursor {
14343  sqlite3_vtab_cursor base;       /* Base class.  Must be first */
14344  sqlite3_stmt *pStmt;            /* For fetching database pages */
14345
14346  int iPgno;                      /* Current page number */
14347  u8 *aPage;                      /* Buffer containing page */
14348  int nPage;                      /* Size of aPage[] in bytes */
14349  int nCell;                      /* Number of cells on aPage[] */
14350  int iCell;                      /* Current cell number */
14351  int bOnePage;                   /* True to stop after one page */
14352  int szDb;
14353  sqlite3_int64 iRowid;
14354
14355  /* Only for the sqlite_dbdata table */
14356  u8 *pRec;                       /* Buffer containing current record */
14357  sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
14358  sqlite3_int64 nHdr;             /* Size of header in bytes */
14359  int iField;                     /* Current field number */
14360  u8 *pHdrPtr;
14361  u8 *pPtr;
14362  u32 enc;                        /* Text encoding */
14363
14364  sqlite3_int64 iIntkey;          /* Integer key value */
14365};
14366
14367/* Table object */
14368struct DbdataTable {
14369  sqlite3_vtab base;              /* Base class.  Must be first */
14370  sqlite3 *db;                    /* The database connection */
14371  sqlite3_stmt *pStmt;            /* For fetching database pages */
14372  int bPtr;                       /* True for sqlite3_dbptr table */
14373};
14374
14375/* Column and schema definitions for sqlite_dbdata */
14376#define DBDATA_COLUMN_PGNO        0
14377#define DBDATA_COLUMN_CELL        1
14378#define DBDATA_COLUMN_FIELD       2
14379#define DBDATA_COLUMN_VALUE       3
14380#define DBDATA_COLUMN_SCHEMA      4
14381#define DBDATA_SCHEMA             \
14382      "CREATE TABLE x("           \
14383      "  pgno INTEGER,"           \
14384      "  cell INTEGER,"           \
14385      "  field INTEGER,"          \
14386      "  value ANY,"              \
14387      "  schema TEXT HIDDEN"      \
14388      ")"
14389
14390/* Column and schema definitions for sqlite_dbptr */
14391#define DBPTR_COLUMN_PGNO         0
14392#define DBPTR_COLUMN_CHILD        1
14393#define DBPTR_COLUMN_SCHEMA       2
14394#define DBPTR_SCHEMA              \
14395      "CREATE TABLE x("           \
14396      "  pgno INTEGER,"           \
14397      "  child INTEGER,"          \
14398      "  schema TEXT HIDDEN"      \
14399      ")"
14400
14401/*
14402** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
14403** table.
14404*/
14405static int dbdataConnect(
14406  sqlite3 *db,
14407  void *pAux,
14408  int argc, const char *const*argv,
14409  sqlite3_vtab **ppVtab,
14410  char **pzErr
14411){
14412  DbdataTable *pTab = 0;
14413  int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
14414
14415  (void)argc;
14416  (void)argv;
14417  (void)pzErr;
14418  sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
14419  if( rc==SQLITE_OK ){
14420    pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
14421    if( pTab==0 ){
14422      rc = SQLITE_NOMEM;
14423    }else{
14424      memset(pTab, 0, sizeof(DbdataTable));
14425      pTab->db = db;
14426      pTab->bPtr = (pAux!=0);
14427    }
14428  }
14429
14430  *ppVtab = (sqlite3_vtab*)pTab;
14431  return rc;
14432}
14433
14434/*
14435** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
14436*/
14437static int dbdataDisconnect(sqlite3_vtab *pVtab){
14438  DbdataTable *pTab = (DbdataTable*)pVtab;
14439  if( pTab ){
14440    sqlite3_finalize(pTab->pStmt);
14441    sqlite3_free(pVtab);
14442  }
14443  return SQLITE_OK;
14444}
14445
14446/*
14447** This function interprets two types of constraints:
14448**
14449**       schema=?
14450**       pgno=?
14451**
14452** If neither are present, idxNum is set to 0. If schema=? is present,
14453** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
14454** in idxNum is set.
14455**
14456** If both parameters are present, schema is in position 0 and pgno in
14457** position 1.
14458*/
14459static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
14460  DbdataTable *pTab = (DbdataTable*)tab;
14461  int i;
14462  int iSchema = -1;
14463  int iPgno = -1;
14464  int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
14465
14466  for(i=0; i<pIdx->nConstraint; i++){
14467    struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
14468    if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
14469      if( p->iColumn==colSchema ){
14470        if( p->usable==0 ) return SQLITE_CONSTRAINT;
14471        iSchema = i;
14472      }
14473      if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
14474        iPgno = i;
14475      }
14476    }
14477  }
14478
14479  if( iSchema>=0 ){
14480    pIdx->aConstraintUsage[iSchema].argvIndex = 1;
14481    pIdx->aConstraintUsage[iSchema].omit = 1;
14482  }
14483  if( iPgno>=0 ){
14484    pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
14485    pIdx->aConstraintUsage[iPgno].omit = 1;
14486    pIdx->estimatedCost = 100;
14487    pIdx->estimatedRows =  50;
14488
14489    if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
14490      int iCol = pIdx->aOrderBy[0].iColumn;
14491      if( pIdx->nOrderBy==1 ){
14492        pIdx->orderByConsumed = (iCol==0 || iCol==1);
14493      }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
14494        pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
14495      }
14496    }
14497
14498  }else{
14499    pIdx->estimatedCost = 100000000;
14500    pIdx->estimatedRows = 1000000000;
14501  }
14502  pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
14503  return SQLITE_OK;
14504}
14505
14506/*
14507** Open a new sqlite_dbdata or sqlite_dbptr cursor.
14508*/
14509static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
14510  DbdataCursor *pCsr;
14511
14512  pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
14513  if( pCsr==0 ){
14514    return SQLITE_NOMEM;
14515  }else{
14516    memset(pCsr, 0, sizeof(DbdataCursor));
14517    pCsr->base.pVtab = pVTab;
14518  }
14519
14520  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
14521  return SQLITE_OK;
14522}
14523
14524/*
14525** Restore a cursor object to the state it was in when first allocated
14526** by dbdataOpen().
14527*/
14528static void dbdataResetCursor(DbdataCursor *pCsr){
14529  DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
14530  if( pTab->pStmt==0 ){
14531    pTab->pStmt = pCsr->pStmt;
14532  }else{
14533    sqlite3_finalize(pCsr->pStmt);
14534  }
14535  pCsr->pStmt = 0;
14536  pCsr->iPgno = 1;
14537  pCsr->iCell = 0;
14538  pCsr->iField = 0;
14539  pCsr->bOnePage = 0;
14540  sqlite3_free(pCsr->aPage);
14541  sqlite3_free(pCsr->pRec);
14542  pCsr->pRec = 0;
14543  pCsr->aPage = 0;
14544}
14545
14546/*
14547** Close an sqlite_dbdata or sqlite_dbptr cursor.
14548*/
14549static int dbdataClose(sqlite3_vtab_cursor *pCursor){
14550  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14551  dbdataResetCursor(pCsr);
14552  sqlite3_free(pCsr);
14553  return SQLITE_OK;
14554}
14555
14556/*
14557** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
14558*/
14559static u32 get_uint16(unsigned char *a){
14560  return (a[0]<<8)|a[1];
14561}
14562static u32 get_uint32(unsigned char *a){
14563  return ((u32)a[0]<<24)
14564       | ((u32)a[1]<<16)
14565       | ((u32)a[2]<<8)
14566       | ((u32)a[3]);
14567}
14568
14569/*
14570** Load page pgno from the database via the sqlite_dbpage virtual table.
14571** If successful, set (*ppPage) to point to a buffer containing the page
14572** data, (*pnPage) to the size of that buffer in bytes and return
14573** SQLITE_OK. In this case it is the responsibility of the caller to
14574** eventually free the buffer using sqlite3_free().
14575**
14576** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
14577** return an SQLite error code.
14578*/
14579static int dbdataLoadPage(
14580  DbdataCursor *pCsr,             /* Cursor object */
14581  u32 pgno,                       /* Page number of page to load */
14582  u8 **ppPage,                    /* OUT: pointer to page buffer */
14583  int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
14584){
14585  int rc2;
14586  int rc = SQLITE_OK;
14587  sqlite3_stmt *pStmt = pCsr->pStmt;
14588
14589  *ppPage = 0;
14590  *pnPage = 0;
14591  if( pgno>0 ){
14592    sqlite3_bind_int64(pStmt, 2, pgno);
14593    if( SQLITE_ROW==sqlite3_step(pStmt) ){
14594      int nCopy = sqlite3_column_bytes(pStmt, 0);
14595      if( nCopy>0 ){
14596        u8 *pPage;
14597        pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
14598        if( pPage==0 ){
14599          rc = SQLITE_NOMEM;
14600        }else{
14601          const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
14602          memcpy(pPage, pCopy, nCopy);
14603          memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
14604        }
14605        *ppPage = pPage;
14606        *pnPage = nCopy;
14607      }
14608    }
14609    rc2 = sqlite3_reset(pStmt);
14610    if( rc==SQLITE_OK ) rc = rc2;
14611  }
14612
14613  return rc;
14614}
14615
14616/*
14617** Read a varint.  Put the value in *pVal and return the number of bytes.
14618*/
14619static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
14620  sqlite3_uint64 u = 0;
14621  int i;
14622  for(i=0; i<8; i++){
14623    u = (u<<7) + (z[i]&0x7f);
14624    if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
14625  }
14626  u = (u<<8) + (z[i]&0xff);
14627  *pVal = (sqlite3_int64)u;
14628  return 9;
14629}
14630
14631/*
14632** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
14633** or greater than 0xFFFFFFFF. This can be used for all varints in an
14634** SQLite database except for key values in intkey tables.
14635*/
14636static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
14637  sqlite3_int64 val;
14638  int nRet = dbdataGetVarint(z, &val);
14639  if( val<0 || val>0xFFFFFFFF ) val = 0;
14640  *pVal = val;
14641  return nRet;
14642}
14643
14644/*
14645** Return the number of bytes of space used by an SQLite value of type
14646** eType.
14647*/
14648static int dbdataValueBytes(int eType){
14649  switch( eType ){
14650    case 0: case 8: case 9:
14651    case 10: case 11:
14652      return 0;
14653    case 1:
14654      return 1;
14655    case 2:
14656      return 2;
14657    case 3:
14658      return 3;
14659    case 4:
14660      return 4;
14661    case 5:
14662      return 6;
14663    case 6:
14664    case 7:
14665      return 8;
14666    default:
14667      if( eType>0 ){
14668        return ((eType-12) / 2);
14669      }
14670      return 0;
14671  }
14672}
14673
14674/*
14675** Load a value of type eType from buffer pData and use it to set the
14676** result of context object pCtx.
14677*/
14678static void dbdataValue(
14679  sqlite3_context *pCtx,
14680  u32 enc,
14681  int eType,
14682  u8 *pData,
14683  sqlite3_int64 nData
14684){
14685  if( eType>=0 && dbdataValueBytes(eType)<=nData ){
14686    switch( eType ){
14687      case 0:
14688      case 10:
14689      case 11:
14690        sqlite3_result_null(pCtx);
14691        break;
14692
14693      case 8:
14694        sqlite3_result_int(pCtx, 0);
14695        break;
14696      case 9:
14697        sqlite3_result_int(pCtx, 1);
14698        break;
14699
14700      case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
14701        sqlite3_uint64 v = (signed char)pData[0];
14702        pData++;
14703        switch( eType ){
14704          case 7:
14705          case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
14706          case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
14707          case 4:  v = (v<<8) + pData[0];  pData++;
14708          case 3:  v = (v<<8) + pData[0];  pData++;
14709          case 2:  v = (v<<8) + pData[0];  pData++;
14710        }
14711
14712        if( eType==7 ){
14713          double r;
14714          memcpy(&r, &v, sizeof(r));
14715          sqlite3_result_double(pCtx, r);
14716        }else{
14717          sqlite3_result_int64(pCtx, (sqlite3_int64)v);
14718        }
14719        break;
14720      }
14721
14722      default: {
14723        int n = ((eType-12) / 2);
14724        if( eType % 2 ){
14725          switch( enc ){
14726#ifndef SQLITE_OMIT_UTF16
14727            case SQLITE_UTF16BE:
14728              sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14729              break;
14730            case SQLITE_UTF16LE:
14731              sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14732              break;
14733#endif
14734            default:
14735              sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
14736              break;
14737          }
14738        }else{
14739          sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
14740        }
14741      }
14742    }
14743  }
14744}
14745
14746/*
14747** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
14748*/
14749static int dbdataNext(sqlite3_vtab_cursor *pCursor){
14750  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14751  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
14752
14753  pCsr->iRowid++;
14754  while( 1 ){
14755    int rc;
14756    int iOff = (pCsr->iPgno==1 ? 100 : 0);
14757    int bNextPage = 0;
14758
14759    if( pCsr->aPage==0 ){
14760      while( 1 ){
14761        if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
14762        rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
14763        if( rc!=SQLITE_OK ) return rc;
14764        if( pCsr->aPage && pCsr->nPage>=256 ) break;
14765        sqlite3_free(pCsr->aPage);
14766        pCsr->aPage = 0;
14767        if( pCsr->bOnePage ) return SQLITE_OK;
14768        pCsr->iPgno++;
14769      }
14770
14771      assert( iOff+3+2<=pCsr->nPage );
14772      pCsr->iCell = pTab->bPtr ? -2 : 0;
14773      pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
14774    }
14775
14776    if( pTab->bPtr ){
14777      if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
14778        pCsr->iCell = pCsr->nCell;
14779      }
14780      pCsr->iCell++;
14781      if( pCsr->iCell>=pCsr->nCell ){
14782        sqlite3_free(pCsr->aPage);
14783        pCsr->aPage = 0;
14784        if( pCsr->bOnePage ) return SQLITE_OK;
14785        pCsr->iPgno++;
14786      }else{
14787        return SQLITE_OK;
14788      }
14789    }else{
14790      /* If there is no record loaded, load it now. */
14791      if( pCsr->pRec==0 ){
14792        int bHasRowid = 0;
14793        int nPointer = 0;
14794        sqlite3_int64 nPayload = 0;
14795        sqlite3_int64 nHdr = 0;
14796        int iHdr;
14797        int U, X;
14798        int nLocal;
14799
14800        switch( pCsr->aPage[iOff] ){
14801          case 0x02:
14802            nPointer = 4;
14803            break;
14804          case 0x0a:
14805            break;
14806          case 0x0d:
14807            bHasRowid = 1;
14808            break;
14809          default:
14810            /* This is not a b-tree page with records on it. Continue. */
14811            pCsr->iCell = pCsr->nCell;
14812            break;
14813        }
14814
14815        if( pCsr->iCell>=pCsr->nCell ){
14816          bNextPage = 1;
14817        }else{
14818
14819          iOff += 8 + nPointer + pCsr->iCell*2;
14820          if( iOff>pCsr->nPage ){
14821            bNextPage = 1;
14822          }else{
14823            iOff = get_uint16(&pCsr->aPage[iOff]);
14824          }
14825
14826          /* For an interior node cell, skip past the child-page number */
14827          iOff += nPointer;
14828
14829          /* Load the "byte of payload including overflow" field */
14830          if( bNextPage || iOff>pCsr->nPage ){
14831            bNextPage = 1;
14832          }else{
14833            iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
14834            if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
14835          }
14836
14837          /* If this is a leaf intkey cell, load the rowid */
14838          if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
14839            iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
14840          }
14841
14842          /* Figure out how much data to read from the local page */
14843          U = pCsr->nPage;
14844          if( bHasRowid ){
14845            X = U-35;
14846          }else{
14847            X = ((U-12)*64/255)-23;
14848          }
14849          if( nPayload<=X ){
14850            nLocal = nPayload;
14851          }else{
14852            int M, K;
14853            M = ((U-12)*32/255)-23;
14854            K = M+((nPayload-M)%(U-4));
14855            if( K<=X ){
14856              nLocal = K;
14857            }else{
14858              nLocal = M;
14859            }
14860          }
14861
14862          if( bNextPage || nLocal+iOff>pCsr->nPage ){
14863            bNextPage = 1;
14864          }else{
14865
14866            /* Allocate space for payload. And a bit more to catch small buffer
14867            ** overruns caused by attempting to read a varint or similar from
14868            ** near the end of a corrupt record.  */
14869            pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
14870            if( pCsr->pRec==0 ) return SQLITE_NOMEM;
14871            memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
14872            pCsr->nRec = nPayload;
14873
14874            /* Load the nLocal bytes of payload */
14875            memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
14876            iOff += nLocal;
14877
14878            /* Load content from overflow pages */
14879            if( nPayload>nLocal ){
14880              sqlite3_int64 nRem = nPayload - nLocal;
14881              u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
14882              while( nRem>0 ){
14883                u8 *aOvfl = 0;
14884                int nOvfl = 0;
14885                int nCopy;
14886                rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
14887                assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
14888                if( rc!=SQLITE_OK ) return rc;
14889                if( aOvfl==0 ) break;
14890
14891                nCopy = U-4;
14892                if( nCopy>nRem ) nCopy = nRem;
14893                memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
14894                nRem -= nCopy;
14895
14896                pgnoOvfl = get_uint32(aOvfl);
14897                sqlite3_free(aOvfl);
14898              }
14899            }
14900
14901            iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
14902            if( nHdr>nPayload ) nHdr = 0;
14903            pCsr->nHdr = nHdr;
14904            pCsr->pHdrPtr = &pCsr->pRec[iHdr];
14905            pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
14906            pCsr->iField = (bHasRowid ? -1 : 0);
14907          }
14908        }
14909      }else{
14910        pCsr->iField++;
14911        if( pCsr->iField>0 ){
14912          sqlite3_int64 iType;
14913          if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
14914            bNextPage = 1;
14915          }else{
14916            int szField = 0;
14917            pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
14918            szField = dbdataValueBytes(iType);
14919            if( (pCsr->nRec - (pCsr->pPtr - pCsr->pRec))<szField ){
14920              pCsr->pPtr = &pCsr->pRec[pCsr->nRec];
14921            }else{
14922              pCsr->pPtr += szField;
14923            }
14924          }
14925        }
14926      }
14927
14928      if( bNextPage ){
14929        sqlite3_free(pCsr->aPage);
14930        sqlite3_free(pCsr->pRec);
14931        pCsr->aPage = 0;
14932        pCsr->pRec = 0;
14933        if( pCsr->bOnePage ) return SQLITE_OK;
14934        pCsr->iPgno++;
14935      }else{
14936        if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
14937          return SQLITE_OK;
14938        }
14939
14940        /* Advance to the next cell. The next iteration of the loop will load
14941        ** the record and so on. */
14942        sqlite3_free(pCsr->pRec);
14943        pCsr->pRec = 0;
14944        pCsr->iCell++;
14945      }
14946    }
14947  }
14948
14949  assert( !"can't get here" );
14950  return SQLITE_OK;
14951}
14952
14953/*
14954** Return true if the cursor is at EOF.
14955*/
14956static int dbdataEof(sqlite3_vtab_cursor *pCursor){
14957  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14958  return pCsr->aPage==0;
14959}
14960
14961/*
14962** Return true if nul-terminated string zSchema ends in "()". Or false
14963** otherwise.
14964*/
14965static int dbdataIsFunction(const char *zSchema){
14966  size_t n = strlen(zSchema);
14967  if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
14968    return (int)n-2;
14969  }
14970  return 0;
14971}
14972
14973/*
14974** Determine the size in pages of database zSchema (where zSchema is
14975** "main", "temp" or the name of an attached database) and set
14976** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
14977** an SQLite error code.
14978*/
14979static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
14980  DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
14981  char *zSql = 0;
14982  int rc, rc2;
14983  int nFunc = 0;
14984  sqlite3_stmt *pStmt = 0;
14985
14986  if( (nFunc = dbdataIsFunction(zSchema))>0 ){
14987    zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
14988  }else{
14989    zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
14990  }
14991  if( zSql==0 ) return SQLITE_NOMEM;
14992
14993  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
14994  sqlite3_free(zSql);
14995  if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
14996    pCsr->szDb = sqlite3_column_int(pStmt, 0);
14997  }
14998  rc2 = sqlite3_finalize(pStmt);
14999  if( rc==SQLITE_OK ) rc = rc2;
15000  return rc;
15001}
15002
15003/*
15004** Attempt to figure out the encoding of the database by retrieving page 1
15005** and inspecting the header field. If successful, set the pCsr->enc variable
15006** and return SQLITE_OK. Otherwise, return an SQLite error code.
15007*/
15008static int dbdataGetEncoding(DbdataCursor *pCsr){
15009  int rc = SQLITE_OK;
15010  int nPg1 = 0;
15011  u8 *aPg1 = 0;
15012  rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
15013  if( rc==SQLITE_OK && nPg1>=(56+4) ){
15014    pCsr->enc = get_uint32(&aPg1[56]);
15015  }
15016  sqlite3_free(aPg1);
15017  return rc;
15018}
15019
15020
15021/*
15022** xFilter method for sqlite_dbdata and sqlite_dbptr.
15023*/
15024static int dbdataFilter(
15025  sqlite3_vtab_cursor *pCursor,
15026  int idxNum, const char *idxStr,
15027  int argc, sqlite3_value **argv
15028){
15029  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15030  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
15031  int rc = SQLITE_OK;
15032  const char *zSchema = "main";
15033  (void)idxStr;
15034  (void)argc;
15035
15036  dbdataResetCursor(pCsr);
15037  assert( pCsr->iPgno==1 );
15038  if( idxNum & 0x01 ){
15039    zSchema = (const char*)sqlite3_value_text(argv[0]);
15040    if( zSchema==0 ) zSchema = "";
15041  }
15042  if( idxNum & 0x02 ){
15043    pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
15044    pCsr->bOnePage = 1;
15045  }else{
15046    rc = dbdataDbsize(pCsr, zSchema);
15047  }
15048
15049  if( rc==SQLITE_OK ){
15050    int nFunc = 0;
15051    if( pTab->pStmt ){
15052      pCsr->pStmt = pTab->pStmt;
15053      pTab->pStmt = 0;
15054    }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
15055      char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
15056      if( zSql==0 ){
15057        rc = SQLITE_NOMEM;
15058      }else{
15059        rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
15060        sqlite3_free(zSql);
15061      }
15062    }else{
15063      rc = sqlite3_prepare_v2(pTab->db,
15064          "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
15065          &pCsr->pStmt, 0
15066      );
15067    }
15068  }
15069  if( rc==SQLITE_OK ){
15070    rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
15071  }
15072
15073  /* Try to determine the encoding of the db by inspecting the header
15074  ** field on page 1. */
15075  if( rc==SQLITE_OK ){
15076    rc = dbdataGetEncoding(pCsr);
15077  }
15078
15079  if( rc!=SQLITE_OK ){
15080    pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
15081  }
15082
15083  if( rc==SQLITE_OK ){
15084    rc = dbdataNext(pCursor);
15085  }
15086  return rc;
15087}
15088
15089/*
15090** Return a column for the sqlite_dbdata or sqlite_dbptr table.
15091*/
15092static int dbdataColumn(
15093  sqlite3_vtab_cursor *pCursor,
15094  sqlite3_context *ctx,
15095  int i
15096){
15097  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15098  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
15099  if( pTab->bPtr ){
15100    switch( i ){
15101      case DBPTR_COLUMN_PGNO:
15102        sqlite3_result_int64(ctx, pCsr->iPgno);
15103        break;
15104      case DBPTR_COLUMN_CHILD: {
15105        int iOff = pCsr->iPgno==1 ? 100 : 0;
15106        if( pCsr->iCell<0 ){
15107          iOff += 8;
15108        }else{
15109          iOff += 12 + pCsr->iCell*2;
15110          if( iOff>pCsr->nPage ) return SQLITE_OK;
15111          iOff = get_uint16(&pCsr->aPage[iOff]);
15112        }
15113        if( iOff<=pCsr->nPage ){
15114          sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
15115        }
15116        break;
15117      }
15118    }
15119  }else{
15120    switch( i ){
15121      case DBDATA_COLUMN_PGNO:
15122        sqlite3_result_int64(ctx, pCsr->iPgno);
15123        break;
15124      case DBDATA_COLUMN_CELL:
15125        sqlite3_result_int(ctx, pCsr->iCell);
15126        break;
15127      case DBDATA_COLUMN_FIELD:
15128        sqlite3_result_int(ctx, pCsr->iField);
15129        break;
15130      case DBDATA_COLUMN_VALUE: {
15131        if( pCsr->iField<0 ){
15132          sqlite3_result_int64(ctx, pCsr->iIntkey);
15133        }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
15134          sqlite3_int64 iType;
15135          dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
15136          dbdataValue(
15137              ctx, pCsr->enc, iType, pCsr->pPtr,
15138              &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
15139          );
15140        }
15141        break;
15142      }
15143    }
15144  }
15145  return SQLITE_OK;
15146}
15147
15148/*
15149** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
15150*/
15151static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
15152  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15153  *pRowid = pCsr->iRowid;
15154  return SQLITE_OK;
15155}
15156
15157
15158/*
15159** Invoke this routine to register the "sqlite_dbdata" virtual table module
15160*/
15161static int sqlite3DbdataRegister(sqlite3 *db){
15162  static sqlite3_module dbdata_module = {
15163    0,                            /* iVersion */
15164    0,                            /* xCreate */
15165    dbdataConnect,                /* xConnect */
15166    dbdataBestIndex,              /* xBestIndex */
15167    dbdataDisconnect,             /* xDisconnect */
15168    0,                            /* xDestroy */
15169    dbdataOpen,                   /* xOpen - open a cursor */
15170    dbdataClose,                  /* xClose - close a cursor */
15171    dbdataFilter,                 /* xFilter - configure scan constraints */
15172    dbdataNext,                   /* xNext - advance a cursor */
15173    dbdataEof,                    /* xEof - check for end of scan */
15174    dbdataColumn,                 /* xColumn - read data */
15175    dbdataRowid,                  /* xRowid - read data */
15176    0,                            /* xUpdate */
15177    0,                            /* xBegin */
15178    0,                            /* xSync */
15179    0,                            /* xCommit */
15180    0,                            /* xRollback */
15181    0,                            /* xFindMethod */
15182    0,                            /* xRename */
15183    0,                            /* xSavepoint */
15184    0,                            /* xRelease */
15185    0,                            /* xRollbackTo */
15186    0,                            /* xShadowName */
15187    0                             /* xIntegrity */
15188  };
15189
15190  int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
15191  if( rc==SQLITE_OK ){
15192    rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
15193  }
15194  return rc;
15195}
15196
15197int sqlite3_dbdata_init(
15198  sqlite3 *db,
15199  char **pzErrMsg,
15200  const sqlite3_api_routines *pApi
15201){
15202  (void)pzErrMsg;
15203  return sqlite3DbdataRegister(db);
15204}
15205
15206#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
15207
15208/************************* End ../ext/recover/dbdata.c ********************/
15209/************************* Begin ../ext/recover/sqlite3recover.c ******************/
15210/*
15211** 2022-08-27
15212**
15213** The author disclaims copyright to this source code.  In place of
15214** a legal notice, here is a blessing:
15215**
15216**    May you do good and not evil.
15217**    May you find forgiveness for yourself and forgive others.
15218**    May you share freely, never taking more than you give.
15219**
15220*************************************************************************
15221**
15222*/
15223
15224
15225/* #include "sqlite3recover.h" */
15226#include <assert.h>
15227#include <string.h>
15228
15229#ifndef SQLITE_OMIT_VIRTUALTABLE
15230
15231/*
15232** Declaration for public API function in file dbdata.c. This may be called
15233** with NULL as the final two arguments to register the sqlite_dbptr and
15234** sqlite_dbdata virtual tables with a database handle.
15235*/
15236#ifdef _WIN32
15237
15238#endif
15239int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
15240
15241/* typedef unsigned int u32; */
15242/* typedef unsigned char u8; */
15243/* typedef sqlite3_int64 i64; */
15244
15245typedef struct RecoverTable RecoverTable;
15246typedef struct RecoverColumn RecoverColumn;
15247
15248/*
15249** When recovering rows of data that can be associated with table
15250** definitions recovered from the sqlite_schema table, each table is
15251** represented by an instance of the following object.
15252**
15253** iRoot:
15254**   The root page in the original database. Not necessarily (and usually
15255**   not) the same in the recovered database.
15256**
15257** zTab:
15258**   Name of the table.
15259**
15260** nCol/aCol[]:
15261**   aCol[] is an array of nCol columns. In the order in which they appear
15262**   in the table.
15263**
15264** bIntkey:
15265**   Set to true for intkey tables, false for WITHOUT ROWID.
15266**
15267** iRowidBind:
15268**   Each column in the aCol[] array has associated with it the index of
15269**   the bind parameter its values will be bound to in the INSERT statement
15270**   used to construct the output database. If the table does has a rowid
15271**   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
15272**   index of the bind paramater to which the rowid value should be bound.
15273**   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
15274**   KEY column, then the rowid value should be bound to the index associated
15275**   with the column.
15276**
15277** pNext:
15278**   All RecoverTable objects used by the recovery operation are allocated
15279**   and populated as part of creating the recovered database schema in
15280**   the output database, before any non-schema data are recovered. They
15281**   are then stored in a singly-linked list linked by this variable beginning
15282**   at sqlite3_recover.pTblList.
15283*/
15284struct RecoverTable {
15285  u32 iRoot;                      /* Root page in original database */
15286  char *zTab;                     /* Name of table */
15287  int nCol;                       /* Number of columns in table */
15288  RecoverColumn *aCol;            /* Array of columns */
15289  int bIntkey;                    /* True for intkey, false for without rowid */
15290  int iRowidBind;                 /* If >0, bind rowid to INSERT here */
15291  RecoverTable *pNext;
15292};
15293
15294/*
15295** Each database column is represented by an instance of the following object
15296** stored in the RecoverTable.aCol[] array of the associated table.
15297**
15298** iField:
15299**   The index of the associated field within database records. Or -1 if
15300**   there is no associated field (e.g. for virtual generated columns).
15301**
15302** iBind:
15303**   The bind index of the INSERT statement to bind this columns values
15304**   to. Or 0 if there is no such index (iff (iField<0)).
15305**
15306** bIPK:
15307**   True if this is the INTEGER PRIMARY KEY column.
15308**
15309** zCol:
15310**   Name of column.
15311**
15312** eHidden:
15313**   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
15314*/
15315struct RecoverColumn {
15316  int iField;                     /* Field in record on disk */
15317  int iBind;                      /* Binding to use in INSERT */
15318  int bIPK;                       /* True for IPK column */
15319  char *zCol;
15320  int eHidden;
15321};
15322
15323#define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
15324#define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
15325#define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
15326#define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
15327
15328/*
15329** Bitmap object used to track pages in the input database. Allocated
15330** and manipulated only by the following functions:
15331**
15332**     recoverBitmapAlloc()
15333**     recoverBitmapFree()
15334**     recoverBitmapSet()
15335**     recoverBitmapQuery()
15336**
15337** nPg:
15338**   Largest page number that may be stored in the bitmap. The range
15339**   of valid keys is 1 to nPg, inclusive.
15340**
15341** aElem[]:
15342**   Array large enough to contain a bit for each key. For key value
15343**   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
15344**   In other words, the following is true if bit iKey is set, or
15345**   false if it is clear:
15346**
15347**       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
15348*/
15349typedef struct RecoverBitmap RecoverBitmap;
15350struct RecoverBitmap {
15351  i64 nPg;                        /* Size of bitmap */
15352  u32 aElem[1];                   /* Array of 32-bit bitmasks */
15353};
15354
15355/*
15356** State variables (part of the sqlite3_recover structure) used while
15357** recovering data for tables identified in the recovered schema (state
15358** RECOVER_STATE_WRITING).
15359*/
15360typedef struct RecoverStateW1 RecoverStateW1;
15361struct RecoverStateW1 {
15362  sqlite3_stmt *pTbls;
15363  sqlite3_stmt *pSel;
15364  sqlite3_stmt *pInsert;
15365  int nInsert;
15366
15367  RecoverTable *pTab;             /* Table currently being written */
15368  int nMax;                       /* Max column count in any schema table */
15369  sqlite3_value **apVal;          /* Array of nMax values */
15370  int nVal;                       /* Number of valid entries in apVal[] */
15371  int bHaveRowid;
15372  i64 iRowid;
15373  i64 iPrevPage;
15374  int iPrevCell;
15375};
15376
15377/*
15378** State variables (part of the sqlite3_recover structure) used while
15379** recovering data destined for the lost and found table (states
15380** RECOVER_STATE_LOSTANDFOUND[123]).
15381*/
15382typedef struct RecoverStateLAF RecoverStateLAF;
15383struct RecoverStateLAF {
15384  RecoverBitmap *pUsed;
15385  i64 nPg;                        /* Size of db in pages */
15386  sqlite3_stmt *pAllAndParent;
15387  sqlite3_stmt *pMapInsert;
15388  sqlite3_stmt *pMaxField;
15389  sqlite3_stmt *pUsedPages;
15390  sqlite3_stmt *pFindRoot;
15391  sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
15392  sqlite3_stmt *pAllPage;
15393  sqlite3_stmt *pPageData;
15394  sqlite3_value **apVal;
15395  int nMaxField;
15396};
15397
15398/*
15399** Main recover handle structure.
15400*/
15401struct sqlite3_recover {
15402  /* Copies of sqlite3_recover_init[_sql]() parameters */
15403  sqlite3 *dbIn;                  /* Input database */
15404  char *zDb;                      /* Name of input db ("main" etc.) */
15405  char *zUri;                     /* URI for output database */
15406  void *pSqlCtx;                  /* SQL callback context */
15407  int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
15408
15409  /* Values configured by sqlite3_recover_config() */
15410  char *zStateDb;                 /* State database to use (or NULL) */
15411  char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
15412  int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
15413  int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
15414  int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
15415
15416  int pgsz;
15417  int detected_pgsz;
15418  int nReserve;
15419  u8 *pPage1Disk;
15420  u8 *pPage1Cache;
15421
15422  /* Error code and error message */
15423  int errCode;                    /* For sqlite3_recover_errcode() */
15424  char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
15425
15426  int eState;
15427  int bCloseTransaction;
15428
15429  /* Variables used with eState==RECOVER_STATE_WRITING */
15430  RecoverStateW1 w1;
15431
15432  /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
15433  RecoverStateLAF laf;
15434
15435  /* Fields used within sqlite3_recover_run() */
15436  sqlite3 *dbOut;                 /* Output database */
15437  sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
15438  RecoverTable *pTblList;         /* List of tables recovered from schema */
15439};
15440
15441/*
15442** The various states in which an sqlite3_recover object may exist:
15443**
15444**   RECOVER_STATE_INIT:
15445**    The object is initially created in this state. sqlite3_recover_step()
15446**    has yet to be called. This is the only state in which it is permitted
15447**    to call sqlite3_recover_config().
15448**
15449**   RECOVER_STATE_WRITING:
15450**
15451**   RECOVER_STATE_LOSTANDFOUND1:
15452**    State to populate the bitmap of pages used by other tables or the
15453**    database freelist.
15454**
15455**   RECOVER_STATE_LOSTANDFOUND2:
15456**    Populate the recovery.map table - used to figure out a "root" page
15457**    for each lost page from in the database from which records are
15458**    extracted.
15459**
15460**   RECOVER_STATE_LOSTANDFOUND3:
15461**    Populate the lost-and-found table itself.
15462*/
15463#define RECOVER_STATE_INIT           0
15464#define RECOVER_STATE_WRITING        1
15465#define RECOVER_STATE_LOSTANDFOUND1  2
15466#define RECOVER_STATE_LOSTANDFOUND2  3
15467#define RECOVER_STATE_LOSTANDFOUND3  4
15468#define RECOVER_STATE_SCHEMA2        5
15469#define RECOVER_STATE_DONE           6
15470
15471
15472/*
15473** Global variables used by this extension.
15474*/
15475typedef struct RecoverGlobal RecoverGlobal;
15476struct RecoverGlobal {
15477  const sqlite3_io_methods *pMethods;
15478  sqlite3_recover *p;
15479};
15480static RecoverGlobal recover_g;
15481
15482/*
15483** Use this static SQLite mutex to protect the globals during the
15484** first call to sqlite3_recover_step().
15485*/
15486#define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
15487
15488
15489/*
15490** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
15491*/
15492#define RECOVER_ROWID_DEFAULT 1
15493
15494/*
15495** Mutex handling:
15496**
15497**    recoverEnterMutex()       -   Enter the recovery mutex
15498**    recoverLeaveMutex()       -   Leave the recovery mutex
15499**    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
15500*/
15501#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
15502# define recoverEnterMutex()
15503# define recoverLeaveMutex()
15504#else
15505static void recoverEnterMutex(void){
15506  sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
15507}
15508static void recoverLeaveMutex(void){
15509  sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
15510}
15511#endif
15512#if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
15513static void recoverAssertMutexHeld(void){
15514  assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
15515}
15516#else
15517# define recoverAssertMutexHeld()
15518#endif
15519
15520
15521/*
15522** Like strlen(). But handles NULL pointer arguments.
15523*/
15524static int recoverStrlen(const char *zStr){
15525  if( zStr==0 ) return 0;
15526  return (int)(strlen(zStr)&0x7fffffff);
15527}
15528
15529/*
15530** This function is a no-op if the recover handle passed as the first
15531** argument already contains an error (if p->errCode!=SQLITE_OK).
15532**
15533** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
15534** bytes in size. If successful, a pointer to the new buffer is returned. Or,
15535** if an OOM error occurs, NULL is returned and the handle error code
15536** (p->errCode) set to SQLITE_NOMEM.
15537*/
15538static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
15539  void *pRet = 0;
15540  assert( nByte>0 );
15541  if( p->errCode==SQLITE_OK ){
15542    pRet = sqlite3_malloc64(nByte);
15543    if( pRet ){
15544      memset(pRet, 0, nByte);
15545    }else{
15546      p->errCode = SQLITE_NOMEM;
15547    }
15548  }
15549  return pRet;
15550}
15551
15552/*
15553** Set the error code and error message for the recover handle passed as
15554** the first argument. The error code is set to the value of parameter
15555** errCode.
15556**
15557** Parameter zFmt must be a printf() style formatting string. The handle
15558** error message is set to the result of using any trailing arguments for
15559** parameter substitutions in the formatting string.
15560**
15561** For example:
15562**
15563**   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
15564*/
15565static int recoverError(
15566  sqlite3_recover *p,
15567  int errCode,
15568  const char *zFmt, ...
15569){
15570  char *z = 0;
15571  va_list ap;
15572  va_start(ap, zFmt);
15573  if( zFmt ){
15574    z = sqlite3_vmprintf(zFmt, ap);
15575    va_end(ap);
15576  }
15577  sqlite3_free(p->zErrMsg);
15578  p->zErrMsg = z;
15579  p->errCode = errCode;
15580  return errCode;
15581}
15582
15583
15584/*
15585** This function is a no-op if p->errCode is initially other than SQLITE_OK.
15586** In this case it returns NULL.
15587**
15588** Otherwise, an attempt is made to allocate and return a bitmap object
15589** large enough to store a bit for all page numbers between 1 and nPg,
15590** inclusive. The bitmap is initially zeroed.
15591*/
15592static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
15593  int nElem = (nPg+1+31) / 32;
15594  int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
15595  RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
15596
15597  if( pRet ){
15598    pRet->nPg = nPg;
15599  }
15600  return pRet;
15601}
15602
15603/*
15604** Free a bitmap object allocated by recoverBitmapAlloc().
15605*/
15606static void recoverBitmapFree(RecoverBitmap *pMap){
15607  sqlite3_free(pMap);
15608}
15609
15610/*
15611** Set the bit associated with page iPg in bitvec pMap.
15612*/
15613static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
15614  if( iPg<=pMap->nPg ){
15615    int iElem = (iPg / 32);
15616    int iBit = (iPg % 32);
15617    pMap->aElem[iElem] |= (((u32)1) << iBit);
15618  }
15619}
15620
15621/*
15622** Query bitmap object pMap for the state of the bit associated with page
15623** iPg. Return 1 if it is set, or 0 otherwise.
15624*/
15625static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
15626  int ret = 1;
15627  if( iPg<=pMap->nPg && iPg>0 ){
15628    int iElem = (iPg / 32);
15629    int iBit = (iPg % 32);
15630    ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
15631  }
15632  return ret;
15633}
15634
15635/*
15636** Set the recover handle error to the error code and message returned by
15637** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
15638** handle db.
15639*/
15640static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
15641  return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
15642}
15643
15644/*
15645** This function is a no-op if recover handle p already contains an error
15646** (if p->errCode!=SQLITE_OK).
15647**
15648** Otherwise, it attempts to prepare the SQL statement in zSql against
15649** database handle db. If successful, the statement handle is returned.
15650** Or, if an error occurs, NULL is returned and an error left in the
15651** recover handle.
15652*/
15653static sqlite3_stmt *recoverPrepare(
15654  sqlite3_recover *p,
15655  sqlite3 *db,
15656  const char *zSql
15657){
15658  sqlite3_stmt *pStmt = 0;
15659  if( p->errCode==SQLITE_OK ){
15660    if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
15661      recoverDbError(p, db);
15662    }
15663  }
15664  return pStmt;
15665}
15666
15667/*
15668** This function is a no-op if recover handle p already contains an error
15669** (if p->errCode!=SQLITE_OK).
15670**
15671** Otherwise, argument zFmt is used as a printf() style format string,
15672** along with any trailing arguments, to create an SQL statement. This
15673** SQL statement is prepared against database handle db and, if successful,
15674** the statment handle returned. Or, if an error occurs - either during
15675** the printf() formatting or when preparing the resulting SQL - an
15676** error code and message are left in the recover handle.
15677*/
15678static sqlite3_stmt *recoverPreparePrintf(
15679  sqlite3_recover *p,
15680  sqlite3 *db,
15681  const char *zFmt, ...
15682){
15683  sqlite3_stmt *pStmt = 0;
15684  if( p->errCode==SQLITE_OK ){
15685    va_list ap;
15686    char *z;
15687    va_start(ap, zFmt);
15688    z = sqlite3_vmprintf(zFmt, ap);
15689    va_end(ap);
15690    if( z==0 ){
15691      p->errCode = SQLITE_NOMEM;
15692    }else{
15693      pStmt = recoverPrepare(p, db, z);
15694      sqlite3_free(z);
15695    }
15696  }
15697  return pStmt;
15698}
15699
15700/*
15701** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
15702** indicates that an error occurred, and there is not already an error
15703** in the recover handle passed as the first argument, set the error
15704** code and error message appropriately.
15705**
15706** This function returns a copy of the statement handle pointer passed
15707** as the second argument.
15708*/
15709static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
15710  int rc = sqlite3_reset(pStmt);
15711  if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
15712    recoverDbError(p, sqlite3_db_handle(pStmt));
15713  }
15714  return pStmt;
15715}
15716
15717/*
15718** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
15719** indicates that an error occurred, and there is not already an error
15720** in the recover handle passed as the first argument, set the error
15721** code and error message appropriately.
15722*/
15723static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
15724  sqlite3 *db = sqlite3_db_handle(pStmt);
15725  int rc = sqlite3_finalize(pStmt);
15726  if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
15727    recoverDbError(p, db);
15728  }
15729}
15730
15731/*
15732** This function is a no-op if recover handle p already contains an error
15733** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
15734** case.
15735**
15736** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
15737** Or, if an error occurs, leave an error code and message in the recover
15738** handle and return a copy of the error code.
15739*/
15740static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
15741  if( p->errCode==SQLITE_OK ){
15742    int rc = sqlite3_exec(db, zSql, 0, 0, 0);
15743    if( rc ){
15744      recoverDbError(p, db);
15745    }
15746  }
15747  return p->errCode;
15748}
15749
15750/*
15751** Bind the value pVal to parameter iBind of statement pStmt. Leave an
15752** error in the recover handle passed as the first argument if an error
15753** (e.g. an OOM) occurs.
15754*/
15755static void recoverBindValue(
15756  sqlite3_recover *p,
15757  sqlite3_stmt *pStmt,
15758  int iBind,
15759  sqlite3_value *pVal
15760){
15761  if( p->errCode==SQLITE_OK ){
15762    int rc = sqlite3_bind_value(pStmt, iBind, pVal);
15763    if( rc ) recoverError(p, rc, 0);
15764  }
15765}
15766
15767/*
15768** This function is a no-op if recover handle p already contains an error
15769** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
15770**
15771** Otherwise, an attempt is made to interpret zFmt as a printf() style
15772** formatting string and the result of using the trailing arguments for
15773** parameter substitution with it written into a buffer obtained from
15774** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
15775** It is the responsibility of the caller to eventually free the buffer
15776** using sqlite3_free().
15777**
15778** Or, if an error occurs, an error code and message is left in the recover
15779** handle and NULL returned.
15780*/
15781static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
15782  va_list ap;
15783  char *z;
15784  va_start(ap, zFmt);
15785  z = sqlite3_vmprintf(zFmt, ap);
15786  va_end(ap);
15787  if( p->errCode==SQLITE_OK ){
15788    if( z==0 ) p->errCode = SQLITE_NOMEM;
15789  }else{
15790    sqlite3_free(z);
15791    z = 0;
15792  }
15793  return z;
15794}
15795
15796/*
15797** This function is a no-op if recover handle p already contains an error
15798** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
15799**
15800** Otherwise, execute "PRAGMA page_count" against the input database. If
15801** successful, return the integer result. Or, if an error occurs, leave an
15802** error code and error message in the sqlite3_recover handle and return
15803** zero.
15804*/
15805static i64 recoverPageCount(sqlite3_recover *p){
15806  i64 nPg = 0;
15807  if( p->errCode==SQLITE_OK ){
15808    sqlite3_stmt *pStmt = 0;
15809    pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
15810    if( pStmt ){
15811      sqlite3_step(pStmt);
15812      nPg = sqlite3_column_int64(pStmt, 0);
15813    }
15814    recoverFinalize(p, pStmt);
15815  }
15816  return nPg;
15817}
15818
15819/*
15820** Implementation of SQL scalar function "read_i32". The first argument to
15821** this function must be a blob. The second a non-negative integer. This
15822** function reads and returns a 32-bit big-endian integer from byte
15823** offset (4*<arg2>) of the blob.
15824**
15825**     SELECT read_i32(<blob>, <idx>)
15826*/
15827static void recoverReadI32(
15828  sqlite3_context *context,
15829  int argc,
15830  sqlite3_value **argv
15831){
15832  const unsigned char *pBlob;
15833  int nBlob;
15834  int iInt;
15835
15836  assert( argc==2 );
15837  nBlob = sqlite3_value_bytes(argv[0]);
15838  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
15839  iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
15840
15841  if( (iInt+1)*4<=nBlob ){
15842    const unsigned char *a = &pBlob[iInt*4];
15843    i64 iVal = ((i64)a[0]<<24)
15844             + ((i64)a[1]<<16)
15845             + ((i64)a[2]<< 8)
15846             + ((i64)a[3]<< 0);
15847    sqlite3_result_int64(context, iVal);
15848  }
15849}
15850
15851/*
15852** Implementation of SQL scalar function "page_is_used". This function
15853** is used as part of the procedure for locating orphan rows for the
15854** lost-and-found table, and it depends on those routines having populated
15855** the sqlite3_recover.laf.pUsed variable.
15856**
15857** The only argument to this function is a page-number. It returns true
15858** if the page has already been used somehow during data recovery, or false
15859** otherwise.
15860**
15861**     SELECT page_is_used(<pgno>);
15862*/
15863static void recoverPageIsUsed(
15864  sqlite3_context *pCtx,
15865  int nArg,
15866  sqlite3_value **apArg
15867){
15868  sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15869  i64 pgno = sqlite3_value_int64(apArg[0]);
15870  assert( nArg==1 );
15871  sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
15872}
15873
15874/*
15875** The implementation of a user-defined SQL function invoked by the
15876** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
15877** of the database being recovered.
15878**
15879** This function always takes a single integer argument. If the argument
15880** is zero, then the value returned is the number of pages in the db being
15881** recovered. If the argument is greater than zero, it is a page number.
15882** The value returned in this case is an SQL blob containing the data for
15883** the identified page of the db being recovered. e.g.
15884**
15885**     SELECT getpage(0);       -- return number of pages in db
15886**     SELECT getpage(4);       -- return page 4 of db as a blob of data
15887*/
15888static void recoverGetPage(
15889  sqlite3_context *pCtx,
15890  int nArg,
15891  sqlite3_value **apArg
15892){
15893  sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15894  i64 pgno = sqlite3_value_int64(apArg[0]);
15895  sqlite3_stmt *pStmt = 0;
15896
15897  assert( nArg==1 );
15898  if( pgno==0 ){
15899    i64 nPg = recoverPageCount(p);
15900    sqlite3_result_int64(pCtx, nPg);
15901    return;
15902  }else{
15903    if( p->pGetPage==0 ){
15904      pStmt = p->pGetPage = recoverPreparePrintf(
15905          p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
15906      );
15907    }else if( p->errCode==SQLITE_OK ){
15908      pStmt = p->pGetPage;
15909    }
15910
15911    if( pStmt ){
15912      sqlite3_bind_int64(pStmt, 1, pgno);
15913      if( SQLITE_ROW==sqlite3_step(pStmt) ){
15914        const u8 *aPg;
15915        int nPg;
15916        assert( p->errCode==SQLITE_OK );
15917        aPg = sqlite3_column_blob(pStmt, 0);
15918        nPg = sqlite3_column_bytes(pStmt, 0);
15919        if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
15920          aPg = p->pPage1Disk;
15921        }
15922        sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
15923      }
15924      recoverReset(p, pStmt);
15925    }
15926  }
15927
15928  if( p->errCode ){
15929    if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
15930    sqlite3_result_error_code(pCtx, p->errCode);
15931  }
15932}
15933
15934/*
15935** Find a string that is not found anywhere in z[].  Return a pointer
15936** to that string.
15937**
15938** Try to use zA and zB first.  If both of those are already found in z[]
15939** then make up some string and store it in the buffer zBuf.
15940*/
15941static const char *recoverUnusedString(
15942  const char *z,                    /* Result must not appear anywhere in z */
15943  const char *zA, const char *zB,   /* Try these first */
15944  char *zBuf                        /* Space to store a generated string */
15945){
15946  unsigned i = 0;
15947  if( strstr(z, zA)==0 ) return zA;
15948  if( strstr(z, zB)==0 ) return zB;
15949  do{
15950    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
15951  }while( strstr(z,zBuf)!=0 );
15952  return zBuf;
15953}
15954
15955/*
15956** Implementation of scalar SQL function "escape_crnl".  The argument passed to
15957** this function is the output of built-in function quote(). If the first
15958** character of the input is "'", indicating that the value passed to quote()
15959** was a text value, then this function searches the input for "\n" and "\r"
15960** characters and adds a wrapper similar to the following:
15961**
15962**   replace(replace(<input>, '\n', char(10), '\r', char(13));
15963**
15964** Or, if the first character of the input is not "'", then a copy of the input
15965** is returned.
15966*/
15967static void recoverEscapeCrnl(
15968  sqlite3_context *context,
15969  int argc,
15970  sqlite3_value **argv
15971){
15972  const char *zText = (const char*)sqlite3_value_text(argv[0]);
15973  (void)argc;
15974  if( zText && zText[0]=='\'' ){
15975    int nText = sqlite3_value_bytes(argv[0]);
15976    int i;
15977    char zBuf1[20];
15978    char zBuf2[20];
15979    const char *zNL = 0;
15980    const char *zCR = 0;
15981    int nCR = 0;
15982    int nNL = 0;
15983
15984    for(i=0; zText[i]; i++){
15985      if( zNL==0 && zText[i]=='\n' ){
15986        zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
15987        nNL = (int)strlen(zNL);
15988      }
15989      if( zCR==0 && zText[i]=='\r' ){
15990        zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
15991        nCR = (int)strlen(zCR);
15992      }
15993    }
15994
15995    if( zNL || zCR ){
15996      int iOut = 0;
15997      i64 nMax = (nNL > nCR) ? nNL : nCR;
15998      i64 nAlloc = nMax * nText + (nMax+64)*2;
15999      char *zOut = (char*)sqlite3_malloc64(nAlloc);
16000      if( zOut==0 ){
16001        sqlite3_result_error_nomem(context);
16002        return;
16003      }
16004
16005      if( zNL && zCR ){
16006        memcpy(&zOut[iOut], "replace(replace(", 16);
16007        iOut += 16;
16008      }else{
16009        memcpy(&zOut[iOut], "replace(", 8);
16010        iOut += 8;
16011      }
16012      for(i=0; zText[i]; i++){
16013        if( zText[i]=='\n' ){
16014          memcpy(&zOut[iOut], zNL, nNL);
16015          iOut += nNL;
16016        }else if( zText[i]=='\r' ){
16017          memcpy(&zOut[iOut], zCR, nCR);
16018          iOut += nCR;
16019        }else{
16020          zOut[iOut] = zText[i];
16021          iOut++;
16022        }
16023      }
16024
16025      if( zNL ){
16026        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16027        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
16028        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
16029      }
16030      if( zCR ){
16031        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16032        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
16033        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
16034      }
16035
16036      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
16037      sqlite3_free(zOut);
16038      return;
16039    }
16040  }
16041
16042  sqlite3_result_value(context, argv[0]);
16043}
16044
16045/*
16046** This function is a no-op if recover handle p already contains an error
16047** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16048** this case.
16049**
16050** Otherwise, attempt to populate temporary table "recovery.schema" with the
16051** parts of the database schema that can be extracted from the input database.
16052**
16053** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
16054** and error message are left in the recover handle and a copy of the
16055** error code returned. It is not considered an error if part of all of
16056** the database schema cannot be recovered due to corruption.
16057*/
16058static int recoverCacheSchema(sqlite3_recover *p){
16059  return recoverExec(p, p->dbOut,
16060    "WITH RECURSIVE pages(p) AS ("
16061    "  SELECT 1"
16062    "    UNION"
16063    "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
16064    ")"
16065    "INSERT INTO recovery.schema SELECT"
16066    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
16067    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
16068    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
16069    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
16070    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
16071    "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
16072    "  SELECT p FROM pages"
16073    ") GROUP BY pgno, cell"
16074  );
16075}
16076
16077/*
16078** If this recover handle is not in SQL callback mode (i.e. was not created
16079** using sqlite3_recover_init_sql()) of if an error has already occurred,
16080** this function is a no-op. Otherwise, issue a callback with SQL statement
16081** zSql as the parameter.
16082**
16083** If the callback returns non-zero, set the recover handle error code to
16084** the value returned (so that the caller will abandon processing).
16085*/
16086static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
16087  if( p->errCode==SQLITE_OK && p->xSql ){
16088    int res = p->xSql(p->pSqlCtx, zSql);
16089    if( res ){
16090      recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
16091    }
16092  }
16093}
16094
16095/*
16096** Transfer the following settings from the input database to the output
16097** database:
16098**
16099**   + page-size,
16100**   + auto-vacuum settings,
16101**   + database encoding,
16102**   + user-version (PRAGMA user_version), and
16103**   + application-id (PRAGMA application_id), and
16104*/
16105static void recoverTransferSettings(sqlite3_recover *p){
16106  const char *aPragma[] = {
16107    "encoding",
16108    "page_size",
16109    "auto_vacuum",
16110    "user_version",
16111    "application_id"
16112  };
16113  int ii;
16114
16115  /* Truncate the output database to 0 pages in size. This is done by
16116  ** opening a new, empty, temp db, then using the backup API to clobber
16117  ** any existing output db with a copy of it. */
16118  if( p->errCode==SQLITE_OK ){
16119    sqlite3 *db2 = 0;
16120    int rc = sqlite3_open("", &db2);
16121    if( rc!=SQLITE_OK ){
16122      recoverDbError(p, db2);
16123      return;
16124    }
16125
16126    for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
16127      const char *zPrag = aPragma[ii];
16128      sqlite3_stmt *p1 = 0;
16129      p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
16130      if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
16131        const char *zArg = (const char*)sqlite3_column_text(p1, 0);
16132        char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
16133        recoverSqlCallback(p, z2);
16134        recoverExec(p, db2, z2);
16135        sqlite3_free(z2);
16136        if( zArg==0 ){
16137          recoverError(p, SQLITE_NOMEM, 0);
16138        }
16139      }
16140      recoverFinalize(p, p1);
16141    }
16142    recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
16143
16144    if( p->errCode==SQLITE_OK ){
16145      sqlite3 *db = p->dbOut;
16146      sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
16147      if( pBackup ){
16148        sqlite3_backup_step(pBackup, -1);
16149        p->errCode = sqlite3_backup_finish(pBackup);
16150      }else{
16151        recoverDbError(p, db);
16152      }
16153    }
16154
16155    sqlite3_close(db2);
16156  }
16157}
16158
16159/*
16160** This function is a no-op if recover handle p already contains an error
16161** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
16162** this case.
16163**
16164** Otherwise, an attempt is made to open the output database, attach
16165** and create the schema of the temporary database used to store
16166** intermediate data, and to register all required user functions and
16167** virtual table modules with the output handle.
16168**
16169** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
16170** and error message are left in the recover handle and a copy of the
16171** error code returned.
16172*/
16173static int recoverOpenOutput(sqlite3_recover *p){
16174  struct Func {
16175    const char *zName;
16176    int nArg;
16177    void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
16178  } aFunc[] = {
16179    { "getpage", 1, recoverGetPage },
16180    { "page_is_used", 1, recoverPageIsUsed },
16181    { "read_i32", 2, recoverReadI32 },
16182    { "escape_crnl", 1, recoverEscapeCrnl },
16183  };
16184
16185  const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
16186  sqlite3 *db = 0;                /* New database handle */
16187  int ii;                         /* For iterating through aFunc[] */
16188
16189  assert( p->dbOut==0 );
16190
16191  if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
16192    recoverDbError(p, db);
16193  }
16194
16195  /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
16196  ** These two are registered with the output database handle - this
16197  ** module depends on the input handle supporting the sqlite_dbpage
16198  ** virtual table only.  */
16199  if( p->errCode==SQLITE_OK ){
16200    p->errCode = sqlite3_dbdata_init(db, 0, 0);
16201  }
16202
16203  /* Register the custom user-functions with the output handle. */
16204  for(ii=0;
16205      p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
16206      ii++){
16207    p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
16208        aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
16209    );
16210  }
16211
16212  p->dbOut = db;
16213  return p->errCode;
16214}
16215
16216/*
16217** Attach the auxiliary database 'recovery' to the output database handle.
16218** This temporary database is used during the recovery process and then
16219** discarded.
16220*/
16221static void recoverOpenRecovery(sqlite3_recover *p){
16222  char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
16223  recoverExec(p, p->dbOut, zSql);
16224  recoverExec(p, p->dbOut,
16225      "PRAGMA writable_schema = 1;"
16226      "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
16227      "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
16228  );
16229  sqlite3_free(zSql);
16230}
16231
16232
16233/*
16234** This function is a no-op if recover handle p already contains an error
16235** (if p->errCode!=SQLITE_OK).
16236**
16237** Otherwise, argument zName must be the name of a table that has just been
16238** created in the output database. This function queries the output db
16239** for the schema of said table, and creates a RecoverTable object to
16240** store the schema in memory. The new RecoverTable object is linked into
16241** the list at sqlite3_recover.pTblList.
16242**
16243** Parameter iRoot must be the root page of table zName in the INPUT
16244** database.
16245*/
16246static void recoverAddTable(
16247  sqlite3_recover *p,
16248  const char *zName,              /* Name of table created in output db */
16249  i64 iRoot                       /* Root page of same table in INPUT db */
16250){
16251  sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
16252      "PRAGMA table_xinfo(%Q)", zName
16253  );
16254
16255  if( pStmt ){
16256    int iPk = -1;
16257    int iBind = 1;
16258    RecoverTable *pNew = 0;
16259    int nCol = 0;
16260    int nName = recoverStrlen(zName);
16261    int nByte = 0;
16262    while( sqlite3_step(pStmt)==SQLITE_ROW ){
16263      nCol++;
16264      nByte += (sqlite3_column_bytes(pStmt, 1)+1);
16265    }
16266    nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
16267    recoverReset(p, pStmt);
16268
16269    pNew = recoverMalloc(p, nByte);
16270    if( pNew ){
16271      int i = 0;
16272      int iField = 0;
16273      char *csr = 0;
16274      pNew->aCol = (RecoverColumn*)&pNew[1];
16275      pNew->zTab = csr = (char*)&pNew->aCol[nCol];
16276      pNew->nCol = nCol;
16277      pNew->iRoot = iRoot;
16278      memcpy(csr, zName, nName);
16279      csr += nName+1;
16280
16281      for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
16282        int iPKF = sqlite3_column_int(pStmt, 5);
16283        int n = sqlite3_column_bytes(pStmt, 1);
16284        const char *z = (const char*)sqlite3_column_text(pStmt, 1);
16285        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
16286        int eHidden = sqlite3_column_int(pStmt, 6);
16287
16288        if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
16289        if( iPKF>1 ) iPk = -2;
16290        pNew->aCol[i].zCol = csr;
16291        pNew->aCol[i].eHidden = eHidden;
16292        if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
16293          pNew->aCol[i].iField = -1;
16294        }else{
16295          pNew->aCol[i].iField = iField++;
16296        }
16297        if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
16298         && eHidden!=RECOVER_EHIDDEN_STORED
16299        ){
16300          pNew->aCol[i].iBind = iBind++;
16301        }
16302        memcpy(csr, z, n);
16303        csr += (n+1);
16304      }
16305
16306      pNew->pNext = p->pTblList;
16307      p->pTblList = pNew;
16308      pNew->bIntkey = 1;
16309    }
16310
16311    recoverFinalize(p, pStmt);
16312
16313    pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
16314    while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
16315      int iField = sqlite3_column_int(pStmt, 0);
16316      int iCol = sqlite3_column_int(pStmt, 1);
16317
16318      assert( iCol<pNew->nCol );
16319      pNew->aCol[iCol].iField = iField;
16320
16321      pNew->bIntkey = 0;
16322      iPk = -2;
16323    }
16324    recoverFinalize(p, pStmt);
16325
16326    if( p->errCode==SQLITE_OK ){
16327      if( iPk>=0 ){
16328        pNew->aCol[iPk].bIPK = 1;
16329      }else if( pNew->bIntkey ){
16330        pNew->iRowidBind = iBind++;
16331      }
16332    }
16333  }
16334}
16335
16336/*
16337** This function is called after recoverCacheSchema() has cached those parts
16338** of the input database schema that could be recovered in temporary table
16339** "recovery.schema". This function creates in the output database copies
16340** of all parts of that schema that must be created before the tables can
16341** be populated. Specifically, this means:
16342**
16343**     * all tables that are not VIRTUAL, and
16344**     * UNIQUE indexes.
16345**
16346** If the recovery handle uses SQL callbacks, then callbacks containing
16347** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
16348**
16349** Additionally, records are added to the sqlite_schema table of the
16350** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
16351** records are written directly to sqlite_schema, not actually executed.
16352** If the handle is in SQL callback mode, then callbacks are invoked
16353** with equivalent SQL statements.
16354*/
16355static int recoverWriteSchema1(sqlite3_recover *p){
16356  sqlite3_stmt *pSelect = 0;
16357  sqlite3_stmt *pTblname = 0;
16358
16359  pSelect = recoverPrepare(p, p->dbOut,
16360      "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
16361      "  SELECT rootpage, name, sql, "
16362      "    type='table', "
16363      "    sql LIKE 'create virtual%',"
16364      "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
16365      "  FROM recovery.schema"
16366      ")"
16367      "SELECT rootpage, tbl, isVirtual, name, sql"
16368      " FROM dbschema "
16369      "  WHERE tbl OR isIndex"
16370      "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
16371  );
16372
16373  pTblname = recoverPrepare(p, p->dbOut,
16374      "SELECT name FROM sqlite_schema "
16375      "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
16376  );
16377
16378  if( pSelect ){
16379    sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
16380    while( sqlite3_step(pSelect)==SQLITE_ROW ){
16381      i64 iRoot = sqlite3_column_int64(pSelect, 0);
16382      int bTable = sqlite3_column_int(pSelect, 1);
16383      int bVirtual = sqlite3_column_int(pSelect, 2);
16384      const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
16385      const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
16386      char *zFree = 0;
16387      int rc = SQLITE_OK;
16388
16389      if( bVirtual ){
16390        zSql = (const char*)(zFree = recoverMPrintf(p,
16391            "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
16392            zName, zName, zSql
16393        ));
16394      }
16395      rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
16396      if( rc==SQLITE_OK ){
16397        recoverSqlCallback(p, zSql);
16398        if( bTable && !bVirtual ){
16399          if( SQLITE_ROW==sqlite3_step(pTblname) ){
16400            const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
16401            recoverAddTable(p, zTbl, iRoot);
16402          }
16403          recoverReset(p, pTblname);
16404        }
16405      }else if( rc!=SQLITE_ERROR ){
16406        recoverDbError(p, p->dbOut);
16407      }
16408      sqlite3_free(zFree);
16409    }
16410  }
16411  recoverFinalize(p, pSelect);
16412  recoverFinalize(p, pTblname);
16413
16414  return p->errCode;
16415}
16416
16417/*
16418** This function is called after the output database has been populated. It
16419** adds all recovered schema elements that were not created in the output
16420** database by recoverWriteSchema1() - everything except for tables and
16421** UNIQUE indexes. Specifically:
16422**
16423**     * views,
16424**     * triggers,
16425**     * non-UNIQUE indexes.
16426**
16427** If the recover handle is in SQL callback mode, then equivalent callbacks
16428** are issued to create the schema elements.
16429*/
16430static int recoverWriteSchema2(sqlite3_recover *p){
16431  sqlite3_stmt *pSelect = 0;
16432
16433  pSelect = recoverPrepare(p, p->dbOut,
16434      p->bSlowIndexes ?
16435      "SELECT rootpage, sql FROM recovery.schema "
16436      "  WHERE type!='table' AND type!='index'"
16437      :
16438      "SELECT rootpage, sql FROM recovery.schema "
16439      "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
16440  );
16441
16442  if( pSelect ){
16443    while( sqlite3_step(pSelect)==SQLITE_ROW ){
16444      const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
16445      int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
16446      if( rc==SQLITE_OK ){
16447        recoverSqlCallback(p, zSql);
16448      }else if( rc!=SQLITE_ERROR ){
16449        recoverDbError(p, p->dbOut);
16450      }
16451    }
16452  }
16453  recoverFinalize(p, pSelect);
16454
16455  return p->errCode;
16456}
16457
16458/*
16459** This function is a no-op if recover handle p already contains an error
16460** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
16461**
16462** Otherwise, if the recover handle is configured to create an output
16463** database (was created by sqlite3_recover_init()), then this function
16464** prepares and returns an SQL statement to INSERT a new record into table
16465** pTab, assuming the first nField fields of a record extracted from disk
16466** are valid.
16467**
16468** For example, if table pTab is:
16469**
16470**     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
16471**
16472** And nField is 4, then the SQL statement prepared and returned is:
16473**
16474**     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
16475**
16476** In this case even though 4 values were extracted from the input db,
16477** only 3 are written to the output, as the generated STORED column
16478** cannot be written.
16479**
16480** If the recover handle is in SQL callback mode, then the SQL statement
16481** prepared is such that evaluating it returns a single row containing
16482** a single text value - itself an SQL statement similar to the above,
16483** except with SQL literals in place of the variables. For example:
16484**
16485**     SELECT 'INSERT INTO (a, c, d) VALUES ('
16486**          || quote(?1) || ', '
16487**          || quote(?2) || ', '
16488**          || quote(?3) || ')';
16489**
16490** In either case, it is the responsibility of the caller to eventually
16491** free the statement handle using sqlite3_finalize().
16492*/
16493static sqlite3_stmt *recoverInsertStmt(
16494  sqlite3_recover *p,
16495  RecoverTable *pTab,
16496  int nField
16497){
16498  sqlite3_stmt *pRet = 0;
16499  const char *zSep = "";
16500  const char *zSqlSep = "";
16501  char *zSql = 0;
16502  char *zFinal = 0;
16503  char *zBind = 0;
16504  int ii;
16505  int bSql = p->xSql ? 1 : 0;
16506
16507  if( nField<=0 ) return 0;
16508
16509  assert( nField<=pTab->nCol );
16510
16511  zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
16512
16513  if( pTab->iRowidBind ){
16514    assert( pTab->bIntkey );
16515    zSql = recoverMPrintf(p, "%z_rowid_", zSql);
16516    if( bSql ){
16517      zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
16518    }else{
16519      zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
16520    }
16521    zSqlSep = "||', '||";
16522    zSep = ", ";
16523  }
16524
16525  for(ii=0; ii<nField; ii++){
16526    int eHidden = pTab->aCol[ii].eHidden;
16527    if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
16528     && eHidden!=RECOVER_EHIDDEN_STORED
16529    ){
16530      assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
16531      zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
16532
16533      if( bSql ){
16534        zBind = recoverMPrintf(p,
16535            "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
16536        );
16537        zSqlSep = "||', '||";
16538      }else{
16539        zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
16540      }
16541      zSep = ", ";
16542    }
16543  }
16544
16545  if( bSql ){
16546    zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
16547        zSql, zBind
16548    );
16549  }else{
16550    zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
16551  }
16552
16553  pRet = recoverPrepare(p, p->dbOut, zFinal);
16554  sqlite3_free(zSql);
16555  sqlite3_free(zBind);
16556  sqlite3_free(zFinal);
16557
16558  return pRet;
16559}
16560
16561
16562/*
16563** Search the list of RecoverTable objects at p->pTblList for one that
16564** has root page iRoot in the input database. If such an object is found,
16565** return a pointer to it. Otherwise, return NULL.
16566*/
16567static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
16568  RecoverTable *pRet = 0;
16569  for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
16570  return pRet;
16571}
16572
16573/*
16574** This function attempts to create a lost and found table within the
16575** output db. If successful, it returns a pointer to a buffer containing
16576** the name of the new table. It is the responsibility of the caller to
16577** eventually free this buffer using sqlite3_free().
16578**
16579** If an error occurs, NULL is returned and an error code and error
16580** message left in the recover handle.
16581*/
16582static char *recoverLostAndFoundCreate(
16583  sqlite3_recover *p,             /* Recover object */
16584  int nField                      /* Number of column fields in new table */
16585){
16586  char *zTbl = 0;
16587  sqlite3_stmt *pProbe = 0;
16588  int ii = 0;
16589
16590  pProbe = recoverPrepare(p, p->dbOut,
16591    "SELECT 1 FROM sqlite_schema WHERE name=?"
16592  );
16593  for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
16594    int bFail = 0;
16595    if( ii<0 ){
16596      zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
16597    }else{
16598      zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
16599    }
16600
16601    if( p->errCode==SQLITE_OK ){
16602      sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
16603      if( SQLITE_ROW==sqlite3_step(pProbe) ){
16604        bFail = 1;
16605      }
16606      recoverReset(p, pProbe);
16607    }
16608
16609    if( bFail ){
16610      sqlite3_clear_bindings(pProbe);
16611      sqlite3_free(zTbl);
16612      zTbl = 0;
16613    }
16614  }
16615  recoverFinalize(p, pProbe);
16616
16617  if( zTbl ){
16618    const char *zSep = 0;
16619    char *zField = 0;
16620    char *zSql = 0;
16621
16622    zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
16623    for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
16624      zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
16625      zSep = ", ";
16626    }
16627
16628    zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
16629    sqlite3_free(zField);
16630
16631    recoverExec(p, p->dbOut, zSql);
16632    recoverSqlCallback(p, zSql);
16633    sqlite3_free(zSql);
16634  }else if( p->errCode==SQLITE_OK ){
16635    recoverError(
16636        p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
16637    );
16638  }
16639
16640  return zTbl;
16641}
16642
16643/*
16644** Synthesize and prepare an INSERT statement to write to the lost_and_found
16645** table in the output database. The name of the table is zTab, and it has
16646** nField c* fields.
16647*/
16648static sqlite3_stmt *recoverLostAndFoundInsert(
16649  sqlite3_recover *p,
16650  const char *zTab,
16651  int nField
16652){
16653  int nTotal = nField + 4;
16654  int ii;
16655  char *zBind = 0;
16656  sqlite3_stmt *pRet = 0;
16657
16658  if( p->xSql==0 ){
16659    for(ii=0; ii<nTotal; ii++){
16660      zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
16661    }
16662    pRet = recoverPreparePrintf(
16663        p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
16664    );
16665  }else{
16666    const char *zSep = "";
16667    for(ii=0; ii<nTotal; ii++){
16668      zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
16669      zSep = "|| ', ' ||";
16670    }
16671    pRet = recoverPreparePrintf(
16672        p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
16673    );
16674  }
16675
16676  sqlite3_free(zBind);
16677  return pRet;
16678}
16679
16680/*
16681** Input database page iPg contains data that will be written to the
16682** lost-and-found table of the output database. This function attempts
16683** to identify the root page of the tree that page iPg belonged to.
16684** If successful, it sets output variable (*piRoot) to the page number
16685** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
16686** an SQLite error code is returned and the final value of *piRoot
16687** undefined.
16688*/
16689static int recoverLostAndFoundFindRoot(
16690  sqlite3_recover *p,
16691  i64 iPg,
16692  i64 *piRoot
16693){
16694  RecoverStateLAF *pLaf = &p->laf;
16695
16696  if( pLaf->pFindRoot==0 ){
16697    pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
16698        "WITH RECURSIVE p(pgno) AS ("
16699        "  SELECT ?"
16700        "    UNION"
16701        "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
16702        ") "
16703        "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
16704        "    AND m.parent IS NULL"
16705    );
16706  }
16707  if( p->errCode==SQLITE_OK ){
16708    sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
16709    if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
16710      *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
16711    }else{
16712      *piRoot = iPg;
16713    }
16714    recoverReset(p, pLaf->pFindRoot);
16715  }
16716  return p->errCode;
16717}
16718
16719/*
16720** Recover data from page iPage of the input database and write it to
16721** the lost-and-found table in the output database.
16722*/
16723static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
16724  RecoverStateLAF *pLaf = &p->laf;
16725  sqlite3_value **apVal = pLaf->apVal;
16726  sqlite3_stmt *pPageData = pLaf->pPageData;
16727  sqlite3_stmt *pInsert = pLaf->pInsert;
16728
16729  int nVal = -1;
16730  int iPrevCell = 0;
16731  i64 iRoot = 0;
16732  int bHaveRowid = 0;
16733  i64 iRowid = 0;
16734  int ii = 0;
16735
16736  if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
16737  sqlite3_bind_int64(pPageData, 1, iPage);
16738  while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
16739    int iCell = sqlite3_column_int64(pPageData, 0);
16740    int iField = sqlite3_column_int64(pPageData, 1);
16741
16742    if( iPrevCell!=iCell && nVal>=0 ){
16743      /* Insert the new row */
16744      sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
16745      sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
16746      sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
16747      if( bHaveRowid ){
16748        sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
16749      }
16750      for(ii=0; ii<nVal; ii++){
16751        recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
16752      }
16753      if( sqlite3_step(pInsert)==SQLITE_ROW ){
16754        recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
16755      }
16756      recoverReset(p, pInsert);
16757
16758      /* Discard the accumulated row data */
16759      for(ii=0; ii<nVal; ii++){
16760        sqlite3_value_free(apVal[ii]);
16761        apVal[ii] = 0;
16762      }
16763      sqlite3_clear_bindings(pInsert);
16764      bHaveRowid = 0;
16765      nVal = -1;
16766    }
16767
16768    if( iCell<0 ) break;
16769
16770    if( iField<0 ){
16771      assert( nVal==-1 );
16772      iRowid = sqlite3_column_int64(pPageData, 2);
16773      bHaveRowid = 1;
16774      nVal = 0;
16775    }else if( iField<pLaf->nMaxField ){
16776      sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
16777      apVal[iField] = sqlite3_value_dup(pVal);
16778      assert( iField==nVal || (nVal==-1 && iField==0) );
16779      nVal = iField+1;
16780      if( apVal[iField]==0 ){
16781        recoverError(p, SQLITE_NOMEM, 0);
16782      }
16783    }
16784
16785    iPrevCell = iCell;
16786  }
16787  recoverReset(p, pPageData);
16788
16789  for(ii=0; ii<nVal; ii++){
16790    sqlite3_value_free(apVal[ii]);
16791    apVal[ii] = 0;
16792  }
16793}
16794
16795/*
16796** Perform one step (sqlite3_recover_step()) of work for the connection
16797** passed as the only argument, which is guaranteed to be in
16798** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
16799** table of the output database is populated with recovered data that can
16800** not be assigned to any recovered schema object.
16801*/
16802static int recoverLostAndFound3Step(sqlite3_recover *p){
16803  RecoverStateLAF *pLaf = &p->laf;
16804  if( p->errCode==SQLITE_OK ){
16805    if( pLaf->pInsert==0 ){
16806      return SQLITE_DONE;
16807    }else{
16808      if( p->errCode==SQLITE_OK ){
16809        int res = sqlite3_step(pLaf->pAllPage);
16810        if( res==SQLITE_ROW ){
16811          i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
16812          if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
16813            recoverLostAndFoundOnePage(p, iPage);
16814          }
16815        }else{
16816          recoverReset(p, pLaf->pAllPage);
16817          return SQLITE_DONE;
16818        }
16819      }
16820    }
16821  }
16822  return SQLITE_OK;
16823}
16824
16825/*
16826** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
16827** state - during which the lost-and-found table of the output database
16828** is populated with recovered data that can not be assigned to any
16829** recovered schema object.
16830*/
16831static void recoverLostAndFound3Init(sqlite3_recover *p){
16832  RecoverStateLAF *pLaf = &p->laf;
16833
16834  if( pLaf->nMaxField>0 ){
16835    char *zTab = 0;               /* Name of lost_and_found table */
16836
16837    zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
16838    pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
16839    sqlite3_free(zTab);
16840
16841    pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
16842        "WITH RECURSIVE seq(ii) AS ("
16843        "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
16844        ")"
16845        "SELECT ii FROM seq" , p->laf.nPg
16846    );
16847    pLaf->pPageData = recoverPrepare(p, p->dbOut,
16848        "SELECT cell, field, value "
16849        "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
16850        "UNION ALL "
16851        "SELECT -1, -1, -1"
16852    );
16853
16854    pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
16855        pLaf->nMaxField*sizeof(sqlite3_value*)
16856    );
16857  }
16858}
16859
16860/*
16861** Initialize resources required in RECOVER_STATE_WRITING state - during which
16862** tables recovered from the schema of the input database are populated with
16863** recovered data.
16864*/
16865static int recoverWriteDataInit(sqlite3_recover *p){
16866  RecoverStateW1 *p1 = &p->w1;
16867  RecoverTable *pTbl = 0;
16868  int nByte = 0;
16869
16870  /* Figure out the maximum number of columns for any table in the schema */
16871  assert( p1->nMax==0 );
16872  for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
16873    if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
16874  }
16875
16876  /* Allocate an array of (sqlite3_value*) in which to accumulate the values
16877  ** that will be written to the output database in a single row. */
16878  nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
16879  p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
16880  if( p1->apVal==0 ) return p->errCode;
16881
16882  /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
16883  ** to loop through cells that appear to belong to a single table (pSel). */
16884  p1->pTbls = recoverPrepare(p, p->dbOut,
16885      "SELECT rootpage FROM recovery.schema "
16886      "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
16887      "  ORDER BY (tbl_name='sqlite_sequence') ASC"
16888  );
16889  p1->pSel = recoverPrepare(p, p->dbOut,
16890      "WITH RECURSIVE pages(page) AS ("
16891      "  SELECT ?1"
16892      "    UNION"
16893      "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
16894      "    WHERE pgno=page"
16895      ") "
16896      "SELECT page, cell, field, value "
16897      "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
16898      "UNION ALL "
16899      "SELECT 0, 0, 0, 0"
16900  );
16901
16902  return p->errCode;
16903}
16904
16905/*
16906** Clean up resources allocated by recoverWriteDataInit() (stuff in
16907** sqlite3_recover.w1).
16908*/
16909static void recoverWriteDataCleanup(sqlite3_recover *p){
16910  RecoverStateW1 *p1 = &p->w1;
16911  int ii;
16912  for(ii=0; ii<p1->nVal; ii++){
16913    sqlite3_value_free(p1->apVal[ii]);
16914  }
16915  sqlite3_free(p1->apVal);
16916  recoverFinalize(p, p1->pInsert);
16917  recoverFinalize(p, p1->pTbls);
16918  recoverFinalize(p, p1->pSel);
16919  memset(p1, 0, sizeof(*p1));
16920}
16921
16922/*
16923** Perform one step (sqlite3_recover_step()) of work for the connection
16924** passed as the only argument, which is guaranteed to be in
16925** RECOVER_STATE_WRITING state - during which tables recovered from the
16926** schema of the input database are populated with recovered data.
16927*/
16928static int recoverWriteDataStep(sqlite3_recover *p){
16929  RecoverStateW1 *p1 = &p->w1;
16930  sqlite3_stmt *pSel = p1->pSel;
16931  sqlite3_value **apVal = p1->apVal;
16932
16933  if( p->errCode==SQLITE_OK && p1->pTab==0 ){
16934    if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
16935      i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
16936      p1->pTab = recoverFindTable(p, iRoot);
16937
16938      recoverFinalize(p, p1->pInsert);
16939      p1->pInsert = 0;
16940
16941      /* If this table is unknown, return early. The caller will invoke this
16942      ** function again and it will move on to the next table.  */
16943      if( p1->pTab==0 ) return p->errCode;
16944
16945      /* If this is the sqlite_sequence table, delete any rows added by
16946      ** earlier INSERT statements on tables with AUTOINCREMENT primary
16947      ** keys before recovering its contents. The p1->pTbls SELECT statement
16948      ** is rigged to deliver "sqlite_sequence" last of all, so we don't
16949      ** worry about it being modified after it is recovered. */
16950      if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
16951        recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
16952        recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
16953      }
16954
16955      /* Bind the root page of this table within the original database to
16956      ** SELECT statement p1->pSel. The SELECT statement will then iterate
16957      ** through cells that look like they belong to table pTab.  */
16958      sqlite3_bind_int64(pSel, 1, iRoot);
16959
16960      p1->nVal = 0;
16961      p1->bHaveRowid = 0;
16962      p1->iPrevPage = -1;
16963      p1->iPrevCell = -1;
16964    }else{
16965      return SQLITE_DONE;
16966    }
16967  }
16968  assert( p->errCode!=SQLITE_OK || p1->pTab );
16969
16970  if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
16971    RecoverTable *pTab = p1->pTab;
16972
16973    i64 iPage = sqlite3_column_int64(pSel, 0);
16974    int iCell = sqlite3_column_int(pSel, 1);
16975    int iField = sqlite3_column_int(pSel, 2);
16976    sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
16977    int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
16978
16979    assert( bNewCell==0 || (iField==-1 || iField==0) );
16980    assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
16981
16982    if( bNewCell ){
16983      int ii = 0;
16984      if( p1->nVal>=0 ){
16985        if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
16986          recoverFinalize(p, p1->pInsert);
16987          p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
16988          p1->nInsert = p1->nVal;
16989        }
16990        if( p1->nVal>0 ){
16991          sqlite3_stmt *pInsert = p1->pInsert;
16992          for(ii=0; ii<pTab->nCol; ii++){
16993            RecoverColumn *pCol = &pTab->aCol[ii];
16994            int iBind = pCol->iBind;
16995            if( iBind>0 ){
16996              if( pCol->bIPK ){
16997                sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
16998              }else if( pCol->iField<p1->nVal ){
16999                recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
17000              }
17001            }
17002          }
17003          if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
17004            sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
17005          }
17006          if( SQLITE_ROW==sqlite3_step(pInsert) ){
17007            const char *z = (const char*)sqlite3_column_text(pInsert, 0);
17008            recoverSqlCallback(p, z);
17009          }
17010          recoverReset(p, pInsert);
17011          assert( p->errCode || pInsert );
17012          if( pInsert ) sqlite3_clear_bindings(pInsert);
17013        }
17014      }
17015
17016      for(ii=0; ii<p1->nVal; ii++){
17017        sqlite3_value_free(apVal[ii]);
17018        apVal[ii] = 0;
17019      }
17020      p1->nVal = -1;
17021      p1->bHaveRowid = 0;
17022    }
17023
17024    if( iPage!=0 ){
17025      if( iField<0 ){
17026        p1->iRowid = sqlite3_column_int64(pSel, 3);
17027        assert( p1->nVal==-1 );
17028        p1->nVal = 0;
17029        p1->bHaveRowid = 1;
17030      }else if( iField<pTab->nCol ){
17031        assert( apVal[iField]==0 );
17032        apVal[iField] = sqlite3_value_dup( pVal );
17033        if( apVal[iField]==0 ){
17034          recoverError(p, SQLITE_NOMEM, 0);
17035        }
17036        p1->nVal = iField+1;
17037      }
17038      p1->iPrevCell = iCell;
17039      p1->iPrevPage = iPage;
17040    }
17041  }else{
17042    recoverReset(p, pSel);
17043    p1->pTab = 0;
17044  }
17045
17046  return p->errCode;
17047}
17048
17049/*
17050** Initialize resources required by sqlite3_recover_step() in
17051** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17052** already allocated to a recovered schema element is determined.
17053*/
17054static void recoverLostAndFound1Init(sqlite3_recover *p){
17055  RecoverStateLAF *pLaf = &p->laf;
17056  sqlite3_stmt *pStmt = 0;
17057
17058  assert( p->laf.pUsed==0 );
17059  pLaf->nPg = recoverPageCount(p);
17060  pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
17061
17062  /* Prepare a statement to iterate through all pages that are part of any tree
17063  ** in the recoverable part of the input database schema to the bitmap. And,
17064  ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
17065  ** freelist.  */
17066  pStmt = recoverPrepare(
17067      p, p->dbOut,
17068      "WITH trunk(pgno) AS ("
17069      "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
17070      "    UNION"
17071      "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
17072      "),"
17073      "trunkdata(pgno, data) AS ("
17074      "  SELECT pgno, getpage(pgno) FROM trunk"
17075      "),"
17076      "freelist(data, n, freepgno) AS ("
17077      "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
17078      "    UNION ALL"
17079      "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
17080      "),"
17081      ""
17082      "roots(r) AS ("
17083      "  SELECT 1 UNION ALL"
17084      "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
17085      "),"
17086      "used(page) AS ("
17087      "  SELECT r FROM roots"
17088      "    UNION"
17089      "  SELECT child FROM sqlite_dbptr('getpage()'), used "
17090      "    WHERE pgno=page"
17091      ") "
17092      "SELECT page FROM used"
17093      " UNION ALL "
17094      "SELECT freepgno FROM freelist WHERE NOT ?"
17095  );
17096  if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
17097  pLaf->pUsedPages = pStmt;
17098}
17099
17100/*
17101** Perform one step (sqlite3_recover_step()) of work for the connection
17102** passed as the only argument, which is guaranteed to be in
17103** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
17104** already allocated to a recovered schema element is determined.
17105*/
17106static int recoverLostAndFound1Step(sqlite3_recover *p){
17107  RecoverStateLAF *pLaf = &p->laf;
17108  int rc = p->errCode;
17109  if( rc==SQLITE_OK ){
17110    rc = sqlite3_step(pLaf->pUsedPages);
17111    if( rc==SQLITE_ROW ){
17112      i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
17113      recoverBitmapSet(pLaf->pUsed, iPg);
17114      rc = SQLITE_OK;
17115    }else{
17116      recoverFinalize(p, pLaf->pUsedPages);
17117      pLaf->pUsedPages = 0;
17118    }
17119  }
17120  return rc;
17121}
17122
17123/*
17124** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
17125** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
17126** are sorted into sets that likely belonged to the same database tree.
17127*/
17128static void recoverLostAndFound2Init(sqlite3_recover *p){
17129  RecoverStateLAF *pLaf = &p->laf;
17130
17131  assert( p->laf.pAllAndParent==0 );
17132  assert( p->laf.pMapInsert==0 );
17133  assert( p->laf.pMaxField==0 );
17134  assert( p->laf.nMaxField==0 );
17135
17136  pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
17137      "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
17138  );
17139  pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
17140      "WITH RECURSIVE seq(ii) AS ("
17141      "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
17142      ")"
17143      "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
17144      " UNION ALL "
17145      "SELECT NULL, ii FROM seq", p->laf.nPg
17146  );
17147  pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
17148      "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
17149  );
17150}
17151
17152/*
17153** Perform one step (sqlite3_recover_step()) of work for the connection
17154** passed as the only argument, which is guaranteed to be in
17155** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
17156** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
17157** to the same database tree.
17158*/
17159static int recoverLostAndFound2Step(sqlite3_recover *p){
17160  RecoverStateLAF *pLaf = &p->laf;
17161  if( p->errCode==SQLITE_OK ){
17162    int res = sqlite3_step(pLaf->pAllAndParent);
17163    if( res==SQLITE_ROW ){
17164      i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
17165      if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
17166        sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
17167        sqlite3_bind_value(pLaf->pMapInsert, 2,
17168            sqlite3_column_value(pLaf->pAllAndParent, 0)
17169        );
17170        sqlite3_step(pLaf->pMapInsert);
17171        recoverReset(p, pLaf->pMapInsert);
17172        sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
17173        if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
17174          int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
17175          if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
17176        }
17177        recoverReset(p, pLaf->pMaxField);
17178      }
17179    }else{
17180      recoverFinalize(p, pLaf->pAllAndParent);
17181      pLaf->pAllAndParent =0;
17182      return SQLITE_DONE;
17183    }
17184  }
17185  return p->errCode;
17186}
17187
17188/*
17189** Free all resources allocated as part of sqlite3_recover_step() calls
17190** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
17191*/
17192static void recoverLostAndFoundCleanup(sqlite3_recover *p){
17193  recoverBitmapFree(p->laf.pUsed);
17194  p->laf.pUsed = 0;
17195  sqlite3_finalize(p->laf.pUsedPages);
17196  sqlite3_finalize(p->laf.pAllAndParent);
17197  sqlite3_finalize(p->laf.pMapInsert);
17198  sqlite3_finalize(p->laf.pMaxField);
17199  sqlite3_finalize(p->laf.pFindRoot);
17200  sqlite3_finalize(p->laf.pInsert);
17201  sqlite3_finalize(p->laf.pAllPage);
17202  sqlite3_finalize(p->laf.pPageData);
17203  p->laf.pUsedPages = 0;
17204  p->laf.pAllAndParent = 0;
17205  p->laf.pMapInsert = 0;
17206  p->laf.pMaxField = 0;
17207  p->laf.pFindRoot = 0;
17208  p->laf.pInsert = 0;
17209  p->laf.pAllPage = 0;
17210  p->laf.pPageData = 0;
17211  sqlite3_free(p->laf.apVal);
17212  p->laf.apVal = 0;
17213}
17214
17215/*
17216** Free all resources allocated as part of sqlite3_recover_step() calls.
17217*/
17218static void recoverFinalCleanup(sqlite3_recover *p){
17219  RecoverTable *pTab = 0;
17220  RecoverTable *pNext = 0;
17221
17222  recoverWriteDataCleanup(p);
17223  recoverLostAndFoundCleanup(p);
17224
17225  for(pTab=p->pTblList; pTab; pTab=pNext){
17226    pNext = pTab->pNext;
17227    sqlite3_free(pTab);
17228  }
17229  p->pTblList = 0;
17230  sqlite3_finalize(p->pGetPage);
17231  p->pGetPage = 0;
17232  sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
17233
17234  {
17235#ifndef NDEBUG
17236    int res =
17237#endif
17238       sqlite3_close(p->dbOut);
17239    assert( res==SQLITE_OK );
17240  }
17241  p->dbOut = 0;
17242}
17243
17244/*
17245** Decode and return an unsigned 16-bit big-endian integer value from
17246** buffer a[].
17247*/
17248static u32 recoverGetU16(const u8 *a){
17249  return (((u32)a[0])<<8) + ((u32)a[1]);
17250}
17251
17252/*
17253** Decode and return an unsigned 32-bit big-endian integer value from
17254** buffer a[].
17255*/
17256static u32 recoverGetU32(const u8 *a){
17257  return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
17258}
17259
17260/*
17261** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
17262** and return the number of bytes consumed.
17263*/
17264static int recoverGetVarint(const u8 *a, i64 *pVal){
17265  sqlite3_uint64 u = 0;
17266  int i;
17267  for(i=0; i<8; i++){
17268    u = (u<<7) + (a[i]&0x7f);
17269    if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
17270  }
17271  u = (u<<8) + (a[i]&0xff);
17272  *pVal = (sqlite3_int64)u;
17273  return 9;
17274}
17275
17276/*
17277** The second argument points to a buffer n bytes in size. If this buffer
17278** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
17279** return the page-size in bytes. Otherwise, if the buffer does not
17280** appear to contain a well-formed b-tree page, return 0.
17281*/
17282static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
17283  u8 *aUsed = aTmp;
17284  int nFrag = 0;
17285  int nActual = 0;
17286  int iFree = 0;
17287  int nCell = 0;                  /* Number of cells on page */
17288  int iCellOff = 0;               /* Offset of cell array in page */
17289  int iContent = 0;
17290  int eType = 0;
17291  int ii = 0;
17292
17293  eType = (int)a[0];
17294  if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
17295
17296  iFree = (int)recoverGetU16(&a[1]);
17297  nCell = (int)recoverGetU16(&a[3]);
17298  iContent = (int)recoverGetU16(&a[5]);
17299  if( iContent==0 ) iContent = 65536;
17300  nFrag = (int)a[7];
17301
17302  if( iContent>n ) return 0;
17303
17304  memset(aUsed, 0, n);
17305  memset(aUsed, 0xFF, iContent);
17306
17307  /* Follow the free-list. This is the same format for all b-tree pages. */
17308  if( iFree && iFree<=iContent ) return 0;
17309  while( iFree ){
17310    int iNext = 0;
17311    int nByte = 0;
17312    if( iFree>(n-4) ) return 0;
17313    iNext = recoverGetU16(&a[iFree]);
17314    nByte = recoverGetU16(&a[iFree+2]);
17315    if( iFree+nByte>n || nByte<4 ) return 0;
17316    if( iNext && iNext<iFree+nByte ) return 0;
17317    memset(&aUsed[iFree], 0xFF, nByte);
17318    iFree = iNext;
17319  }
17320
17321  /* Run through the cells */
17322  if( eType==0x02 || eType==0x05 ){
17323    iCellOff = 12;
17324  }else{
17325    iCellOff = 8;
17326  }
17327  if( (iCellOff + 2*nCell)>iContent ) return 0;
17328  for(ii=0; ii<nCell; ii++){
17329    int iByte;
17330    i64 nPayload = 0;
17331    int nByte = 0;
17332    int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
17333    if( iOff<iContent || iOff>n ){
17334      return 0;
17335    }
17336    if( eType==0x05 || eType==0x02 ) nByte += 4;
17337    nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
17338    if( eType==0x0D ){
17339      i64 dummy = 0;
17340      nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
17341    }
17342    if( eType!=0x05 ){
17343      int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
17344      int M = ((n-12)*32/255)-23;
17345      int K = M+((nPayload-M)%(n-4));
17346
17347      if( nPayload<X ){
17348        nByte += nPayload;
17349      }else if( K<=X ){
17350        nByte += K+4;
17351      }else{
17352        nByte += M+4;
17353      }
17354    }
17355
17356    if( iOff+nByte>n ){
17357      return 0;
17358    }
17359    for(iByte=iOff; iByte<(iOff+nByte); iByte++){
17360      if( aUsed[iByte]!=0 ){
17361        return 0;
17362      }
17363      aUsed[iByte] = 0xFF;
17364    }
17365  }
17366
17367  nActual = 0;
17368  for(ii=0; ii<n; ii++){
17369    if( aUsed[ii]==0 ) nActual++;
17370  }
17371  return (nActual==nFrag);
17372}
17373
17374
17375static int recoverVfsClose(sqlite3_file*);
17376static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
17377static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
17378static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
17379static int recoverVfsSync(sqlite3_file*, int flags);
17380static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
17381static int recoverVfsLock(sqlite3_file*, int);
17382static int recoverVfsUnlock(sqlite3_file*, int);
17383static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
17384static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
17385static int recoverVfsSectorSize(sqlite3_file*);
17386static int recoverVfsDeviceCharacteristics(sqlite3_file*);
17387static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
17388static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
17389static void recoverVfsShmBarrier(sqlite3_file*);
17390static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
17391static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
17392static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
17393
17394static sqlite3_io_methods recover_methods = {
17395  2, /* iVersion */
17396  recoverVfsClose,
17397  recoverVfsRead,
17398  recoverVfsWrite,
17399  recoverVfsTruncate,
17400  recoverVfsSync,
17401  recoverVfsFileSize,
17402  recoverVfsLock,
17403  recoverVfsUnlock,
17404  recoverVfsCheckReservedLock,
17405  recoverVfsFileControl,
17406  recoverVfsSectorSize,
17407  recoverVfsDeviceCharacteristics,
17408  recoverVfsShmMap,
17409  recoverVfsShmLock,
17410  recoverVfsShmBarrier,
17411  recoverVfsShmUnmap,
17412  recoverVfsFetch,
17413  recoverVfsUnfetch
17414};
17415
17416static int recoverVfsClose(sqlite3_file *pFd){
17417  assert( pFd->pMethods!=&recover_methods );
17418  return pFd->pMethods->xClose(pFd);
17419}
17420
17421/*
17422** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
17423*/
17424static void recoverPutU16(u8 *a, u32 v){
17425  a[0] = (v>>8) & 0x00FF;
17426  a[1] = (v>>0) & 0x00FF;
17427}
17428
17429/*
17430** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
17431*/
17432static void recoverPutU32(u8 *a, u32 v){
17433  a[0] = (v>>24) & 0x00FF;
17434  a[1] = (v>>16) & 0x00FF;
17435  a[2] = (v>>8) & 0x00FF;
17436  a[3] = (v>>0) & 0x00FF;
17437}
17438
17439/*
17440** Detect the page-size of the database opened by file-handle pFd by
17441** searching the first part of the file for a well-formed SQLite b-tree
17442** page. If parameter nReserve is non-zero, then as well as searching for
17443** a b-tree page with zero reserved bytes, this function searches for one
17444** with nReserve reserved bytes at the end of it.
17445**
17446** If successful, set variable p->detected_pgsz to the detected page-size
17447** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
17448** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
17449** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
17450** is returned. The final value of p->detected_pgsz is undefined in this
17451** case.
17452*/
17453static int recoverVfsDetectPagesize(
17454  sqlite3_recover *p,             /* Recover handle */
17455  sqlite3_file *pFd,              /* File-handle open on input database */
17456  u32 nReserve,                   /* Possible nReserve value */
17457  i64 nSz                         /* Size of database file in bytes */
17458){
17459  int rc = SQLITE_OK;
17460  const int nMin = 512;
17461  const int nMax = 65536;
17462  const int nMaxBlk = 4;
17463  u32 pgsz = 0;
17464  int iBlk = 0;
17465  u8 *aPg = 0;
17466  u8 *aTmp = 0;
17467  int nBlk = 0;
17468
17469  aPg = (u8*)sqlite3_malloc(2*nMax);
17470  if( aPg==0 ) return SQLITE_NOMEM;
17471  aTmp = &aPg[nMax];
17472
17473  nBlk = (nSz+nMax-1)/nMax;
17474  if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
17475
17476  do {
17477    for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
17478      int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
17479      memset(aPg, 0, nMax);
17480      rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
17481      if( rc==SQLITE_OK ){
17482        int pgsz2;
17483        for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
17484          int iOff;
17485          for(iOff=0; iOff<nMax; iOff+=pgsz2){
17486            if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
17487              pgsz = pgsz2;
17488              break;
17489            }
17490          }
17491        }
17492      }
17493    }
17494    if( pgsz>(u32)p->detected_pgsz ){
17495      p->detected_pgsz = pgsz;
17496      p->nReserve = nReserve;
17497    }
17498    if( nReserve==0 ) break;
17499    nReserve = 0;
17500  }while( 1 );
17501
17502  p->detected_pgsz = pgsz;
17503  sqlite3_free(aPg);
17504  return rc;
17505}
17506
17507/*
17508** The xRead() method of the wrapper VFS. This is used to intercept calls
17509** to read page 1 of the input database.
17510*/
17511static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
17512  int rc = SQLITE_OK;
17513  if( pFd->pMethods==&recover_methods ){
17514    pFd->pMethods = recover_g.pMethods;
17515    rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
17516    if( nByte==16 ){
17517      sqlite3_randomness(16, aBuf);
17518    }else
17519    if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
17520      /* Ensure that the database has a valid header file. The only fields
17521      ** that really matter to recovery are:
17522      **
17523      **   + Database page size (16-bits at offset 16)
17524      **   + Size of db in pages (32-bits at offset 28)
17525      **   + Database encoding (32-bits at offset 56)
17526      **
17527      ** Also preserved are:
17528      **
17529      **   + first freelist page (32-bits at offset 32)
17530      **   + size of freelist (32-bits at offset 36)
17531      **   + the wal-mode flags (16-bits at offset 18)
17532      **
17533      ** We also try to preserve the auto-vacuum, incr-value, user-version
17534      ** and application-id fields - all 32 bit quantities at offsets
17535      ** 52, 60, 64 and 68. All other fields are set to known good values.
17536      **
17537      ** Byte offset 105 should also contain the page-size as a 16-bit
17538      ** integer.
17539      */
17540      const int aPreserve[] = {32, 36, 52, 60, 64, 68};
17541      u8 aHdr[108] = {
17542        0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
17543        0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
17544        0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
17545        0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
17546        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17547        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
17548        0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
17549        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17550        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
17551        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17552        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17553        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
17554        0x00, 0x2e, 0x5b, 0x30,
17555
17556        0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
17557      };
17558      u8 *a = (u8*)aBuf;
17559
17560      u32 pgsz = recoverGetU16(&a[16]);
17561      u32 nReserve = a[20];
17562      u32 enc = recoverGetU32(&a[56]);
17563      u32 dbsz = 0;
17564      i64 dbFileSize = 0;
17565      int ii;
17566      sqlite3_recover *p = recover_g.p;
17567
17568      if( pgsz==0x01 ) pgsz = 65536;
17569      rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
17570
17571      if( rc==SQLITE_OK && p->detected_pgsz==0 ){
17572        rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
17573      }
17574      if( p->detected_pgsz ){
17575        pgsz = p->detected_pgsz;
17576        nReserve = p->nReserve;
17577      }
17578
17579      if( pgsz ){
17580        dbsz = dbFileSize / pgsz;
17581      }
17582      if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
17583        enc = SQLITE_UTF8;
17584      }
17585
17586      sqlite3_free(p->pPage1Cache);
17587      p->pPage1Cache = 0;
17588      p->pPage1Disk = 0;
17589
17590      p->pgsz = nByte;
17591      p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
17592      if( p->pPage1Cache ){
17593        p->pPage1Disk = &p->pPage1Cache[nByte];
17594        memcpy(p->pPage1Disk, aBuf, nByte);
17595        aHdr[18] = a[18];
17596        aHdr[19] = a[19];
17597        recoverPutU32(&aHdr[28], dbsz);
17598        recoverPutU32(&aHdr[56], enc);
17599        recoverPutU16(&aHdr[105], pgsz-nReserve);
17600        if( pgsz==65536 ) pgsz = 1;
17601        recoverPutU16(&aHdr[16], pgsz);
17602        aHdr[20] = nReserve;
17603        for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
17604          memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
17605        }
17606        memcpy(aBuf, aHdr, sizeof(aHdr));
17607        memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
17608
17609        memcpy(p->pPage1Cache, aBuf, nByte);
17610      }else{
17611        rc = p->errCode;
17612      }
17613
17614    }
17615    pFd->pMethods = &recover_methods;
17616  }else{
17617    rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
17618  }
17619  return rc;
17620}
17621
17622/*
17623** Used to make sqlite3_io_methods wrapper methods less verbose.
17624*/
17625#define RECOVER_VFS_WRAPPER(code)                         \
17626  int rc = SQLITE_OK;                                     \
17627  if( pFd->pMethods==&recover_methods ){                  \
17628    pFd->pMethods = recover_g.pMethods;                   \
17629    rc = code;                                            \
17630    pFd->pMethods = &recover_methods;                     \
17631  }else{                                                  \
17632    rc = code;                                            \
17633  }                                                       \
17634  return rc;
17635
17636/*
17637** Methods of the wrapper VFS. All methods except for xRead() and xClose()
17638** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
17639** method on the lower level VFS, then reinstall the wrapper before returning.
17640** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
17641*/
17642static int recoverVfsWrite(
17643  sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
17644){
17645  RECOVER_VFS_WRAPPER (
17646      pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
17647  );
17648}
17649static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
17650  RECOVER_VFS_WRAPPER (
17651      pFd->pMethods->xTruncate(pFd, size)
17652  );
17653}
17654static int recoverVfsSync(sqlite3_file *pFd, int flags){
17655  RECOVER_VFS_WRAPPER (
17656      pFd->pMethods->xSync(pFd, flags)
17657  );
17658}
17659static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
17660  RECOVER_VFS_WRAPPER (
17661      pFd->pMethods->xFileSize(pFd, pSize)
17662  );
17663}
17664static int recoverVfsLock(sqlite3_file *pFd, int eLock){
17665  RECOVER_VFS_WRAPPER (
17666      pFd->pMethods->xLock(pFd, eLock)
17667  );
17668}
17669static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
17670  RECOVER_VFS_WRAPPER (
17671      pFd->pMethods->xUnlock(pFd, eLock)
17672  );
17673}
17674static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
17675  RECOVER_VFS_WRAPPER (
17676      pFd->pMethods->xCheckReservedLock(pFd, pResOut)
17677  );
17678}
17679static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
17680  RECOVER_VFS_WRAPPER (
17681    (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
17682  );
17683}
17684static int recoverVfsSectorSize(sqlite3_file *pFd){
17685  RECOVER_VFS_WRAPPER (
17686      pFd->pMethods->xSectorSize(pFd)
17687  );
17688}
17689static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
17690  RECOVER_VFS_WRAPPER (
17691      pFd->pMethods->xDeviceCharacteristics(pFd)
17692  );
17693}
17694static int recoverVfsShmMap(
17695  sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
17696){
17697  RECOVER_VFS_WRAPPER (
17698      pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
17699  );
17700}
17701static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
17702  RECOVER_VFS_WRAPPER (
17703      pFd->pMethods->xShmLock(pFd, offset, n, flags)
17704  );
17705}
17706static void recoverVfsShmBarrier(sqlite3_file *pFd){
17707  if( pFd->pMethods==&recover_methods ){
17708    pFd->pMethods = recover_g.pMethods;
17709    pFd->pMethods->xShmBarrier(pFd);
17710    pFd->pMethods = &recover_methods;
17711  }else{
17712    pFd->pMethods->xShmBarrier(pFd);
17713  }
17714}
17715static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
17716  RECOVER_VFS_WRAPPER (
17717      pFd->pMethods->xShmUnmap(pFd, deleteFlag)
17718  );
17719}
17720
17721static int recoverVfsFetch(
17722  sqlite3_file *pFd,
17723  sqlite3_int64 iOff,
17724  int iAmt,
17725  void **pp
17726){
17727  (void)pFd;
17728  (void)iOff;
17729  (void)iAmt;
17730  *pp = 0;
17731  return SQLITE_OK;
17732}
17733static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
17734  (void)pFd;
17735  (void)iOff;
17736  (void)p;
17737  return SQLITE_OK;
17738}
17739
17740/*
17741** Install the VFS wrapper around the file-descriptor open on the input
17742** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
17743** when this function is called.
17744*/
17745static void recoverInstallWrapper(sqlite3_recover *p){
17746  sqlite3_file *pFd = 0;
17747  assert( recover_g.pMethods==0 );
17748  recoverAssertMutexHeld();
17749  sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
17750  assert( pFd==0 || pFd->pMethods!=&recover_methods );
17751  if( pFd && pFd->pMethods ){
17752    int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
17753    recover_g.pMethods = pFd->pMethods;
17754    recover_g.p = p;
17755    recover_methods.iVersion = iVersion;
17756    pFd->pMethods = &recover_methods;
17757  }
17758}
17759
17760/*
17761** Uninstall the VFS wrapper that was installed around the file-descriptor open
17762** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
17763** held when this function is called.
17764*/
17765static void recoverUninstallWrapper(sqlite3_recover *p){
17766  sqlite3_file *pFd = 0;
17767  recoverAssertMutexHeld();
17768  sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
17769  if( pFd && pFd->pMethods ){
17770    pFd->pMethods = recover_g.pMethods;
17771    recover_g.pMethods = 0;
17772    recover_g.p = 0;
17773  }
17774}
17775
17776/*
17777** This function does the work of a single sqlite3_recover_step() call. It
17778** is guaranteed that the handle is not in an error state when this
17779** function is called.
17780*/
17781static void recoverStep(sqlite3_recover *p){
17782  assert( p && p->errCode==SQLITE_OK );
17783  switch( p->eState ){
17784    case RECOVER_STATE_INIT:
17785      /* This is the very first call to sqlite3_recover_step() on this object.
17786      */
17787      recoverSqlCallback(p, "BEGIN");
17788      recoverSqlCallback(p, "PRAGMA writable_schema = on");
17789
17790      recoverEnterMutex();
17791      recoverInstallWrapper(p);
17792
17793      /* Open the output database. And register required virtual tables and
17794      ** user functions with the new handle. */
17795      recoverOpenOutput(p);
17796
17797      /* Open transactions on both the input and output databases. */
17798      sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
17799      recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
17800      recoverExec(p, p->dbIn, "BEGIN");
17801      if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
17802      recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
17803      recoverTransferSettings(p);
17804      recoverOpenRecovery(p);
17805      recoverCacheSchema(p);
17806
17807      recoverUninstallWrapper(p);
17808      recoverLeaveMutex();
17809
17810      recoverExec(p, p->dbOut, "BEGIN");
17811
17812      recoverWriteSchema1(p);
17813      p->eState = RECOVER_STATE_WRITING;
17814      break;
17815
17816    case RECOVER_STATE_WRITING: {
17817      if( p->w1.pTbls==0 ){
17818        recoverWriteDataInit(p);
17819      }
17820      if( SQLITE_DONE==recoverWriteDataStep(p) ){
17821        recoverWriteDataCleanup(p);
17822        if( p->zLostAndFound ){
17823          p->eState = RECOVER_STATE_LOSTANDFOUND1;
17824        }else{
17825          p->eState = RECOVER_STATE_SCHEMA2;
17826        }
17827      }
17828      break;
17829    }
17830
17831    case RECOVER_STATE_LOSTANDFOUND1: {
17832      if( p->laf.pUsed==0 ){
17833        recoverLostAndFound1Init(p);
17834      }
17835      if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
17836        p->eState = RECOVER_STATE_LOSTANDFOUND2;
17837      }
17838      break;
17839    }
17840    case RECOVER_STATE_LOSTANDFOUND2: {
17841      if( p->laf.pAllAndParent==0 ){
17842        recoverLostAndFound2Init(p);
17843      }
17844      if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
17845        p->eState = RECOVER_STATE_LOSTANDFOUND3;
17846      }
17847      break;
17848    }
17849
17850    case RECOVER_STATE_LOSTANDFOUND3: {
17851      if( p->laf.pInsert==0 ){
17852        recoverLostAndFound3Init(p);
17853      }
17854      if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
17855        p->eState = RECOVER_STATE_SCHEMA2;
17856      }
17857      break;
17858    }
17859
17860    case RECOVER_STATE_SCHEMA2: {
17861      int rc = SQLITE_OK;
17862
17863      recoverWriteSchema2(p);
17864      p->eState = RECOVER_STATE_DONE;
17865
17866      /* If no error has occurred, commit the write transaction on the output
17867      ** database. Regardless of whether or not an error has occurred, make
17868      ** an attempt to end the read transaction on the input database.  */
17869      recoverExec(p, p->dbOut, "COMMIT");
17870      rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
17871      if( p->errCode==SQLITE_OK ) p->errCode = rc;
17872
17873      recoverSqlCallback(p, "PRAGMA writable_schema = off");
17874      recoverSqlCallback(p, "COMMIT");
17875      p->eState = RECOVER_STATE_DONE;
17876      recoverFinalCleanup(p);
17877      break;
17878    };
17879
17880    case RECOVER_STATE_DONE: {
17881      /* no-op */
17882      break;
17883    };
17884  }
17885}
17886
17887
17888/*
17889** This is a worker function that does the heavy lifting for both init
17890** functions:
17891**
17892**     sqlite3_recover_init()
17893**     sqlite3_recover_init_sql()
17894**
17895** All this function does is allocate space for the recover handle and
17896** take copies of the input parameters. All the real work is done within
17897** sqlite3_recover_run().
17898*/
17899sqlite3_recover *recoverInit(
17900  sqlite3* db,
17901  const char *zDb,
17902  const char *zUri,               /* Output URI for _recover_init() */
17903  int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
17904  void *pSqlCtx                   /* Context arg for _recover_init_sql() */
17905){
17906  sqlite3_recover *pRet = 0;
17907  int nDb = 0;
17908  int nUri = 0;
17909  int nByte = 0;
17910
17911  if( zDb==0 ){ zDb = "main"; }
17912
17913  nDb = recoverStrlen(zDb);
17914  nUri = recoverStrlen(zUri);
17915
17916  nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
17917  pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
17918  if( pRet ){
17919    memset(pRet, 0, nByte);
17920    pRet->dbIn = db;
17921    pRet->zDb = (char*)&pRet[1];
17922    pRet->zUri = &pRet->zDb[nDb+1];
17923    memcpy(pRet->zDb, zDb, nDb);
17924    if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
17925    pRet->xSql = xSql;
17926    pRet->pSqlCtx = pSqlCtx;
17927    pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
17928  }
17929
17930  return pRet;
17931}
17932
17933/*
17934** Initialize a recovery handle that creates a new database containing
17935** the recovered data.
17936*/
17937sqlite3_recover *sqlite3_recover_init(
17938  sqlite3* db,
17939  const char *zDb,
17940  const char *zUri
17941){
17942  return recoverInit(db, zDb, zUri, 0, 0);
17943}
17944
17945/*
17946** Initialize a recovery handle that returns recovered data in the
17947** form of SQL statements via a callback.
17948*/
17949sqlite3_recover *sqlite3_recover_init_sql(
17950  sqlite3* db,
17951  const char *zDb,
17952  int (*xSql)(void*, const char*),
17953  void *pSqlCtx
17954){
17955  return recoverInit(db, zDb, 0, xSql, pSqlCtx);
17956}
17957
17958/*
17959** Return the handle error message, if any.
17960*/
17961const char *sqlite3_recover_errmsg(sqlite3_recover *p){
17962  return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
17963}
17964
17965/*
17966** Return the handle error code.
17967*/
17968int sqlite3_recover_errcode(sqlite3_recover *p){
17969  return p ? p->errCode : SQLITE_NOMEM;
17970}
17971
17972/*
17973** Configure the handle.
17974*/
17975int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
17976  int rc = SQLITE_OK;
17977  if( p==0 ){
17978    rc = SQLITE_NOMEM;
17979  }else if( p->eState!=RECOVER_STATE_INIT ){
17980    rc = SQLITE_MISUSE;
17981  }else{
17982    switch( op ){
17983      case 789:
17984        /* This undocumented magic configuration option is used to set the
17985        ** name of the auxiliary database that is ATTACH-ed to the database
17986        ** connection and used to hold state information during the
17987        ** recovery process.  This option is for debugging use only and
17988        ** is subject to change or removal at any time. */
17989        sqlite3_free(p->zStateDb);
17990        p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
17991        break;
17992
17993      case SQLITE_RECOVER_LOST_AND_FOUND: {
17994        const char *zArg = (const char*)pArg;
17995        sqlite3_free(p->zLostAndFound);
17996        if( zArg ){
17997          p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
17998        }else{
17999          p->zLostAndFound = 0;
18000        }
18001        break;
18002      }
18003
18004      case SQLITE_RECOVER_FREELIST_CORRUPT:
18005        p->bFreelistCorrupt = *(int*)pArg;
18006        break;
18007
18008      case SQLITE_RECOVER_ROWIDS:
18009        p->bRecoverRowid = *(int*)pArg;
18010        break;
18011
18012      case SQLITE_RECOVER_SLOWINDEXES:
18013        p->bSlowIndexes = *(int*)pArg;
18014        break;
18015
18016      default:
18017        rc = SQLITE_NOTFOUND;
18018        break;
18019    }
18020  }
18021
18022  return rc;
18023}
18024
18025/*
18026** Do a unit of work towards the recovery job. Return SQLITE_OK if
18027** no error has occurred but database recovery is not finished, SQLITE_DONE
18028** if database recovery has been successfully completed, or an SQLite
18029** error code if an error has occurred.
18030*/
18031int sqlite3_recover_step(sqlite3_recover *p){
18032  if( p==0 ) return SQLITE_NOMEM;
18033  if( p->errCode==SQLITE_OK ) recoverStep(p);
18034  if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
18035    return SQLITE_DONE;
18036  }
18037  return p->errCode;
18038}
18039
18040/*
18041** Do the configured recovery operation. Return SQLITE_OK if successful, or
18042** else an SQLite error code.
18043*/
18044int sqlite3_recover_run(sqlite3_recover *p){
18045  while( SQLITE_OK==sqlite3_recover_step(p) );
18046  return sqlite3_recover_errcode(p);
18047}
18048
18049
18050/*
18051** Free all resources associated with the recover handle passed as the only
18052** argument. The results of using a handle with any sqlite3_recover_**
18053** API function after it has been passed to this function are undefined.
18054**
18055** A copy of the value returned by the first call made to sqlite3_recover_run()
18056** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
18057** not been called on this handle.
18058*/
18059int sqlite3_recover_finish(sqlite3_recover *p){
18060  int rc;
18061  if( p==0 ){
18062    rc = SQLITE_NOMEM;
18063  }else{
18064    recoverFinalCleanup(p);
18065    if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
18066      rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
18067      if( p->errCode==SQLITE_OK ) p->errCode = rc;
18068    }
18069    rc = p->errCode;
18070    sqlite3_free(p->zErrMsg);
18071    sqlite3_free(p->zStateDb);
18072    sqlite3_free(p->zLostAndFound);
18073    sqlite3_free(p->pPage1Cache);
18074    sqlite3_free(p);
18075  }
18076  return rc;
18077}
18078
18079#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
18080
18081/************************* End ../ext/recover/sqlite3recover.c ********************/
18082# endif /* SQLITE_HAVE_SQLITE3R */
18083#endif
18084#ifdef SQLITE_SHELL_EXTSRC
18085# include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
18086#endif
18087
18088#if defined(SQLITE_ENABLE_SESSION)
18089/*
18090** State information for a single open session
18091*/
18092typedef struct OpenSession OpenSession;
18093struct OpenSession {
18094  char *zName;             /* Symbolic name for this session */
18095  int nFilter;             /* Number of xFilter rejection GLOB patterns */
18096  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
18097  sqlite3_session *p;      /* The open session */
18098};
18099#endif
18100
18101typedef struct ExpertInfo ExpertInfo;
18102struct ExpertInfo {
18103  sqlite3expert *pExpert;
18104  int bVerbose;
18105};
18106
18107/* A single line in the EQP output */
18108typedef struct EQPGraphRow EQPGraphRow;
18109struct EQPGraphRow {
18110  int iEqpId;           /* ID for this row */
18111  int iParentId;        /* ID of the parent row */
18112  EQPGraphRow *pNext;   /* Next row in sequence */
18113  char zText[1];        /* Text to display for this row */
18114};
18115
18116/* All EQP output is collected into an instance of the following */
18117typedef struct EQPGraph EQPGraph;
18118struct EQPGraph {
18119  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
18120  EQPGraphRow *pLast;   /* Last element of the pRow list */
18121  char zPrefix[100];    /* Graph prefix */
18122};
18123
18124/* Parameters affecting columnar mode result display (defaulting together) */
18125typedef struct ColModeOpts {
18126  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
18127  u8 bQuote;            /* Quote results for .mode box and table */
18128  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
18129} ColModeOpts;
18130#define ColModeOpts_default { 60, 0, 0 }
18131#define ColModeOpts_default_qbox { 60, 1, 0 }
18132
18133/*
18134** State information about the database connection is contained in an
18135** instance of the following structure.
18136*/
18137typedef struct ShellState ShellState;
18138struct ShellState {
18139  sqlite3 *db;           /* The database */
18140  u8 autoExplain;        /* Automatically turn on .explain mode */
18141  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
18142  u8 autoEQPtest;        /* autoEQP is in test mode */
18143  u8 autoEQPtrace;       /* autoEQP is in trace mode */
18144  u8 scanstatsOn;        /* True to display scan stats before each finalize */
18145  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
18146  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
18147  u8 nEqpLevel;          /* Depth of the EQP output graph */
18148  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
18149  u8 bSafeMode;          /* True to prohibit unsafe operations */
18150  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
18151  u8 eRestoreState;      /* See comments above doAutoDetectRestore() */
18152  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
18153  unsigned statsOn;      /* True to display memory stats before each finalize */
18154  unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
18155  int inputNesting;      /* Track nesting level of .read and other redirects */
18156  int outCount;          /* Revert to stdout when reaching zero */
18157  int cnt;               /* Number of records displayed so far */
18158  int lineno;            /* Line number of last line read from in */
18159  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
18160  FILE *in;              /* Read commands from this stream */
18161  FILE *out;             /* Write results here */
18162  FILE *traceOut;        /* Output for sqlite3_trace() */
18163  int nErr;              /* Number of errors seen */
18164  int mode;              /* An output mode setting */
18165  int modePrior;         /* Saved mode */
18166  int cMode;             /* temporary output mode for the current query */
18167  int normalMode;        /* Output mode before ".explain on" */
18168  int writableSchema;    /* True if PRAGMA writable_schema=ON */
18169  int showHeader;        /* True to show column names in List or Column mode */
18170  int nCheck;            /* Number of ".check" commands run */
18171  unsigned nProgress;    /* Number of progress callbacks encountered */
18172  unsigned mxProgress;   /* Maximum progress callbacks before failing */
18173  unsigned flgProgress;  /* Flags for the progress callback */
18174  unsigned shellFlgs;    /* Various flags */
18175  unsigned priorShFlgs;  /* Saved copy of flags */
18176  sqlite3_int64 szMax;   /* --maxsize argument to .open */
18177  char *zDestTable;      /* Name of destination table when MODE_Insert */
18178  char *zTempFile;       /* Temporary file that might need deleting */
18179  char zTestcase[30];    /* Name of current test case */
18180  char colSeparator[20]; /* Column separator character for several modes */
18181  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
18182  char colSepPrior[20];  /* Saved column separator */
18183  char rowSepPrior[20];  /* Saved row separator */
18184  int *colWidth;         /* Requested width of each column in columnar modes */
18185  int *actualWidth;      /* Actual width of each column */
18186  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
18187  char nullValue[20];    /* The text to print when a NULL comes back from
18188                         ** the database */
18189  char outfile[FILENAME_MAX]; /* Filename for *out */
18190  sqlite3_stmt *pStmt;   /* Current statement if any. */
18191  FILE *pLog;            /* Write log output here */
18192  struct AuxDb {         /* Storage space for auxiliary database connections */
18193    sqlite3 *db;               /* Connection pointer */
18194    const char *zDbFilename;   /* Filename used to open the connection */
18195    char *zFreeOnClose;        /* Free this memory allocation on close */
18196#if defined(SQLITE_ENABLE_SESSION)
18197    int nSession;              /* Number of active sessions */
18198    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
18199#endif
18200  } aAuxDb[5],           /* Array of all database connections */
18201    *pAuxDb;             /* Currently active database connection */
18202  int *aiIndent;         /* Array of indents used in MODE_Explain */
18203  int nIndent;           /* Size of array aiIndent[] */
18204  int iIndent;           /* Index of current op in aiIndent[] */
18205  char *zNonce;          /* Nonce for temporary safe-mode escapes */
18206  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
18207  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
18208#ifdef SQLITE_SHELL_FIDDLE
18209  struct {
18210    const char * zInput; /* Input string from wasm/JS proxy */
18211    const char * zPos;   /* Cursor pos into zInput */
18212    const char * zDefaultDbName; /* Default name for db file */
18213  } wasm;
18214#endif
18215};
18216
18217#ifdef SQLITE_SHELL_FIDDLE
18218static ShellState shellState;
18219#endif
18220
18221
18222/* Allowed values for ShellState.autoEQP
18223*/
18224#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
18225#define AUTOEQP_on       1           /* Automatic EQP is on */
18226#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
18227#define AUTOEQP_full     3           /* Show full EXPLAIN */
18228
18229/* Allowed values for ShellState.openMode
18230*/
18231#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
18232#define SHELL_OPEN_NORMAL      1      /* Normal database file */
18233#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
18234#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
18235#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
18236#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
18237#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
18238
18239/* Allowed values for ShellState.eTraceType
18240*/
18241#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
18242#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
18243#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
18244
18245/* Bits in the ShellState.flgProgress variable */
18246#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
18247#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
18248                                   ** callback limit is reached, and for each
18249                                   ** top-level SQL statement */
18250#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
18251
18252/*
18253** These are the allowed shellFlgs values
18254*/
18255#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
18256#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
18257#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
18258#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
18259#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
18260#define SHFLG_CountChanges   0x00000020 /* .changes setting */
18261#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
18262#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
18263#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
18264#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
18265#define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
18266
18267/*
18268** Macros for testing and setting shellFlgs
18269*/
18270#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
18271#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
18272#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
18273
18274/*
18275** These are the allowed modes.
18276*/
18277#define MODE_Line     0  /* One column per line.  Blank line between records */
18278#define MODE_Column   1  /* One record per line in neat columns */
18279#define MODE_List     2  /* One record per line with a separator */
18280#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
18281#define MODE_Html     4  /* Generate an XHTML table */
18282#define MODE_Insert   5  /* Generate SQL "insert" statements */
18283#define MODE_Quote    6  /* Quote values as for SQL */
18284#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
18285#define MODE_Csv      8  /* Quote strings, numbers are plain */
18286#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
18287#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
18288#define MODE_Pretty  11  /* Pretty-print schemas */
18289#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
18290#define MODE_Json    13  /* Output JSON */
18291#define MODE_Markdown 14 /* Markdown formatting */
18292#define MODE_Table   15  /* MySQL-style table formatting */
18293#define MODE_Box     16  /* Unicode box-drawing characters */
18294#define MODE_Count   17  /* Output only a count of the rows of output */
18295#define MODE_Off     18  /* No query output shown */
18296#define MODE_ScanExp 19  /* Like MODE_Explain, but for ".scanstats vm" */
18297
18298static const char *modeDescr[] = {
18299  "line",
18300  "column",
18301  "list",
18302  "semi",
18303  "html",
18304  "insert",
18305  "quote",
18306  "tcl",
18307  "csv",
18308  "explain",
18309  "ascii",
18310  "prettyprint",
18311  "eqp",
18312  "json",
18313  "markdown",
18314  "table",
18315  "box",
18316  "count",
18317  "off"
18318};
18319
18320/*
18321** These are the column/row/line separators used by the various
18322** import/export modes.
18323*/
18324#define SEP_Column    "|"
18325#define SEP_Row       "\n"
18326#define SEP_Tab       "\t"
18327#define SEP_Space     " "
18328#define SEP_Comma     ","
18329#define SEP_CrLf      "\r\n"
18330#define SEP_Unit      "\x1F"
18331#define SEP_Record    "\x1E"
18332
18333/*
18334** Limit input nesting via .read or any other input redirect.
18335** It's not too expensive, so a generous allowance can be made.
18336*/
18337#define MAX_INPUT_NESTING 25
18338
18339/*
18340** A callback for the sqlite3_log() interface.
18341*/
18342static void shellLog(void *pArg, int iErrCode, const char *zMsg){
18343  ShellState *p = (ShellState*)pArg;
18344  if( p->pLog==0 ) return;
18345  sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
18346  fflush(p->pLog);
18347}
18348
18349/*
18350** SQL function:  shell_putsnl(X)
18351**
18352** Write the text X to the screen (or whatever output is being directed)
18353** adding a newline at the end, and then return X.
18354*/
18355static void shellPutsFunc(
18356  sqlite3_context *pCtx,
18357  int nVal,
18358  sqlite3_value **apVal
18359){
18360  /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
18361  (void)nVal;
18362  oputf("%s\n", sqlite3_value_text(apVal[0]));
18363  sqlite3_result_value(pCtx, apVal[0]);
18364}
18365
18366/*
18367** If in safe mode, print an error message described by the arguments
18368** and exit immediately.
18369*/
18370static void failIfSafeMode(
18371  ShellState *p,
18372  const char *zErrMsg,
18373  ...
18374){
18375  if( p->bSafeMode ){
18376    va_list ap;
18377    char *zMsg;
18378    va_start(ap, zErrMsg);
18379    zMsg = sqlite3_vmprintf(zErrMsg, ap);
18380    va_end(ap);
18381    eputf("line %d: %s\n", p->lineno, zMsg);
18382    exit(1);
18383  }
18384}
18385
18386/*
18387** SQL function:   edit(VALUE)
18388**                 edit(VALUE,EDITOR)
18389**
18390** These steps:
18391**
18392**     (1) Write VALUE into a temporary file.
18393**     (2) Run program EDITOR on that temporary file.
18394**     (3) Read the temporary file back and return its content as the result.
18395**     (4) Delete the temporary file
18396**
18397** If the EDITOR argument is omitted, use the value in the VISUAL
18398** environment variable.  If still there is no EDITOR, through an error.
18399**
18400** Also throw an error if the EDITOR program returns a non-zero exit code.
18401*/
18402#ifndef SQLITE_NOHAVE_SYSTEM
18403static void editFunc(
18404  sqlite3_context *context,
18405  int argc,
18406  sqlite3_value **argv
18407){
18408  const char *zEditor;
18409  char *zTempFile = 0;
18410  sqlite3 *db;
18411  char *zCmd = 0;
18412  int bBin;
18413  int rc;
18414  int hasCRNL = 0;
18415  FILE *f = 0;
18416  sqlite3_int64 sz;
18417  sqlite3_int64 x;
18418  unsigned char *p = 0;
18419
18420  if( argc==2 ){
18421    zEditor = (const char*)sqlite3_value_text(argv[1]);
18422  }else{
18423    zEditor = getenv("VISUAL");
18424  }
18425  if( zEditor==0 ){
18426    sqlite3_result_error(context, "no editor for edit()", -1);
18427    return;
18428  }
18429  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
18430    sqlite3_result_error(context, "NULL input to edit()", -1);
18431    return;
18432  }
18433  db = sqlite3_context_db_handle(context);
18434  zTempFile = 0;
18435  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
18436  if( zTempFile==0 ){
18437    sqlite3_uint64 r = 0;
18438    sqlite3_randomness(sizeof(r), &r);
18439    zTempFile = sqlite3_mprintf("temp%llx", r);
18440    if( zTempFile==0 ){
18441      sqlite3_result_error_nomem(context);
18442      return;
18443    }
18444  }
18445  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
18446  /* When writing the file to be edited, do \n to \r\n conversions on systems
18447  ** that want \r\n line endings */
18448  f = fopen(zTempFile, bBin ? "wb" : "w");
18449  if( f==0 ){
18450    sqlite3_result_error(context, "edit() cannot open temp file", -1);
18451    goto edit_func_end;
18452  }
18453  sz = sqlite3_value_bytes(argv[0]);
18454  if( bBin ){
18455    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
18456  }else{
18457    const char *z = (const char*)sqlite3_value_text(argv[0]);
18458    /* Remember whether or not the value originally contained \r\n */
18459    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
18460    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
18461  }
18462  fclose(f);
18463  f = 0;
18464  if( x!=sz ){
18465    sqlite3_result_error(context, "edit() could not write the whole file", -1);
18466    goto edit_func_end;
18467  }
18468  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
18469  if( zCmd==0 ){
18470    sqlite3_result_error_nomem(context);
18471    goto edit_func_end;
18472  }
18473  rc = system(zCmd);
18474  sqlite3_free(zCmd);
18475  if( rc ){
18476    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
18477    goto edit_func_end;
18478  }
18479  f = fopen(zTempFile, "rb");
18480  if( f==0 ){
18481    sqlite3_result_error(context,
18482      "edit() cannot reopen temp file after edit", -1);
18483    goto edit_func_end;
18484  }
18485  fseek(f, 0, SEEK_END);
18486  sz = ftell(f);
18487  rewind(f);
18488  p = sqlite3_malloc64( sz+1 );
18489  if( p==0 ){
18490    sqlite3_result_error_nomem(context);
18491    goto edit_func_end;
18492  }
18493  x = fread(p, 1, (size_t)sz, f);
18494  fclose(f);
18495  f = 0;
18496  if( x!=sz ){
18497    sqlite3_result_error(context, "could not read back the whole file", -1);
18498    goto edit_func_end;
18499  }
18500  if( bBin ){
18501    sqlite3_result_blob64(context, p, sz, sqlite3_free);
18502  }else{
18503    sqlite3_int64 i, j;
18504    if( hasCRNL ){
18505      /* If the original contains \r\n then do no conversions back to \n */
18506    }else{
18507      /* If the file did not originally contain \r\n then convert any new
18508      ** \r\n back into \n */
18509      p[sz] = 0;
18510      for(i=j=0; i<sz; i++){
18511        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
18512        p[j++] = p[i];
18513      }
18514      sz = j;
18515      p[sz] = 0;
18516    }
18517    sqlite3_result_text64(context, (const char*)p, sz,
18518                          sqlite3_free, SQLITE_UTF8);
18519  }
18520  p = 0;
18521
18522edit_func_end:
18523  if( f ) fclose(f);
18524  unlink(zTempFile);
18525  sqlite3_free(zTempFile);
18526  sqlite3_free(p);
18527}
18528#endif /* SQLITE_NOHAVE_SYSTEM */
18529
18530/*
18531** Save or restore the current output mode
18532*/
18533static void outputModePush(ShellState *p){
18534  p->modePrior = p->mode;
18535  p->priorShFlgs = p->shellFlgs;
18536  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
18537  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
18538}
18539static void outputModePop(ShellState *p){
18540  p->mode = p->modePrior;
18541  p->shellFlgs = p->priorShFlgs;
18542  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
18543  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
18544}
18545
18546/*
18547** Output the given string as a hex-encoded blob (eg. X'1234' )
18548*/
18549static void output_hex_blob(const void *pBlob, int nBlob){
18550  int i;
18551  unsigned char *aBlob = (unsigned char*)pBlob;
18552
18553  char *zStr = sqlite3_malloc(nBlob*2 + 1);
18554  shell_check_oom(zStr);
18555
18556  for(i=0; i<nBlob; i++){
18557    static const char aHex[] = {
18558        '0', '1', '2', '3', '4', '5', '6', '7',
18559        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
18560    };
18561    zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
18562    zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
18563  }
18564  zStr[i*2] = '\0';
18565
18566  oputf("X'%s'", zStr);
18567  sqlite3_free(zStr);
18568}
18569
18570/*
18571** Find a string that is not found anywhere in z[].  Return a pointer
18572** to that string.
18573**
18574** Try to use zA and zB first.  If both of those are already found in z[]
18575** then make up some string and store it in the buffer zBuf.
18576*/
18577static const char *unused_string(
18578  const char *z,                    /* Result must not appear anywhere in z */
18579  const char *zA, const char *zB,   /* Try these first */
18580  char *zBuf                        /* Space to store a generated string */
18581){
18582  unsigned i = 0;
18583  if( strstr(z, zA)==0 ) return zA;
18584  if( strstr(z, zB)==0 ) return zB;
18585  do{
18586    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
18587  }while( strstr(z,zBuf)!=0 );
18588  return zBuf;
18589}
18590
18591/*
18592** Output the given string as a quoted string using SQL quoting conventions.
18593**
18594** See also: output_quoted_escaped_string()
18595*/
18596static void output_quoted_string(const char *z){
18597  int i;
18598  char c;
18599#ifndef SQLITE_SHELL_FIDDLE
18600  FILE *pfO = setOutputStream(invalidFileStream);
18601  setBinaryMode(pfO, 1);
18602#endif
18603  if( z==0 ) return;
18604  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
18605  if( c==0 ){
18606    oputf("'%s'",z);
18607  }else{
18608    oputz("'");
18609    while( *z ){
18610      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
18611      if( c=='\'' ) i++;
18612      if( i ){
18613        oputf("%.*s", i, z);
18614        z += i;
18615      }
18616      if( c=='\'' ){
18617        oputz("'");
18618        continue;
18619      }
18620      if( c==0 ){
18621        break;
18622      }
18623      z++;
18624    }
18625    oputz("'");
18626  }
18627#ifndef SQLITE_SHELL_FIDDLE
18628  setTextMode(pfO, 1);
18629#else
18630  setTextMode(stdout, 1);
18631#endif
18632}
18633
18634/*
18635** Output the given string as a quoted string using SQL quoting conventions.
18636** Additionallly , escape the "\n" and "\r" characters so that they do not
18637** get corrupted by end-of-line translation facilities in some operating
18638** systems.
18639**
18640** This is like output_quoted_string() but with the addition of the \r\n
18641** escape mechanism.
18642*/
18643static void output_quoted_escaped_string(const char *z){
18644  int i;
18645  char c;
18646#ifndef SQLITE_SHELL_FIDDLE
18647  FILE *pfO = setOutputStream(invalidFileStream);
18648  setBinaryMode(pfO, 1);
18649#endif
18650  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
18651  if( c==0 ){
18652    oputf("'%s'",z);
18653  }else{
18654    const char *zNL = 0;
18655    const char *zCR = 0;
18656    int nNL = 0;
18657    int nCR = 0;
18658    char zBuf1[20], zBuf2[20];
18659    for(i=0; z[i]; i++){
18660      if( z[i]=='\n' ) nNL++;
18661      if( z[i]=='\r' ) nCR++;
18662    }
18663    if( nNL ){
18664      oputz("replace(");
18665      zNL = unused_string(z, "\\n", "\\012", zBuf1);
18666    }
18667    if( nCR ){
18668      oputz("replace(");
18669      zCR = unused_string(z, "\\r", "\\015", zBuf2);
18670    }
18671    oputz("'");
18672    while( *z ){
18673      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
18674      if( c=='\'' ) i++;
18675      if( i ){
18676        oputf("%.*s", i, z);
18677        z += i;
18678      }
18679      if( c=='\'' ){
18680        oputz("'");
18681        continue;
18682      }
18683      if( c==0 ){
18684        break;
18685      }
18686      z++;
18687      if( c=='\n' ){
18688        oputz(zNL);
18689        continue;
18690      }
18691      oputz(zCR);
18692    }
18693    oputz("'");
18694    if( nCR ){
18695      oputf(",'%s',char(13))", zCR);
18696    }
18697    if( nNL ){
18698      oputf(",'%s',char(10))", zNL);
18699    }
18700  }
18701#ifndef SQLITE_SHELL_FIDDLE
18702  setTextMode(pfO, 1);
18703#else
18704  setTextMode(stdout, 1);
18705#endif
18706}
18707
18708/*
18709** Find earliest of chars within s specified in zAny.
18710** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
18711*/
18712static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
18713  const char *pcFirst = 0;
18714  if( ns == ~(size_t)0 ) ns = strlen(s);
18715  while(*zAny){
18716    const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
18717    if( pc ){
18718      pcFirst = pc;
18719      ns = pcFirst - s;
18720    }
18721    ++zAny;
18722  }
18723  return pcFirst;
18724}
18725/*
18726** Output the given string as a quoted according to C or TCL quoting rules.
18727*/
18728static void output_c_string(const char *z){
18729  char c;
18730  static const char *zq = "\"";
18731  static long ctrlMask = ~0L;
18732  static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
18733  char ace[3] = "\\?";
18734  char cbsSay;
18735  oputz(zq);
18736  while( *z!=0 ){
18737    const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
18738    const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
18739    const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
18740    if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
18741    if( (c = *pcEnd)==0 ) break;
18742    ++pcEnd;
18743    switch( c ){
18744    case '\\': case '"':
18745      cbsSay = (char)c;
18746      break;
18747    case '\t': cbsSay = 't'; break;
18748    case '\n': cbsSay = 'n'; break;
18749    case '\r': cbsSay = 'r'; break;
18750    case '\f': cbsSay = 'f'; break;
18751    default: cbsSay = 0; break;
18752    }
18753    if( cbsSay ){
18754      ace[1] = cbsSay;
18755      oputz(ace);
18756    }else if( !isprint(c&0xff) ){
18757      oputf("\\%03o", c&0xff);
18758    }else{
18759      ace[1] = (char)c;
18760      oputz(ace+1);
18761    }
18762    z = pcEnd;
18763  }
18764  oputz(zq);
18765}
18766
18767/*
18768** Output the given string as a quoted according to JSON quoting rules.
18769*/
18770static void output_json_string(const char *z, i64 n){
18771  char c;
18772  static const char *zq = "\"";
18773  static long ctrlMask = ~0L;
18774  static const char *zDQBS = "\"\\";
18775  const char *pcLimit;
18776  char ace[3] = "\\?";
18777  char cbsSay;
18778
18779  if( z==0 ) z = "";
18780  pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
18781  oputz(zq);
18782  while( z < pcLimit ){
18783    const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
18784    const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
18785    const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
18786    if( pcEnd > z ){
18787      oputb(z, (int)(pcEnd-z));
18788      z = pcEnd;
18789    }
18790    if( z >= pcLimit ) break;
18791    c = *(z++);
18792    switch( c ){
18793    case '"': case '\\':
18794      cbsSay = (char)c;
18795      break;
18796    case '\b': cbsSay = 'b'; break;
18797    case '\f': cbsSay = 'f'; break;
18798    case '\n': cbsSay = 'n'; break;
18799    case '\r': cbsSay = 'r'; break;
18800    case '\t': cbsSay = 't'; break;
18801    default: cbsSay = 0; break;
18802    }
18803    if( cbsSay ){
18804      ace[1] = cbsSay;
18805      oputz(ace);
18806    }else if( c<=0x1f ){
18807      oputf("u%04x", c);
18808    }else{
18809      ace[1] = (char)c;
18810      oputz(ace+1);
18811    }
18812  }
18813  oputz(zq);
18814}
18815
18816/*
18817** Output the given string with characters that are special to
18818** HTML escaped.
18819*/
18820static void output_html_string(const char *z){
18821  int i;
18822  if( z==0 ) z = "";
18823  while( *z ){
18824    for(i=0;   z[i]
18825            && z[i]!='<'
18826            && z[i]!='&'
18827            && z[i]!='>'
18828            && z[i]!='\"'
18829            && z[i]!='\'';
18830        i++){}
18831    if( i>0 ){
18832      oputf("%.*s",i,z);
18833    }
18834    if( z[i]=='<' ){
18835      oputz("&lt;");
18836    }else if( z[i]=='&' ){
18837      oputz("&amp;");
18838    }else if( z[i]=='>' ){
18839      oputz("&gt;");
18840    }else if( z[i]=='\"' ){
18841      oputz("&quot;");
18842    }else if( z[i]=='\'' ){
18843      oputz("&#39;");
18844    }else{
18845      break;
18846    }
18847    z += i + 1;
18848  }
18849}
18850
18851/*
18852** If a field contains any character identified by a 1 in the following
18853** array, then the string must be quoted for CSV.
18854*/
18855static const char needCsvQuote[] = {
18856  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18857  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18858  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
18859  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18860  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18861  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18862  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18863  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
18864  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18865  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18866  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18867  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18868  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18869  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18870  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18871  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18872};
18873
18874/*
18875** Output a single term of CSV.  Actually, p->colSeparator is used for
18876** the separator, which may or may not be a comma.  p->nullValue is
18877** the null value.  Strings are quoted if necessary.  The separator
18878** is only issued if bSep is true.
18879*/
18880static void output_csv(ShellState *p, const char *z, int bSep){
18881  if( z==0 ){
18882    oputf("%s",p->nullValue);
18883  }else{
18884    unsigned i;
18885    for(i=0; z[i]; i++){
18886      if( needCsvQuote[((unsigned char*)z)[i]] ){
18887        i = 0;
18888        break;
18889      }
18890    }
18891    if( i==0 || strstr(z, p->colSeparator)!=0 ){
18892      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
18893      shell_check_oom(zQuoted);
18894      oputz(zQuoted);
18895      sqlite3_free(zQuoted);
18896    }else{
18897      oputz(z);
18898    }
18899  }
18900  if( bSep ){
18901    oputz(p->colSeparator);
18902  }
18903}
18904
18905/*
18906** This routine runs when the user presses Ctrl-C
18907*/
18908static void interrupt_handler(int NotUsed){
18909  UNUSED_PARAMETER(NotUsed);
18910  if( ++seenInterrupt>1 ) exit(1);
18911  if( globalDb ) sqlite3_interrupt(globalDb);
18912}
18913
18914#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
18915/*
18916** This routine runs for console events (e.g. Ctrl-C) on Win32
18917*/
18918static BOOL WINAPI ConsoleCtrlHandler(
18919  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
18920){
18921  if( dwCtrlType==CTRL_C_EVENT ){
18922    interrupt_handler(0);
18923    return TRUE;
18924  }
18925  return FALSE;
18926}
18927#endif
18928
18929#ifndef SQLITE_OMIT_AUTHORIZATION
18930/*
18931** This authorizer runs in safe mode.
18932*/
18933static int safeModeAuth(
18934  void *pClientData,
18935  int op,
18936  const char *zA1,
18937  const char *zA2,
18938  const char *zA3,
18939  const char *zA4
18940){
18941  ShellState *p = (ShellState*)pClientData;
18942  static const char *azProhibitedFunctions[] = {
18943    "edit",
18944    "fts3_tokenizer",
18945    "load_extension",
18946    "readfile",
18947    "writefile",
18948    "zipfile",
18949    "zipfile_cds",
18950  };
18951  UNUSED_PARAMETER(zA1);
18952  UNUSED_PARAMETER(zA3);
18953  UNUSED_PARAMETER(zA4);
18954  switch( op ){
18955    case SQLITE_ATTACH: {
18956#ifndef SQLITE_SHELL_FIDDLE
18957      /* In WASM builds the filesystem is a virtual sandbox, so
18958      ** there's no harm in using ATTACH. */
18959      failIfSafeMode(p, "cannot run ATTACH in safe mode");
18960#endif
18961      break;
18962    }
18963    case SQLITE_FUNCTION: {
18964      int i;
18965      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
18966        if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
18967          failIfSafeMode(p, "cannot use the %s() function in safe mode",
18968                         azProhibitedFunctions[i]);
18969        }
18970      }
18971      break;
18972    }
18973  }
18974  return SQLITE_OK;
18975}
18976
18977/*
18978** When the ".auth ON" is set, the following authorizer callback is
18979** invoked.  It always returns SQLITE_OK.
18980*/
18981static int shellAuth(
18982  void *pClientData,
18983  int op,
18984  const char *zA1,
18985  const char *zA2,
18986  const char *zA3,
18987  const char *zA4
18988){
18989  ShellState *p = (ShellState*)pClientData;
18990  static const char *azAction[] = { 0,
18991     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
18992     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
18993     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
18994     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
18995     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
18996     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
18997     "PRAGMA",               "READ",                 "SELECT",
18998     "TRANSACTION",          "UPDATE",               "ATTACH",
18999     "DETACH",               "ALTER_TABLE",          "REINDEX",
19000     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
19001     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
19002  };
19003  int i;
19004  const char *az[4];
19005  az[0] = zA1;
19006  az[1] = zA2;
19007  az[2] = zA3;
19008  az[3] = zA4;
19009  oputf("authorizer: %s", azAction[op]);
19010  for(i=0; i<4; i++){
19011    oputz(" ");
19012    if( az[i] ){
19013      output_c_string(az[i]);
19014    }else{
19015      oputz("NULL");
19016    }
19017  }
19018  oputz("\n");
19019  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
19020  return SQLITE_OK;
19021}
19022#endif
19023
19024/*
19025** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
19026**
19027** This routine converts some CREATE TABLE statements for shadow tables
19028** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
19029**
19030** If the schema statement in z[] contains a start-of-comment and if
19031** sqlite3_complete() returns false, try to terminate the comment before
19032** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
19033*/
19034static void printSchemaLine(const char *z, const char *zTail){
19035  char *zToFree = 0;
19036  if( z==0 ) return;
19037  if( zTail==0 ) return;
19038  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
19039    const char *zOrig = z;
19040    static const char *azTerm[] = { "", "*/", "\n" };
19041    int i;
19042    for(i=0; i<ArraySize(azTerm); i++){
19043      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
19044      shell_check_oom(zNew);
19045      if( sqlite3_complete(zNew) ){
19046        size_t n = strlen(zNew);
19047        zNew[n-1] = 0;
19048        zToFree = zNew;
19049        z = zNew;
19050        break;
19051      }
19052      sqlite3_free(zNew);
19053    }
19054  }
19055  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
19056    oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
19057  }else{
19058    oputf("%s%s", z, zTail);
19059  }
19060  sqlite3_free(zToFree);
19061}
19062static void printSchemaLineN(char *z, int n, const char *zTail){
19063  char c = z[n];
19064  z[n] = 0;
19065  printSchemaLine(z, zTail);
19066  z[n] = c;
19067}
19068
19069/*
19070** Return true if string z[] has nothing but whitespace and comments to the
19071** end of the first line.
19072*/
19073static int wsToEol(const char *z){
19074  int i;
19075  for(i=0; z[i]; i++){
19076    if( z[i]=='\n' ) return 1;
19077    if( IsSpace(z[i]) ) continue;
19078    if( z[i]=='-' && z[i+1]=='-' ) return 1;
19079    return 0;
19080  }
19081  return 1;
19082}
19083
19084/*
19085** Add a new entry to the EXPLAIN QUERY PLAN data
19086*/
19087static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
19088  EQPGraphRow *pNew;
19089  i64 nText;
19090  if( zText==0 ) return;
19091  nText = strlen(zText);
19092  if( p->autoEQPtest ){
19093    oputf("%d,%d,%s\n", iEqpId, p2, zText);
19094  }
19095  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
19096  shell_check_oom(pNew);
19097  pNew->iEqpId = iEqpId;
19098  pNew->iParentId = p2;
19099  memcpy(pNew->zText, zText, nText+1);
19100  pNew->pNext = 0;
19101  if( p->sGraph.pLast ){
19102    p->sGraph.pLast->pNext = pNew;
19103  }else{
19104    p->sGraph.pRow = pNew;
19105  }
19106  p->sGraph.pLast = pNew;
19107}
19108
19109/*
19110** Free and reset the EXPLAIN QUERY PLAN data that has been collected
19111** in p->sGraph.
19112*/
19113static void eqp_reset(ShellState *p){
19114  EQPGraphRow *pRow, *pNext;
19115  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
19116    pNext = pRow->pNext;
19117    sqlite3_free(pRow);
19118  }
19119  memset(&p->sGraph, 0, sizeof(p->sGraph));
19120}
19121
19122/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
19123** pOld, or return the first such line if pOld is NULL
19124*/
19125static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
19126  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
19127  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
19128  return pRow;
19129}
19130
19131/* Render a single level of the graph that has iEqpId as its parent.  Called
19132** recursively to render sublevels.
19133*/
19134static void eqp_render_level(ShellState *p, int iEqpId){
19135  EQPGraphRow *pRow, *pNext;
19136  i64 n = strlen(p->sGraph.zPrefix);
19137  char *z;
19138  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
19139    pNext = eqp_next_row(p, iEqpId, pRow);
19140    z = pRow->zText;
19141    oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
19142    if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
19143      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
19144      eqp_render_level(p, pRow->iEqpId);
19145      p->sGraph.zPrefix[n] = 0;
19146    }
19147  }
19148}
19149
19150/*
19151** Display and reset the EXPLAIN QUERY PLAN data
19152*/
19153static void eqp_render(ShellState *p, i64 nCycle){
19154  EQPGraphRow *pRow = p->sGraph.pRow;
19155  if( pRow ){
19156    if( pRow->zText[0]=='-' ){
19157      if( pRow->pNext==0 ){
19158        eqp_reset(p);
19159        return;
19160      }
19161      oputf("%s\n", pRow->zText+3);
19162      p->sGraph.pRow = pRow->pNext;
19163      sqlite3_free(pRow);
19164    }else if( nCycle>0 ){
19165      oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
19166    }else{
19167      oputz("QUERY PLAN\n");
19168    }
19169    p->sGraph.zPrefix[0] = 0;
19170    eqp_render_level(p, 0);
19171    eqp_reset(p);
19172  }
19173}
19174
19175#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19176/*
19177** Progress handler callback.
19178*/
19179static int progress_handler(void *pClientData) {
19180  ShellState *p = (ShellState*)pClientData;
19181  p->nProgress++;
19182  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
19183    oputf("Progress limit reached (%u)\n", p->nProgress);
19184    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
19185    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
19186    return 1;
19187  }
19188  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
19189    oputf("Progress %u\n", p->nProgress);
19190  }
19191  return 0;
19192}
19193#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
19194
19195/*
19196** Print N dashes
19197*/
19198static void print_dashes(int N){
19199  const char zDash[] = "--------------------------------------------------";
19200  const int nDash = sizeof(zDash) - 1;
19201  while( N>nDash ){
19202    oputz(zDash);
19203    N -= nDash;
19204  }
19205  oputf("%.*s", N, zDash);
19206}
19207
19208/*
19209** Print a markdown or table-style row separator using ascii-art
19210*/
19211static void print_row_separator(
19212  ShellState *p,
19213  int nArg,
19214  const char *zSep
19215){
19216  int i;
19217  if( nArg>0 ){
19218    oputz(zSep);
19219    print_dashes(p->actualWidth[0]+2);
19220    for(i=1; i<nArg; i++){
19221      oputz(zSep);
19222      print_dashes(p->actualWidth[i]+2);
19223    }
19224    oputz(zSep);
19225  }
19226  oputz("\n");
19227}
19228
19229/*
19230** This is the callback routine that the shell
19231** invokes for each row of a query result.
19232*/
19233static int shell_callback(
19234  void *pArg,
19235  int nArg,        /* Number of result columns */
19236  char **azArg,    /* Text of each result column */
19237  char **azCol,    /* Column names */
19238  int *aiType      /* Column types.  Might be NULL */
19239){
19240  int i;
19241  ShellState *p = (ShellState*)pArg;
19242
19243  if( azArg==0 ) return 0;
19244  switch( p->cMode ){
19245    case MODE_Count:
19246    case MODE_Off: {
19247      break;
19248    }
19249    case MODE_Line: {
19250      int w = 5;
19251      if( azArg==0 ) break;
19252      for(i=0; i<nArg; i++){
19253        int len = strlen30(azCol[i] ? azCol[i] : "");
19254        if( len>w ) w = len;
19255      }
19256      if( p->cnt++>0 ) oputz(p->rowSeparator);
19257      for(i=0; i<nArg; i++){
19258        oputf("%*s = %s%s", w, azCol[i],
19259              azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
19260      }
19261      break;
19262    }
19263    case MODE_ScanExp:
19264    case MODE_Explain: {
19265      static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
19266      static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
19267      static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
19268      static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
19269
19270      const int *aWidth = aExplainWidth;
19271      const int *aMap = aExplainMap;
19272      int nWidth = ArraySize(aExplainWidth);
19273      int iIndent = 1;
19274
19275      if( p->cMode==MODE_ScanExp ){
19276        aWidth = aScanExpWidth;
19277        aMap = aScanExpMap;
19278        nWidth = ArraySize(aScanExpWidth);
19279        iIndent = 3;
19280      }
19281      if( nArg>nWidth ) nArg = nWidth;
19282
19283      /* If this is the first row seen, print out the headers */
19284      if( p->cnt++==0 ){
19285        for(i=0; i<nArg; i++){
19286          utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
19287          oputz(i==nArg-1 ? "\n" : "  ");
19288        }
19289        for(i=0; i<nArg; i++){
19290          print_dashes(aWidth[i]);
19291          oputz(i==nArg-1 ? "\n" : "  ");
19292        }
19293      }
19294
19295      /* If there is no data, exit early. */
19296      if( azArg==0 ) break;
19297
19298      for(i=0; i<nArg; i++){
19299        const char *zSep = "  ";
19300        int w = aWidth[i];
19301        const char *zVal = azArg[ aMap[i] ];
19302        if( i==nArg-1 ) w = 0;
19303        if( zVal && strlenChar(zVal)>w ){
19304          w = strlenChar(zVal);
19305          zSep = " ";
19306        }
19307        if( i==iIndent && p->aiIndent && p->pStmt ){
19308          if( p->iIndent<p->nIndent ){
19309            oputf("%*.s", p->aiIndent[p->iIndent], "");
19310          }
19311          p->iIndent++;
19312        }
19313        utf8_width_print(w, zVal ? zVal : p->nullValue);
19314        oputz(i==nArg-1 ? "\n" : zSep);
19315      }
19316      break;
19317    }
19318    case MODE_Semi: {   /* .schema and .fullschema output */
19319      printSchemaLine(azArg[0], ";\n");
19320      break;
19321    }
19322    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
19323      char *z;
19324      int j;
19325      int nParen = 0;
19326      char cEnd = 0;
19327      char c;
19328      int nLine = 0;
19329      assert( nArg==1 );
19330      if( azArg[0]==0 ) break;
19331      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
19332       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
19333      ){
19334        oputf("%s;\n", azArg[0]);
19335        break;
19336      }
19337      z = sqlite3_mprintf("%s", azArg[0]);
19338      shell_check_oom(z);
19339      j = 0;
19340      for(i=0; IsSpace(z[i]); i++){}
19341      for(; (c = z[i])!=0; i++){
19342        if( IsSpace(c) ){
19343          if( z[j-1]=='\r' ) z[j-1] = '\n';
19344          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
19345        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
19346          j--;
19347        }
19348        z[j++] = c;
19349      }
19350      while( j>0 && IsSpace(z[j-1]) ){ j--; }
19351      z[j] = 0;
19352      if( strlen30(z)>=79 ){
19353        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
19354          if( c==cEnd ){
19355            cEnd = 0;
19356          }else if( c=='"' || c=='\'' || c=='`' ){
19357            cEnd = c;
19358          }else if( c=='[' ){
19359            cEnd = ']';
19360          }else if( c=='-' && z[i+1]=='-' ){
19361            cEnd = '\n';
19362          }else if( c=='(' ){
19363            nParen++;
19364          }else if( c==')' ){
19365            nParen--;
19366            if( nLine>0 && nParen==0 && j>0 ){
19367              printSchemaLineN(z, j, "\n");
19368              j = 0;
19369            }
19370          }
19371          z[j++] = c;
19372          if( nParen==1 && cEnd==0
19373           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
19374          ){
19375            if( c=='\n' ) j--;
19376            printSchemaLineN(z, j, "\n  ");
19377            j = 0;
19378            nLine++;
19379            while( IsSpace(z[i+1]) ){ i++; }
19380          }
19381        }
19382        z[j] = 0;
19383      }
19384      printSchemaLine(z, ";\n");
19385      sqlite3_free(z);
19386      break;
19387    }
19388    case MODE_List: {
19389      if( p->cnt++==0 && p->showHeader ){
19390        for(i=0; i<nArg; i++){
19391          oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
19392        }
19393      }
19394      if( azArg==0 ) break;
19395      for(i=0; i<nArg; i++){
19396        char *z = azArg[i];
19397        if( z==0 ) z = p->nullValue;
19398        oputz(z);
19399        oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
19400      }
19401      break;
19402    }
19403    case MODE_Html: {
19404      if( p->cnt++==0 && p->showHeader ){
19405        oputz("<TR>");
19406        for(i=0; i<nArg; i++){
19407          oputz("<TH>");
19408          output_html_string(azCol[i]);
19409          oputz("</TH>\n");
19410        }
19411        oputz("</TR>\n");
19412      }
19413      if( azArg==0 ) break;
19414      oputz("<TR>");
19415      for(i=0; i<nArg; i++){
19416        oputz("<TD>");
19417        output_html_string(azArg[i] ? azArg[i] : p->nullValue);
19418        oputz("</TD>\n");
19419      }
19420      oputz("</TR>\n");
19421      break;
19422    }
19423    case MODE_Tcl: {
19424      if( p->cnt++==0 && p->showHeader ){
19425        for(i=0; i<nArg; i++){
19426          output_c_string(azCol[i] ? azCol[i] : "");
19427          if(i<nArg-1) oputz(p->colSeparator);
19428        }
19429        oputz(p->rowSeparator);
19430      }
19431      if( azArg==0 ) break;
19432      for(i=0; i<nArg; i++){
19433        output_c_string(azArg[i] ? azArg[i] : p->nullValue);
19434        if(i<nArg-1) oputz(p->colSeparator);
19435      }
19436      oputz(p->rowSeparator);
19437      break;
19438    }
19439    case MODE_Csv: {
19440      setBinaryMode(p->out, 1);
19441      if( p->cnt++==0 && p->showHeader ){
19442        for(i=0; i<nArg; i++){
19443          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
19444        }
19445        oputz(p->rowSeparator);
19446      }
19447      if( nArg>0 ){
19448        for(i=0; i<nArg; i++){
19449          output_csv(p, azArg[i], i<nArg-1);
19450        }
19451        oputz(p->rowSeparator);
19452      }
19453      setTextMode(p->out, 1);
19454      break;
19455    }
19456    case MODE_Insert: {
19457      if( azArg==0 ) break;
19458      oputf("INSERT INTO %s",p->zDestTable);
19459      if( p->showHeader ){
19460        oputz("(");
19461        for(i=0; i<nArg; i++){
19462          if( i>0 ) oputz(",");
19463          if( quoteChar(azCol[i]) ){
19464            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
19465            shell_check_oom(z);
19466            oputz(z);
19467            sqlite3_free(z);
19468          }else{
19469            oputf("%s", azCol[i]);
19470          }
19471        }
19472        oputz(")");
19473      }
19474      p->cnt++;
19475      for(i=0; i<nArg; i++){
19476        oputz(i>0 ? "," : " VALUES(");
19477        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19478          oputz("NULL");
19479        }else if( aiType && aiType[i]==SQLITE_TEXT ){
19480          if( ShellHasFlag(p, SHFLG_Newlines) ){
19481            output_quoted_string(azArg[i]);
19482          }else{
19483            output_quoted_escaped_string(azArg[i]);
19484          }
19485        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
19486          oputz(azArg[i]);
19487        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19488          char z[50];
19489          double r = sqlite3_column_double(p->pStmt, i);
19490          sqlite3_uint64 ur;
19491          memcpy(&ur,&r,sizeof(r));
19492          if( ur==0x7ff0000000000000LL ){
19493            oputz("9.0e+999");
19494          }else if( ur==0xfff0000000000000LL ){
19495            oputz("-9.0e+999");
19496          }else{
19497            sqlite3_int64 ir = (sqlite3_int64)r;
19498            if( r==(double)ir ){
19499              sqlite3_snprintf(50,z,"%lld.0", ir);
19500            }else{
19501              sqlite3_snprintf(50,z,"%!.20g", r);
19502            }
19503            oputz(z);
19504          }
19505        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19506          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19507          int nBlob = sqlite3_column_bytes(p->pStmt, i);
19508          output_hex_blob(pBlob, nBlob);
19509        }else if( isNumber(azArg[i], 0) ){
19510          oputz(azArg[i]);
19511        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
19512          output_quoted_string(azArg[i]);
19513        }else{
19514          output_quoted_escaped_string(azArg[i]);
19515        }
19516      }
19517      oputz(");\n");
19518      break;
19519    }
19520    case MODE_Json: {
19521      if( azArg==0 ) break;
19522      if( p->cnt==0 ){
19523        fputs("[{", p->out);
19524      }else{
19525        fputs(",\n{", p->out);
19526      }
19527      p->cnt++;
19528      for(i=0; i<nArg; i++){
19529        output_json_string(azCol[i], -1);
19530        oputz(":");
19531        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19532          oputz("null");
19533        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19534          char z[50];
19535          double r = sqlite3_column_double(p->pStmt, i);
19536          sqlite3_uint64 ur;
19537          memcpy(&ur,&r,sizeof(r));
19538          if( ur==0x7ff0000000000000LL ){
19539            oputz("9.0e+999");
19540          }else if( ur==0xfff0000000000000LL ){
19541            oputz("-9.0e+999");
19542          }else{
19543            sqlite3_snprintf(50,z,"%!.20g", r);
19544            oputz(z);
19545          }
19546        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19547          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19548          int nBlob = sqlite3_column_bytes(p->pStmt, i);
19549          output_json_string(pBlob, nBlob);
19550        }else if( aiType && aiType[i]==SQLITE_TEXT ){
19551          output_json_string(azArg[i], -1);
19552        }else{
19553          oputz(azArg[i]);
19554        }
19555        if( i<nArg-1 ){
19556          oputz(",");
19557        }
19558      }
19559      oputz("}");
19560      break;
19561    }
19562    case MODE_Quote: {
19563      if( azArg==0 ) break;
19564      if( p->cnt==0 && p->showHeader ){
19565        for(i=0; i<nArg; i++){
19566          if( i>0 ) fputs(p->colSeparator, p->out);
19567          output_quoted_string(azCol[i]);
19568        }
19569        fputs(p->rowSeparator, p->out);
19570      }
19571      p->cnt++;
19572      for(i=0; i<nArg; i++){
19573        if( i>0 ) fputs(p->colSeparator, p->out);
19574        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
19575          oputz("NULL");
19576        }else if( aiType && aiType[i]==SQLITE_TEXT ){
19577          output_quoted_string(azArg[i]);
19578        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
19579          oputz(azArg[i]);
19580        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
19581          char z[50];
19582          double r = sqlite3_column_double(p->pStmt, i);
19583          sqlite3_snprintf(50,z,"%!.20g", r);
19584          oputz(z);
19585        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
19586          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
19587          int nBlob = sqlite3_column_bytes(p->pStmt, i);
19588          output_hex_blob(pBlob, nBlob);
19589        }else if( isNumber(azArg[i], 0) ){
19590          oputz(azArg[i]);
19591        }else{
19592          output_quoted_string(azArg[i]);
19593        }
19594      }
19595      fputs(p->rowSeparator, p->out);
19596      break;
19597    }
19598    case MODE_Ascii: {
19599      if( p->cnt++==0 && p->showHeader ){
19600        for(i=0; i<nArg; i++){
19601          if( i>0 ) oputz(p->colSeparator);
19602          oputz(azCol[i] ? azCol[i] : "");
19603        }
19604        oputz(p->rowSeparator);
19605      }
19606      if( azArg==0 ) break;
19607      for(i=0; i<nArg; i++){
19608        if( i>0 ) oputz(p->colSeparator);
19609        oputz(azArg[i] ? azArg[i] : p->nullValue);
19610      }
19611      oputz(p->rowSeparator);
19612      break;
19613    }
19614    case MODE_EQP: {
19615      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
19616      break;
19617    }
19618  }
19619  return 0;
19620}
19621
19622/*
19623** This is the callback routine that the SQLite library
19624** invokes for each row of a query result.
19625*/
19626static int callback(void *pArg, int nArg, char **azArg, char **azCol){
19627  /* since we don't have type info, call the shell_callback with a NULL value */
19628  return shell_callback(pArg, nArg, azArg, azCol, NULL);
19629}
19630
19631/*
19632** This is the callback routine from sqlite3_exec() that appends all
19633** output onto the end of a ShellText object.
19634*/
19635static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
19636  ShellText *p = (ShellText*)pArg;
19637  int i;
19638  UNUSED_PARAMETER(az);
19639  if( azArg==0 ) return 0;
19640  if( p->n ) appendText(p, "|", 0);
19641  for(i=0; i<nArg; i++){
19642    if( i ) appendText(p, ",", 0);
19643    if( azArg[i] ) appendText(p, azArg[i], 0);
19644  }
19645  return 0;
19646}
19647
19648/*
19649** Generate an appropriate SELFTEST table in the main database.
19650*/
19651static void createSelftestTable(ShellState *p){
19652  char *zErrMsg = 0;
19653  sqlite3_exec(p->db,
19654    "SAVEPOINT selftest_init;\n"
19655    "CREATE TABLE IF NOT EXISTS selftest(\n"
19656    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
19657    "  op TEXT,\n"                   /* Operator:  memo run */
19658    "  cmd TEXT,\n"                  /* Command text */
19659    "  ans TEXT\n"                   /* Desired answer */
19660    ");"
19661    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
19662    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
19663    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
19664    "         'memo','Tests generated by --init');\n"
19665    "INSERT INTO [_shell$self]\n"
19666    "  SELECT 'run',\n"
19667    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
19668                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
19669    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
19670                          "FROM sqlite_schema ORDER BY 2',224));\n"
19671    "INSERT INTO [_shell$self]\n"
19672    "  SELECT 'run',"
19673    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
19674    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
19675    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
19676    "  FROM (\n"
19677    "    SELECT name FROM sqlite_schema\n"
19678    "     WHERE type='table'\n"
19679    "       AND name<>'selftest'\n"
19680    "       AND coalesce(rootpage,0)>0\n"
19681    "  )\n"
19682    " ORDER BY name;\n"
19683    "INSERT INTO [_shell$self]\n"
19684    "  VALUES('run','PRAGMA integrity_check','ok');\n"
19685    "INSERT INTO selftest(tno,op,cmd,ans)"
19686    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
19687    "DROP TABLE [_shell$self];"
19688    ,0,0,&zErrMsg);
19689  if( zErrMsg ){
19690    eputf("SELFTEST initialization failure: %s\n", zErrMsg);
19691    sqlite3_free(zErrMsg);
19692  }
19693  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
19694}
19695
19696
19697/*
19698** Set the destination table field of the ShellState structure to
19699** the name of the table given.  Escape any quote characters in the
19700** table name.
19701*/
19702static void set_table_name(ShellState *p, const char *zName){
19703  int i, n;
19704  char cQuote;
19705  char *z;
19706
19707  if( p->zDestTable ){
19708    free(p->zDestTable);
19709    p->zDestTable = 0;
19710  }
19711  if( zName==0 ) return;
19712  cQuote = quoteChar(zName);
19713  n = strlen30(zName);
19714  if( cQuote ) n += n+2;
19715  z = p->zDestTable = malloc( n+1 );
19716  shell_check_oom(z);
19717  n = 0;
19718  if( cQuote ) z[n++] = cQuote;
19719  for(i=0; zName[i]; i++){
19720    z[n++] = zName[i];
19721    if( zName[i]==cQuote ) z[n++] = cQuote;
19722  }
19723  if( cQuote ) z[n++] = cQuote;
19724  z[n] = 0;
19725}
19726
19727/*
19728** Maybe construct two lines of text that point out the position of a
19729** syntax error.  Return a pointer to the text, in memory obtained from
19730** sqlite3_malloc().  Or, if the most recent error does not involve a
19731** specific token that we can point to, return an empty string.
19732**
19733** In all cases, the memory returned is obtained from sqlite3_malloc64()
19734** and should be released by the caller invoking sqlite3_free().
19735*/
19736static char *shell_error_context(const char *zSql, sqlite3 *db){
19737  int iOffset;
19738  size_t len;
19739  char *zCode;
19740  char *zMsg;
19741  int i;
19742  if( db==0
19743   || zSql==0
19744   || (iOffset = sqlite3_error_offset(db))<0
19745   || iOffset>=(int)strlen(zSql)
19746  ){
19747    return sqlite3_mprintf("");
19748  }
19749  while( iOffset>50 ){
19750    iOffset--;
19751    zSql++;
19752    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
19753  }
19754  len = strlen(zSql);
19755  if( len>78 ){
19756    len = 78;
19757    while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
19758  }
19759  zCode = sqlite3_mprintf("%.*s", len, zSql);
19760  shell_check_oom(zCode);
19761  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
19762  if( iOffset<25 ){
19763    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
19764  }else{
19765    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
19766  }
19767  return zMsg;
19768}
19769
19770
19771/*
19772** Execute a query statement that will generate SQL output.  Print
19773** the result columns, comma-separated, on a line and then add a
19774** semicolon terminator to the end of that line.
19775**
19776** If the number of columns is 1 and that column contains text "--"
19777** then write the semicolon on a separate line.  That way, if a
19778** "--" comment occurs at the end of the statement, the comment
19779** won't consume the semicolon terminator.
19780*/
19781static int run_table_dump_query(
19782  ShellState *p,           /* Query context */
19783  const char *zSelect      /* SELECT statement to extract content */
19784){
19785  sqlite3_stmt *pSelect;
19786  int rc;
19787  int nResult;
19788  int i;
19789  const char *z;
19790  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
19791  if( rc!=SQLITE_OK || !pSelect ){
19792    char *zContext = shell_error_context(zSelect, p->db);
19793    oputf("/**** ERROR: (%d) %s *****/\n%s",
19794          rc, sqlite3_errmsg(p->db), zContext);
19795    sqlite3_free(zContext);
19796    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19797    return rc;
19798  }
19799  rc = sqlite3_step(pSelect);
19800  nResult = sqlite3_column_count(pSelect);
19801  while( rc==SQLITE_ROW ){
19802    z = (const char*)sqlite3_column_text(pSelect, 0);
19803    oputf("%s", z);
19804    for(i=1; i<nResult; i++){
19805      oputf(",%s", sqlite3_column_text(pSelect, i));
19806    }
19807    if( z==0 ) z = "";
19808    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
19809    if( z[0] ){
19810      oputz("\n;\n");
19811    }else{
19812      oputz(";\n");
19813    }
19814    rc = sqlite3_step(pSelect);
19815  }
19816  rc = sqlite3_finalize(pSelect);
19817  if( rc!=SQLITE_OK ){
19818    oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
19819    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19820  }
19821  return rc;
19822}
19823
19824/*
19825** Allocate space and save off string indicating current error.
19826*/
19827static char *save_err_msg(
19828  sqlite3 *db,           /* Database to query */
19829  const char *zPhase,    /* When the error occurs */
19830  int rc,                /* Error code returned from API */
19831  const char *zSql       /* SQL string, or NULL */
19832){
19833  char *zErr;
19834  char *zContext;
19835  sqlite3_str *pStr = sqlite3_str_new(0);
19836  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
19837  if( rc>1 ){
19838    sqlite3_str_appendf(pStr, " (%d)", rc);
19839  }
19840  zContext = shell_error_context(zSql, db);
19841  if( zContext ){
19842    sqlite3_str_appendall(pStr, zContext);
19843    sqlite3_free(zContext);
19844  }
19845  zErr = sqlite3_str_finish(pStr);
19846  shell_check_oom(zErr);
19847  return zErr;
19848}
19849
19850#ifdef __linux__
19851/*
19852** Attempt to display I/O stats on Linux using /proc/PID/io
19853*/
19854static void displayLinuxIoStats(void){
19855  FILE *in;
19856  char z[200];
19857  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
19858  in = fopen(z, "rb");
19859  if( in==0 ) return;
19860  while( fgets(z, sizeof(z), in)!=0 ){
19861    static const struct {
19862      const char *zPattern;
19863      const char *zDesc;
19864    } aTrans[] = {
19865      { "rchar: ",                  "Bytes received by read():" },
19866      { "wchar: ",                  "Bytes sent to write():"    },
19867      { "syscr: ",                  "Read() system calls:"      },
19868      { "syscw: ",                  "Write() system calls:"     },
19869      { "read_bytes: ",             "Bytes read from storage:"  },
19870      { "write_bytes: ",            "Bytes written to storage:" },
19871      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
19872    };
19873    int i;
19874    for(i=0; i<ArraySize(aTrans); i++){
19875      int n = strlen30(aTrans[i].zPattern);
19876      if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
19877        oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
19878        break;
19879      }
19880    }
19881  }
19882  fclose(in);
19883}
19884#endif
19885
19886/*
19887** Display a single line of status using 64-bit values.
19888*/
19889static void displayStatLine(
19890  char *zLabel,             /* Label for this one line */
19891  char *zFormat,            /* Format for the result */
19892  int iStatusCtrl,          /* Which status to display */
19893  int bReset                /* True to reset the stats */
19894){
19895  sqlite3_int64 iCur = -1;
19896  sqlite3_int64 iHiwtr = -1;
19897  int i, nPercent;
19898  char zLine[200];
19899  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
19900  for(i=0, nPercent=0; zFormat[i]; i++){
19901    if( zFormat[i]=='%' ) nPercent++;
19902  }
19903  if( nPercent>1 ){
19904    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
19905  }else{
19906    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
19907  }
19908  oputf("%-36s %s\n", zLabel, zLine);
19909}
19910
19911/*
19912** Display memory stats.
19913*/
19914static int display_stats(
19915  sqlite3 *db,                /* Database to query */
19916  ShellState *pArg,           /* Pointer to ShellState */
19917  int bReset                  /* True to reset the stats */
19918){
19919  int iCur;
19920  int iHiwtr;
19921  if( pArg==0 || pArg->out==0 ) return 0;
19922
19923  if( pArg->pStmt && pArg->statsOn==2 ){
19924    int nCol, i, x;
19925    sqlite3_stmt *pStmt = pArg->pStmt;
19926    char z[100];
19927    nCol = sqlite3_column_count(pStmt);
19928    oputf("%-36s %d\n", "Number of output columns:", nCol);
19929    for(i=0; i<nCol; i++){
19930      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
19931      oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
19932#ifndef SQLITE_OMIT_DECLTYPE
19933      sqlite3_snprintf(30, z+x, "declared type:");
19934      oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
19935#endif
19936#ifdef SQLITE_ENABLE_COLUMN_METADATA
19937      sqlite3_snprintf(30, z+x, "database name:");
19938      oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
19939      sqlite3_snprintf(30, z+x, "table name:");
19940      oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
19941      sqlite3_snprintf(30, z+x, "origin name:");
19942      oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
19943#endif
19944    }
19945  }
19946
19947  if( pArg->statsOn==3 ){
19948    if( pArg->pStmt ){
19949      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
19950      oputf("VM-steps: %d\n", iCur);
19951    }
19952    return 0;
19953  }
19954
19955  displayStatLine("Memory Used:",
19956     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
19957  displayStatLine("Number of Outstanding Allocations:",
19958     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
19959  if( pArg->shellFlgs & SHFLG_Pagecache ){
19960    displayStatLine("Number of Pcache Pages Used:",
19961       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
19962  }
19963  displayStatLine("Number of Pcache Overflow Bytes:",
19964     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
19965  displayStatLine("Largest Allocation:",
19966     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
19967  displayStatLine("Largest Pcache Allocation:",
19968     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
19969#ifdef YYTRACKMAXSTACKDEPTH
19970  displayStatLine("Deepest Parser Stack:",
19971     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
19972#endif
19973
19974  if( db ){
19975    if( pArg->shellFlgs & SHFLG_Lookaside ){
19976      iHiwtr = iCur = -1;
19977      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
19978                        &iCur, &iHiwtr, bReset);
19979      oputf("Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
19980      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
19981                        &iCur, &iHiwtr, bReset);
19982      oputf("Successful lookaside attempts:       %d\n", iHiwtr);
19983      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
19984                        &iCur, &iHiwtr, bReset);
19985      oputf("Lookaside failures due to size:      %d\n", iHiwtr);
19986      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
19987                        &iCur, &iHiwtr, bReset);
19988      oputf("Lookaside failures due to OOM:       %d\n", iHiwtr);
19989    }
19990    iHiwtr = iCur = -1;
19991    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
19992    oputf("Pager Heap Usage:                    %d bytes\n", iCur);
19993    iHiwtr = iCur = -1;
19994    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
19995    oputf("Page cache hits:                     %d\n", iCur);
19996    iHiwtr = iCur = -1;
19997    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
19998    oputf("Page cache misses:                   %d\n", iCur);
19999    iHiwtr = iCur = -1;
20000    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
20001    oputf("Page cache writes:                   %d\n", iCur);
20002    iHiwtr = iCur = -1;
20003    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
20004    oputf("Page cache spills:                   %d\n", iCur);
20005    iHiwtr = iCur = -1;
20006    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
20007    oputf("Schema Heap Usage:                   %d bytes\n", iCur);
20008    iHiwtr = iCur = -1;
20009    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
20010    oputf("Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
20011  }
20012
20013  if( pArg->pStmt ){
20014    int iHit, iMiss;
20015    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
20016                               bReset);
20017    oputf("Fullscan Steps:                      %d\n", iCur);
20018    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
20019    oputf("Sort Operations:                     %d\n", iCur);
20020    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
20021    oputf("Autoindex Inserts:                   %d\n", iCur);
20022    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
20023                               bReset);
20024    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
20025                                bReset);
20026    if( iHit || iMiss ){
20027      oputf("Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
20028    }
20029    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
20030    oputf("Virtual Machine Steps:               %d\n", iCur);
20031    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
20032    oputf("Reprepare operations:                %d\n", iCur);
20033    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
20034    oputf("Number of times run:                 %d\n", iCur);
20035    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
20036    oputf("Memory used by prepared stmt:        %d\n", iCur);
20037  }
20038
20039#ifdef __linux__
20040  displayLinuxIoStats();
20041#endif
20042
20043  /* Do not remove this machine readable comment: extra-stats-output-here */
20044
20045  return 0;
20046}
20047
20048
20049#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
20050static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
20051  int iPid = 0;
20052  int ret = 1;
20053  sqlite3_stmt_scanstatus_v2(p, iEntry,
20054      SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
20055  );
20056  while( iPid!=0 ){
20057    int ii;
20058    for(ii=0; 1; ii++){
20059      int iId;
20060      int res;
20061      res = sqlite3_stmt_scanstatus_v2(p, ii,
20062          SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
20063      );
20064      if( res ) break;
20065      if( iId==iPid ){
20066        sqlite3_stmt_scanstatus_v2(p, ii,
20067            SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
20068        );
20069      }
20070    }
20071    ret++;
20072  }
20073  return ret;
20074}
20075#endif
20076
20077#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
20078static void display_explain_scanstats(
20079  sqlite3 *db,                    /* Database to query */
20080  ShellState *pArg                /* Pointer to ShellState */
20081){
20082  static const int f = SQLITE_SCANSTAT_COMPLEX;
20083  sqlite3_stmt *p = pArg->pStmt;
20084  int ii = 0;
20085  i64 nTotal = 0;
20086  int nWidth = 0;
20087  eqp_reset(pArg);
20088
20089  for(ii=0; 1; ii++){
20090    const char *z = 0;
20091    int n = 0;
20092    if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
20093      break;
20094    }
20095    n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
20096    if( n>nWidth ) nWidth = n;
20097  }
20098  nWidth += 4;
20099
20100  sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
20101  for(ii=0; 1; ii++){
20102    i64 nLoop = 0;
20103    i64 nRow = 0;
20104    i64 nCycle = 0;
20105    int iId = 0;
20106    int iPid = 0;
20107    const char *zo = 0;
20108    const char *zName = 0;
20109    char *zText = 0;
20110    double rEst = 0.0;
20111
20112    if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
20113      break;
20114    }
20115    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
20116    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
20117    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
20118    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
20119    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
20120    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
20121    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
20122
20123    zText = sqlite3_mprintf("%s", zo);
20124    if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
20125      char *z = 0;
20126      if( nCycle>=0 && nTotal>0 ){
20127        z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
20128            nCycle, ((nCycle*100)+nTotal/2) / nTotal
20129        );
20130      }
20131      if( nLoop>=0 ){
20132        z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
20133      }
20134      if( nRow>=0 ){
20135        z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
20136      }
20137
20138      if( zName && pArg->scanstatsOn>1 ){
20139        double rpl = (double)nRow / (double)nLoop;
20140        z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
20141      }
20142
20143      zText = sqlite3_mprintf(
20144          "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
20145      );
20146    }
20147
20148    eqp_append(pArg, iId, iPid, zText);
20149    sqlite3_free(zText);
20150  }
20151
20152  eqp_render(pArg, nTotal);
20153}
20154#endif
20155
20156
20157/*
20158** Parameter azArray points to a zero-terminated array of strings. zStr
20159** points to a single nul-terminated string. Return non-zero if zStr
20160** is equal, according to strcmp(), to any of the strings in the array.
20161** Otherwise, return zero.
20162*/
20163static int str_in_array(const char *zStr, const char **azArray){
20164  int i;
20165  for(i=0; azArray[i]; i++){
20166    if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
20167  }
20168  return 0;
20169}
20170
20171/*
20172** If compiled statement pSql appears to be an EXPLAIN statement, allocate
20173** and populate the ShellState.aiIndent[] array with the number of
20174** spaces each opcode should be indented before it is output.
20175**
20176** The indenting rules are:
20177**
20178**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
20179**       all opcodes that occur between the p2 jump destination and the opcode
20180**       itself by 2 spaces.
20181**
20182**     * Do the previous for "Return" instructions for when P2 is positive.
20183**       See tag-20220407a in wherecode.c and vdbe.c.
20184**
20185**     * For each "Goto", if the jump destination is earlier in the program
20186**       and ends on one of:
20187**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
20188**       or if the P1 parameter is one instead of zero,
20189**       then indent all opcodes between the earlier instruction
20190**       and "Goto" by 2 spaces.
20191*/
20192static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
20193  int *abYield = 0;               /* True if op is an OP_Yield */
20194  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
20195  int iOp;                        /* Index of operation in p->aiIndent[] */
20196
20197  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
20198                           "Return", 0 };
20199  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
20200                            "Rewind", 0 };
20201  const char *azGoto[] = { "Goto", 0 };
20202
20203  /* The caller guarantees that the leftmost 4 columns of the statement
20204  ** passed to this function are equivalent to the leftmost 4 columns
20205  ** of EXPLAIN statement output. In practice the statement may be
20206  ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
20207  assert( sqlite3_column_count(pSql)>=4 );
20208  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
20209  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
20210  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
20211  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
20212
20213  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
20214    int i;
20215    int iAddr = sqlite3_column_int(pSql, 0);
20216    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
20217    int p1 = sqlite3_column_int(pSql, 2);
20218    int p2 = sqlite3_column_int(pSql, 3);
20219
20220    /* Assuming that p2 is an instruction address, set variable p2op to the
20221    ** index of that instruction in the aiIndent[] array. p2 and p2op may be
20222    ** different if the current instruction is part of a sub-program generated
20223    ** by an SQL trigger or foreign key.  */
20224    int p2op = (p2 + (iOp-iAddr));
20225
20226    /* Grow the p->aiIndent array as required */
20227    if( iOp>=nAlloc ){
20228      nAlloc += 100;
20229      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
20230      shell_check_oom(p->aiIndent);
20231      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
20232      shell_check_oom(abYield);
20233    }
20234
20235    abYield[iOp] = str_in_array(zOp, azYield);
20236    p->aiIndent[iOp] = 0;
20237    p->nIndent = iOp+1;
20238    if( str_in_array(zOp, azNext) && p2op>0 ){
20239      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
20240    }
20241    if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
20242      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
20243    }
20244  }
20245
20246  p->iIndent = 0;
20247  sqlite3_free(abYield);
20248  sqlite3_reset(pSql);
20249}
20250
20251/*
20252** Free the array allocated by explain_data_prepare().
20253*/
20254static void explain_data_delete(ShellState *p){
20255  sqlite3_free(p->aiIndent);
20256  p->aiIndent = 0;
20257  p->nIndent = 0;
20258  p->iIndent = 0;
20259}
20260
20261static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
20262
20263/*
20264** Display scan stats.
20265*/
20266static void display_scanstats(
20267  sqlite3 *db,                    /* Database to query */
20268  ShellState *pArg                /* Pointer to ShellState */
20269){
20270#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
20271  UNUSED_PARAMETER(db);
20272  UNUSED_PARAMETER(pArg);
20273#else
20274  if( pArg->scanstatsOn==3 ){
20275    const char *zSql =
20276      "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
20277      "   round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
20278      "   FROM bytecode(?)";
20279
20280    int rc = SQLITE_OK;
20281    sqlite3_stmt *pStmt = 0;
20282    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
20283    if( rc==SQLITE_OK ){
20284      sqlite3_stmt *pSave = pArg->pStmt;
20285      pArg->pStmt = pStmt;
20286      sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
20287
20288      pArg->cnt = 0;
20289      pArg->cMode = MODE_ScanExp;
20290      explain_data_prepare(pArg, pStmt);
20291      exec_prepared_stmt(pArg, pStmt);
20292      explain_data_delete(pArg);
20293
20294      sqlite3_finalize(pStmt);
20295      pArg->pStmt = pSave;
20296    }
20297  }else{
20298    display_explain_scanstats(db, pArg);
20299  }
20300#endif
20301}
20302
20303/*
20304** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
20305*/
20306static unsigned int savedSelectTrace;
20307static unsigned int savedWhereTrace;
20308static void disable_debug_trace_modes(void){
20309  unsigned int zero = 0;
20310  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
20311  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
20312  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
20313  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
20314}
20315static void restore_debug_trace_modes(void){
20316  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
20317  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
20318}
20319
20320/* Create the TEMP table used to store parameter bindings */
20321static void bind_table_init(ShellState *p){
20322  int wrSchema = 0;
20323  int defensiveMode = 0;
20324  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
20325  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
20326  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
20327  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
20328  sqlite3_exec(p->db,
20329    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
20330    "  key TEXT PRIMARY KEY,\n"
20331    "  value\n"
20332    ") WITHOUT ROWID;",
20333    0, 0, 0);
20334  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
20335  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
20336}
20337
20338/*
20339** Bind parameters on a prepared statement.
20340**
20341** Parameter bindings are taken from a TEMP table of the form:
20342**
20343**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
20344**    WITHOUT ROWID;
20345**
20346** No bindings occur if this table does not exist.  The name of the table
20347** begins with "sqlite_" so that it will not collide with ordinary application
20348** tables.  The table must be in the TEMP schema.
20349*/
20350static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
20351  int nVar;
20352  int i;
20353  int rc;
20354  sqlite3_stmt *pQ = 0;
20355
20356  nVar = sqlite3_bind_parameter_count(pStmt);
20357  if( nVar==0 ) return;  /* Nothing to do */
20358  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
20359                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
20360    rc = SQLITE_NOTFOUND;
20361    pQ = 0;
20362  }else{
20363    rc = sqlite3_prepare_v2(pArg->db,
20364            "SELECT value FROM temp.sqlite_parameters"
20365            " WHERE key=?1", -1, &pQ, 0);
20366  }
20367  for(i=1; i<=nVar; i++){
20368    char zNum[30];
20369    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
20370    if( zVar==0 ){
20371      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
20372      zVar = zNum;
20373    }
20374    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
20375    if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
20376      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
20377#ifdef NAN
20378    }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
20379      sqlite3_bind_double(pStmt, i, NAN);
20380#endif
20381#ifdef INFINITY
20382    }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
20383      sqlite3_bind_double(pStmt, i, INFINITY);
20384#endif
20385    }else{
20386      sqlite3_bind_null(pStmt, i);
20387    }
20388    sqlite3_reset(pQ);
20389  }
20390  sqlite3_finalize(pQ);
20391}
20392
20393/*
20394** UTF8 box-drawing characters.  Imagine box lines like this:
20395**
20396**           1
20397**           |
20398**       4 --+-- 2
20399**           |
20400**           3
20401**
20402** Each box characters has between 2 and 4 of the lines leading from
20403** the center.  The characters are here identified by the numbers of
20404** their corresponding lines.
20405*/
20406#define BOX_24   "\342\224\200"  /* U+2500 --- */
20407#define BOX_13   "\342\224\202"  /* U+2502  |  */
20408#define BOX_23   "\342\224\214"  /* U+250c  ,- */
20409#define BOX_34   "\342\224\220"  /* U+2510 -,  */
20410#define BOX_12   "\342\224\224"  /* U+2514  '- */
20411#define BOX_14   "\342\224\230"  /* U+2518 -'  */
20412#define BOX_123  "\342\224\234"  /* U+251c  |- */
20413#define BOX_134  "\342\224\244"  /* U+2524 -|  */
20414#define BOX_234  "\342\224\254"  /* U+252c -,- */
20415#define BOX_124  "\342\224\264"  /* U+2534 -'- */
20416#define BOX_1234 "\342\224\274"  /* U+253c -|- */
20417
20418/* Draw horizontal line N characters long using unicode box
20419** characters
20420*/
20421static void print_box_line(int N){
20422  const char zDash[] =
20423      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
20424      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
20425  const int nDash = sizeof(zDash) - 1;
20426  N *= 3;
20427  while( N>nDash ){
20428    oputz(zDash);
20429    N -= nDash;
20430  }
20431  oputf("%.*s", N, zDash);
20432}
20433
20434/*
20435** Draw a horizontal separator for a MODE_Box table.
20436*/
20437static void print_box_row_separator(
20438  ShellState *p,
20439  int nArg,
20440  const char *zSep1,
20441  const char *zSep2,
20442  const char *zSep3
20443){
20444  int i;
20445  if( nArg>0 ){
20446    oputz(zSep1);
20447    print_box_line(p->actualWidth[0]+2);
20448    for(i=1; i<nArg; i++){
20449      oputz(zSep2);
20450      print_box_line(p->actualWidth[i]+2);
20451    }
20452    oputz(zSep3);
20453  }
20454  oputz("\n");
20455}
20456
20457/*
20458** z[] is a line of text that is to be displayed the .mode box or table or
20459** similar tabular formats.  z[] might contain control characters such
20460** as \n, \t, \f, or \r.
20461**
20462** Compute characters to display on the first line of z[].  Stop at the
20463** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
20464** from malloc()) of that first line, which caller should free sometime.
20465** Write anything to display on the next line into *pzTail.  If this is
20466** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
20467*/
20468static char *translateForDisplayAndDup(
20469  const unsigned char *z,            /* Input text to be transformed */
20470  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
20471  int mxWidth,                       /* Max width.  0 means no limit */
20472  u8 bWordWrap                       /* If true, avoid breaking mid-word */
20473){
20474  int i;                 /* Input bytes consumed */
20475  int j;                 /* Output bytes generated */
20476  int k;                 /* Input bytes to be displayed */
20477  int n;                 /* Output column number */
20478  unsigned char *zOut;   /* Output text */
20479
20480  if( z==0 ){
20481    *pzTail = 0;
20482    return 0;
20483  }
20484  if( mxWidth<0 ) mxWidth = -mxWidth;
20485  if( mxWidth==0 ) mxWidth = 1000000;
20486  i = j = n = 0;
20487  while( n<mxWidth ){
20488    if( z[i]>=' ' ){
20489      n++;
20490      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
20491      continue;
20492    }
20493    if( z[i]=='\t' ){
20494      do{
20495        n++;
20496        j++;
20497      }while( (n&7)!=0 && n<mxWidth );
20498      i++;
20499      continue;
20500    }
20501    break;
20502  }
20503  if( n>=mxWidth && bWordWrap  ){
20504    /* Perhaps try to back up to a better place to break the line */
20505    for(k=i; k>i/2; k--){
20506      if( isspace(z[k-1]) ) break;
20507    }
20508    if( k<=i/2 ){
20509      for(k=i; k>i/2; k--){
20510        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
20511      }
20512    }
20513    if( k<=i/2 ){
20514      k = i;
20515    }else{
20516      i = k;
20517      while( z[i]==' ' ) i++;
20518    }
20519  }else{
20520    k = i;
20521  }
20522  if( n>=mxWidth && z[i]>=' ' ){
20523   *pzTail = &z[i];
20524  }else if( z[i]=='\r' && z[i+1]=='\n' ){
20525    *pzTail = z[i+2] ? &z[i+2] : 0;
20526  }else if( z[i]==0 || z[i+1]==0 ){
20527    *pzTail = 0;
20528  }else{
20529    *pzTail = &z[i+1];
20530  }
20531  zOut = malloc( j+1 );
20532  shell_check_oom(zOut);
20533  i = j = n = 0;
20534  while( i<k ){
20535    if( z[i]>=' ' ){
20536      n++;
20537      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
20538      continue;
20539    }
20540    if( z[i]=='\t' ){
20541      do{
20542        n++;
20543        zOut[j++] = ' ';
20544      }while( (n&7)!=0 && n<mxWidth );
20545      i++;
20546      continue;
20547    }
20548    break;
20549  }
20550  zOut[j] = 0;
20551  return (char*)zOut;
20552}
20553
20554/* Extract the value of the i-th current column for pStmt as an SQL literal
20555** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
20556** the caller.
20557*/
20558static char *quoted_column(sqlite3_stmt *pStmt, int i){
20559  switch( sqlite3_column_type(pStmt, i) ){
20560    case SQLITE_NULL: {
20561      return sqlite3_mprintf("NULL");
20562    }
20563    case SQLITE_INTEGER:
20564    case SQLITE_FLOAT: {
20565      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
20566    }
20567    case SQLITE_TEXT: {
20568      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
20569    }
20570    case SQLITE_BLOB: {
20571      int j;
20572      sqlite3_str *pStr = sqlite3_str_new(0);
20573      const unsigned char *a = sqlite3_column_blob(pStmt,i);
20574      int n = sqlite3_column_bytes(pStmt,i);
20575      sqlite3_str_append(pStr, "x'", 2);
20576      for(j=0; j<n; j++){
20577        sqlite3_str_appendf(pStr, "%02x", a[j]);
20578      }
20579      sqlite3_str_append(pStr, "'", 1);
20580      return sqlite3_str_finish(pStr);
20581    }
20582  }
20583  return 0; /* Not reached */
20584}
20585
20586/*
20587** Run a prepared statement and output the result in one of the
20588** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
20589** or MODE_Box.
20590**
20591** This is different from ordinary exec_prepared_stmt() in that
20592** it has to run the entire query and gather the results into memory
20593** first, in order to determine column widths, before providing
20594** any output.
20595*/
20596static void exec_prepared_stmt_columnar(
20597  ShellState *p,                        /* Pointer to ShellState */
20598  sqlite3_stmt *pStmt                   /* Statement to run */
20599){
20600  sqlite3_int64 nRow = 0;
20601  int nColumn = 0;
20602  char **azData = 0;
20603  sqlite3_int64 nAlloc = 0;
20604  char *abRowDiv = 0;
20605  const unsigned char *uz;
20606  const char *z;
20607  char **azQuoted = 0;
20608  int rc;
20609  sqlite3_int64 i, nData;
20610  int j, nTotal, w, n;
20611  const char *colSep = 0;
20612  const char *rowSep = 0;
20613  const unsigned char **azNextLine = 0;
20614  int bNextLine = 0;
20615  int bMultiLineRowExists = 0;
20616  int bw = p->cmOpts.bWordWrap;
20617  const char *zEmpty = "";
20618  const char *zShowNull = p->nullValue;
20619
20620  rc = sqlite3_step(pStmt);
20621  if( rc!=SQLITE_ROW ) return;
20622  nColumn = sqlite3_column_count(pStmt);
20623  nAlloc = nColumn*4;
20624  if( nAlloc<=0 ) nAlloc = 1;
20625  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
20626  shell_check_oom(azData);
20627  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
20628  shell_check_oom(azNextLine);
20629  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
20630  if( p->cmOpts.bQuote ){
20631    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
20632    shell_check_oom(azQuoted);
20633    memset(azQuoted, 0, nColumn*sizeof(char*) );
20634  }
20635  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
20636  shell_check_oom(abRowDiv);
20637  if( nColumn>p->nWidth ){
20638    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
20639    shell_check_oom(p->colWidth);
20640    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
20641    p->nWidth = nColumn;
20642    p->actualWidth = &p->colWidth[nColumn];
20643  }
20644  memset(p->actualWidth, 0, nColumn*sizeof(int));
20645  for(i=0; i<nColumn; i++){
20646    w = p->colWidth[i];
20647    if( w<0 ) w = -w;
20648    p->actualWidth[i] = w;
20649  }
20650  for(i=0; i<nColumn; i++){
20651    const unsigned char *zNotUsed;
20652    int wx = p->colWidth[i];
20653    if( wx==0 ){
20654      wx = p->cmOpts.iWrap;
20655    }
20656    if( wx<0 ) wx = -wx;
20657    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
20658    if( uz==0 ) uz = (u8*)"";
20659    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
20660  }
20661  do{
20662    int useNextLine = bNextLine;
20663    bNextLine = 0;
20664    if( (nRow+2)*nColumn >= nAlloc ){
20665      nAlloc *= 2;
20666      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
20667      shell_check_oom(azData);
20668      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
20669      shell_check_oom(abRowDiv);
20670    }
20671    abRowDiv[nRow] = 1;
20672    nRow++;
20673    for(i=0; i<nColumn; i++){
20674      int wx = p->colWidth[i];
20675      if( wx==0 ){
20676        wx = p->cmOpts.iWrap;
20677      }
20678      if( wx<0 ) wx = -wx;
20679      if( useNextLine ){
20680        uz = azNextLine[i];
20681        if( uz==0 ) uz = (u8*)zEmpty;
20682      }else if( p->cmOpts.bQuote ){
20683        sqlite3_free(azQuoted[i]);
20684        azQuoted[i] = quoted_column(pStmt,i);
20685        uz = (const unsigned char*)azQuoted[i];
20686      }else{
20687        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
20688        if( uz==0 ) uz = (u8*)zShowNull;
20689      }
20690      azData[nRow*nColumn + i]
20691        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
20692      if( azNextLine[i] ){
20693        bNextLine = 1;
20694        abRowDiv[nRow-1] = 0;
20695        bMultiLineRowExists = 1;
20696      }
20697    }
20698  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
20699  nTotal = nColumn*(nRow+1);
20700  for(i=0; i<nTotal; i++){
20701    z = azData[i];
20702    if( z==0 ) z = (char*)zEmpty;
20703    n = strlenChar(z);
20704    j = i%nColumn;
20705    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
20706  }
20707  if( seenInterrupt ) goto columnar_end;
20708  if( nColumn==0 ) goto columnar_end;
20709  switch( p->cMode ){
20710    case MODE_Column: {
20711      colSep = "  ";
20712      rowSep = "\n";
20713      if( p->showHeader ){
20714        for(i=0; i<nColumn; i++){
20715          w = p->actualWidth[i];
20716          if( p->colWidth[i]<0 ) w = -w;
20717          utf8_width_print(w, azData[i]);
20718          fputs(i==nColumn-1?"\n":"  ", p->out);
20719        }
20720        for(i=0; i<nColumn; i++){
20721          print_dashes(p->actualWidth[i]);
20722          fputs(i==nColumn-1?"\n":"  ", p->out);
20723        }
20724      }
20725      break;
20726    }
20727    case MODE_Table: {
20728      colSep = " | ";
20729      rowSep = " |\n";
20730      print_row_separator(p, nColumn, "+");
20731      fputs("| ", p->out);
20732      for(i=0; i<nColumn; i++){
20733        w = p->actualWidth[i];
20734        n = strlenChar(azData[i]);
20735        oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
20736        oputz(i==nColumn-1?" |\n":" | ");
20737      }
20738      print_row_separator(p, nColumn, "+");
20739      break;
20740    }
20741    case MODE_Markdown: {
20742      colSep = " | ";
20743      rowSep = " |\n";
20744      fputs("| ", p->out);
20745      for(i=0; i<nColumn; i++){
20746        w = p->actualWidth[i];
20747        n = strlenChar(azData[i]);
20748        oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
20749        oputz(i==nColumn-1?" |\n":" | ");
20750      }
20751      print_row_separator(p, nColumn, "|");
20752      break;
20753    }
20754    case MODE_Box: {
20755      colSep = " " BOX_13 " ";
20756      rowSep = " " BOX_13 "\n";
20757      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
20758      oputz(BOX_13 " ");
20759      for(i=0; i<nColumn; i++){
20760        w = p->actualWidth[i];
20761        n = strlenChar(azData[i]);
20762        oputf("%*s%s%*s%s",
20763              (w-n)/2, "", azData[i], (w-n+1)/2, "",
20764              i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
20765      }
20766      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20767      break;
20768    }
20769  }
20770  for(i=nColumn, j=0; i<nTotal; i++, j++){
20771    if( j==0 && p->cMode!=MODE_Column ){
20772      oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
20773    }
20774    z = azData[i];
20775    if( z==0 ) z = p->nullValue;
20776    w = p->actualWidth[j];
20777    if( p->colWidth[j]<0 ) w = -w;
20778    utf8_width_print(w, z);
20779    if( j==nColumn-1 ){
20780      oputz(rowSep);
20781      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
20782        if( p->cMode==MODE_Table ){
20783          print_row_separator(p, nColumn, "+");
20784        }else if( p->cMode==MODE_Box ){
20785          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20786        }else if( p->cMode==MODE_Column ){
20787          oputz("\n");
20788        }
20789      }
20790      j = -1;
20791      if( seenInterrupt ) goto columnar_end;
20792    }else{
20793      oputz(colSep);
20794    }
20795  }
20796  if( p->cMode==MODE_Table ){
20797    print_row_separator(p, nColumn, "+");
20798  }else if( p->cMode==MODE_Box ){
20799    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
20800  }
20801columnar_end:
20802  if( seenInterrupt ){
20803    oputz("Interrupt\n");
20804  }
20805  nData = (nRow+1)*nColumn;
20806  for(i=0; i<nData; i++){
20807    z = azData[i];
20808    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
20809  }
20810  sqlite3_free(azData);
20811  sqlite3_free((void*)azNextLine);
20812  sqlite3_free(abRowDiv);
20813  if( azQuoted ){
20814    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
20815    sqlite3_free(azQuoted);
20816  }
20817}
20818
20819/*
20820** Run a prepared statement
20821*/
20822static void exec_prepared_stmt(
20823  ShellState *pArg,                                /* Pointer to ShellState */
20824  sqlite3_stmt *pStmt                              /* Statement to run */
20825){
20826  int rc;
20827  sqlite3_uint64 nRow = 0;
20828
20829  if( pArg->cMode==MODE_Column
20830   || pArg->cMode==MODE_Table
20831   || pArg->cMode==MODE_Box
20832   || pArg->cMode==MODE_Markdown
20833  ){
20834    exec_prepared_stmt_columnar(pArg, pStmt);
20835    return;
20836  }
20837
20838  /* perform the first step.  this will tell us if we
20839  ** have a result set or not and how wide it is.
20840  */
20841  rc = sqlite3_step(pStmt);
20842  /* if we have a result set... */
20843  if( SQLITE_ROW == rc ){
20844    /* allocate space for col name ptr, value ptr, and type */
20845    int nCol = sqlite3_column_count(pStmt);
20846    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
20847    if( !pData ){
20848      shell_out_of_memory();
20849    }else{
20850      char **azCols = (char **)pData;      /* Names of result columns */
20851      char **azVals = &azCols[nCol];       /* Results */
20852      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
20853      int i, x;
20854      assert(sizeof(int) <= sizeof(char *));
20855      /* save off ptrs to column names */
20856      for(i=0; i<nCol; i++){
20857        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
20858      }
20859      do{
20860        nRow++;
20861        /* extract the data and data types */
20862        for(i=0; i<nCol; i++){
20863          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
20864          if( x==SQLITE_BLOB
20865           && pArg
20866           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
20867          ){
20868            azVals[i] = "";
20869          }else{
20870            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
20871          }
20872          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
20873            rc = SQLITE_NOMEM;
20874            break; /* from for */
20875          }
20876        } /* end for */
20877
20878        /* if data and types extracted successfully... */
20879        if( SQLITE_ROW == rc ){
20880          /* call the supplied callback with the result row data */
20881          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
20882            rc = SQLITE_ABORT;
20883          }else{
20884            rc = sqlite3_step(pStmt);
20885          }
20886        }
20887      } while( SQLITE_ROW == rc );
20888      sqlite3_free(pData);
20889      if( pArg->cMode==MODE_Json ){
20890        fputs("]\n", pArg->out);
20891      }else if( pArg->cMode==MODE_Count ){
20892        char zBuf[200];
20893        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
20894                         nRow, nRow!=1 ? "s" : "");
20895        printf("%s", zBuf);
20896      }
20897    }
20898  }
20899}
20900
20901#ifndef SQLITE_OMIT_VIRTUALTABLE
20902/*
20903** This function is called to process SQL if the previous shell command
20904** was ".expert". It passes the SQL in the second argument directly to
20905** the sqlite3expert object.
20906**
20907** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20908** code. In this case, (*pzErr) may be set to point to a buffer containing
20909** an English language error message. It is the responsibility of the
20910** caller to eventually free this buffer using sqlite3_free().
20911*/
20912static int expertHandleSQL(
20913  ShellState *pState,
20914  const char *zSql,
20915  char **pzErr
20916){
20917  assert( pState->expert.pExpert );
20918  assert( pzErr==0 || *pzErr==0 );
20919  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
20920}
20921
20922/*
20923** This function is called either to silently clean up the object
20924** created by the ".expert" command (if bCancel==1), or to generate a
20925** report from it and then clean it up (if bCancel==0).
20926**
20927** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20928** code. In this case, (*pzErr) may be set to point to a buffer containing
20929** an English language error message. It is the responsibility of the
20930** caller to eventually free this buffer using sqlite3_free().
20931*/
20932static int expertFinish(
20933  ShellState *pState,
20934  int bCancel,
20935  char **pzErr
20936){
20937  int rc = SQLITE_OK;
20938  sqlite3expert *p = pState->expert.pExpert;
20939  assert( p );
20940  assert( bCancel || pzErr==0 || *pzErr==0 );
20941  if( bCancel==0 ){
20942    int bVerbose = pState->expert.bVerbose;
20943
20944    rc = sqlite3_expert_analyze(p, pzErr);
20945    if( rc==SQLITE_OK ){
20946      int nQuery = sqlite3_expert_count(p);
20947      int i;
20948
20949      if( bVerbose ){
20950        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
20951        oputz("-- Candidates -----------------------------\n");
20952        oputf("%s\n", zCand);
20953      }
20954      for(i=0; i<nQuery; i++){
20955        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
20956        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
20957        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
20958        if( zIdx==0 ) zIdx = "(no new indexes)\n";
20959        if( bVerbose ){
20960          oputf("-- Query %d --------------------------------\n",i+1);
20961          oputf("%s\n\n", zSql);
20962        }
20963        oputf("%s\n", zIdx);
20964        oputf("%s\n", zEQP);
20965      }
20966    }
20967  }
20968  sqlite3_expert_destroy(p);
20969  pState->expert.pExpert = 0;
20970  return rc;
20971}
20972
20973/*
20974** Implementation of ".expert" dot command.
20975*/
20976static int expertDotCommand(
20977  ShellState *pState,             /* Current shell tool state */
20978  char **azArg,                   /* Array of arguments passed to dot command */
20979  int nArg                        /* Number of entries in azArg[] */
20980){
20981  int rc = SQLITE_OK;
20982  char *zErr = 0;
20983  int i;
20984  int iSample = 0;
20985
20986  assert( pState->expert.pExpert==0 );
20987  memset(&pState->expert, 0, sizeof(ExpertInfo));
20988
20989  for(i=1; rc==SQLITE_OK && i<nArg; i++){
20990    char *z = azArg[i];
20991    int n;
20992    if( z[0]=='-' && z[1]=='-' ) z++;
20993    n = strlen30(z);
20994    if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
20995      pState->expert.bVerbose = 1;
20996    }
20997    else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
20998      if( i==(nArg-1) ){
20999        eputf("option requires an argument: %s\n", z);
21000        rc = SQLITE_ERROR;
21001      }else{
21002        iSample = (int)integerValue(azArg[++i]);
21003        if( iSample<0 || iSample>100 ){
21004          eputf("value out of range: %s\n", azArg[i]);
21005          rc = SQLITE_ERROR;
21006        }
21007      }
21008    }
21009    else{
21010      eputf("unknown option: %s\n", z);
21011      rc = SQLITE_ERROR;
21012    }
21013  }
21014
21015  if( rc==SQLITE_OK ){
21016    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
21017    if( pState->expert.pExpert==0 ){
21018      eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
21019      rc = SQLITE_ERROR;
21020    }else{
21021      sqlite3_expert_config(
21022          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
21023      );
21024    }
21025  }
21026  sqlite3_free(zErr);
21027
21028  return rc;
21029}
21030#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
21031
21032/*
21033** Execute a statement or set of statements.  Print
21034** any result rows/columns depending on the current mode
21035** set via the supplied callback.
21036**
21037** This is very similar to SQLite's built-in sqlite3_exec()
21038** function except it takes a slightly different callback
21039** and callback data argument.
21040*/
21041static int shell_exec(
21042  ShellState *pArg,                         /* Pointer to ShellState */
21043  const char *zSql,                         /* SQL to be evaluated */
21044  char **pzErrMsg                           /* Error msg written here */
21045){
21046  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
21047  int rc = SQLITE_OK;             /* Return Code */
21048  int rc2;
21049  const char *zLeftover;          /* Tail of unprocessed SQL */
21050  sqlite3 *db = pArg->db;
21051
21052  if( pzErrMsg ){
21053    *pzErrMsg = NULL;
21054  }
21055
21056#ifndef SQLITE_OMIT_VIRTUALTABLE
21057  if( pArg->expert.pExpert ){
21058    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
21059    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
21060  }
21061#endif
21062
21063  while( zSql[0] && (SQLITE_OK == rc) ){
21064    static const char *zStmtSql;
21065    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
21066    if( SQLITE_OK != rc ){
21067      if( pzErrMsg ){
21068        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
21069      }
21070    }else{
21071      if( !pStmt ){
21072        /* this happens for a comment or white-space */
21073        zSql = zLeftover;
21074        while( IsSpace(zSql[0]) ) zSql++;
21075        continue;
21076      }
21077      zStmtSql = sqlite3_sql(pStmt);
21078      if( zStmtSql==0 ) zStmtSql = "";
21079      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
21080
21081      /* save off the prepared statement handle and reset row count */
21082      if( pArg ){
21083        pArg->pStmt = pStmt;
21084        pArg->cnt = 0;
21085      }
21086
21087      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
21088      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
21089        sqlite3_stmt *pExplain;
21090        int triggerEQP = 0;
21091        disable_debug_trace_modes();
21092        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
21093        if( pArg->autoEQP>=AUTOEQP_trigger ){
21094          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
21095        }
21096        pExplain = pStmt;
21097        sqlite3_reset(pExplain);
21098        rc = sqlite3_stmt_explain(pExplain, 2);
21099        if( rc==SQLITE_OK ){
21100          while( sqlite3_step(pExplain)==SQLITE_ROW ){
21101            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
21102            int iEqpId = sqlite3_column_int(pExplain, 0);
21103            int iParentId = sqlite3_column_int(pExplain, 1);
21104            if( zEQPLine==0 ) zEQPLine = "";
21105            if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
21106            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
21107          }
21108          eqp_render(pArg, 0);
21109        }
21110        if( pArg->autoEQP>=AUTOEQP_full ){
21111          /* Also do an EXPLAIN for ".eqp full" mode */
21112          sqlite3_reset(pExplain);
21113          rc = sqlite3_stmt_explain(pExplain, 1);
21114          if( rc==SQLITE_OK ){
21115            pArg->cMode = MODE_Explain;
21116            assert( sqlite3_stmt_isexplain(pExplain)==1 );
21117            explain_data_prepare(pArg, pExplain);
21118            exec_prepared_stmt(pArg, pExplain);
21119            explain_data_delete(pArg);
21120          }
21121        }
21122        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
21123          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
21124        }
21125        sqlite3_reset(pStmt);
21126        sqlite3_stmt_explain(pStmt, 0);
21127        restore_debug_trace_modes();
21128      }
21129
21130      if( pArg ){
21131        int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
21132        pArg->cMode = pArg->mode;
21133        if( pArg->autoExplain ){
21134          if( bIsExplain ){
21135            pArg->cMode = MODE_Explain;
21136          }
21137          if( sqlite3_stmt_isexplain(pStmt)==2 ){
21138            pArg->cMode = MODE_EQP;
21139          }
21140        }
21141
21142        /* If the shell is currently in ".explain" mode, gather the extra
21143        ** data required to add indents to the output.*/
21144        if( pArg->cMode==MODE_Explain && bIsExplain ){
21145          explain_data_prepare(pArg, pStmt);
21146        }
21147      }
21148
21149      bind_prepared_stmt(pArg, pStmt);
21150      exec_prepared_stmt(pArg, pStmt);
21151      explain_data_delete(pArg);
21152      eqp_render(pArg, 0);
21153
21154      /* print usage stats if stats on */
21155      if( pArg && pArg->statsOn ){
21156        display_stats(db, pArg, 0);
21157      }
21158
21159      /* print loop-counters if required */
21160      if( pArg && pArg->scanstatsOn ){
21161        display_scanstats(db, pArg);
21162      }
21163
21164      /* Finalize the statement just executed. If this fails, save a
21165      ** copy of the error message. Otherwise, set zSql to point to the
21166      ** next statement to execute. */
21167      rc2 = sqlite3_finalize(pStmt);
21168      if( rc!=SQLITE_NOMEM ) rc = rc2;
21169      if( rc==SQLITE_OK ){
21170        zSql = zLeftover;
21171        while( IsSpace(zSql[0]) ) zSql++;
21172      }else if( pzErrMsg ){
21173        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
21174      }
21175
21176      /* clear saved stmt handle */
21177      if( pArg ){
21178        pArg->pStmt = NULL;
21179      }
21180    }
21181  } /* end while */
21182
21183  return rc;
21184}
21185
21186/*
21187** Release memory previously allocated by tableColumnList().
21188*/
21189static void freeColumnList(char **azCol){
21190  int i;
21191  for(i=1; azCol[i]; i++){
21192    sqlite3_free(azCol[i]);
21193  }
21194  /* azCol[0] is a static string */
21195  sqlite3_free(azCol);
21196}
21197
21198/*
21199** Return a list of pointers to strings which are the names of all
21200** columns in table zTab.   The memory to hold the names is dynamically
21201** allocated and must be released by the caller using a subsequent call
21202** to freeColumnList().
21203**
21204** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
21205** value that needs to be preserved, then azCol[0] is filled in with the
21206** name of the rowid column.
21207**
21208** The first regular column in the table is azCol[1].  The list is terminated
21209** by an entry with azCol[i]==0.
21210*/
21211static char **tableColumnList(ShellState *p, const char *zTab){
21212  char **azCol = 0;
21213  sqlite3_stmt *pStmt;
21214  char *zSql;
21215  int nCol = 0;
21216  int nAlloc = 0;
21217  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
21218  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
21219  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
21220  int rc;
21221
21222  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
21223  shell_check_oom(zSql);
21224  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
21225  sqlite3_free(zSql);
21226  if( rc ) return 0;
21227  while( sqlite3_step(pStmt)==SQLITE_ROW ){
21228    if( nCol>=nAlloc-2 ){
21229      nAlloc = nAlloc*2 + nCol + 10;
21230      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
21231      shell_check_oom(azCol);
21232    }
21233    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
21234    shell_check_oom(azCol[nCol]);
21235    if( sqlite3_column_int(pStmt, 5) ){
21236      nPK++;
21237      if( nPK==1
21238       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
21239                          "INTEGER")==0
21240      ){
21241        isIPK = 1;
21242      }else{
21243        isIPK = 0;
21244      }
21245    }
21246  }
21247  sqlite3_finalize(pStmt);
21248  if( azCol==0 ) return 0;
21249  azCol[0] = 0;
21250  azCol[nCol+1] = 0;
21251
21252  /* The decision of whether or not a rowid really needs to be preserved
21253  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
21254  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
21255  ** rowids on tables where the rowid is inaccessible because there are other
21256  ** columns in the table named "rowid", "_rowid_", and "oid".
21257  */
21258  if( preserveRowid && isIPK ){
21259    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
21260    ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
21261    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
21262    ** ROWID aliases.  To distinguish these cases, check to see if
21263    ** there is a "pk" entry in "PRAGMA index_list".  There will be
21264    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
21265    */
21266    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
21267                           " WHERE origin='pk'", zTab);
21268    shell_check_oom(zSql);
21269    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
21270    sqlite3_free(zSql);
21271    if( rc ){
21272      freeColumnList(azCol);
21273      return 0;
21274    }
21275    rc = sqlite3_step(pStmt);
21276    sqlite3_finalize(pStmt);
21277    preserveRowid = rc==SQLITE_ROW;
21278  }
21279  if( preserveRowid ){
21280    /* Only preserve the rowid if we can find a name to use for the
21281    ** rowid */
21282    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
21283    int i, j;
21284    for(j=0; j<3; j++){
21285      for(i=1; i<=nCol; i++){
21286        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
21287      }
21288      if( i>nCol ){
21289        /* At this point, we know that azRowid[j] is not the name of any
21290        ** ordinary column in the table.  Verify that azRowid[j] is a valid
21291        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
21292        ** tables will fail this last check */
21293        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
21294        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
21295        break;
21296      }
21297    }
21298  }
21299  return azCol;
21300}
21301
21302/*
21303** Toggle the reverse_unordered_selects setting.
21304*/
21305static void toggleSelectOrder(sqlite3 *db){
21306  sqlite3_stmt *pStmt = 0;
21307  int iSetting = 0;
21308  char zStmt[100];
21309  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
21310  if( sqlite3_step(pStmt)==SQLITE_ROW ){
21311    iSetting = sqlite3_column_int(pStmt, 0);
21312  }
21313  sqlite3_finalize(pStmt);
21314  sqlite3_snprintf(sizeof(zStmt), zStmt,
21315       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
21316  sqlite3_exec(db, zStmt, 0, 0, 0);
21317}
21318
21319/*
21320** This is a different callback routine used for dumping the database.
21321** Each row received by this callback consists of a table name,
21322** the table type ("index" or "table") and SQL to create the table.
21323** This routine should print text sufficient to recreate the table.
21324*/
21325static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
21326  int rc;
21327  const char *zTable;
21328  const char *zType;
21329  const char *zSql;
21330  ShellState *p = (ShellState *)pArg;
21331  int dataOnly;
21332  int noSys;
21333
21334  UNUSED_PARAMETER(azNotUsed);
21335  if( nArg!=3 || azArg==0 ) return 0;
21336  zTable = azArg[0];
21337  zType = azArg[1];
21338  zSql = azArg[2];
21339  if( zTable==0 ) return 0;
21340  if( zType==0 ) return 0;
21341  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
21342  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
21343
21344  if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
21345    if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
21346  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
21347    if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
21348  }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
21349    return 0;
21350  }else if( dataOnly ){
21351    /* no-op */
21352  }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
21353    char *zIns;
21354    if( !p->writableSchema ){
21355      oputz("PRAGMA writable_schema=ON;\n");
21356      p->writableSchema = 1;
21357    }
21358    zIns = sqlite3_mprintf(
21359       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
21360       "VALUES('table','%q','%q',0,'%q');",
21361       zTable, zTable, zSql);
21362    shell_check_oom(zIns);
21363    oputf("%s\n", zIns);
21364    sqlite3_free(zIns);
21365    return 0;
21366  }else{
21367    printSchemaLine(zSql, ";\n");
21368  }
21369
21370  if( cli_strcmp(zType, "table")==0 ){
21371    ShellText sSelect;
21372    ShellText sTable;
21373    char **azCol;
21374    int i;
21375    char *savedDestTable;
21376    int savedMode;
21377
21378    azCol = tableColumnList(p, zTable);
21379    if( azCol==0 ){
21380      p->nErr++;
21381      return 0;
21382    }
21383
21384    /* Always quote the table name, even if it appears to be pure ascii,
21385    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
21386    initText(&sTable);
21387    appendText(&sTable, zTable, quoteChar(zTable));
21388    /* If preserving the rowid, add a column list after the table name.
21389    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
21390    ** instead of the usual "INSERT INTO tab VALUES(...)".
21391    */
21392    if( azCol[0] ){
21393      appendText(&sTable, "(", 0);
21394      appendText(&sTable, azCol[0], 0);
21395      for(i=1; azCol[i]; i++){
21396        appendText(&sTable, ",", 0);
21397        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
21398      }
21399      appendText(&sTable, ")", 0);
21400    }
21401
21402    /* Build an appropriate SELECT statement */
21403    initText(&sSelect);
21404    appendText(&sSelect, "SELECT ", 0);
21405    if( azCol[0] ){
21406      appendText(&sSelect, azCol[0], 0);
21407      appendText(&sSelect, ",", 0);
21408    }
21409    for(i=1; azCol[i]; i++){
21410      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
21411      if( azCol[i+1] ){
21412        appendText(&sSelect, ",", 0);
21413      }
21414    }
21415    freeColumnList(azCol);
21416    appendText(&sSelect, " FROM ", 0);
21417    appendText(&sSelect, zTable, quoteChar(zTable));
21418
21419    savedDestTable = p->zDestTable;
21420    savedMode = p->mode;
21421    p->zDestTable = sTable.z;
21422    p->mode = p->cMode = MODE_Insert;
21423    rc = shell_exec(p, sSelect.z, 0);
21424    if( (rc&0xff)==SQLITE_CORRUPT ){
21425      oputz("/****** CORRUPTION ERROR *******/\n");
21426      toggleSelectOrder(p->db);
21427      shell_exec(p, sSelect.z, 0);
21428      toggleSelectOrder(p->db);
21429    }
21430    p->zDestTable = savedDestTable;
21431    p->mode = savedMode;
21432    freeText(&sTable);
21433    freeText(&sSelect);
21434    if( rc ) p->nErr++;
21435  }
21436  return 0;
21437}
21438
21439/*
21440** Run zQuery.  Use dump_callback() as the callback routine so that
21441** the contents of the query are output as SQL statements.
21442**
21443** If we get a SQLITE_CORRUPT error, rerun the query after appending
21444** "ORDER BY rowid DESC" to the end.
21445*/
21446static int run_schema_dump_query(
21447  ShellState *p,
21448  const char *zQuery
21449){
21450  int rc;
21451  char *zErr = 0;
21452  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
21453  if( rc==SQLITE_CORRUPT ){
21454    char *zQ2;
21455    int len = strlen30(zQuery);
21456    oputz("/****** CORRUPTION ERROR *******/\n");
21457    if( zErr ){
21458      oputf("/****** %s ******/\n", zErr);
21459      sqlite3_free(zErr);
21460      zErr = 0;
21461    }
21462    zQ2 = malloc( len+100 );
21463    if( zQ2==0 ) return rc;
21464    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
21465    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
21466    if( rc ){
21467      oputf("/****** ERROR: %s ******/\n", zErr);
21468    }else{
21469      rc = SQLITE_CORRUPT;
21470    }
21471    sqlite3_free(zErr);
21472    free(zQ2);
21473  }
21474  return rc;
21475}
21476
21477/*
21478** Text of help messages.
21479**
21480** The help text for each individual command begins with a line that starts
21481** with ".".  Subsequent lines are supplemental information.
21482**
21483** There must be two or more spaces between the end of the command and the
21484** start of the description of what that command does.
21485*/
21486static const char *(azHelp[]) = {
21487#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
21488  && !defined(SQLITE_SHELL_FIDDLE)
21489  ".archive ...             Manage SQL archives",
21490  "   Each command must have exactly one of the following options:",
21491  "     -c, --create               Create a new archive",
21492  "     -u, --update               Add or update files with changed mtime",
21493  "     -i, --insert               Like -u but always add even if unchanged",
21494  "     -r, --remove               Remove files from archive",
21495  "     -t, --list                 List contents of archive",
21496  "     -x, --extract              Extract files from archive",
21497  "   Optional arguments:",
21498  "     -v, --verbose              Print each filename as it is processed",
21499  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
21500  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
21501  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
21502  "     -g, --glob                 Use glob matching for names in archive",
21503  "     -n, --dryrun               Show the SQL that would have occurred",
21504  "   Examples:",
21505  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
21506  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
21507  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
21508  "   See also:",
21509  "      http://sqlite.org/cli.html#sqlite_archive_support",
21510#endif
21511#ifndef SQLITE_OMIT_AUTHORIZATION
21512  ".auth ON|OFF             Show authorizer callbacks",
21513#endif
21514#ifndef SQLITE_SHELL_FIDDLE
21515  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
21516  "   Options:",
21517  "       --append            Use the appendvfs",
21518  "       --async             Write to FILE without journal and fsync()",
21519#endif
21520  ".bail on|off             Stop after hitting an error.  Default OFF",
21521#ifndef SQLITE_SHELL_FIDDLE
21522  ".cd DIRECTORY            Change the working directory to DIRECTORY",
21523#endif
21524  ".changes on|off          Show number of rows changed by SQL",
21525#ifndef SQLITE_SHELL_FIDDLE
21526  ".check GLOB              Fail if output since .testcase does not match",
21527  ".clone NEWDB             Clone data into NEWDB from the existing database",
21528#endif
21529  ".connection [close] [#]  Open or close an auxiliary database connection",
21530#if defined(_WIN32) || defined(WIN32)
21531  ".crnl on|off             Translate \\n to \\r\\n.  Default ON",
21532#endif
21533  ".databases               List names and files of attached databases",
21534  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
21535#if SQLITE_SHELL_HAVE_RECOVER
21536  ".dbinfo ?DB?             Show status information about the database",
21537#endif
21538  ".dump ?OBJECTS?          Render database content as SQL",
21539  "   Options:",
21540  "     --data-only            Output only INSERT statements",
21541  "     --newlines             Allow unescaped newline characters in output",
21542  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
21543  "     --preserve-rowids      Include ROWID values in the output",
21544  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
21545  "   Additional LIKE patterns can be given in subsequent arguments",
21546  ".echo on|off             Turn command echo on or off",
21547  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
21548  "   Other Modes:",
21549#ifdef SQLITE_DEBUG
21550  "      test                  Show raw EXPLAIN QUERY PLAN output",
21551  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
21552#endif
21553  "      trigger               Like \"full\" but also show trigger bytecode",
21554#ifndef SQLITE_SHELL_FIDDLE
21555  ".excel                   Display the output of next command in spreadsheet",
21556  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
21557#endif
21558#ifndef SQLITE_SHELL_FIDDLE
21559  ".exit ?CODE?             Exit this program with return-code CODE",
21560#endif
21561  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
21562  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
21563  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
21564  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
21565  "   --help                  Show CMD details",
21566  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
21567  ".headers on|off          Turn display of headers on or off",
21568  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
21569#ifndef SQLITE_SHELL_FIDDLE
21570  ".import FILE TABLE       Import data from FILE into TABLE",
21571  "   Options:",
21572  "     --ascii               Use \\037 and \\036 as column and row separators",
21573  "     --csv                 Use , and \\n as column and row separators",
21574  "     --skip N              Skip the first N rows of input",
21575  "     --schema S            Target table to be S.TABLE",
21576  "     -v                    \"Verbose\" - increase auxiliary output",
21577  "   Notes:",
21578  "     *  If TABLE does not exist, it is created.  The first row of input",
21579  "        determines the column names.",
21580  "     *  If neither --csv or --ascii are used, the input mode is derived",
21581  "        from the \".mode\" output mode",
21582  "     *  If FILE begins with \"|\" then it is a command that generates the",
21583  "        input text.",
21584#endif
21585#ifndef SQLITE_OMIT_TEST_CONTROL
21586  ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
21587#endif
21588  ".indexes ?TABLE?         Show names of indexes",
21589  "                           If TABLE is specified, only show indexes for",
21590  "                           tables matching TABLE using the LIKE operator.",
21591#ifdef SQLITE_ENABLE_IOTRACE
21592  ",iotrace FILE            Enable I/O diagnostic logging to FILE",
21593#endif
21594  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
21595  ".lint OPTIONS            Report potential schema issues.",
21596  "     Options:",
21597  "        fkey-indexes     Find missing foreign key indexes",
21598#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
21599  ".load FILE ?ENTRY?       Load an extension library",
21600#endif
21601#if !defined(SQLITE_SHELL_FIDDLE)
21602  ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
21603#else
21604  ".log on|off              Turn logging on or off.",
21605#endif
21606  ".mode MODE ?OPTIONS?     Set output mode",
21607  "   MODE is one of:",
21608  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
21609  "     box         Tables using unicode box-drawing characters",
21610  "     csv         Comma-separated values",
21611  "     column      Output in columns.  (See .width)",
21612  "     html        HTML <table> code",
21613  "     insert      SQL insert statements for TABLE",
21614  "     json        Results in a JSON array",
21615  "     line        One value per line",
21616  "     list        Values delimited by \"|\"",
21617  "     markdown    Markdown table format",
21618  "     qbox        Shorthand for \"box --wrap 60 --quote\"",
21619  "     quote       Escape answers as for SQL",
21620  "     table       ASCII-art table",
21621  "     tabs        Tab-separated values",
21622  "     tcl         TCL list elements",
21623  "   OPTIONS: (for columnar modes or insert mode):",
21624  "     --wrap N       Wrap output lines to no longer than N characters",
21625  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
21626  "     --ww           Shorthand for \"--wordwrap 1\"",
21627  "     --quote        Quote output text as SQL literals",
21628  "     --noquote      Do not quote output text",
21629  "     TABLE          The name of SQL table used for \"insert\" mode",
21630#ifndef SQLITE_SHELL_FIDDLE
21631  ".nonce STRING            Suspend safe mode for one command if nonce matches",
21632#endif
21633  ".nullvalue STRING        Use STRING in place of NULL values",
21634#ifndef SQLITE_SHELL_FIDDLE
21635  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
21636  "     If FILE begins with '|' then open as a pipe",
21637  "       --bom  Put a UTF8 byte-order mark at the beginning",
21638  "       -e     Send output to the system text editor",
21639  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
21640  /* Note that .open is (partially) available in WASM builds but is
21641  ** currently only intended to be used by the fiddle tool, not
21642  ** end users, so is "undocumented." */
21643  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
21644  "     Options:",
21645  "        --append        Use appendvfs to append database to the end of FILE",
21646#endif
21647#ifndef SQLITE_OMIT_DESERIALIZE
21648  "        --deserialize   Load into memory using sqlite3_deserialize()",
21649  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
21650  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
21651#endif
21652  "        --new           Initialize FILE to an empty database",
21653  "        --nofollow      Do not follow symbolic links",
21654  "        --readonly      Open FILE readonly",
21655  "        --zip           FILE is a ZIP archive",
21656#ifndef SQLITE_SHELL_FIDDLE
21657  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
21658  "   If FILE begins with '|' then open it as a pipe.",
21659  "   Options:",
21660  "     --bom                 Prefix output with a UTF8 byte-order mark",
21661  "     -e                    Send output to the system text editor",
21662  "     -x                    Send output as CSV to a spreadsheet",
21663#endif
21664  ".parameter CMD ...       Manage SQL parameter bindings",
21665  "   clear                   Erase all bindings",
21666  "   init                    Initialize the TEMP table that holds bindings",
21667  "   list                    List the current parameter bindings",
21668  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
21669  "                           PARAMETER should start with one of: $ : @ ?",
21670  "   unset PARAMETER         Remove PARAMETER from the binding table",
21671  ".print STRING...         Print literal STRING",
21672#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
21673  ".progress N              Invoke progress handler after every N opcodes",
21674  "   --limit N                 Interrupt after N progress callbacks",
21675  "   --once                    Do no more than one progress interrupt",
21676  "   --quiet|-q                No output except at interrupts",
21677  "   --reset                   Reset the count for each input and interrupt",
21678#endif
21679  ".prompt MAIN CONTINUE    Replace the standard prompts",
21680#ifndef SQLITE_SHELL_FIDDLE
21681  ".quit                    Stop interpreting input stream, exit if primary.",
21682  ".read FILE               Read input from FILE or command output",
21683  "    If FILE begins with \"|\", it is a command that generates the input.",
21684#endif
21685#if SQLITE_SHELL_HAVE_RECOVER
21686  ".recover                 Recover as much data as possible from corrupt db.",
21687  "   --ignore-freelist        Ignore pages that appear to be on db freelist",
21688  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
21689  "   --no-rowids              Do not attempt to recover rowid values",
21690  "                            that are not also INTEGER PRIMARY KEYs",
21691#endif
21692#ifndef SQLITE_SHELL_FIDDLE
21693  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
21694  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
21695#endif
21696  ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
21697  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
21698  "   Options:",
21699  "      --indent             Try to pretty-print the schema",
21700  "      --nosys              Omit objects whose names start with \"sqlite_\"",
21701  ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
21702  "    Options:",
21703  "       --init               Create a new SELFTEST table",
21704  "       -v                   Verbose output",
21705  ".separator COL ?ROW?     Change the column and row separators",
21706#if defined(SQLITE_ENABLE_SESSION)
21707  ".session ?NAME? CMD ...  Create or control sessions",
21708  "   Subcommands:",
21709  "     attach TABLE             Attach TABLE",
21710  "     changeset FILE           Write a changeset into FILE",
21711  "     close                    Close one session",
21712  "     enable ?BOOLEAN?         Set or query the enable bit",
21713  "     filter GLOB...           Reject tables matching GLOBs",
21714  "     indirect ?BOOLEAN?       Mark or query the indirect status",
21715  "     isempty                  Query whether the session is empty",
21716  "     list                     List currently open session names",
21717  "     open DB NAME             Open a new session on DB",
21718  "     patchset FILE            Write a patchset into FILE",
21719  "   If ?NAME? is omitted, the first defined session is used.",
21720#endif
21721  ".sha3sum ...             Compute a SHA3 hash of database content",
21722  "    Options:",
21723  "      --schema              Also hash the sqlite_schema table",
21724  "      --sha3-224            Use the sha3-224 algorithm",
21725  "      --sha3-256            Use the sha3-256 algorithm (default)",
21726  "      --sha3-384            Use the sha3-384 algorithm",
21727  "      --sha3-512            Use the sha3-512 algorithm",
21728  "    Any other argument is a LIKE pattern for tables to hash",
21729#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
21730  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
21731#endif
21732  ".show                    Show the current values for various settings",
21733  ".stats ?ARG?             Show stats or turn stats on or off",
21734  "   off                      Turn off automatic stat display",
21735  "   on                       Turn on automatic stat display",
21736  "   stmt                     Show statement stats",
21737  "   vmstep                   Show the virtual machine step count only",
21738#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
21739  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
21740#endif
21741  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
21742#ifndef SQLITE_SHELL_FIDDLE
21743  ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
21744#endif
21745  ",testctrl CMD ...        Run various sqlite3_test_control() operations",
21746  "                           Run \".testctrl\" with no arguments for details",
21747  ".timeout MS              Try opening locked tables for MS milliseconds",
21748  ".timer on|off            Turn SQL timer on or off",
21749#ifndef SQLITE_OMIT_TRACE
21750  ".trace ?OPTIONS?         Output each SQL statement as it is run",
21751  "    FILE                    Send output to FILE",
21752  "    stdout                  Send output to stdout",
21753  "    stderr                  Send output to stderr",
21754  "    off                     Disable tracing",
21755  "    --expanded              Expand query parameters",
21756#ifdef SQLITE_ENABLE_NORMALIZE
21757  "    --normalized            Normal the SQL statements",
21758#endif
21759  "    --plain                 Show SQL as it is input",
21760  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
21761  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
21762  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
21763  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
21764#endif /* SQLITE_OMIT_TRACE */
21765#ifdef SQLITE_DEBUG
21766  ".unmodule NAME ...       Unregister virtual table modules",
21767  "    --allexcept             Unregister everything except those named",
21768#endif
21769  ".version                 Show source, library and compiler versions",
21770  ".vfsinfo ?AUX?           Information about the top-level VFS",
21771  ".vfslist                 List all available VFSes",
21772  ".vfsname ?AUX?           Print the name of the VFS stack",
21773  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
21774  "     Negative values right-justify",
21775};
21776
21777/*
21778** Output help text.
21779**
21780** zPattern describes the set of commands for which help text is provided.
21781** If zPattern is NULL, then show all commands, but only give a one-line
21782** description of each.
21783**
21784** Return the number of matches.
21785*/
21786static int showHelp(FILE *out, const char *zPattern){
21787  int i = 0;
21788  int j = 0;
21789  int n = 0;
21790  char *zPat;
21791  if( zPattern==0
21792   || zPattern[0]=='0'
21793   || cli_strcmp(zPattern,"-a")==0
21794   || cli_strcmp(zPattern,"-all")==0
21795   || cli_strcmp(zPattern,"--all")==0
21796  ){
21797    enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
21798    enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
21799    /* Show all or most commands
21800    ** *zPattern==0   => summary of documented commands only
21801    ** *zPattern=='0' => whole help for undocumented commands
21802    ** Otherwise      => whole help for documented commands
21803    */
21804    enum HelpWanted hw = HW_SummaryOnly;
21805    enum HelpHave hh = HH_More;
21806    if( zPattern!=0 ){
21807      hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
21808    }
21809    for(i=0; i<ArraySize(azHelp); i++){
21810      switch( azHelp[i][0] ){
21811      case ',':
21812        hh = HH_Summary|HH_Undoc;
21813        break;
21814      case '.':
21815        hh = HH_Summary;
21816        break;
21817      default:
21818        hh &= ~HH_Summary;
21819        break;
21820      }
21821      if( ((hw^hh)&HH_Undoc)==0 ){
21822        if( (hh&HH_Summary)!=0 ){
21823          sputf(out, ".%s\n", azHelp[i]+1);
21824          ++n;
21825        }else if( (hw&HW_SummaryOnly)==0 ){
21826          sputf(out, "%s\n", azHelp[i]);
21827        }
21828      }
21829    }
21830  }else{
21831    /* Seek documented commands for which zPattern is an exact prefix */
21832    zPat = sqlite3_mprintf(".%s*", zPattern);
21833    shell_check_oom(zPat);
21834    for(i=0; i<ArraySize(azHelp); i++){
21835      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
21836        sputf(out, "%s\n", azHelp[i]);
21837        j = i+1;
21838        n++;
21839      }
21840    }
21841    sqlite3_free(zPat);
21842    if( n ){
21843      if( n==1 ){
21844        /* when zPattern is a prefix of exactly one command, then include
21845        ** the details of that command, which should begin at offset j */
21846        while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
21847          sputf(out, "%s\n", azHelp[j]);
21848          j++;
21849        }
21850      }
21851      return n;
21852    }
21853    /* Look for documented commands that contain zPattern anywhere.
21854    ** Show complete text of all documented commands that match. */
21855    zPat = sqlite3_mprintf("%%%s%%", zPattern);
21856    shell_check_oom(zPat);
21857    for(i=0; i<ArraySize(azHelp); i++){
21858      if( azHelp[i][0]==',' ){
21859        while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
21860        continue;
21861      }
21862      if( azHelp[i][0]=='.' ) j = i;
21863      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
21864        sputf(out, "%s\n", azHelp[j]);
21865        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
21866          j++;
21867          sputf(out, "%s\n", azHelp[j]);
21868        }
21869        i = j;
21870        n++;
21871      }
21872    }
21873    sqlite3_free(zPat);
21874  }
21875  return n;
21876}
21877
21878/* Forward reference */
21879static int process_input(ShellState *p);
21880
21881/*
21882** Read the content of file zName into memory obtained from sqlite3_malloc64()
21883** and return a pointer to the buffer. The caller is responsible for freeing
21884** the memory.
21885**
21886** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
21887** read.
21888**
21889** For convenience, a nul-terminator byte is always appended to the data read
21890** from the file before the buffer is returned. This byte is not included in
21891** the final value of (*pnByte), if applicable.
21892**
21893** NULL is returned if any error is encountered. The final value of *pnByte
21894** is undefined in this case.
21895*/
21896static char *readFile(const char *zName, int *pnByte){
21897  FILE *in = fopen(zName, "rb");
21898  long nIn;
21899  size_t nRead;
21900  char *pBuf;
21901  int rc;
21902  if( in==0 ) return 0;
21903  rc = fseek(in, 0, SEEK_END);
21904  if( rc!=0 ){
21905    eputf("Error: '%s' not seekable\n", zName);
21906    fclose(in);
21907    return 0;
21908  }
21909  nIn = ftell(in);
21910  rewind(in);
21911  pBuf = sqlite3_malloc64( nIn+1 );
21912  if( pBuf==0 ){
21913    eputz("Error: out of memory\n");
21914    fclose(in);
21915    return 0;
21916  }
21917  nRead = fread(pBuf, nIn, 1, in);
21918  fclose(in);
21919  if( nRead!=1 ){
21920    sqlite3_free(pBuf);
21921    eputf("Error: cannot read '%s'\n", zName);
21922    return 0;
21923  }
21924  pBuf[nIn] = 0;
21925  if( pnByte ) *pnByte = nIn;
21926  return pBuf;
21927}
21928
21929#if defined(SQLITE_ENABLE_SESSION)
21930/*
21931** Close a single OpenSession object and release all of its associated
21932** resources.
21933*/
21934static void session_close(OpenSession *pSession){
21935  int i;
21936  sqlite3session_delete(pSession->p);
21937  sqlite3_free(pSession->zName);
21938  for(i=0; i<pSession->nFilter; i++){
21939    sqlite3_free(pSession->azFilter[i]);
21940  }
21941  sqlite3_free(pSession->azFilter);
21942  memset(pSession, 0, sizeof(OpenSession));
21943}
21944#endif
21945
21946/*
21947** Close all OpenSession objects and release all associated resources.
21948*/
21949#if defined(SQLITE_ENABLE_SESSION)
21950static void session_close_all(ShellState *p, int i){
21951  int j;
21952  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
21953  for(j=0; j<pAuxDb->nSession; j++){
21954    session_close(&pAuxDb->aSession[j]);
21955  }
21956  pAuxDb->nSession = 0;
21957}
21958#else
21959# define session_close_all(X,Y)
21960#endif
21961
21962/*
21963** Implementation of the xFilter function for an open session.  Omit
21964** any tables named by ".session filter" but let all other table through.
21965*/
21966#if defined(SQLITE_ENABLE_SESSION)
21967static int session_filter(void *pCtx, const char *zTab){
21968  OpenSession *pSession = (OpenSession*)pCtx;
21969  int i;
21970  for(i=0; i<pSession->nFilter; i++){
21971    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
21972  }
21973  return 1;
21974}
21975#endif
21976
21977/*
21978** Try to deduce the type of file for zName based on its content.  Return
21979** one of the SHELL_OPEN_* constants.
21980**
21981** If the file does not exist or is empty but its name looks like a ZIP
21982** archive and the dfltZip flag is true, then assume it is a ZIP archive.
21983** Otherwise, assume an ordinary database regardless of the filename if
21984** the type cannot be determined from content.
21985*/
21986static int deduceDatabaseType(const char *zName, int dfltZip){
21987  FILE *f = fopen(zName, "rb");
21988  size_t n;
21989  int rc = SHELL_OPEN_UNSPEC;
21990  char zBuf[100];
21991  if( f==0 ){
21992    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
21993       return SHELL_OPEN_ZIPFILE;
21994    }else{
21995       return SHELL_OPEN_NORMAL;
21996    }
21997  }
21998  n = fread(zBuf, 16, 1, f);
21999  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
22000    fclose(f);
22001    return SHELL_OPEN_NORMAL;
22002  }
22003  fseek(f, -25, SEEK_END);
22004  n = fread(zBuf, 25, 1, f);
22005  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
22006    rc = SHELL_OPEN_APPENDVFS;
22007  }else{
22008    fseek(f, -22, SEEK_END);
22009    n = fread(zBuf, 22, 1, f);
22010    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
22011       && zBuf[3]==0x06 ){
22012      rc = SHELL_OPEN_ZIPFILE;
22013    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
22014      rc = SHELL_OPEN_ZIPFILE;
22015    }
22016  }
22017  fclose(f);
22018  return rc;
22019}
22020
22021#ifndef SQLITE_OMIT_DESERIALIZE
22022/*
22023** Reconstruct an in-memory database using the output from the "dbtotxt"
22024** program.  Read content from the file in p->aAuxDb[].zDbFilename.
22025** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
22026*/
22027static unsigned char *readHexDb(ShellState *p, int *pnData){
22028  unsigned char *a = 0;
22029  int nLine;
22030  int n = 0;
22031  int pgsz = 0;
22032  int iOffset = 0;
22033  int j, k;
22034  int rc;
22035  FILE *in;
22036  const char *zDbFilename = p->pAuxDb->zDbFilename;
22037  unsigned int x[16];
22038  char zLine[1000];
22039  if( zDbFilename ){
22040    in = fopen(zDbFilename, "r");
22041    if( in==0 ){
22042      eputf("cannot open \"%s\" for reading\n", zDbFilename);
22043      return 0;
22044    }
22045    nLine = 0;
22046  }else{
22047    in = p->in;
22048    nLine = p->lineno;
22049    if( in==0 ) in = stdin;
22050  }
22051  *pnData = 0;
22052  nLine++;
22053  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
22054  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
22055  if( rc!=2 ) goto readHexDb_error;
22056  if( n<0 ) goto readHexDb_error;
22057  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
22058  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
22059  a = sqlite3_malloc( n ? n : 1 );
22060  shell_check_oom(a);
22061  memset(a, 0, n);
22062  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
22063    eputz("invalid pagesize\n");
22064    goto readHexDb_error;
22065  }
22066  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
22067    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
22068    if( rc==2 ){
22069      iOffset = k;
22070      continue;
22071    }
22072    if( cli_strncmp(zLine, "| end ", 6)==0 ){
22073      break;
22074    }
22075    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
22076                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
22077                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
22078    if( rc==17 ){
22079      k = iOffset+j;
22080      if( k+16<=n && k>=0 ){
22081        int ii;
22082        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
22083      }
22084    }
22085  }
22086  *pnData = n;
22087  if( in!=p->in ){
22088    fclose(in);
22089  }else{
22090    p->lineno = nLine;
22091  }
22092  return a;
22093
22094readHexDb_error:
22095  if( in!=p->in ){
22096    fclose(in);
22097  }else{
22098    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
22099      nLine++;
22100      if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
22101    }
22102    p->lineno = nLine;
22103  }
22104  sqlite3_free(a);
22105  eputf("Error on line %d of --hexdb input\n", nLine);
22106  return 0;
22107}
22108#endif /* SQLITE_OMIT_DESERIALIZE */
22109
22110/*
22111** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
22112*/
22113static void shellUSleepFunc(
22114  sqlite3_context *context,
22115  int argcUnused,
22116  sqlite3_value **argv
22117){
22118  int sleep = sqlite3_value_int(argv[0]);
22119  (void)argcUnused;
22120  sqlite3_sleep(sleep/1000);
22121  sqlite3_result_int(context, sleep);
22122}
22123
22124/* Flags for open_db().
22125**
22126** The default behavior of open_db() is to exit(1) if the database fails to
22127** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
22128** but still returns without calling exit.
22129**
22130** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
22131** ZIP archive if the file does not exist or is empty and its name matches
22132** the *.zip pattern.
22133*/
22134#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
22135#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
22136
22137/*
22138** Make sure the database is open.  If it is not, then open it.  If
22139** the database fails to open, print an error message and exit.
22140*/
22141static void open_db(ShellState *p, int openFlags){
22142  if( p->db==0 ){
22143    const char *zDbFilename = p->pAuxDb->zDbFilename;
22144    if( p->openMode==SHELL_OPEN_UNSPEC ){
22145      if( zDbFilename==0 || zDbFilename[0]==0 ){
22146        p->openMode = SHELL_OPEN_NORMAL;
22147      }else{
22148        p->openMode = (u8)deduceDatabaseType(zDbFilename,
22149                             (openFlags & OPEN_DB_ZIPFILE)!=0);
22150      }
22151    }
22152    switch( p->openMode ){
22153      case SHELL_OPEN_APPENDVFS: {
22154        sqlite3_open_v2(zDbFilename, &p->db,
22155           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
22156        break;
22157      }
22158      case SHELL_OPEN_HEXDB:
22159      case SHELL_OPEN_DESERIALIZE: {
22160        sqlite3_open(0, &p->db);
22161        break;
22162      }
22163      case SHELL_OPEN_ZIPFILE: {
22164        sqlite3_open(":memory:", &p->db);
22165        break;
22166      }
22167      case SHELL_OPEN_READONLY: {
22168        sqlite3_open_v2(zDbFilename, &p->db,
22169            SQLITE_OPEN_READONLY|p->openFlags, 0);
22170        break;
22171      }
22172      case SHELL_OPEN_UNSPEC:
22173      case SHELL_OPEN_NORMAL: {
22174        sqlite3_open_v2(zDbFilename, &p->db,
22175           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
22176        break;
22177      }
22178    }
22179    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22180      eputf("Error: unable to open database \"%s\": %s\n",
22181            zDbFilename, sqlite3_errmsg(p->db));
22182      if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
22183        exit(1);
22184      }
22185      sqlite3_close(p->db);
22186      sqlite3_open(":memory:", &p->db);
22187      if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22188        eputz("Also: unable to open substitute in-memory database.\n");
22189        exit(1);
22190      }else{
22191        eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
22192              zDbFilename);
22193      }
22194    }
22195    globalDb = p->db;
22196    sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
22197
22198    /* Reflect the use or absence of --unsafe-testing invocation. */
22199    {
22200      int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
22201      sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
22202      sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
22203    }
22204
22205#ifndef SQLITE_OMIT_LOAD_EXTENSION
22206    sqlite3_enable_load_extension(p->db, 1);
22207#endif
22208    sqlite3_shathree_init(p->db, 0, 0);
22209    sqlite3_uint_init(p->db, 0, 0);
22210    sqlite3_decimal_init(p->db, 0, 0);
22211    sqlite3_base64_init(p->db, 0, 0);
22212    sqlite3_base85_init(p->db, 0, 0);
22213    sqlite3_regexp_init(p->db, 0, 0);
22214    sqlite3_ieee_init(p->db, 0, 0);
22215    sqlite3_series_init(p->db, 0, 0);
22216#ifndef SQLITE_SHELL_FIDDLE
22217    sqlite3_fileio_init(p->db, 0, 0);
22218    sqlite3_completion_init(p->db, 0, 0);
22219#endif
22220#ifdef SQLITE_HAVE_ZLIB
22221    if( !p->bSafeModePersist ){
22222      sqlite3_zipfile_init(p->db, 0, 0);
22223      sqlite3_sqlar_init(p->db, 0, 0);
22224    }
22225#endif
22226#ifdef SQLITE_SHELL_EXTFUNCS
22227    /* Create a preprocessing mechanism for extensions to make
22228     * their own provisions for being built into the shell.
22229     * This is a short-span macro. See further below for usage.
22230     */
22231#define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
22232#define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
22233    /* Let custom-included extensions get their ..._init() called.
22234     * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
22235     * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
22236     * initialization routine to be called.
22237     */
22238    {
22239      int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
22240    /* Let custom-included extensions expose their functionality.
22241     * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
22242     * the SQL functions, virtual tables, collating sequences or
22243     * VFS's implemented by the extension to be registered.
22244     */
22245      if( irc==SQLITE_OK
22246          || irc==SQLITE_OK_LOAD_PERMANENTLY ){
22247        SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
22248      }
22249#undef SHELL_SUB_MACRO
22250#undef SHELL_SUBMACRO
22251    }
22252#endif
22253
22254    sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
22255                            shellStrtod, 0, 0);
22256    sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
22257                            shellDtostr, 0, 0);
22258    sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
22259                            shellDtostr, 0, 0);
22260    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
22261                            shellAddSchemaName, 0, 0);
22262    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
22263                            shellModuleSchema, 0, 0);
22264    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
22265                            shellPutsFunc, 0, 0);
22266    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
22267                            shellUSleepFunc, 0, 0);
22268#ifndef SQLITE_NOHAVE_SYSTEM
22269    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
22270                            editFunc, 0, 0);
22271    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
22272                            editFunc, 0, 0);
22273#endif
22274
22275    if( p->openMode==SHELL_OPEN_ZIPFILE ){
22276      char *zSql = sqlite3_mprintf(
22277         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
22278      shell_check_oom(zSql);
22279      sqlite3_exec(p->db, zSql, 0, 0, 0);
22280      sqlite3_free(zSql);
22281    }
22282#ifndef SQLITE_OMIT_DESERIALIZE
22283    else
22284    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
22285      int rc;
22286      int nData = 0;
22287      unsigned char *aData;
22288      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
22289        aData = (unsigned char*)readFile(zDbFilename, &nData);
22290      }else{
22291        aData = readHexDb(p, &nData);
22292      }
22293      if( aData==0 ){
22294        return;
22295      }
22296      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
22297                   SQLITE_DESERIALIZE_RESIZEABLE |
22298                   SQLITE_DESERIALIZE_FREEONCLOSE);
22299      if( rc ){
22300        eputf("Error: sqlite3_deserialize() returns %d\n", rc);
22301      }
22302      if( p->szMax>0 ){
22303        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
22304      }
22305    }
22306#endif
22307  }
22308  if( p->db!=0 ){
22309    if( p->bSafeModePersist ){
22310      sqlite3_set_authorizer(p->db, safeModeAuth, p);
22311    }
22312    sqlite3_db_config(
22313        p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
22314    );
22315  }
22316}
22317
22318/*
22319** Attempt to close the database connection.  Report errors.
22320*/
22321static void close_db(sqlite3 *db){
22322  int rc = sqlite3_close(db);
22323  if( rc ){
22324    eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
22325  }
22326}
22327
22328#if HAVE_READLINE || HAVE_EDITLINE
22329/*
22330** Readline completion callbacks
22331*/
22332static char *readline_completion_generator(const char *text, int state){
22333  static sqlite3_stmt *pStmt = 0;
22334  char *zRet;
22335  if( state==0 ){
22336    char *zSql;
22337    sqlite3_finalize(pStmt);
22338    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
22339                           "  FROM completion(%Q) ORDER BY 1", text);
22340    shell_check_oom(zSql);
22341    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
22342    sqlite3_free(zSql);
22343  }
22344  if( sqlite3_step(pStmt)==SQLITE_ROW ){
22345    const char *z = (const char*)sqlite3_column_text(pStmt,0);
22346    zRet = z ? strdup(z) : 0;
22347  }else{
22348    sqlite3_finalize(pStmt);
22349    pStmt = 0;
22350    zRet = 0;
22351  }
22352  return zRet;
22353}
22354static char **readline_completion(const char *zText, int iStart, int iEnd){
22355  (void)iStart;
22356  (void)iEnd;
22357  rl_attempted_completion_over = 1;
22358  return rl_completion_matches(zText, readline_completion_generator);
22359}
22360
22361#elif HAVE_LINENOISE
22362/*
22363** Linenoise completion callback
22364*/
22365static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
22366  i64 nLine = strlen(zLine);
22367  i64 i, iStart;
22368  sqlite3_stmt *pStmt = 0;
22369  char *zSql;
22370  char zBuf[1000];
22371
22372  if( nLine>(i64)sizeof(zBuf)-30 ) return;
22373  if( zLine[0]=='.' || zLine[0]=='#') return;
22374  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
22375  if( i==nLine-1 ) return;
22376  iStart = i+1;
22377  memcpy(zBuf, zLine, iStart);
22378  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
22379                         "  FROM completion(%Q,%Q) ORDER BY 1",
22380                         &zLine[iStart], zLine);
22381  shell_check_oom(zSql);
22382  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
22383  sqlite3_free(zSql);
22384  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
22385  while( sqlite3_step(pStmt)==SQLITE_ROW ){
22386    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
22387    int nCompletion = sqlite3_column_bytes(pStmt, 0);
22388    if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
22389      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
22390      linenoiseAddCompletion(lc, zBuf);
22391    }
22392  }
22393  sqlite3_finalize(pStmt);
22394}
22395#endif
22396
22397/*
22398** Do C-language style dequoting.
22399**
22400**    \a    -> alarm
22401**    \b    -> backspace
22402**    \t    -> tab
22403**    \n    -> newline
22404**    \v    -> vertical tab
22405**    \f    -> form feed
22406**    \r    -> carriage return
22407**    \s    -> space
22408**    \"    -> "
22409**    \'    -> '
22410**    \\    -> backslash
22411**    \NNN  -> ascii character NNN in octal
22412**    \xHH  -> ascii character HH in hexadecimal
22413*/
22414static void resolve_backslashes(char *z){
22415  int i, j;
22416  char c;
22417  while( *z && *z!='\\' ) z++;
22418  for(i=j=0; (c = z[i])!=0; i++, j++){
22419    if( c=='\\' && z[i+1]!=0 ){
22420      c = z[++i];
22421      if( c=='a' ){
22422        c = '\a';
22423      }else if( c=='b' ){
22424        c = '\b';
22425      }else if( c=='t' ){
22426        c = '\t';
22427      }else if( c=='n' ){
22428        c = '\n';
22429      }else if( c=='v' ){
22430        c = '\v';
22431      }else if( c=='f' ){
22432        c = '\f';
22433      }else if( c=='r' ){
22434        c = '\r';
22435      }else if( c=='"' ){
22436        c = '"';
22437      }else if( c=='\'' ){
22438        c = '\'';
22439      }else if( c=='\\' ){
22440        c = '\\';
22441      }else if( c=='x' ){
22442        int nhd = 0, hdv;
22443        u8 hv = 0;
22444        while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
22445          hv = (u8)((hv<<4)|hdv);
22446          ++nhd;
22447        }
22448        i += nhd;
22449        c = (u8)hv;
22450      }else if( c>='0' && c<='7' ){
22451        c -= '0';
22452        if( z[i+1]>='0' && z[i+1]<='7' ){
22453          i++;
22454          c = (c<<3) + z[i] - '0';
22455          if( z[i+1]>='0' && z[i+1]<='7' ){
22456            i++;
22457            c = (c<<3) + z[i] - '0';
22458          }
22459        }
22460      }
22461    }
22462    z[j] = c;
22463  }
22464  if( j<i ) z[j] = 0;
22465}
22466
22467/*
22468** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
22469** for TRUE and FALSE.  Return the integer value if appropriate.
22470*/
22471static int booleanValue(const char *zArg){
22472  int i;
22473  if( zArg[0]=='0' && zArg[1]=='x' ){
22474    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
22475  }else{
22476    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
22477  }
22478  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
22479  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
22480    return 1;
22481  }
22482  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
22483    return 0;
22484  }
22485  eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
22486  return 0;
22487}
22488
22489/*
22490** Set or clear a shell flag according to a boolean value.
22491*/
22492static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
22493  if( booleanValue(zArg) ){
22494    ShellSetFlag(p, mFlag);
22495  }else{
22496    ShellClearFlag(p, mFlag);
22497  }
22498}
22499
22500/*
22501** Close an output file, assuming it is not stderr or stdout
22502*/
22503static void output_file_close(FILE *f){
22504  if( f && f!=stdout && f!=stderr ) fclose(f);
22505}
22506
22507/*
22508** Try to open an output file.   The names "stdout" and "stderr" are
22509** recognized and do the right thing.  NULL is returned if the output
22510** filename is "off".
22511*/
22512static FILE *output_file_open(const char *zFile, int bTextMode){
22513  FILE *f;
22514  if( cli_strcmp(zFile,"stdout")==0 ){
22515    f = stdout;
22516  }else if( cli_strcmp(zFile, "stderr")==0 ){
22517    f = stderr;
22518  }else if( cli_strcmp(zFile, "off")==0 ){
22519    f = 0;
22520  }else{
22521    f = fopen(zFile, bTextMode ? "w" : "wb");
22522    if( f==0 ){
22523      eputf("Error: cannot open \"%s\"\n", zFile);
22524    }
22525  }
22526  return f;
22527}
22528
22529#ifndef SQLITE_OMIT_TRACE
22530/*
22531** A routine for handling output from sqlite3_trace().
22532*/
22533static int sql_trace_callback(
22534  unsigned mType,         /* The trace type */
22535  void *pArg,             /* The ShellState pointer */
22536  void *pP,               /* Usually a pointer to sqlite_stmt */
22537  void *pX                /* Auxiliary output */
22538){
22539  ShellState *p = (ShellState*)pArg;
22540  sqlite3_stmt *pStmt;
22541  const char *zSql;
22542  i64 nSql;
22543  if( p->traceOut==0 ) return 0;
22544  if( mType==SQLITE_TRACE_CLOSE ){
22545    sputz(p->traceOut, "-- closing database connection\n");
22546    return 0;
22547  }
22548  if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
22549    zSql = (const char*)pX;
22550  }else{
22551    pStmt = (sqlite3_stmt*)pP;
22552    switch( p->eTraceType ){
22553      case SHELL_TRACE_EXPANDED: {
22554        zSql = sqlite3_expanded_sql(pStmt);
22555        break;
22556      }
22557#ifdef SQLITE_ENABLE_NORMALIZE
22558      case SHELL_TRACE_NORMALIZED: {
22559        zSql = sqlite3_normalized_sql(pStmt);
22560        break;
22561      }
22562#endif
22563      default: {
22564        zSql = sqlite3_sql(pStmt);
22565        break;
22566      }
22567    }
22568  }
22569  if( zSql==0 ) return 0;
22570  nSql = strlen(zSql);
22571  if( nSql>1000000000 ) nSql = 1000000000;
22572  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
22573  switch( mType ){
22574    case SQLITE_TRACE_ROW:
22575    case SQLITE_TRACE_STMT: {
22576      sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
22577      break;
22578    }
22579    case SQLITE_TRACE_PROFILE: {
22580      sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
22581      sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
22582      break;
22583    }
22584  }
22585  return 0;
22586}
22587#endif
22588
22589/*
22590** A no-op routine that runs with the ".breakpoint" doc-command.  This is
22591** a useful spot to set a debugger breakpoint.
22592**
22593** This routine does not do anything practical.  The code are there simply
22594** to prevent the compiler from optimizing this routine out.
22595*/
22596static void test_breakpoint(void){
22597  static unsigned int nCall = 0;
22598  if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
22599}
22600
22601/*
22602** An object used to read a CSV and other files for import.
22603*/
22604typedef struct ImportCtx ImportCtx;
22605struct ImportCtx {
22606  const char *zFile;  /* Name of the input file */
22607  FILE *in;           /* Read the CSV text from this input stream */
22608  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
22609  char *z;            /* Accumulated text for a field */
22610  int n;              /* Number of bytes in z */
22611  int nAlloc;         /* Space allocated for z[] */
22612  int nLine;          /* Current line number */
22613  int nRow;           /* Number of rows imported */
22614  int nErr;           /* Number of errors encountered */
22615  int bNotFirst;      /* True if one or more bytes already read */
22616  int cTerm;          /* Character that terminated the most recent field */
22617  int cColSep;        /* The column separator character.  (Usually ",") */
22618  int cRowSep;        /* The row separator character.  (Usually "\n") */
22619};
22620
22621/* Clean up resourced used by an ImportCtx */
22622static void import_cleanup(ImportCtx *p){
22623  if( p->in!=0 && p->xCloser!=0 ){
22624    p->xCloser(p->in);
22625    p->in = 0;
22626  }
22627  sqlite3_free(p->z);
22628  p->z = 0;
22629}
22630
22631/* Append a single byte to z[] */
22632static void import_append_char(ImportCtx *p, int c){
22633  if( p->n+1>=p->nAlloc ){
22634    p->nAlloc += p->nAlloc + 100;
22635    p->z = sqlite3_realloc64(p->z, p->nAlloc);
22636    shell_check_oom(p->z);
22637  }
22638  p->z[p->n++] = (char)c;
22639}
22640
22641/* Read a single field of CSV text.  Compatible with rfc4180 and extended
22642** with the option of having a separator other than ",".
22643**
22644**   +  Input comes from p->in.
22645**   +  Store results in p->z of length p->n.  Space to hold p->z comes
22646**      from sqlite3_malloc64().
22647**   +  Use p->cSep as the column separator.  The default is ",".
22648**   +  Use p->rSep as the row separator.  The default is "\n".
22649**   +  Keep track of the line number in p->nLine.
22650**   +  Store the character that terminates the field in p->cTerm.  Store
22651**      EOF on end-of-file.
22652**   +  Report syntax errors on stderr
22653*/
22654static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
22655  int c;
22656  int cSep = (u8)p->cColSep;
22657  int rSep = (u8)p->cRowSep;
22658  p->n = 0;
22659  c = fgetc(p->in);
22660  if( c==EOF || seenInterrupt ){
22661    p->cTerm = EOF;
22662    return 0;
22663  }
22664  if( c=='"' ){
22665    int pc, ppc;
22666    int startLine = p->nLine;
22667    int cQuote = c;
22668    pc = ppc = 0;
22669    while( 1 ){
22670      c = fgetc(p->in);
22671      if( c==rSep ) p->nLine++;
22672      if( c==cQuote ){
22673        if( pc==cQuote ){
22674          pc = 0;
22675          continue;
22676        }
22677      }
22678      if( (c==cSep && pc==cQuote)
22679       || (c==rSep && pc==cQuote)
22680       || (c==rSep && pc=='\r' && ppc==cQuote)
22681       || (c==EOF && pc==cQuote)
22682      ){
22683        do{ p->n--; }while( p->z[p->n]!=cQuote );
22684        p->cTerm = c;
22685        break;
22686      }
22687      if( pc==cQuote && c!='\r' ){
22688        eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
22689      }
22690      if( c==EOF ){
22691        eputf("%s:%d: unterminated %c-quoted field\n",
22692              p->zFile, startLine, cQuote);
22693        p->cTerm = c;
22694        break;
22695      }
22696      import_append_char(p, c);
22697      ppc = pc;
22698      pc = c;
22699    }
22700  }else{
22701    /* If this is the first field being parsed and it begins with the
22702    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
22703    if( (c&0xff)==0xef && p->bNotFirst==0 ){
22704      import_append_char(p, c);
22705      c = fgetc(p->in);
22706      if( (c&0xff)==0xbb ){
22707        import_append_char(p, c);
22708        c = fgetc(p->in);
22709        if( (c&0xff)==0xbf ){
22710          p->bNotFirst = 1;
22711          p->n = 0;
22712          return csv_read_one_field(p);
22713        }
22714      }
22715    }
22716    while( c!=EOF && c!=cSep && c!=rSep ){
22717      import_append_char(p, c);
22718      c = fgetc(p->in);
22719    }
22720    if( c==rSep ){
22721      p->nLine++;
22722      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
22723    }
22724    p->cTerm = c;
22725  }
22726  if( p->z ) p->z[p->n] = 0;
22727  p->bNotFirst = 1;
22728  return p->z;
22729}
22730
22731/* Read a single field of ASCII delimited text.
22732**
22733**   +  Input comes from p->in.
22734**   +  Store results in p->z of length p->n.  Space to hold p->z comes
22735**      from sqlite3_malloc64().
22736**   +  Use p->cSep as the column separator.  The default is "\x1F".
22737**   +  Use p->rSep as the row separator.  The default is "\x1E".
22738**   +  Keep track of the row number in p->nLine.
22739**   +  Store the character that terminates the field in p->cTerm.  Store
22740**      EOF on end-of-file.
22741**   +  Report syntax errors on stderr
22742*/
22743static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
22744  int c;
22745  int cSep = (u8)p->cColSep;
22746  int rSep = (u8)p->cRowSep;
22747  p->n = 0;
22748  c = fgetc(p->in);
22749  if( c==EOF || seenInterrupt ){
22750    p->cTerm = EOF;
22751    return 0;
22752  }
22753  while( c!=EOF && c!=cSep && c!=rSep ){
22754    import_append_char(p, c);
22755    c = fgetc(p->in);
22756  }
22757  if( c==rSep ){
22758    p->nLine++;
22759  }
22760  p->cTerm = c;
22761  if( p->z ) p->z[p->n] = 0;
22762  return p->z;
22763}
22764
22765/*
22766** Try to transfer data for table zTable.  If an error is seen while
22767** moving forward, try to go backwards.  The backwards movement won't
22768** work for WITHOUT ROWID tables.
22769*/
22770static void tryToCloneData(
22771  ShellState *p,
22772  sqlite3 *newDb,
22773  const char *zTable
22774){
22775  sqlite3_stmt *pQuery = 0;
22776  sqlite3_stmt *pInsert = 0;
22777  char *zQuery = 0;
22778  char *zInsert = 0;
22779  int rc;
22780  int i, j, n;
22781  int nTable = strlen30(zTable);
22782  int k = 0;
22783  int cnt = 0;
22784  const int spinRate = 10000;
22785
22786  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
22787  shell_check_oom(zQuery);
22788  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22789  if( rc ){
22790    eputf("Error %d: %s on [%s]\n",
22791          sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
22792    goto end_data_xfer;
22793  }
22794  n = sqlite3_column_count(pQuery);
22795  zInsert = sqlite3_malloc64(200 + nTable + n*3);
22796  shell_check_oom(zInsert);
22797  sqlite3_snprintf(200+nTable,zInsert,
22798                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
22799  i = strlen30(zInsert);
22800  for(j=1; j<n; j++){
22801    memcpy(zInsert+i, ",?", 2);
22802    i += 2;
22803  }
22804  memcpy(zInsert+i, ");", 3);
22805  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
22806  if( rc ){
22807    eputf("Error %d: %s on [%s]\n",
22808          sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
22809    goto end_data_xfer;
22810  }
22811  for(k=0; k<2; k++){
22812    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22813      for(i=0; i<n; i++){
22814        switch( sqlite3_column_type(pQuery, i) ){
22815          case SQLITE_NULL: {
22816            sqlite3_bind_null(pInsert, i+1);
22817            break;
22818          }
22819          case SQLITE_INTEGER: {
22820            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
22821            break;
22822          }
22823          case SQLITE_FLOAT: {
22824            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
22825            break;
22826          }
22827          case SQLITE_TEXT: {
22828            sqlite3_bind_text(pInsert, i+1,
22829                             (const char*)sqlite3_column_text(pQuery,i),
22830                             -1, SQLITE_STATIC);
22831            break;
22832          }
22833          case SQLITE_BLOB: {
22834            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
22835                                            sqlite3_column_bytes(pQuery,i),
22836                                            SQLITE_STATIC);
22837            break;
22838          }
22839        }
22840      } /* End for */
22841      rc = sqlite3_step(pInsert);
22842      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
22843        eputf("Error %d: %s\n",
22844              sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
22845      }
22846      sqlite3_reset(pInsert);
22847      cnt++;
22848      if( (cnt%spinRate)==0 ){
22849        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
22850        fflush(stdout);
22851      }
22852    } /* End while */
22853    if( rc==SQLITE_DONE ) break;
22854    sqlite3_finalize(pQuery);
22855    sqlite3_free(zQuery);
22856    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
22857                             zTable);
22858    shell_check_oom(zQuery);
22859    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22860    if( rc ){
22861      eputf("Warning: cannot step \"%s\" backwards", zTable);
22862      break;
22863    }
22864  } /* End for(k=0...) */
22865
22866end_data_xfer:
22867  sqlite3_finalize(pQuery);
22868  sqlite3_finalize(pInsert);
22869  sqlite3_free(zQuery);
22870  sqlite3_free(zInsert);
22871}
22872
22873
22874/*
22875** Try to transfer all rows of the schema that match zWhere.  For
22876** each row, invoke xForEach() on the object defined by that row.
22877** If an error is encountered while moving forward through the
22878** sqlite_schema table, try again moving backwards.
22879*/
22880static void tryToCloneSchema(
22881  ShellState *p,
22882  sqlite3 *newDb,
22883  const char *zWhere,
22884  void (*xForEach)(ShellState*,sqlite3*,const char*)
22885){
22886  sqlite3_stmt *pQuery = 0;
22887  char *zQuery = 0;
22888  int rc;
22889  const unsigned char *zName;
22890  const unsigned char *zSql;
22891  char *zErrMsg = 0;
22892
22893  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22894                           " WHERE %s ORDER BY rowid ASC", zWhere);
22895  shell_check_oom(zQuery);
22896  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22897  if( rc ){
22898    eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
22899          sqlite3_errmsg(p->db), zQuery);
22900    goto end_schema_xfer;
22901  }
22902  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22903    zName = sqlite3_column_text(pQuery, 0);
22904    zSql = sqlite3_column_text(pQuery, 1);
22905    if( zName==0 || zSql==0 ) continue;
22906    if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
22907      sputf(stdout, "%s... ", zName); fflush(stdout);
22908      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22909      if( zErrMsg ){
22910        eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22911        sqlite3_free(zErrMsg);
22912        zErrMsg = 0;
22913      }
22914    }
22915    if( xForEach ){
22916      xForEach(p, newDb, (const char*)zName);
22917    }
22918    sputz(stdout, "done\n");
22919  }
22920  if( rc!=SQLITE_DONE ){
22921    sqlite3_finalize(pQuery);
22922    sqlite3_free(zQuery);
22923    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22924                             " WHERE %s ORDER BY rowid DESC", zWhere);
22925    shell_check_oom(zQuery);
22926    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22927    if( rc ){
22928      eputf("Error: (%d) %s on [%s]\n",
22929            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
22930      goto end_schema_xfer;
22931    }
22932    while( sqlite3_step(pQuery)==SQLITE_ROW ){
22933      zName = sqlite3_column_text(pQuery, 0);
22934      zSql = sqlite3_column_text(pQuery, 1);
22935      if( zName==0 || zSql==0 ) continue;
22936      if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
22937      sputf(stdout, "%s... ", zName); fflush(stdout);
22938      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22939      if( zErrMsg ){
22940        eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22941        sqlite3_free(zErrMsg);
22942        zErrMsg = 0;
22943      }
22944      if( xForEach ){
22945        xForEach(p, newDb, (const char*)zName);
22946      }
22947      sputz(stdout, "done\n");
22948    }
22949  }
22950end_schema_xfer:
22951  sqlite3_finalize(pQuery);
22952  sqlite3_free(zQuery);
22953}
22954
22955/*
22956** Open a new database file named "zNewDb".  Try to recover as much information
22957** as possible out of the main database (which might be corrupt) and write it
22958** into zNewDb.
22959*/
22960static void tryToClone(ShellState *p, const char *zNewDb){
22961  int rc;
22962  sqlite3 *newDb = 0;
22963  if( access(zNewDb,0)==0 ){
22964    eputf("File \"%s\" already exists.\n", zNewDb);
22965    return;
22966  }
22967  rc = sqlite3_open(zNewDb, &newDb);
22968  if( rc ){
22969    eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
22970  }else{
22971    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
22972    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
22973    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
22974    tryToCloneSchema(p, newDb, "type!='table'", 0);
22975    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
22976    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
22977  }
22978  close_db(newDb);
22979}
22980
22981#ifndef SQLITE_SHELL_FIDDLE
22982/*
22983** Change the output stream (file or pipe or console) to something else.
22984*/
22985static void output_redir(ShellState *p, FILE *pfNew){
22986  if( p->out != stdout ) eputz("Output already redirected.\n");
22987  else{
22988    p->out = pfNew;
22989    setOutputStream(pfNew);
22990  }
22991}
22992
22993/*
22994** Change the output file back to stdout.
22995**
22996** If the p->doXdgOpen flag is set, that means the output was being
22997** redirected to a temporary file named by p->zTempFile.  In that case,
22998** launch start/open/xdg-open on that temporary file.
22999*/
23000static void output_reset(ShellState *p){
23001  if( p->outfile[0]=='|' ){
23002#ifndef SQLITE_OMIT_POPEN
23003    pclose(p->out);
23004#endif
23005  }else{
23006    output_file_close(p->out);
23007#ifndef SQLITE_NOHAVE_SYSTEM
23008    if( p->doXdgOpen ){
23009      const char *zXdgOpenCmd =
23010#if defined(_WIN32)
23011      "start";
23012#elif defined(__APPLE__)
23013      "open";
23014#else
23015      "xdg-open";
23016#endif
23017      char *zCmd;
23018      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
23019      if( system(zCmd) ){
23020        eputf("Failed: [%s]\n", zCmd);
23021      }else{
23022        /* Give the start/open/xdg-open command some time to get
23023        ** going before we continue, and potential delete the
23024        ** p->zTempFile data file out from under it */
23025        sqlite3_sleep(2000);
23026      }
23027      sqlite3_free(zCmd);
23028      outputModePop(p);
23029      p->doXdgOpen = 0;
23030    }
23031#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
23032  }
23033  p->outfile[0] = 0;
23034  p->out = stdout;
23035  setOutputStream(stdout);
23036}
23037#else
23038# define output_redir(SS,pfO)
23039# define output_reset(SS)
23040#endif
23041
23042/*
23043** Run an SQL command and return the single integer result.
23044*/
23045static int db_int(sqlite3 *db, const char *zSql){
23046  sqlite3_stmt *pStmt;
23047  int res = 0;
23048  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
23049  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
23050    res = sqlite3_column_int(pStmt,0);
23051  }
23052  sqlite3_finalize(pStmt);
23053  return res;
23054}
23055
23056#if SQLITE_SHELL_HAVE_RECOVER
23057/*
23058** Convert a 2-byte or 4-byte big-endian integer into a native integer
23059*/
23060static unsigned int get2byteInt(unsigned char *a){
23061  return (a[0]<<8) + a[1];
23062}
23063static unsigned int get4byteInt(unsigned char *a){
23064  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
23065}
23066
23067/*
23068** Implementation of the ".dbinfo" command.
23069**
23070** Return 1 on error, 2 to exit, and 0 otherwise.
23071*/
23072static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
23073  static const struct { const char *zName; int ofst; } aField[] = {
23074     { "file change counter:",  24  },
23075     { "database page count:",  28  },
23076     { "freelist page count:",  36  },
23077     { "schema cookie:",        40  },
23078     { "schema format:",        44  },
23079     { "default cache size:",   48  },
23080     { "autovacuum top root:",  52  },
23081     { "incremental vacuum:",   64  },
23082     { "text encoding:",        56  },
23083     { "user version:",         60  },
23084     { "application id:",       68  },
23085     { "software version:",     96  },
23086  };
23087  static const struct { const char *zName; const char *zSql; } aQuery[] = {
23088     { "number of tables:",
23089       "SELECT count(*) FROM %s WHERE type='table'" },
23090     { "number of indexes:",
23091       "SELECT count(*) FROM %s WHERE type='index'" },
23092     { "number of triggers:",
23093       "SELECT count(*) FROM %s WHERE type='trigger'" },
23094     { "number of views:",
23095       "SELECT count(*) FROM %s WHERE type='view'" },
23096     { "schema size:",
23097       "SELECT total(length(sql)) FROM %s" },
23098  };
23099  int i, rc;
23100  unsigned iDataVersion;
23101  char *zSchemaTab;
23102  char *zDb = nArg>=2 ? azArg[1] : "main";
23103  sqlite3_stmt *pStmt = 0;
23104  unsigned char aHdr[100];
23105  open_db(p, 0);
23106  if( p->db==0 ) return 1;
23107  rc = sqlite3_prepare_v2(p->db,
23108             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
23109             -1, &pStmt, 0);
23110  if( rc ){
23111    eputf("error: %s\n", sqlite3_errmsg(p->db));
23112    sqlite3_finalize(pStmt);
23113    return 1;
23114  }
23115  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
23116  if( sqlite3_step(pStmt)==SQLITE_ROW
23117   && sqlite3_column_bytes(pStmt,0)>100
23118  ){
23119    const u8 *pb = sqlite3_column_blob(pStmt,0);
23120    shell_check_oom(pb);
23121    memcpy(aHdr, pb, 100);
23122    sqlite3_finalize(pStmt);
23123  }else{
23124    eputz("unable to read database header\n");
23125    sqlite3_finalize(pStmt);
23126    return 1;
23127  }
23128  i = get2byteInt(aHdr+16);
23129  if( i==1 ) i = 65536;
23130  oputf("%-20s %d\n", "database page size:", i);
23131  oputf("%-20s %d\n", "write format:", aHdr[18]);
23132  oputf("%-20s %d\n", "read format:", aHdr[19]);
23133  oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
23134  for(i=0; i<ArraySize(aField); i++){
23135    int ofst = aField[i].ofst;
23136    unsigned int val = get4byteInt(aHdr + ofst);
23137    oputf("%-20s %u", aField[i].zName, val);
23138    switch( ofst ){
23139      case 56: {
23140        if( val==1 ) oputz(" (utf8)");
23141        if( val==2 ) oputz(" (utf16le)");
23142        if( val==3 ) oputz(" (utf16be)");
23143      }
23144    }
23145    oputz("\n");
23146  }
23147  if( zDb==0 ){
23148    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
23149  }else if( cli_strcmp(zDb,"temp")==0 ){
23150    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
23151  }else{
23152    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
23153  }
23154  for(i=0; i<ArraySize(aQuery); i++){
23155    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
23156    int val = db_int(p->db, zSql);
23157    sqlite3_free(zSql);
23158    oputf("%-20s %d\n", aQuery[i].zName, val);
23159  }
23160  sqlite3_free(zSchemaTab);
23161  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
23162  oputf("%-20s %u\n", "data version", iDataVersion);
23163  return 0;
23164}
23165#endif /* SQLITE_SHELL_HAVE_RECOVER */
23166
23167/*
23168** Print the current sqlite3_errmsg() value to stderr and return 1.
23169*/
23170static int shellDatabaseError(sqlite3 *db){
23171  const char *zErr = sqlite3_errmsg(db);
23172  eputf("Error: %s\n", zErr);
23173  return 1;
23174}
23175
23176/*
23177** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
23178** if they match and FALSE (0) if they do not match.
23179**
23180** Globbing rules:
23181**
23182**      '*'       Matches any sequence of zero or more characters.
23183**
23184**      '?'       Matches exactly one character.
23185**
23186**     [...]      Matches one character from the enclosed list of
23187**                characters.
23188**
23189**     [^...]     Matches one character not in the enclosed list.
23190**
23191**      '#'       Matches any sequence of one or more digits with an
23192**                optional + or - sign in front
23193**
23194**      ' '       Any span of whitespace matches any other span of
23195**                whitespace.
23196**
23197** Extra whitespace at the end of z[] is ignored.
23198*/
23199static int testcase_glob(const char *zGlob, const char *z){
23200  int c, c2;
23201  int invert;
23202  int seen;
23203
23204  while( (c = (*(zGlob++)))!=0 ){
23205    if( IsSpace(c) ){
23206      if( !IsSpace(*z) ) return 0;
23207      while( IsSpace(*zGlob) ) zGlob++;
23208      while( IsSpace(*z) ) z++;
23209    }else if( c=='*' ){
23210      while( (c=(*(zGlob++))) == '*' || c=='?' ){
23211        if( c=='?' && (*(z++))==0 ) return 0;
23212      }
23213      if( c==0 ){
23214        return 1;
23215      }else if( c=='[' ){
23216        while( *z && testcase_glob(zGlob-1,z)==0 ){
23217          z++;
23218        }
23219        return (*z)!=0;
23220      }
23221      while( (c2 = (*(z++)))!=0 ){
23222        while( c2!=c ){
23223          c2 = *(z++);
23224          if( c2==0 ) return 0;
23225        }
23226        if( testcase_glob(zGlob,z) ) return 1;
23227      }
23228      return 0;
23229    }else if( c=='?' ){
23230      if( (*(z++))==0 ) return 0;
23231    }else if( c=='[' ){
23232      int prior_c = 0;
23233      seen = 0;
23234      invert = 0;
23235      c = *(z++);
23236      if( c==0 ) return 0;
23237      c2 = *(zGlob++);
23238      if( c2=='^' ){
23239        invert = 1;
23240        c2 = *(zGlob++);
23241      }
23242      if( c2==']' ){
23243        if( c==']' ) seen = 1;
23244        c2 = *(zGlob++);
23245      }
23246      while( c2 && c2!=']' ){
23247        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
23248          c2 = *(zGlob++);
23249          if( c>=prior_c && c<=c2 ) seen = 1;
23250          prior_c = 0;
23251        }else{
23252          if( c==c2 ){
23253            seen = 1;
23254          }
23255          prior_c = c2;
23256        }
23257        c2 = *(zGlob++);
23258      }
23259      if( c2==0 || (seen ^ invert)==0 ) return 0;
23260    }else if( c=='#' ){
23261      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
23262      if( !IsDigit(z[0]) ) return 0;
23263      z++;
23264      while( IsDigit(z[0]) ){ z++; }
23265    }else{
23266      if( c!=(*(z++)) ) return 0;
23267    }
23268  }
23269  while( IsSpace(*z) ){ z++; }
23270  return *z==0;
23271}
23272
23273
23274/*
23275** Compare the string as a command-line option with either one or two
23276** initial "-" characters.
23277*/
23278static int optionMatch(const char *zStr, const char *zOpt){
23279  if( zStr[0]!='-' ) return 0;
23280  zStr++;
23281  if( zStr[0]=='-' ) zStr++;
23282  return cli_strcmp(zStr, zOpt)==0;
23283}
23284
23285/*
23286** Delete a file.
23287*/
23288static int shellDeleteFile(const char *zFilename){
23289  int rc;
23290#ifdef _WIN32
23291  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
23292  rc = _wunlink(z);
23293  sqlite3_free(z);
23294#else
23295  rc = unlink(zFilename);
23296#endif
23297  return rc;
23298}
23299
23300/*
23301** Try to delete the temporary file (if there is one) and free the
23302** memory used to hold the name of the temp file.
23303*/
23304static void clearTempFile(ShellState *p){
23305  if( p->zTempFile==0 ) return;
23306  if( p->doXdgOpen ) return;
23307  if( shellDeleteFile(p->zTempFile) ) return;
23308  sqlite3_free(p->zTempFile);
23309  p->zTempFile = 0;
23310}
23311
23312/*
23313** Create a new temp file name with the given suffix.
23314*/
23315static void newTempFile(ShellState *p, const char *zSuffix){
23316  clearTempFile(p);
23317  sqlite3_free(p->zTempFile);
23318  p->zTempFile = 0;
23319  if( p->db ){
23320    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
23321  }
23322  if( p->zTempFile==0 ){
23323    /* If p->db is an in-memory database then the TEMPFILENAME file-control
23324    ** will not work and we will need to fallback to guessing */
23325    char *zTemp;
23326    sqlite3_uint64 r;
23327    sqlite3_randomness(sizeof(r), &r);
23328    zTemp = getenv("TEMP");
23329    if( zTemp==0 ) zTemp = getenv("TMP");
23330    if( zTemp==0 ){
23331#ifdef _WIN32
23332      zTemp = "\\tmp";
23333#else
23334      zTemp = "/tmp";
23335#endif
23336    }
23337    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
23338  }else{
23339    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
23340  }
23341  shell_check_oom(p->zTempFile);
23342}
23343
23344
23345/*
23346** The implementation of SQL scalar function fkey_collate_clause(), used
23347** by the ".lint fkey-indexes" command. This scalar function is always
23348** called with four arguments - the parent table name, the parent column name,
23349** the child table name and the child column name.
23350**
23351**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
23352**
23353** If either of the named tables or columns do not exist, this function
23354** returns an empty string. An empty string is also returned if both tables
23355** and columns exist but have the same default collation sequence. Or,
23356** if both exist but the default collation sequences are different, this
23357** function returns the string " COLLATE <parent-collation>", where
23358** <parent-collation> is the default collation sequence of the parent column.
23359*/
23360static void shellFkeyCollateClause(
23361  sqlite3_context *pCtx,
23362  int nVal,
23363  sqlite3_value **apVal
23364){
23365  sqlite3 *db = sqlite3_context_db_handle(pCtx);
23366  const char *zParent;
23367  const char *zParentCol;
23368  const char *zParentSeq;
23369  const char *zChild;
23370  const char *zChildCol;
23371  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
23372  int rc;
23373
23374  assert( nVal==4 );
23375  zParent = (const char*)sqlite3_value_text(apVal[0]);
23376  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
23377  zChild = (const char*)sqlite3_value_text(apVal[2]);
23378  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
23379
23380  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
23381  rc = sqlite3_table_column_metadata(
23382      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
23383  );
23384  if( rc==SQLITE_OK ){
23385    rc = sqlite3_table_column_metadata(
23386        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
23387    );
23388  }
23389
23390  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
23391    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
23392    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
23393    sqlite3_free(z);
23394  }
23395}
23396
23397
23398/*
23399** The implementation of dot-command ".lint fkey-indexes".
23400*/
23401static int lintFkeyIndexes(
23402  ShellState *pState,             /* Current shell tool state */
23403  char **azArg,                   /* Array of arguments passed to dot command */
23404  int nArg                        /* Number of entries in azArg[] */
23405){
23406  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
23407  int bVerbose = 0;               /* If -verbose is present */
23408  int bGroupByParent = 0;         /* If -groupbyparent is present */
23409  int i;                          /* To iterate through azArg[] */
23410  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
23411  int rc;                         /* Return code */
23412  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
23413
23414  /*
23415  ** This SELECT statement returns one row for each foreign key constraint
23416  ** in the schema of the main database. The column values are:
23417  **
23418  ** 0. The text of an SQL statement similar to:
23419  **
23420  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
23421  **
23422  **    This SELECT is similar to the one that the foreign keys implementation
23423  **    needs to run internally on child tables. If there is an index that can
23424  **    be used to optimize this query, then it can also be used by the FK
23425  **    implementation to optimize DELETE or UPDATE statements on the parent
23426  **    table.
23427  **
23428  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
23429  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
23430  **    contains an index that can be used to optimize the query.
23431  **
23432  ** 2. Human readable text that describes the child table and columns. e.g.
23433  **
23434  **       "child_table(child_key1, child_key2)"
23435  **
23436  ** 3. Human readable text that describes the parent table and columns. e.g.
23437  **
23438  **       "parent_table(parent_key1, parent_key2)"
23439  **
23440  ** 4. A full CREATE INDEX statement for an index that could be used to
23441  **    optimize DELETE or UPDATE statements on the parent table. e.g.
23442  **
23443  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
23444  **
23445  ** 5. The name of the parent table.
23446  **
23447  ** These six values are used by the C logic below to generate the report.
23448  */
23449  const char *zSql =
23450  "SELECT "
23451    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
23452    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
23453    "  || fkey_collate_clause("
23454    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
23455    ", "
23456    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
23457    "  || group_concat('*=?', ' AND ') || ')'"
23458    ", "
23459    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
23460    ", "
23461    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
23462    ", "
23463    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
23464    "  || ' ON ' || quote(s.name) || '('"
23465    "  || group_concat(quote(f.[from]) ||"
23466    "        fkey_collate_clause("
23467    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
23468    "  || ');'"
23469    ", "
23470    "     f.[table] "
23471    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
23472    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
23473    "GROUP BY s.name, f.id "
23474    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
23475  ;
23476  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
23477
23478  for(i=2; i<nArg; i++){
23479    int n = strlen30(azArg[i]);
23480    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
23481      bVerbose = 1;
23482    }
23483    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
23484      bGroupByParent = 1;
23485      zIndent = "    ";
23486    }
23487    else{
23488      eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
23489      return SQLITE_ERROR;
23490    }
23491  }
23492
23493  /* Register the fkey_collate_clause() SQL function */
23494  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
23495      0, shellFkeyCollateClause, 0, 0
23496  );
23497
23498
23499  if( rc==SQLITE_OK ){
23500    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
23501  }
23502  if( rc==SQLITE_OK ){
23503    sqlite3_bind_int(pSql, 1, bGroupByParent);
23504  }
23505
23506  if( rc==SQLITE_OK ){
23507    int rc2;
23508    char *zPrev = 0;
23509    while( SQLITE_ROW==sqlite3_step(pSql) ){
23510      int res = -1;
23511      sqlite3_stmt *pExplain = 0;
23512      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
23513      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
23514      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
23515      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
23516      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
23517      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
23518
23519      if( zEQP==0 ) continue;
23520      if( zGlob==0 ) continue;
23521      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
23522      if( rc!=SQLITE_OK ) break;
23523      if( SQLITE_ROW==sqlite3_step(pExplain) ){
23524        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
23525        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
23526                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
23527      }
23528      rc = sqlite3_finalize(pExplain);
23529      if( rc!=SQLITE_OK ) break;
23530
23531      if( res<0 ){
23532        eputz("Error: internal error");
23533        break;
23534      }else{
23535        if( bGroupByParent
23536        && (bVerbose || res==0)
23537        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
23538        ){
23539          oputf("-- Parent table %s\n", zParent);
23540          sqlite3_free(zPrev);
23541          zPrev = sqlite3_mprintf("%s", zParent);
23542        }
23543
23544        if( res==0 ){
23545          oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
23546        }else if( bVerbose ){
23547          oputf("%s/* no extra indexes required for %s -> %s */\n",
23548                zIndent, zFrom, zTarget
23549          );
23550        }
23551      }
23552    }
23553    sqlite3_free(zPrev);
23554
23555    if( rc!=SQLITE_OK ){
23556      eputf("%s\n", sqlite3_errmsg(db));
23557    }
23558
23559    rc2 = sqlite3_finalize(pSql);
23560    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
23561      rc = rc2;
23562      eputf("%s\n", sqlite3_errmsg(db));
23563    }
23564  }else{
23565    eputf("%s\n", sqlite3_errmsg(db));
23566  }
23567
23568  return rc;
23569}
23570
23571/*
23572** Implementation of ".lint" dot command.
23573*/
23574static int lintDotCommand(
23575  ShellState *pState,             /* Current shell tool state */
23576  char **azArg,                   /* Array of arguments passed to dot command */
23577  int nArg                        /* Number of entries in azArg[] */
23578){
23579  int n;
23580  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
23581  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
23582  return lintFkeyIndexes(pState, azArg, nArg);
23583
23584 usage:
23585  eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
23586  eputz("Where sub-commands are:\n");
23587  eputz("    fkey-indexes\n");
23588  return SQLITE_ERROR;
23589}
23590
23591static void shellPrepare(
23592  sqlite3 *db,
23593  int *pRc,
23594  const char *zSql,
23595  sqlite3_stmt **ppStmt
23596){
23597  *ppStmt = 0;
23598  if( *pRc==SQLITE_OK ){
23599    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
23600    if( rc!=SQLITE_OK ){
23601      eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
23602      *pRc = rc;
23603    }
23604  }
23605}
23606
23607/*
23608** Create a prepared statement using printf-style arguments for the SQL.
23609*/
23610static void shellPreparePrintf(
23611  sqlite3 *db,
23612  int *pRc,
23613  sqlite3_stmt **ppStmt,
23614  const char *zFmt,
23615  ...
23616){
23617  *ppStmt = 0;
23618  if( *pRc==SQLITE_OK ){
23619    va_list ap;
23620    char *z;
23621    va_start(ap, zFmt);
23622    z = sqlite3_vmprintf(zFmt, ap);
23623    va_end(ap);
23624    if( z==0 ){
23625      *pRc = SQLITE_NOMEM;
23626    }else{
23627      shellPrepare(db, pRc, z, ppStmt);
23628      sqlite3_free(z);
23629    }
23630  }
23631}
23632
23633/*
23634** Finalize the prepared statement created using shellPreparePrintf().
23635*/
23636static void shellFinalize(
23637  int *pRc,
23638  sqlite3_stmt *pStmt
23639){
23640  if( pStmt ){
23641    sqlite3 *db = sqlite3_db_handle(pStmt);
23642    int rc = sqlite3_finalize(pStmt);
23643    if( *pRc==SQLITE_OK ){
23644      if( rc!=SQLITE_OK ){
23645        eputf("SQL error: %s\n", sqlite3_errmsg(db));
23646      }
23647      *pRc = rc;
23648    }
23649  }
23650}
23651
23652#if !defined SQLITE_OMIT_VIRTUALTABLE
23653/* Reset the prepared statement created using shellPreparePrintf().
23654**
23655** This routine is could be marked "static".  But it is not always used,
23656** depending on compile-time options.  By omitting the "static", we avoid
23657** nuisance compiler warnings about "defined but not used".
23658*/
23659static void shellReset(
23660  int *pRc,
23661  sqlite3_stmt *pStmt
23662){
23663  int rc = sqlite3_reset(pStmt);
23664  if( *pRc==SQLITE_OK ){
23665    if( rc!=SQLITE_OK ){
23666      sqlite3 *db = sqlite3_db_handle(pStmt);
23667      eputf("SQL error: %s\n", sqlite3_errmsg(db));
23668    }
23669    *pRc = rc;
23670  }
23671}
23672#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
23673
23674#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
23675/******************************************************************************
23676** The ".archive" or ".ar" command.
23677*/
23678/*
23679** Structure representing a single ".ar" command.
23680*/
23681typedef struct ArCommand ArCommand;
23682struct ArCommand {
23683  u8 eCmd;                        /* An AR_CMD_* value */
23684  u8 bVerbose;                    /* True if --verbose */
23685  u8 bZip;                        /* True if the archive is a ZIP */
23686  u8 bDryRun;                     /* True if --dry-run */
23687  u8 bAppend;                     /* True if --append */
23688  u8 bGlob;                       /* True if --glob */
23689  u8 fromCmdLine;                 /* Run from -A instead of .archive */
23690  int nArg;                       /* Number of command arguments */
23691  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
23692  const char *zFile;              /* --file argument, or NULL */
23693  const char *zDir;               /* --directory argument, or NULL */
23694  char **azArg;                   /* Array of command arguments */
23695  ShellState *p;                  /* Shell state */
23696  sqlite3 *db;                    /* Database containing the archive */
23697};
23698
23699/*
23700** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
23701*/
23702static int arUsage(FILE *f){
23703  showHelp(f,"archive");
23704  return SQLITE_ERROR;
23705}
23706
23707/*
23708** Print an error message for the .ar command to stderr and return
23709** SQLITE_ERROR.
23710*/
23711static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
23712  va_list ap;
23713  char *z;
23714  va_start(ap, zFmt);
23715  z = sqlite3_vmprintf(zFmt, ap);
23716  va_end(ap);
23717  eputf("Error: %s\n", z);
23718  if( pAr->fromCmdLine ){
23719    eputz("Use \"-A\" for more help\n");
23720  }else{
23721    eputz("Use \".archive --help\" for more help\n");
23722  }
23723  sqlite3_free(z);
23724  return SQLITE_ERROR;
23725}
23726
23727/*
23728** Values for ArCommand.eCmd.
23729*/
23730#define AR_CMD_CREATE       1
23731#define AR_CMD_UPDATE       2
23732#define AR_CMD_INSERT       3
23733#define AR_CMD_EXTRACT      4
23734#define AR_CMD_LIST         5
23735#define AR_CMD_HELP         6
23736#define AR_CMD_REMOVE       7
23737
23738/*
23739** Other (non-command) switches.
23740*/
23741#define AR_SWITCH_VERBOSE     8
23742#define AR_SWITCH_FILE        9
23743#define AR_SWITCH_DIRECTORY  10
23744#define AR_SWITCH_APPEND     11
23745#define AR_SWITCH_DRYRUN     12
23746#define AR_SWITCH_GLOB       13
23747
23748static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
23749  switch( eSwitch ){
23750    case AR_CMD_CREATE:
23751    case AR_CMD_EXTRACT:
23752    case AR_CMD_LIST:
23753    case AR_CMD_REMOVE:
23754    case AR_CMD_UPDATE:
23755    case AR_CMD_INSERT:
23756    case AR_CMD_HELP:
23757      if( pAr->eCmd ){
23758        return arErrorMsg(pAr, "multiple command options");
23759      }
23760      pAr->eCmd = eSwitch;
23761      break;
23762
23763    case AR_SWITCH_DRYRUN:
23764      pAr->bDryRun = 1;
23765      break;
23766    case AR_SWITCH_GLOB:
23767      pAr->bGlob = 1;
23768      break;
23769    case AR_SWITCH_VERBOSE:
23770      pAr->bVerbose = 1;
23771      break;
23772    case AR_SWITCH_APPEND:
23773      pAr->bAppend = 1;
23774      deliberate_fall_through;
23775    case AR_SWITCH_FILE:
23776      pAr->zFile = zArg;
23777      break;
23778    case AR_SWITCH_DIRECTORY:
23779      pAr->zDir = zArg;
23780      break;
23781  }
23782
23783  return SQLITE_OK;
23784}
23785
23786/*
23787** Parse the command line for an ".ar" command. The results are written into
23788** structure (*pAr). SQLITE_OK is returned if the command line is parsed
23789** successfully, otherwise an error message is written to stderr and
23790** SQLITE_ERROR returned.
23791*/
23792static int arParseCommand(
23793  char **azArg,                   /* Array of arguments passed to dot command */
23794  int nArg,                       /* Number of entries in azArg[] */
23795  ArCommand *pAr                  /* Populate this object */
23796){
23797  struct ArSwitch {
23798    const char *zLong;
23799    char cShort;
23800    u8 eSwitch;
23801    u8 bArg;
23802  } aSwitch[] = {
23803    { "create",    'c', AR_CMD_CREATE,       0 },
23804    { "extract",   'x', AR_CMD_EXTRACT,      0 },
23805    { "insert",    'i', AR_CMD_INSERT,       0 },
23806    { "list",      't', AR_CMD_LIST,         0 },
23807    { "remove",    'r', AR_CMD_REMOVE,       0 },
23808    { "update",    'u', AR_CMD_UPDATE,       0 },
23809    { "help",      'h', AR_CMD_HELP,         0 },
23810    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
23811    { "file",      'f', AR_SWITCH_FILE,      1 },
23812    { "append",    'a', AR_SWITCH_APPEND,    1 },
23813    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
23814    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
23815    { "glob",      'g', AR_SWITCH_GLOB,      0 },
23816  };
23817  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
23818  struct ArSwitch *pEnd = &aSwitch[nSwitch];
23819
23820  if( nArg<=1 ){
23821    eputz("Wrong number of arguments.  Usage:\n");
23822    return arUsage(stderr);
23823  }else{
23824    char *z = azArg[1];
23825    if( z[0]!='-' ){
23826      /* Traditional style [tar] invocation */
23827      int i;
23828      int iArg = 2;
23829      for(i=0; z[i]; i++){
23830        const char *zArg = 0;
23831        struct ArSwitch *pOpt;
23832        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23833          if( z[i]==pOpt->cShort ) break;
23834        }
23835        if( pOpt==pEnd ){
23836          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23837        }
23838        if( pOpt->bArg ){
23839          if( iArg>=nArg ){
23840            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
23841          }
23842          zArg = azArg[iArg++];
23843        }
23844        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23845      }
23846      pAr->nArg = nArg-iArg;
23847      if( pAr->nArg>0 ){
23848        pAr->azArg = &azArg[iArg];
23849      }
23850    }else{
23851      /* Non-traditional invocation */
23852      int iArg;
23853      for(iArg=1; iArg<nArg; iArg++){
23854        int n;
23855        z = azArg[iArg];
23856        if( z[0]!='-' ){
23857          /* All remaining command line words are command arguments. */
23858          pAr->azArg = &azArg[iArg];
23859          pAr->nArg = nArg-iArg;
23860          break;
23861        }
23862        n = strlen30(z);
23863
23864        if( z[1]!='-' ){
23865          int i;
23866          /* One or more short options */
23867          for(i=1; i<n; i++){
23868            const char *zArg = 0;
23869            struct ArSwitch *pOpt;
23870            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23871              if( z[i]==pOpt->cShort ) break;
23872            }
23873            if( pOpt==pEnd ){
23874              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23875            }
23876            if( pOpt->bArg ){
23877              if( i<(n-1) ){
23878                zArg = &z[i+1];
23879                i = n;
23880              }else{
23881                if( iArg>=(nArg-1) ){
23882                  return arErrorMsg(pAr, "option requires an argument: %c",
23883                                    z[i]);
23884                }
23885                zArg = azArg[++iArg];
23886              }
23887            }
23888            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23889          }
23890        }else if( z[2]=='\0' ){
23891          /* A -- option, indicating that all remaining command line words
23892          ** are command arguments.  */
23893          pAr->azArg = &azArg[iArg+1];
23894          pAr->nArg = nArg-iArg-1;
23895          break;
23896        }else{
23897          /* A long option */
23898          const char *zArg = 0;             /* Argument for option, if any */
23899          struct ArSwitch *pMatch = 0;      /* Matching option */
23900          struct ArSwitch *pOpt;            /* Iterator */
23901          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23902            const char *zLong = pOpt->zLong;
23903            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
23904              if( pMatch ){
23905                return arErrorMsg(pAr, "ambiguous option: %s",z);
23906              }else{
23907                pMatch = pOpt;
23908              }
23909            }
23910          }
23911
23912          if( pMatch==0 ){
23913            return arErrorMsg(pAr, "unrecognized option: %s", z);
23914          }
23915          if( pMatch->bArg ){
23916            if( iArg>=(nArg-1) ){
23917              return arErrorMsg(pAr, "option requires an argument: %s", z);
23918            }
23919            zArg = azArg[++iArg];
23920          }
23921          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
23922        }
23923      }
23924    }
23925  }
23926  if( pAr->eCmd==0 ){
23927    eputz("Required argument missing.  Usage:\n");
23928    return arUsage(stderr);
23929  }
23930  return SQLITE_OK;
23931}
23932
23933/*
23934** This function assumes that all arguments within the ArCommand.azArg[]
23935** array refer to archive members, as for the --extract, --list or --remove
23936** commands. It checks that each of them are "present". If any specified
23937** file is not present in the archive, an error is printed to stderr and an
23938** error code returned. Otherwise, if all specified arguments are present
23939** in the archive, SQLITE_OK is returned. Here, "present" means either an
23940** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
23941** when pAr->bGlob is true.
23942**
23943** This function strips any trailing '/' characters from each argument.
23944** This is consistent with the way the [tar] command seems to work on
23945** Linux.
23946*/
23947static int arCheckEntries(ArCommand *pAr){
23948  int rc = SQLITE_OK;
23949  if( pAr->nArg ){
23950    int i, j;
23951    sqlite3_stmt *pTest = 0;
23952    const char *zSel = (pAr->bGlob)
23953      ? "SELECT name FROM %s WHERE glob($name,name)"
23954      : "SELECT name FROM %s WHERE name=$name";
23955
23956    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
23957    j = sqlite3_bind_parameter_index(pTest, "$name");
23958    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
23959      char *z = pAr->azArg[i];
23960      int n = strlen30(z);
23961      int bOk = 0;
23962      while( n>0 && z[n-1]=='/' ) n--;
23963      z[n] = '\0';
23964      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
23965      if( SQLITE_ROW==sqlite3_step(pTest) ){
23966        bOk = 1;
23967      }
23968      shellReset(&rc, pTest);
23969      if( rc==SQLITE_OK && bOk==0 ){
23970        eputf("not found in archive: %s\n", z);
23971        rc = SQLITE_ERROR;
23972      }
23973    }
23974    shellFinalize(&rc, pTest);
23975  }
23976  return rc;
23977}
23978
23979/*
23980** Format a WHERE clause that can be used against the "sqlar" table to
23981** identify all archive members that match the command arguments held
23982** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
23983** The caller is responsible for eventually calling sqlite3_free() on
23984** any non-NULL (*pzWhere) value. Here, "match" means strict equality
23985** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
23986*/
23987static void arWhereClause(
23988  int *pRc,
23989  ArCommand *pAr,
23990  char **pzWhere                  /* OUT: New WHERE clause */
23991){
23992  char *zWhere = 0;
23993  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
23994  if( *pRc==SQLITE_OK ){
23995    if( pAr->nArg==0 ){
23996      zWhere = sqlite3_mprintf("1");
23997    }else{
23998      int i;
23999      const char *zSep = "";
24000      for(i=0; i<pAr->nArg; i++){
24001        const char *z = pAr->azArg[i];
24002        zWhere = sqlite3_mprintf(
24003          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
24004          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
24005        );
24006        if( zWhere==0 ){
24007          *pRc = SQLITE_NOMEM;
24008          break;
24009        }
24010        zSep = " OR ";
24011      }
24012    }
24013  }
24014  *pzWhere = zWhere;
24015}
24016
24017/*
24018** Implementation of .ar "lisT" command.
24019*/
24020static int arListCommand(ArCommand *pAr){
24021  const char *zSql = "SELECT %s FROM %s WHERE %s";
24022  const char *azCols[] = {
24023    "name",
24024    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
24025  };
24026
24027  char *zWhere = 0;
24028  sqlite3_stmt *pSql = 0;
24029  int rc;
24030
24031  rc = arCheckEntries(pAr);
24032  arWhereClause(&rc, pAr, &zWhere);
24033
24034  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
24035                     pAr->zSrcTable, zWhere);
24036  if( pAr->bDryRun ){
24037    oputf("%s\n", sqlite3_sql(pSql));
24038  }else{
24039    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
24040      if( pAr->bVerbose ){
24041        oputf("%s % 10d  %s  %s\n",
24042              sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
24043              sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
24044      }else{
24045        oputf("%s\n", sqlite3_column_text(pSql, 0));
24046      }
24047    }
24048  }
24049  shellFinalize(&rc, pSql);
24050  sqlite3_free(zWhere);
24051  return rc;
24052}
24053
24054/*
24055** Implementation of .ar "Remove" command.
24056*/
24057static int arRemoveCommand(ArCommand *pAr){
24058  int rc = 0;
24059  char *zSql = 0;
24060  char *zWhere = 0;
24061
24062  if( pAr->nArg ){
24063    /* Verify that args actually exist within the archive before proceeding.
24064    ** And formulate a WHERE clause to match them.  */
24065    rc = arCheckEntries(pAr);
24066    arWhereClause(&rc, pAr, &zWhere);
24067  }
24068  if( rc==SQLITE_OK ){
24069    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
24070                           pAr->zSrcTable, zWhere);
24071    if( pAr->bDryRun ){
24072      oputf("%s\n", zSql);
24073    }else{
24074      char *zErr = 0;
24075      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
24076      if( rc==SQLITE_OK ){
24077        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
24078        if( rc!=SQLITE_OK ){
24079          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
24080        }else{
24081          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
24082        }
24083      }
24084      if( zErr ){
24085        sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
24086        sqlite3_free(zErr);
24087      }
24088    }
24089  }
24090  sqlite3_free(zWhere);
24091  sqlite3_free(zSql);
24092  return rc;
24093}
24094
24095/*
24096** Implementation of .ar "eXtract" command.
24097*/
24098static int arExtractCommand(ArCommand *pAr){
24099  const char *zSql1 =
24100    "SELECT "
24101    " ($dir || name),"
24102    " writefile(($dir || name), %s, mode, mtime) "
24103    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
24104    " AND name NOT GLOB '*..[/\\]*'";
24105
24106  const char *azExtraArg[] = {
24107    "sqlar_uncompress(data, sz)",
24108    "data"
24109  };
24110
24111  sqlite3_stmt *pSql = 0;
24112  int rc = SQLITE_OK;
24113  char *zDir = 0;
24114  char *zWhere = 0;
24115  int i, j;
24116
24117  /* If arguments are specified, check that they actually exist within
24118  ** the archive before proceeding. And formulate a WHERE clause to
24119  ** match them.  */
24120  rc = arCheckEntries(pAr);
24121  arWhereClause(&rc, pAr, &zWhere);
24122
24123  if( rc==SQLITE_OK ){
24124    if( pAr->zDir ){
24125      zDir = sqlite3_mprintf("%s/", pAr->zDir);
24126    }else{
24127      zDir = sqlite3_mprintf("");
24128    }
24129    if( zDir==0 ) rc = SQLITE_NOMEM;
24130  }
24131
24132  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
24133      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
24134  );
24135
24136  if( rc==SQLITE_OK ){
24137    j = sqlite3_bind_parameter_index(pSql, "$dir");
24138    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
24139
24140    /* Run the SELECT statement twice. The first time, writefile() is called
24141    ** for all archive members that should be extracted. The second time,
24142    ** only for the directories. This is because the timestamps for
24143    ** extracted directories must be reset after they are populated (as
24144    ** populating them changes the timestamp).  */
24145    for(i=0; i<2; i++){
24146      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
24147      sqlite3_bind_int(pSql, j, i);
24148      if( pAr->bDryRun ){
24149        oputf("%s\n", sqlite3_sql(pSql));
24150      }else{
24151        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
24152          if( i==0 && pAr->bVerbose ){
24153            oputf("%s\n", sqlite3_column_text(pSql, 0));
24154          }
24155        }
24156      }
24157      shellReset(&rc, pSql);
24158    }
24159    shellFinalize(&rc, pSql);
24160  }
24161
24162  sqlite3_free(zDir);
24163  sqlite3_free(zWhere);
24164  return rc;
24165}
24166
24167/*
24168** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
24169*/
24170static int arExecSql(ArCommand *pAr, const char *zSql){
24171  int rc;
24172  if( pAr->bDryRun ){
24173    oputf("%s\n", zSql);
24174    rc = SQLITE_OK;
24175  }else{
24176    char *zErr = 0;
24177    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
24178    if( zErr ){
24179      sputf(stdout, "ERROR: %s\n", zErr);
24180      sqlite3_free(zErr);
24181    }
24182  }
24183  return rc;
24184}
24185
24186
24187/*
24188** Implementation of .ar "create", "insert", and "update" commands.
24189**
24190**     create    ->     Create a new SQL archive
24191**     insert    ->     Insert or reinsert all files listed
24192**     update    ->     Insert files that have changed or that were not
24193**                      previously in the archive
24194**
24195** Create the "sqlar" table in the database if it does not already exist.
24196** Then add each file in the azFile[] array to the archive. Directories
24197** are added recursively. If argument bVerbose is non-zero, a message is
24198** printed on stdout for each file archived.
24199**
24200** The create command is the same as update, except that it drops
24201** any existing "sqlar" table before beginning.  The "insert" command
24202** always overwrites every file named on the command-line, where as
24203** "update" only overwrites if the size or mtime or mode has changed.
24204*/
24205static int arCreateOrUpdateCommand(
24206  ArCommand *pAr,                 /* Command arguments and options */
24207  int bUpdate,                    /* true for a --create. */
24208  int bOnlyIfChanged              /* Only update if file has changed */
24209){
24210  const char *zCreate =
24211      "CREATE TABLE IF NOT EXISTS sqlar(\n"
24212      "  name TEXT PRIMARY KEY,  -- name of the file\n"
24213      "  mode INT,               -- access permissions\n"
24214      "  mtime INT,              -- last modification time\n"
24215      "  sz INT,                 -- original file size\n"
24216      "  data BLOB               -- compressed content\n"
24217      ")";
24218  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
24219  const char *zInsertFmt[2] = {
24220     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
24221     "  SELECT\n"
24222     "    %s,\n"
24223     "    mode,\n"
24224     "    mtime,\n"
24225     "    CASE substr(lsmode(mode),1,1)\n"
24226     "      WHEN '-' THEN length(data)\n"
24227     "      WHEN 'd' THEN 0\n"
24228     "      ELSE -1 END,\n"
24229     "    sqlar_compress(data)\n"
24230     "  FROM fsdir(%Q,%Q) AS disk\n"
24231     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
24232     ,
24233     "REPLACE INTO %s(name,mode,mtime,data)\n"
24234     "  SELECT\n"
24235     "    %s,\n"
24236     "    mode,\n"
24237     "    mtime,\n"
24238     "    data\n"
24239     "  FROM fsdir(%Q,%Q) AS disk\n"
24240     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
24241  };
24242  int i;                          /* For iterating through azFile[] */
24243  int rc;                         /* Return code */
24244  const char *zTab = 0;           /* SQL table into which to insert */
24245  char *zSql;
24246  char zTemp[50];
24247  char *zExists = 0;
24248
24249  arExecSql(pAr, "PRAGMA page_size=512");
24250  rc = arExecSql(pAr, "SAVEPOINT ar;");
24251  if( rc!=SQLITE_OK ) return rc;
24252  zTemp[0] = 0;
24253  if( pAr->bZip ){
24254    /* Initialize the zipfile virtual table, if necessary */
24255    if( pAr->zFile ){
24256      sqlite3_uint64 r;
24257      sqlite3_randomness(sizeof(r),&r);
24258      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
24259      zTab = zTemp;
24260      zSql = sqlite3_mprintf(
24261         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
24262         zTab, pAr->zFile
24263      );
24264      rc = arExecSql(pAr, zSql);
24265      sqlite3_free(zSql);
24266    }else{
24267      zTab = "zip";
24268    }
24269  }else{
24270    /* Initialize the table for an SQLAR */
24271    zTab = "sqlar";
24272    if( bUpdate==0 ){
24273      rc = arExecSql(pAr, zDrop);
24274      if( rc!=SQLITE_OK ) goto end_ar_transaction;
24275    }
24276    rc = arExecSql(pAr, zCreate);
24277  }
24278  if( bOnlyIfChanged ){
24279    zExists = sqlite3_mprintf(
24280      " AND NOT EXISTS("
24281          "SELECT 1 FROM %s AS mem"
24282          " WHERE mem.name=disk.name"
24283          " AND mem.mtime=disk.mtime"
24284          " AND mem.mode=disk.mode)", zTab);
24285  }else{
24286    zExists = sqlite3_mprintf("");
24287  }
24288  if( zExists==0 ) rc = SQLITE_NOMEM;
24289  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
24290    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
24291        pAr->bVerbose ? "shell_putsnl(name)" : "name",
24292        pAr->azArg[i], pAr->zDir, zExists);
24293    rc = arExecSql(pAr, zSql2);
24294    sqlite3_free(zSql2);
24295  }
24296end_ar_transaction:
24297  if( rc!=SQLITE_OK ){
24298    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
24299  }else{
24300    rc = arExecSql(pAr, "RELEASE ar;");
24301    if( pAr->bZip && pAr->zFile ){
24302      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
24303      arExecSql(pAr, zSql);
24304      sqlite3_free(zSql);
24305    }
24306  }
24307  sqlite3_free(zExists);
24308  return rc;
24309}
24310
24311/*
24312** Implementation of ".ar" dot command.
24313*/
24314static int arDotCommand(
24315  ShellState *pState,          /* Current shell tool state */
24316  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
24317  char **azArg,                /* Array of arguments passed to dot command */
24318  int nArg                     /* Number of entries in azArg[] */
24319){
24320  ArCommand cmd;
24321  int rc;
24322  memset(&cmd, 0, sizeof(cmd));
24323  cmd.fromCmdLine = fromCmdLine;
24324  rc = arParseCommand(azArg, nArg, &cmd);
24325  if( rc==SQLITE_OK ){
24326    int eDbType = SHELL_OPEN_UNSPEC;
24327    cmd.p = pState;
24328    cmd.db = pState->db;
24329    if( cmd.zFile ){
24330      eDbType = deduceDatabaseType(cmd.zFile, 1);
24331    }else{
24332      eDbType = pState->openMode;
24333    }
24334    if( eDbType==SHELL_OPEN_ZIPFILE ){
24335      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
24336        if( cmd.zFile==0 ){
24337          cmd.zSrcTable = sqlite3_mprintf("zip");
24338        }else{
24339          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
24340        }
24341      }
24342      cmd.bZip = 1;
24343    }else if( cmd.zFile ){
24344      int flags;
24345      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
24346      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
24347           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
24348        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
24349      }else{
24350        flags = SQLITE_OPEN_READONLY;
24351      }
24352      cmd.db = 0;
24353      if( cmd.bDryRun ){
24354        oputf("-- open database '%s'%s\n", cmd.zFile,
24355              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
24356      }
24357      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
24358             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
24359      if( rc!=SQLITE_OK ){
24360        eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
24361        goto end_ar_command;
24362      }
24363      sqlite3_fileio_init(cmd.db, 0, 0);
24364      sqlite3_sqlar_init(cmd.db, 0, 0);
24365      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
24366                              shellPutsFunc, 0, 0);
24367
24368    }
24369    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
24370      if( cmd.eCmd!=AR_CMD_CREATE
24371       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
24372      ){
24373        eputz("database does not contain an 'sqlar' table\n");
24374        rc = SQLITE_ERROR;
24375        goto end_ar_command;
24376      }
24377      cmd.zSrcTable = sqlite3_mprintf("sqlar");
24378    }
24379
24380    switch( cmd.eCmd ){
24381      case AR_CMD_CREATE:
24382        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
24383        break;
24384
24385      case AR_CMD_EXTRACT:
24386        rc = arExtractCommand(&cmd);
24387        break;
24388
24389      case AR_CMD_LIST:
24390        rc = arListCommand(&cmd);
24391        break;
24392
24393      case AR_CMD_HELP:
24394        arUsage(pState->out);
24395        break;
24396
24397      case AR_CMD_INSERT:
24398        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
24399        break;
24400
24401      case AR_CMD_REMOVE:
24402        rc = arRemoveCommand(&cmd);
24403        break;
24404
24405      default:
24406        assert( cmd.eCmd==AR_CMD_UPDATE );
24407        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
24408        break;
24409    }
24410  }
24411end_ar_command:
24412  if( cmd.db!=pState->db ){
24413    close_db(cmd.db);
24414  }
24415  sqlite3_free(cmd.zSrcTable);
24416
24417  return rc;
24418}
24419/* End of the ".archive" or ".ar" command logic
24420*******************************************************************************/
24421#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
24422
24423#if SQLITE_SHELL_HAVE_RECOVER
24424
24425/*
24426** This function is used as a callback by the recover extension. Simply
24427** print the supplied SQL statement to stdout.
24428*/
24429static int recoverSqlCb(void *pCtx, const char *zSql){
24430  ShellState *pState = (ShellState*)pCtx;
24431  sputf(pState->out, "%s;\n", zSql);
24432  return SQLITE_OK;
24433}
24434
24435/*
24436** This function is called to recover data from the database. A script
24437** to construct a new database containing all recovered data is output
24438** on stream pState->out.
24439*/
24440static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
24441  int rc = SQLITE_OK;
24442  const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
24443  const char *zLAF = "lost_and_found";
24444  int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
24445  int bRowids = 1;                /* 0 if --no-rowids */
24446  sqlite3_recover *p = 0;
24447  int i = 0;
24448
24449  for(i=1; i<nArg; i++){
24450    char *z = azArg[i];
24451    int n;
24452    if( z[0]=='-' && z[1]=='-' ) z++;
24453    n = strlen30(z);
24454    if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
24455      bFreelist = 0;
24456    }else
24457    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
24458      /* This option determines the name of the ATTACH-ed database used
24459      ** internally by the recovery extension.  The default is "" which
24460      ** means to use a temporary database that is automatically deleted
24461      ** when closed.  This option is undocumented and might disappear at
24462      ** any moment. */
24463      i++;
24464      zRecoveryDb = azArg[i];
24465    }else
24466    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
24467      i++;
24468      zLAF = azArg[i];
24469    }else
24470    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
24471      bRowids = 0;
24472    }
24473    else{
24474      eputf("unexpected option: %s\n", azArg[i]);
24475      showHelp(pState->out, azArg[0]);
24476      return 1;
24477    }
24478  }
24479
24480  p = sqlite3_recover_init_sql(
24481      pState->db, "main", recoverSqlCb, (void*)pState
24482  );
24483
24484  sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
24485  sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
24486  sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
24487  sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
24488
24489  sqlite3_recover_run(p);
24490  if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
24491    const char *zErr = sqlite3_recover_errmsg(p);
24492    int errCode = sqlite3_recover_errcode(p);
24493    eputf("sql error: %s (%d)\n", zErr, errCode);
24494  }
24495  rc = sqlite3_recover_finish(p);
24496  return rc;
24497}
24498#endif /* SQLITE_SHELL_HAVE_RECOVER */
24499
24500
24501/*
24502 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
24503 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
24504 *   close db and set it to 0, and return the columns spec, to later
24505 *   be sqlite3_free()'ed by the caller.
24506 * The return is 0 when either:
24507 *   (a) The db was not initialized and zCol==0 (There are no columns.)
24508 *   (b) zCol!=0  (Column was added, db initialized as needed.)
24509 * The 3rd argument, pRenamed, references an out parameter. If the
24510 * pointer is non-zero, its referent will be set to a summary of renames
24511 * done if renaming was necessary, or set to 0 if none was done. The out
24512 * string (if any) must be sqlite3_free()'ed by the caller.
24513 */
24514#ifdef SHELL_DEBUG
24515#define rc_err_oom_die(rc) \
24516  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
24517  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
24518    eputf("E:%d\n",rc), assert(0)
24519#else
24520static void rc_err_oom_die(int rc){
24521  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
24522  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
24523}
24524#endif
24525
24526#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
24527static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
24528#else  /* Otherwise, memory is faster/better for the transient DB. */
24529static const char *zCOL_DB = ":memory:";
24530#endif
24531
24532/* Define character (as C string) to separate generated column ordinal
24533 * from protected part of incoming column names. This defaults to "_"
24534 * so that incoming column identifiers that did not need not be quoted
24535 * remain usable without being quoted. It must be one character.
24536 */
24537#ifndef SHELL_AUTOCOLUMN_SEP
24538# define AUTOCOLUMN_SEP "_"
24539#else
24540# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
24541#endif
24542
24543static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
24544  /* Queries and D{D,M}L used here */
24545  static const char * const zTabMake = "\
24546CREATE TABLE ColNames(\
24547 cpos INTEGER PRIMARY KEY,\
24548 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
24549CREATE VIEW RepeatedNames AS \
24550SELECT DISTINCT t.name FROM ColNames t \
24551WHERE t.name COLLATE NOCASE IN (\
24552 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
24553);\
24554";
24555  static const char * const zTabFill = "\
24556INSERT INTO ColNames(name,nlen,chop,reps,suff)\
24557 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
24558";
24559  static const char * const zHasDupes = "\
24560SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
24561 <count(name) FROM ColNames\
24562";
24563#ifdef SHELL_COLUMN_RENAME_CLEAN
24564  static const char * const zDedoctor = "\
24565UPDATE ColNames SET chop=iif(\
24566  (substring(name,nlen,1) BETWEEN '0' AND '9')\
24567  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
24568 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
24569 0\
24570)\
24571";
24572#endif
24573  static const char * const zSetReps = "\
24574UPDATE ColNames AS t SET reps=\
24575(SELECT count(*) FROM ColNames d \
24576 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
24577 COLLATE NOCASE\
24578)\
24579";
24580#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
24581  static const char * const zColDigits = "\
24582SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
24583";
24584#else
24585  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
24586  static const char * const zColDigits = "\
24587SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
24588 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
24589 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
24590";
24591#endif
24592  static const char * const zRenameRank =
24593#ifdef SHELL_COLUMN_RENAME_CLEAN
24594    "UPDATE ColNames AS t SET suff="
24595    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
24596#else /* ...RENAME_MINIMAL_ONE_PASS */
24597"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
24598"  SELECT 0 AS nlz"
24599"  UNION"
24600"  SELECT nlz+1 AS nlz FROM Lzn"
24601"  WHERE EXISTS("
24602"   SELECT 1"
24603"   FROM ColNames t, ColNames o"
24604"   WHERE"
24605"    iif(t.name IN (SELECT * FROM RepeatedNames),"
24606"     printf('%s"AUTOCOLUMN_SEP"%s',"
24607"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
24608"     t.name"
24609"    )"
24610"    ="
24611"    iif(o.name IN (SELECT * FROM RepeatedNames),"
24612"     printf('%s"AUTOCOLUMN_SEP"%s',"
24613"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
24614"     o.name"
24615"    )"
24616"    COLLATE NOCASE"
24617"    AND o.cpos<>t.cpos"
24618"   GROUP BY t.cpos"
24619"  )"
24620") UPDATE Colnames AS t SET"
24621" chop = 0," /* No chopping, never touch incoming names. */
24622" suff = iif(name IN (SELECT * FROM RepeatedNames),"
24623"  printf('"AUTOCOLUMN_SEP"%s', substring("
24624"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
24625"  ''"
24626" )"
24627#endif
24628    ;
24629  static const char * const zCollectVar = "\
24630SELECT\
24631 '('||x'0a'\
24632 || group_concat(\
24633  cname||' TEXT',\
24634  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
24635 ||')' AS ColsSpec \
24636FROM (\
24637 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
24638 FROM ColNames ORDER BY cpos\
24639)";
24640  static const char * const zRenamesDone =
24641    "SELECT group_concat("
24642    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
24643    " ','||x'0a')"
24644    "FROM ColNames WHERE suff<>'' OR chop!=0"
24645    ;
24646  int rc;
24647  sqlite3_stmt *pStmt = 0;
24648  assert(pDb!=0);
24649  if( zColNew ){
24650    /* Add initial or additional column. Init db if necessary. */
24651    if( *pDb==0 ){
24652      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
24653#ifdef SHELL_COLFIX_DB
24654      if(*zCOL_DB!=':')
24655        sqlite3_exec(*pDb,"drop table if exists ColNames;"
24656                     "drop view if exists RepeatedNames;",0,0,0);
24657#endif
24658#undef SHELL_COLFIX_DB
24659      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
24660      rc_err_oom_die(rc);
24661    }
24662    assert(*pDb!=0);
24663    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
24664    rc_err_oom_die(rc);
24665    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
24666    rc_err_oom_die(rc);
24667    rc = sqlite3_step(pStmt);
24668    rc_err_oom_die(rc);
24669    sqlite3_finalize(pStmt);
24670    return 0;
24671  }else if( *pDb==0 ){
24672    return 0;
24673  }else{
24674    /* Formulate the columns spec, close the DB, zero *pDb. */
24675    char *zColsSpec = 0;
24676    int hasDupes = db_int(*pDb, zHasDupes);
24677    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
24678    if( hasDupes ){
24679#ifdef SHELL_COLUMN_RENAME_CLEAN
24680      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
24681      rc_err_oom_die(rc);
24682#endif
24683      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
24684      rc_err_oom_die(rc);
24685      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
24686      rc_err_oom_die(rc);
24687      sqlite3_bind_int(pStmt, 1, nDigits);
24688      rc = sqlite3_step(pStmt);
24689      sqlite3_finalize(pStmt);
24690      if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
24691    }
24692    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
24693    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
24694    rc_err_oom_die(rc);
24695    rc = sqlite3_step(pStmt);
24696    if( rc==SQLITE_ROW ){
24697      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
24698    }else{
24699      zColsSpec = 0;
24700    }
24701    if( pzRenamed!=0 ){
24702      if( !hasDupes ) *pzRenamed = 0;
24703      else{
24704        sqlite3_finalize(pStmt);
24705        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
24706            && SQLITE_ROW==sqlite3_step(pStmt) ){
24707          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
24708        }else
24709          *pzRenamed = 0;
24710      }
24711    }
24712    sqlite3_finalize(pStmt);
24713    sqlite3_close(*pDb);
24714    *pDb = 0;
24715    return zColsSpec;
24716  }
24717}
24718
24719/*
24720** Check if the sqlite_schema table contains one or more virtual tables. If
24721** parameter zLike is not NULL, then it is an SQL expression that the
24722** sqlite_schema row must also match. If one or more such rows are found,
24723** print the following warning to the output:
24724**
24725** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
24726*/
24727static int outputDumpWarning(ShellState *p, const char *zLike){
24728  int rc = SQLITE_OK;
24729  sqlite3_stmt *pStmt = 0;
24730  shellPreparePrintf(p->db, &rc, &pStmt,
24731    "SELECT 1 FROM sqlite_schema o WHERE "
24732    "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
24733  );
24734  if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24735    oputz("/* WARNING: "
24736          "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
24737    );
24738  }
24739  shellFinalize(&rc, pStmt);
24740  return rc;
24741}
24742
24743/*
24744** If an input line begins with "." then invoke this routine to
24745** process that line.
24746**
24747** Return 1 on error, 2 to exit, and 0 otherwise.
24748*/
24749static int do_meta_command(char *zLine, ShellState *p){
24750  int h = 1;
24751  int nArg = 0;
24752  int n, c;
24753  int rc = 0;
24754  char *azArg[52];
24755
24756#ifndef SQLITE_OMIT_VIRTUALTABLE
24757  if( p->expert.pExpert ){
24758    expertFinish(p, 1, 0);
24759  }
24760#endif
24761
24762  /* Parse the input line into tokens.
24763  */
24764  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
24765    while( IsSpace(zLine[h]) ){ h++; }
24766    if( zLine[h]==0 ) break;
24767    if( zLine[h]=='\'' || zLine[h]=='"' ){
24768      int delim = zLine[h++];
24769      azArg[nArg++] = &zLine[h];
24770      while( zLine[h] && zLine[h]!=delim ){
24771        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
24772        h++;
24773      }
24774      if( zLine[h]==delim ){
24775        zLine[h++] = 0;
24776      }
24777      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
24778    }else{
24779      azArg[nArg++] = &zLine[h];
24780      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
24781      if( zLine[h] ) zLine[h++] = 0;
24782    }
24783  }
24784  azArg[nArg] = 0;
24785
24786  /* Process the input line.
24787  */
24788  if( nArg==0 ) return 0; /* no tokens, no error */
24789  n = strlen30(azArg[0]);
24790  c = azArg[0][0];
24791  clearTempFile(p);
24792
24793#ifndef SQLITE_OMIT_AUTHORIZATION
24794  if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
24795    if( nArg!=2 ){
24796      eputz("Usage: .auth ON|OFF\n");
24797      rc = 1;
24798      goto meta_command_exit;
24799    }
24800    open_db(p, 0);
24801    if( booleanValue(azArg[1]) ){
24802      sqlite3_set_authorizer(p->db, shellAuth, p);
24803    }else if( p->bSafeModePersist ){
24804      sqlite3_set_authorizer(p->db, safeModeAuth, p);
24805    }else{
24806      sqlite3_set_authorizer(p->db, 0, 0);
24807    }
24808  }else
24809#endif
24810
24811#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
24812  && !defined(SQLITE_SHELL_FIDDLE)
24813  if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
24814    open_db(p, 0);
24815    failIfSafeMode(p, "cannot run .archive in safe mode");
24816    rc = arDotCommand(p, 0, azArg, nArg);
24817  }else
24818#endif
24819
24820#ifndef SQLITE_SHELL_FIDDLE
24821  if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
24822   || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
24823  ){
24824    const char *zDestFile = 0;
24825    const char *zDb = 0;
24826    sqlite3 *pDest;
24827    sqlite3_backup *pBackup;
24828    int j;
24829    int bAsync = 0;
24830    const char *zVfs = 0;
24831    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
24832    for(j=1; j<nArg; j++){
24833      const char *z = azArg[j];
24834      if( z[0]=='-' ){
24835        if( z[1]=='-' ) z++;
24836        if( cli_strcmp(z, "-append")==0 ){
24837          zVfs = "apndvfs";
24838        }else
24839        if( cli_strcmp(z, "-async")==0 ){
24840          bAsync = 1;
24841        }else
24842        {
24843          eputf("unknown option: %s\n", azArg[j]);
24844          return 1;
24845        }
24846      }else if( zDestFile==0 ){
24847        zDestFile = azArg[j];
24848      }else if( zDb==0 ){
24849        zDb = zDestFile;
24850        zDestFile = azArg[j];
24851      }else{
24852        eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
24853        return 1;
24854      }
24855    }
24856    if( zDestFile==0 ){
24857      eputz("missing FILENAME argument on .backup\n");
24858      return 1;
24859    }
24860    if( zDb==0 ) zDb = "main";
24861    rc = sqlite3_open_v2(zDestFile, &pDest,
24862                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
24863    if( rc!=SQLITE_OK ){
24864      eputf("Error: cannot open \"%s\"\n", zDestFile);
24865      close_db(pDest);
24866      return 1;
24867    }
24868    if( bAsync ){
24869      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
24870                   0, 0, 0);
24871    }
24872    open_db(p, 0);
24873    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
24874    if( pBackup==0 ){
24875      eputf("Error: %s\n", sqlite3_errmsg(pDest));
24876      close_db(pDest);
24877      return 1;
24878    }
24879    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
24880    sqlite3_backup_finish(pBackup);
24881    if( rc==SQLITE_DONE ){
24882      rc = 0;
24883    }else{
24884      eputf("Error: %s\n", sqlite3_errmsg(pDest));
24885      rc = 1;
24886    }
24887    close_db(pDest);
24888  }else
24889#endif /* !defined(SQLITE_SHELL_FIDDLE) */
24890
24891  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
24892    if( nArg==2 ){
24893      bail_on_error = booleanValue(azArg[1]);
24894    }else{
24895      eputz("Usage: .bail on|off\n");
24896      rc = 1;
24897    }
24898  }else
24899
24900  /* Undocumented.  Legacy only.  See "crnl" below */
24901  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
24902    if( nArg==2 ){
24903      if( booleanValue(azArg[1]) ){
24904        setBinaryMode(p->out, 1);
24905      }else{
24906        setTextMode(p->out, 1);
24907      }
24908    }else{
24909      eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
24910            "Usage: .binary on|off\n");
24911      rc = 1;
24912    }
24913  }else
24914
24915  /* The undocumented ".breakpoint" command causes a call to the no-op
24916  ** routine named test_breakpoint().
24917  */
24918  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
24919    test_breakpoint();
24920  }else
24921
24922#ifndef SQLITE_SHELL_FIDDLE
24923  if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
24924    failIfSafeMode(p, "cannot run .cd in safe mode");
24925    if( nArg==2 ){
24926#if defined(_WIN32) || defined(WIN32)
24927      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
24928      rc = !SetCurrentDirectoryW(z);
24929      sqlite3_free(z);
24930#else
24931      rc = chdir(azArg[1]);
24932#endif
24933      if( rc ){
24934        eputf("Cannot change to directory \"%s\"\n", azArg[1]);
24935        rc = 1;
24936      }
24937    }else{
24938      eputz("Usage: .cd DIRECTORY\n");
24939      rc = 1;
24940    }
24941  }else
24942#endif /* !defined(SQLITE_SHELL_FIDDLE) */
24943
24944  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
24945    if( nArg==2 ){
24946      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
24947    }else{
24948      eputz("Usage: .changes on|off\n");
24949      rc = 1;
24950    }
24951  }else
24952
24953#ifndef SQLITE_SHELL_FIDDLE
24954  /* Cancel output redirection, if it is currently set (by .testcase)
24955  ** Then read the content of the testcase-out.txt file and compare against
24956  ** azArg[1].  If there are differences, report an error and exit.
24957  */
24958  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
24959    char *zRes = 0;
24960    output_reset(p);
24961    if( nArg!=2 ){
24962      eputz("Usage: .check GLOB-PATTERN\n");
24963      rc = 2;
24964    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
24965      rc = 2;
24966    }else if( testcase_glob(azArg[1],zRes)==0 ){
24967      eputf("testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
24968            p->zTestcase, azArg[1], zRes);
24969      rc = 1;
24970    }else{
24971      oputf("testcase-%s ok\n", p->zTestcase);
24972      p->nCheck++;
24973    }
24974    sqlite3_free(zRes);
24975  }else
24976#endif /* !defined(SQLITE_SHELL_FIDDLE) */
24977
24978#ifndef SQLITE_SHELL_FIDDLE
24979  if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
24980    failIfSafeMode(p, "cannot run .clone in safe mode");
24981    if( nArg==2 ){
24982      tryToClone(p, azArg[1]);
24983    }else{
24984      eputz("Usage: .clone FILENAME\n");
24985      rc = 1;
24986    }
24987  }else
24988#endif /* !defined(SQLITE_SHELL_FIDDLE) */
24989
24990  if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
24991    if( nArg==1 ){
24992      /* List available connections */
24993      int i;
24994      for(i=0; i<ArraySize(p->aAuxDb); i++){
24995        const char *zFile = p->aAuxDb[i].zDbFilename;
24996        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
24997          zFile = "(not open)";
24998        }else if( zFile==0 ){
24999          zFile = "(memory)";
25000        }else if( zFile[0]==0 ){
25001          zFile = "(temporary-file)";
25002        }
25003        if( p->pAuxDb == &p->aAuxDb[i] ){
25004          sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
25005        }else if( p->aAuxDb[i].db!=0 ){
25006          sputf(stdout, "       %d: %s\n", i, zFile);
25007        }
25008      }
25009    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
25010      int i = azArg[1][0] - '0';
25011      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
25012        p->pAuxDb->db = p->db;
25013        p->pAuxDb = &p->aAuxDb[i];
25014        globalDb = p->db = p->pAuxDb->db;
25015        p->pAuxDb->db = 0;
25016      }
25017    }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
25018           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
25019      int i = azArg[2][0] - '0';
25020      if( i<0 || i>=ArraySize(p->aAuxDb) ){
25021        /* No-op */
25022      }else if( p->pAuxDb == &p->aAuxDb[i] ){
25023        eputz("cannot close the active database connection\n");
25024        rc = 1;
25025      }else if( p->aAuxDb[i].db ){
25026        session_close_all(p, i);
25027        close_db(p->aAuxDb[i].db);
25028        p->aAuxDb[i].db = 0;
25029      }
25030    }else{
25031      eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
25032      rc = 1;
25033    }
25034  }else
25035
25036  if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
25037    if( nArg==2 ){
25038      if( booleanValue(azArg[1]) ){
25039        setTextMode(p->out, 1);
25040      }else{
25041        setBinaryMode(p->out, 1);
25042      }
25043    }else{
25044#if !defined(_WIN32) && !defined(WIN32)
25045      eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
25046#endif
25047      eputz("Usage: .crnl on|off\n");
25048      rc = 1;
25049    }
25050  }else
25051
25052  if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
25053    char **azName = 0;
25054    int nName = 0;
25055    sqlite3_stmt *pStmt;
25056    int i;
25057    open_db(p, 0);
25058    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
25059    if( rc ){
25060      eputf("Error: %s\n", sqlite3_errmsg(p->db));
25061      rc = 1;
25062    }else{
25063      while( sqlite3_step(pStmt)==SQLITE_ROW ){
25064        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
25065        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
25066        if( zSchema==0 || zFile==0 ) continue;
25067        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
25068        shell_check_oom(azName);
25069        azName[nName*2] = strdup(zSchema);
25070        azName[nName*2+1] = strdup(zFile);
25071        nName++;
25072      }
25073    }
25074    sqlite3_finalize(pStmt);
25075    for(i=0; i<nName; i++){
25076      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
25077      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
25078      const char *z = azName[i*2+1];
25079      oputf("%s: %s %s%s\n",
25080            azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
25081            eTxn==SQLITE_TXN_NONE ? "" :
25082            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
25083      free(azName[i*2]);
25084      free(azName[i*2+1]);
25085    }
25086    sqlite3_free(azName);
25087  }else
25088
25089  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
25090    static const struct DbConfigChoices {
25091      const char *zName;
25092      int op;
25093    } aDbConfig[] = {
25094        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
25095        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
25096        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
25097        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
25098        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
25099        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
25100        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
25101        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
25102        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
25103        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
25104        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
25105        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
25106        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
25107        { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
25108        { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
25109        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
25110        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
25111        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
25112    };
25113    int ii, v;
25114    open_db(p, 0);
25115    for(ii=0; ii<ArraySize(aDbConfig); ii++){
25116      if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
25117      if( nArg>=3 ){
25118        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
25119      }
25120      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
25121      oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
25122      if( nArg>1 ) break;
25123    }
25124    if( nArg>1 && ii==ArraySize(aDbConfig) ){
25125      eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
25126      eputz("Enter \".dbconfig\" with no arguments for a list\n");
25127    }
25128  }else
25129
25130#if SQLITE_SHELL_HAVE_RECOVER
25131  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
25132    rc = shell_dbinfo_command(p, nArg, azArg);
25133  }else
25134
25135  if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
25136    open_db(p, 0);
25137    rc = recoverDatabaseCmd(p, nArg, azArg);
25138  }else
25139#endif /* SQLITE_SHELL_HAVE_RECOVER */
25140
25141  if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
25142    char *zLike = 0;
25143    char *zSql;
25144    int i;
25145    int savedShowHeader = p->showHeader;
25146    int savedShellFlags = p->shellFlgs;
25147    ShellClearFlag(p,
25148       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
25149       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
25150    for(i=1; i<nArg; i++){
25151      if( azArg[i][0]=='-' ){
25152        const char *z = azArg[i]+1;
25153        if( z[0]=='-' ) z++;
25154        if( cli_strcmp(z,"preserve-rowids")==0 ){
25155#ifdef SQLITE_OMIT_VIRTUALTABLE
25156          eputz("The --preserve-rowids option is not compatible"
25157                " with SQLITE_OMIT_VIRTUALTABLE\n");
25158          rc = 1;
25159          sqlite3_free(zLike);
25160          goto meta_command_exit;
25161#else
25162          ShellSetFlag(p, SHFLG_PreserveRowid);
25163#endif
25164        }else
25165        if( cli_strcmp(z,"newlines")==0 ){
25166          ShellSetFlag(p, SHFLG_Newlines);
25167        }else
25168        if( cli_strcmp(z,"data-only")==0 ){
25169          ShellSetFlag(p, SHFLG_DumpDataOnly);
25170        }else
25171        if( cli_strcmp(z,"nosys")==0 ){
25172          ShellSetFlag(p, SHFLG_DumpNoSys);
25173        }else
25174        {
25175          eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
25176          rc = 1;
25177          sqlite3_free(zLike);
25178          goto meta_command_exit;
25179        }
25180      }else{
25181        /* azArg[i] contains a LIKE pattern. This ".dump" request should
25182        ** only dump data for tables for which either the table name matches
25183        ** the LIKE pattern, or the table appears to be a shadow table of
25184        ** a virtual table for which the name matches the LIKE pattern.
25185        */
25186        char *zExpr = sqlite3_mprintf(
25187            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
25188            "  SELECT 1 FROM sqlite_schema WHERE "
25189            "    name LIKE %Q ESCAPE '\\' AND"
25190            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
25191            "    substr(o.name, 1, length(name)+1) == (name||'_')"
25192            ")", azArg[i], azArg[i]
25193        );
25194
25195        if( zLike ){
25196          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
25197        }else{
25198          zLike = zExpr;
25199        }
25200      }
25201    }
25202
25203    open_db(p, 0);
25204
25205    outputDumpWarning(p, zLike);
25206    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25207      /* When playing back a "dump", the content might appear in an order
25208      ** which causes immediate foreign key constraints to be violated.
25209      ** So disable foreign-key constraint enforcement to prevent problems. */
25210      oputz("PRAGMA foreign_keys=OFF;\n");
25211      oputz("BEGIN TRANSACTION;\n");
25212    }
25213    p->writableSchema = 0;
25214    p->showHeader = 0;
25215    /* Set writable_schema=ON since doing so forces SQLite to initialize
25216    ** as much of the schema as it can even if the sqlite_schema table is
25217    ** corrupt. */
25218    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
25219    p->nErr = 0;
25220    if( zLike==0 ) zLike = sqlite3_mprintf("true");
25221    zSql = sqlite3_mprintf(
25222      "SELECT name, type, sql FROM sqlite_schema AS o "
25223      "WHERE (%s) AND type=='table'"
25224      "  AND sql NOT NULL"
25225      " ORDER BY tbl_name='sqlite_sequence', rowid",
25226      zLike
25227    );
25228    run_schema_dump_query(p,zSql);
25229    sqlite3_free(zSql);
25230    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25231      zSql = sqlite3_mprintf(
25232        "SELECT sql FROM sqlite_schema AS o "
25233        "WHERE (%s) AND sql NOT NULL"
25234        "  AND type IN ('index','trigger','view')",
25235        zLike
25236      );
25237      run_table_dump_query(p, zSql);
25238      sqlite3_free(zSql);
25239    }
25240    sqlite3_free(zLike);
25241    if( p->writableSchema ){
25242      oputz("PRAGMA writable_schema=OFF;\n");
25243      p->writableSchema = 0;
25244    }
25245    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
25246    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
25247    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25248      oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
25249    }
25250    p->showHeader = savedShowHeader;
25251    p->shellFlgs = savedShellFlags;
25252  }else
25253
25254  if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
25255    if( nArg==2 ){
25256      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
25257    }else{
25258      eputz("Usage: .echo on|off\n");
25259      rc = 1;
25260    }
25261  }else
25262
25263  if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
25264    if( nArg==2 ){
25265      p->autoEQPtest = 0;
25266      if( p->autoEQPtrace ){
25267        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
25268        p->autoEQPtrace = 0;
25269      }
25270      if( cli_strcmp(azArg[1],"full")==0 ){
25271        p->autoEQP = AUTOEQP_full;
25272      }else if( cli_strcmp(azArg[1],"trigger")==0 ){
25273        p->autoEQP = AUTOEQP_trigger;
25274#ifdef SQLITE_DEBUG
25275      }else if( cli_strcmp(azArg[1],"test")==0 ){
25276        p->autoEQP = AUTOEQP_on;
25277        p->autoEQPtest = 1;
25278      }else if( cli_strcmp(azArg[1],"trace")==0 ){
25279        p->autoEQP = AUTOEQP_full;
25280        p->autoEQPtrace = 1;
25281        open_db(p, 0);
25282        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
25283        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
25284#endif
25285      }else{
25286        p->autoEQP = (u8)booleanValue(azArg[1]);
25287      }
25288    }else{
25289      eputz("Usage: .eqp off|on|trace|trigger|full\n");
25290      rc = 1;
25291    }
25292  }else
25293
25294#ifndef SQLITE_SHELL_FIDDLE
25295  if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
25296    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
25297    rc = 2;
25298  }else
25299#endif
25300
25301  /* The ".explain" command is automatic now.  It is largely pointless.  It
25302  ** retained purely for backwards compatibility */
25303  if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
25304    int val = 1;
25305    if( nArg>=2 ){
25306      if( cli_strcmp(azArg[1],"auto")==0 ){
25307        val = 99;
25308      }else{
25309        val =  booleanValue(azArg[1]);
25310      }
25311    }
25312    if( val==1 && p->mode!=MODE_Explain ){
25313      p->normalMode = p->mode;
25314      p->mode = MODE_Explain;
25315      p->autoExplain = 0;
25316    }else if( val==0 ){
25317      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
25318      p->autoExplain = 0;
25319    }else if( val==99 ){
25320      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
25321      p->autoExplain = 1;
25322    }
25323  }else
25324
25325#ifndef SQLITE_OMIT_VIRTUALTABLE
25326  if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
25327    if( p->bSafeMode ){
25328      eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
25329            azArg[0]);
25330      rc = 1;
25331    }else{
25332      open_db(p, 0);
25333      expertDotCommand(p, azArg, nArg);
25334    }
25335  }else
25336#endif
25337
25338  if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
25339    static const struct {
25340       const char *zCtrlName;   /* Name of a test-control option */
25341       int ctrlCode;            /* Integer code for that option */
25342       const char *zUsage;      /* Usage notes */
25343    } aCtrl[] = {
25344      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
25345      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
25346      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
25347      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
25348      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
25349   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
25350      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
25351      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
25352      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
25353      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
25354   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
25355    };
25356    int filectrl = -1;
25357    int iCtrl = -1;
25358    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
25359    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
25360    int n2, i;
25361    const char *zCmd = 0;
25362    const char *zSchema = 0;
25363
25364    open_db(p, 0);
25365    zCmd = nArg>=2 ? azArg[1] : "help";
25366
25367    if( zCmd[0]=='-'
25368     && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
25369     && nArg>=4
25370    ){
25371      zSchema = azArg[2];
25372      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
25373      nArg -= 2;
25374      zCmd = azArg[1];
25375    }
25376
25377    /* The argument can optionally begin with "-" or "--" */
25378    if( zCmd[0]=='-' && zCmd[1] ){
25379      zCmd++;
25380      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
25381    }
25382
25383    /* --help lists all file-controls */
25384    if( cli_strcmp(zCmd,"help")==0 ){
25385      oputz("Available file-controls:\n");
25386      for(i=0; i<ArraySize(aCtrl); i++){
25387        oputf("  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
25388      }
25389      rc = 1;
25390      goto meta_command_exit;
25391    }
25392
25393    /* convert filectrl text option to value. allow any unique prefix
25394    ** of the option name, or a numerical value. */
25395    n2 = strlen30(zCmd);
25396    for(i=0; i<ArraySize(aCtrl); i++){
25397      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
25398        if( filectrl<0 ){
25399          filectrl = aCtrl[i].ctrlCode;
25400          iCtrl = i;
25401        }else{
25402          eputf("Error: ambiguous file-control: \"%s\"\n"
25403                "Use \".filectrl --help\" for help\n", zCmd);
25404          rc = 1;
25405          goto meta_command_exit;
25406        }
25407      }
25408    }
25409    if( filectrl<0 ){
25410      eputf("Error: unknown file-control: %s\n"
25411            "Use \".filectrl --help\" for help\n", zCmd);
25412    }else{
25413      switch(filectrl){
25414        case SQLITE_FCNTL_SIZE_LIMIT: {
25415          if( nArg!=2 && nArg!=3 ) break;
25416          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
25417          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
25418          isOk = 1;
25419          break;
25420        }
25421        case SQLITE_FCNTL_LOCK_TIMEOUT:
25422        case SQLITE_FCNTL_CHUNK_SIZE: {
25423          int x;
25424          if( nArg!=3 ) break;
25425          x = (int)integerValue(azArg[2]);
25426          sqlite3_file_control(p->db, zSchema, filectrl, &x);
25427          isOk = 2;
25428          break;
25429        }
25430        case SQLITE_FCNTL_PERSIST_WAL:
25431        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
25432          int x;
25433          if( nArg!=2 && nArg!=3 ) break;
25434          x = nArg==3 ? booleanValue(azArg[2]) : -1;
25435          sqlite3_file_control(p->db, zSchema, filectrl, &x);
25436          iRes = x;
25437          isOk = 1;
25438          break;
25439        }
25440        case SQLITE_FCNTL_DATA_VERSION:
25441        case SQLITE_FCNTL_HAS_MOVED: {
25442          int x;
25443          if( nArg!=2 ) break;
25444          sqlite3_file_control(p->db, zSchema, filectrl, &x);
25445          iRes = x;
25446          isOk = 1;
25447          break;
25448        }
25449        case SQLITE_FCNTL_TEMPFILENAME: {
25450          char *z = 0;
25451          if( nArg!=2 ) break;
25452          sqlite3_file_control(p->db, zSchema, filectrl, &z);
25453          if( z ){
25454            oputf("%s\n", z);
25455            sqlite3_free(z);
25456          }
25457          isOk = 2;
25458          break;
25459        }
25460        case SQLITE_FCNTL_RESERVE_BYTES: {
25461          int x;
25462          if( nArg>=3 ){
25463            x = atoi(azArg[2]);
25464            sqlite3_file_control(p->db, zSchema, filectrl, &x);
25465          }
25466          x = -1;
25467          sqlite3_file_control(p->db, zSchema, filectrl, &x);
25468          oputf("%d\n", x);
25469          isOk = 2;
25470          break;
25471        }
25472      }
25473    }
25474    if( isOk==0 && iCtrl>=0 ){
25475      oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
25476      rc = 1;
25477    }else if( isOk==1 ){
25478      char zBuf[100];
25479      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
25480      oputf("%s\n", zBuf);
25481    }
25482  }else
25483
25484  if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
25485    ShellState data;
25486    int doStats = 0;
25487    memcpy(&data, p, sizeof(data));
25488    data.showHeader = 0;
25489    data.cMode = data.mode = MODE_Semi;
25490    if( nArg==2 && optionMatch(azArg[1], "indent") ){
25491      data.cMode = data.mode = MODE_Pretty;
25492      nArg = 1;
25493    }
25494    if( nArg!=1 ){
25495      eputz("Usage: .fullschema ?--indent?\n");
25496      rc = 1;
25497      goto meta_command_exit;
25498    }
25499    open_db(p, 0);
25500    rc = sqlite3_exec(p->db,
25501       "SELECT sql FROM"
25502       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
25503       "     FROM sqlite_schema UNION ALL"
25504       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
25505       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
25506       "ORDER BY x",
25507       callback, &data, 0
25508    );
25509    if( rc==SQLITE_OK ){
25510      sqlite3_stmt *pStmt;
25511      rc = sqlite3_prepare_v2(p->db,
25512               "SELECT rowid FROM sqlite_schema"
25513               " WHERE name GLOB 'sqlite_stat[134]'",
25514               -1, &pStmt, 0);
25515      if( rc==SQLITE_OK ){
25516        doStats = sqlite3_step(pStmt)==SQLITE_ROW;
25517        sqlite3_finalize(pStmt);
25518      }
25519    }
25520    if( doStats==0 ){
25521      oputz("/* No STAT tables available */\n");
25522    }else{
25523      oputz("ANALYZE sqlite_schema;\n");
25524      data.cMode = data.mode = MODE_Insert;
25525      data.zDestTable = "sqlite_stat1";
25526      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
25527      data.zDestTable = "sqlite_stat4";
25528      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
25529      oputz("ANALYZE sqlite_schema;\n");
25530    }
25531  }else
25532
25533  if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
25534    if( nArg==2 ){
25535      p->showHeader = booleanValue(azArg[1]);
25536      p->shellFlgs |= SHFLG_HeaderSet;
25537    }else{
25538      eputz("Usage: .headers on|off\n");
25539      rc = 1;
25540    }
25541  }else
25542
25543  if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
25544    if( nArg>=2 ){
25545      n = showHelp(p->out, azArg[1]);
25546      if( n==0 ){
25547        oputf("Nothing matches '%s'\n", azArg[1]);
25548      }
25549    }else{
25550      showHelp(p->out, 0);
25551    }
25552  }else
25553
25554#ifndef SQLITE_SHELL_FIDDLE
25555  if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
25556    char *zTable = 0;           /* Insert data into this table */
25557    char *zSchema = 0;          /* within this schema (may default to "main") */
25558    char *zFile = 0;            /* Name of file to extra content from */
25559    sqlite3_stmt *pStmt = NULL; /* A statement */
25560    int nCol;                   /* Number of columns in the table */
25561    int nByte;                  /* Number of bytes in an SQL string */
25562    int i, j;                   /* Loop counters */
25563    int needCommit;             /* True to COMMIT or ROLLBACK at end */
25564    int nSep;                   /* Number of bytes in p->colSeparator[] */
25565    char *zSql;                 /* An SQL statement */
25566    char *zFullTabName;         /* Table name with schema if applicable */
25567    ImportCtx sCtx;             /* Reader context */
25568    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
25569    int eVerbose = 0;           /* Larger for more console output */
25570    int nSkip = 0;              /* Initial lines to skip */
25571    int useOutputMode = 1;      /* Use output mode to determine separators */
25572    char *zCreate = 0;          /* CREATE TABLE statement text */
25573
25574    failIfSafeMode(p, "cannot run .import in safe mode");
25575    memset(&sCtx, 0, sizeof(sCtx));
25576    if( p->mode==MODE_Ascii ){
25577      xRead = ascii_read_one_field;
25578    }else{
25579      xRead = csv_read_one_field;
25580    }
25581    rc = 1;
25582    for(i=1; i<nArg; i++){
25583      char *z = azArg[i];
25584      if( z[0]=='-' && z[1]=='-' ) z++;
25585      if( z[0]!='-' ){
25586        if( zFile==0 ){
25587          zFile = z;
25588        }else if( zTable==0 ){
25589          zTable = z;
25590        }else{
25591          oputf("ERROR: extra argument: \"%s\".  Usage:\n", z);
25592          showHelp(p->out, "import");
25593          goto meta_command_exit;
25594        }
25595      }else if( cli_strcmp(z,"-v")==0 ){
25596        eVerbose++;
25597      }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
25598        zSchema = azArg[++i];
25599      }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
25600        nSkip = integerValue(azArg[++i]);
25601      }else if( cli_strcmp(z,"-ascii")==0 ){
25602        sCtx.cColSep = SEP_Unit[0];
25603        sCtx.cRowSep = SEP_Record[0];
25604        xRead = ascii_read_one_field;
25605        useOutputMode = 0;
25606      }else if( cli_strcmp(z,"-csv")==0 ){
25607        sCtx.cColSep = ',';
25608        sCtx.cRowSep = '\n';
25609        xRead = csv_read_one_field;
25610        useOutputMode = 0;
25611      }else{
25612        oputf("ERROR: unknown option: \"%s\".  Usage:\n", z);
25613        showHelp(p->out, "import");
25614        goto meta_command_exit;
25615      }
25616    }
25617    if( zTable==0 ){
25618      oputf("ERROR: missing %s argument. Usage:\n",
25619            zFile==0 ? "FILE" : "TABLE");
25620      showHelp(p->out, "import");
25621      goto meta_command_exit;
25622    }
25623    seenInterrupt = 0;
25624    open_db(p, 0);
25625    if( useOutputMode ){
25626      /* If neither the --csv or --ascii options are specified, then set
25627      ** the column and row separator characters from the output mode. */
25628      nSep = strlen30(p->colSeparator);
25629      if( nSep==0 ){
25630        eputz("Error: non-null column separator required for import\n");
25631        goto meta_command_exit;
25632      }
25633      if( nSep>1 ){
25634        eputz("Error: multi-character column separators not allowed"
25635              " for import\n");
25636        goto meta_command_exit;
25637      }
25638      nSep = strlen30(p->rowSeparator);
25639      if( nSep==0 ){
25640        eputz("Error: non-null row separator required for import\n");
25641        goto meta_command_exit;
25642      }
25643      if( nSep==2 && p->mode==MODE_Csv
25644       && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
25645      ){
25646        /* When importing CSV (only), if the row separator is set to the
25647        ** default output row separator, change it to the default input
25648        ** row separator.  This avoids having to maintain different input
25649        ** and output row separators. */
25650        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25651        nSep = strlen30(p->rowSeparator);
25652      }
25653      if( nSep>1 ){
25654        eputz("Error: multi-character row separators not allowed"
25655              " for import\n");
25656        goto meta_command_exit;
25657      }
25658      sCtx.cColSep = (u8)p->colSeparator[0];
25659      sCtx.cRowSep = (u8)p->rowSeparator[0];
25660    }
25661    sCtx.zFile = zFile;
25662    sCtx.nLine = 1;
25663    if( sCtx.zFile[0]=='|' ){
25664#ifdef SQLITE_OMIT_POPEN
25665      eputz("Error: pipes are not supported in this OS\n");
25666      goto meta_command_exit;
25667#else
25668      sCtx.in = popen(sCtx.zFile+1, "r");
25669      sCtx.zFile = "<pipe>";
25670      sCtx.xCloser = pclose;
25671#endif
25672    }else{
25673      sCtx.in = fopen(sCtx.zFile, "rb");
25674      sCtx.xCloser = fclose;
25675    }
25676    if( sCtx.in==0 ){
25677      eputf("Error: cannot open \"%s\"\n", zFile);
25678      goto meta_command_exit;
25679    }
25680    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
25681      char zSep[2];
25682      zSep[1] = 0;
25683      zSep[0] = sCtx.cColSep;
25684      oputz("Column separator ");
25685      output_c_string(zSep);
25686      oputz(", row separator ");
25687      zSep[0] = sCtx.cRowSep;
25688      output_c_string(zSep);
25689      oputz("\n");
25690    }
25691    sCtx.z = sqlite3_malloc64(120);
25692    if( sCtx.z==0 ){
25693      import_cleanup(&sCtx);
25694      shell_out_of_memory();
25695    }
25696    /* Below, resources must be freed before exit. */
25697    while( (nSkip--)>0 ){
25698      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
25699    }
25700    if( zSchema!=0 ){
25701      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
25702    }else{
25703      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
25704    }
25705    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
25706    if( zSql==0 || zFullTabName==0 ){
25707      import_cleanup(&sCtx);
25708      shell_out_of_memory();
25709    }
25710    nByte = strlen30(zSql);
25711    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25712    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
25713    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
25714      sqlite3 *dbCols = 0;
25715      char *zRenames = 0;
25716      char *zColDefs;
25717      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
25718      while( xRead(&sCtx) ){
25719        zAutoColumn(sCtx.z, &dbCols, 0);
25720        if( sCtx.cTerm!=sCtx.cColSep ) break;
25721      }
25722      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
25723      if( zRenames!=0 ){
25724        sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
25725              "Columns renamed during .import %s due to duplicates:\n"
25726              "%s\n", sCtx.zFile, zRenames);
25727        sqlite3_free(zRenames);
25728      }
25729      assert(dbCols==0);
25730      if( zColDefs==0 ){
25731        eputf("%s: empty file\n", sCtx.zFile);
25732      import_fail:
25733        sqlite3_free(zCreate);
25734        sqlite3_free(zSql);
25735        sqlite3_free(zFullTabName);
25736        import_cleanup(&sCtx);
25737        rc = 1;
25738        goto meta_command_exit;
25739      }
25740      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
25741      if( eVerbose>=1 ){
25742        oputf("%s\n", zCreate);
25743      }
25744      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
25745      if( rc ){
25746        eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
25747        goto import_fail;
25748      }
25749      sqlite3_free(zCreate);
25750      zCreate = 0;
25751      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25752    }
25753    if( rc ){
25754      if (pStmt) sqlite3_finalize(pStmt);
25755      eputf("Error: %s\n", sqlite3_errmsg(p->db));
25756      goto import_fail;
25757    }
25758    sqlite3_free(zSql);
25759    nCol = sqlite3_column_count(pStmt);
25760    sqlite3_finalize(pStmt);
25761    pStmt = 0;
25762    if( nCol==0 ) return 0; /* no columns, no error */
25763    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
25764    if( zSql==0 ){
25765      import_cleanup(&sCtx);
25766      shell_out_of_memory();
25767    }
25768    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
25769    j = strlen30(zSql);
25770    for(i=1; i<nCol; i++){
25771      zSql[j++] = ',';
25772      zSql[j++] = '?';
25773    }
25774    zSql[j++] = ')';
25775    zSql[j] = 0;
25776    if( eVerbose>=2 ){
25777      oputf("Insert using: %s\n", zSql);
25778    }
25779    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25780    if( rc ){
25781      eputf("Error: %s\n", sqlite3_errmsg(p->db));
25782      if (pStmt) sqlite3_finalize(pStmt);
25783      goto import_fail;
25784    }
25785    sqlite3_free(zSql);
25786    sqlite3_free(zFullTabName);
25787    needCommit = sqlite3_get_autocommit(p->db);
25788    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
25789    do{
25790      int startLine = sCtx.nLine;
25791      for(i=0; i<nCol; i++){
25792        char *z = xRead(&sCtx);
25793        /*
25794        ** Did we reach end-of-file before finding any columns?
25795        ** If so, stop instead of NULL filling the remaining columns.
25796        */
25797        if( z==0 && i==0 ) break;
25798        /*
25799        ** Did we reach end-of-file OR end-of-line before finding any
25800        ** columns in ASCII mode?  If so, stop instead of NULL filling
25801        ** the remaining columns.
25802        */
25803        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
25804        /*
25805        ** For CSV mode, per RFC 4180, accept EOF in lieu of final
25806        ** record terminator but only for last field of multi-field row.
25807        ** (If there are too few fields, it's not valid CSV anyway.)
25808        */
25809        if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
25810          z = "";
25811        }
25812        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
25813        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
25814          eputf("%s:%d: expected %d columns but found %d"
25815                " - filling the rest with NULL\n",
25816                sCtx.zFile, startLine, nCol, i+1);
25817          i += 2;
25818          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
25819        }
25820      }
25821      if( sCtx.cTerm==sCtx.cColSep ){
25822        do{
25823          xRead(&sCtx);
25824          i++;
25825        }while( sCtx.cTerm==sCtx.cColSep );
25826        eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
25827              sCtx.zFile, startLine, nCol, i);
25828      }
25829      if( i>=nCol ){
25830        sqlite3_step(pStmt);
25831        rc = sqlite3_reset(pStmt);
25832        if( rc!=SQLITE_OK ){
25833          eputf("%s:%d: INSERT failed: %s\n",
25834                sCtx.zFile, startLine, sqlite3_errmsg(p->db));
25835          sCtx.nErr++;
25836        }else{
25837          sCtx.nRow++;
25838        }
25839      }
25840    }while( sCtx.cTerm!=EOF );
25841
25842    import_cleanup(&sCtx);
25843    sqlite3_finalize(pStmt);
25844    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
25845    if( eVerbose>0 ){
25846      oputf("Added %d rows with %d errors using %d lines of input\n",
25847            sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
25848    }
25849  }else
25850#endif /* !defined(SQLITE_SHELL_FIDDLE) */
25851
25852#ifndef SQLITE_UNTESTABLE
25853  if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
25854    char *zSql;
25855    char *zCollist = 0;
25856    sqlite3_stmt *pStmt;
25857    int tnum = 0;
25858    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
25859    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
25860    int i;
25861    if( !ShellHasFlag(p,SHFLG_TestingMode) ){
25862      eputf(".%s unavailable without --unsafe-testing\n",
25863            "imposter");
25864      rc = 1;
25865      goto meta_command_exit;
25866    }
25867    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
25868      eputz("Usage: .imposter INDEX IMPOSTER\n"
25869            "       .imposter off\n");
25870      /* Also allowed, but not documented:
25871      **
25872      **    .imposter TABLE IMPOSTER
25873      **
25874      ** where TABLE is a WITHOUT ROWID table.  In that case, the
25875      ** imposter is another WITHOUT ROWID table with the columns in
25876      ** storage order. */
25877      rc = 1;
25878      goto meta_command_exit;
25879    }
25880    open_db(p, 0);
25881    if( nArg==2 ){
25882      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
25883      goto meta_command_exit;
25884    }
25885    zSql = sqlite3_mprintf(
25886      "SELECT rootpage, 0 FROM sqlite_schema"
25887      " WHERE name='%q' AND type='index'"
25888      "UNION ALL "
25889      "SELECT rootpage, 1 FROM sqlite_schema"
25890      " WHERE name='%q' AND type='table'"
25891      "   AND sql LIKE '%%without%%rowid%%'",
25892      azArg[1], azArg[1]
25893    );
25894    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25895    sqlite3_free(zSql);
25896    if( sqlite3_step(pStmt)==SQLITE_ROW ){
25897      tnum = sqlite3_column_int(pStmt, 0);
25898      isWO = sqlite3_column_int(pStmt, 1);
25899    }
25900    sqlite3_finalize(pStmt);
25901    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
25902    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25903    sqlite3_free(zSql);
25904    i = 0;
25905    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
25906      char zLabel[20];
25907      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
25908      i++;
25909      if( zCol==0 ){
25910        if( sqlite3_column_int(pStmt,1)==-1 ){
25911          zCol = "_ROWID_";
25912        }else{
25913          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
25914          zCol = zLabel;
25915        }
25916      }
25917      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
25918        lenPK = (int)strlen(zCollist);
25919      }
25920      if( zCollist==0 ){
25921        zCollist = sqlite3_mprintf("\"%w\"", zCol);
25922      }else{
25923        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
25924      }
25925    }
25926    sqlite3_finalize(pStmt);
25927    if( i==0 || tnum==0 ){
25928      eputf("no such index: \"%s\"\n", azArg[1]);
25929      rc = 1;
25930      sqlite3_free(zCollist);
25931      goto meta_command_exit;
25932    }
25933    if( lenPK==0 ) lenPK = 100000;
25934    zSql = sqlite3_mprintf(
25935          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
25936          azArg[2], zCollist, lenPK, zCollist);
25937    sqlite3_free(zCollist);
25938    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
25939    if( rc==SQLITE_OK ){
25940      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
25941      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
25942      if( rc ){
25943        eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
25944      }else{
25945        sputf(stdout, "%s;\n", zSql);
25946        sputf(stdout, "WARNING: writing to an imposter table will corrupt"
25947              " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
25948      }
25949    }else{
25950      eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
25951      rc = 1;
25952    }
25953    sqlite3_free(zSql);
25954  }else
25955#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
25956
25957#ifdef SQLITE_ENABLE_IOTRACE
25958  if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
25959    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
25960    if( iotrace && iotrace!=stdout ) fclose(iotrace);
25961    iotrace = 0;
25962    if( nArg<2 ){
25963      sqlite3IoTrace = 0;
25964    }else if( cli_strcmp(azArg[1], "-")==0 ){
25965      sqlite3IoTrace = iotracePrintf;
25966      iotrace = stdout;
25967    }else{
25968      iotrace = fopen(azArg[1], "w");
25969      if( iotrace==0 ){
25970        eputf("Error: cannot open \"%s\"\n", azArg[1]);
25971        sqlite3IoTrace = 0;
25972        rc = 1;
25973      }else{
25974        sqlite3IoTrace = iotracePrintf;
25975      }
25976    }
25977  }else
25978#endif
25979
25980  if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
25981    static const struct {
25982       const char *zLimitName;   /* Name of a limit */
25983       int limitCode;            /* Integer code for that limit */
25984    } aLimit[] = {
25985      { "length",                SQLITE_LIMIT_LENGTH                    },
25986      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
25987      { "column",                SQLITE_LIMIT_COLUMN                    },
25988      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
25989      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
25990      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
25991      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
25992      { "attached",              SQLITE_LIMIT_ATTACHED                  },
25993      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
25994      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
25995      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
25996      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
25997    };
25998    int i, n2;
25999    open_db(p, 0);
26000    if( nArg==1 ){
26001      for(i=0; i<ArraySize(aLimit); i++){
26002        sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
26003              sqlite3_limit(p->db, aLimit[i].limitCode, -1));
26004      }
26005    }else if( nArg>3 ){
26006      eputz("Usage: .limit NAME ?NEW-VALUE?\n");
26007      rc = 1;
26008      goto meta_command_exit;
26009    }else{
26010      int iLimit = -1;
26011      n2 = strlen30(azArg[1]);
26012      for(i=0; i<ArraySize(aLimit); i++){
26013        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
26014          if( iLimit<0 ){
26015            iLimit = i;
26016          }else{
26017            eputf("ambiguous limit: \"%s\"\n", azArg[1]);
26018            rc = 1;
26019            goto meta_command_exit;
26020          }
26021        }
26022      }
26023      if( iLimit<0 ){
26024        eputf("unknown limit: \"%s\"\n"
26025              "enter \".limits\" with no arguments for a list.\n",
26026              azArg[1]);
26027        rc = 1;
26028        goto meta_command_exit;
26029      }
26030      if( nArg==3 ){
26031        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
26032                      (int)integerValue(azArg[2]));
26033      }
26034      sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
26035            sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
26036    }
26037  }else
26038
26039  if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
26040    open_db(p, 0);
26041    lintDotCommand(p, azArg, nArg);
26042  }else
26043
26044#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
26045  if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
26046    const char *zFile, *zProc;
26047    char *zErrMsg = 0;
26048    failIfSafeMode(p, "cannot run .load in safe mode");
26049    if( nArg<2 || azArg[1][0]==0 ){
26050      /* Must have a non-empty FILE. (Will not load self.) */
26051      eputz("Usage: .load FILE ?ENTRYPOINT?\n");
26052      rc = 1;
26053      goto meta_command_exit;
26054    }
26055    zFile = azArg[1];
26056    zProc = nArg>=3 ? azArg[2] : 0;
26057    open_db(p, 0);
26058    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
26059    if( rc!=SQLITE_OK ){
26060      eputf("Error: %s\n", zErrMsg);
26061      sqlite3_free(zErrMsg);
26062      rc = 1;
26063    }
26064  }else
26065#endif
26066
26067  if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
26068    if( nArg!=2 ){
26069      eputz("Usage: .log FILENAME\n");
26070      rc = 1;
26071    }else{
26072      const char *zFile = azArg[1];
26073      if( p->bSafeMode
26074       && cli_strcmp(zFile,"on")!=0
26075       && cli_strcmp(zFile,"off")!=0
26076      ){
26077        sputz(stdout, "cannot set .log to anything other"
26078              " than \"on\" or \"off\"\n");
26079        zFile = "off";
26080      }
26081      output_file_close(p->pLog);
26082      if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
26083      p->pLog = output_file_open(zFile, 0);
26084    }
26085  }else
26086
26087  if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
26088    const char *zMode = 0;
26089    const char *zTabname = 0;
26090    int i, n2;
26091    ColModeOpts cmOpts = ColModeOpts_default;
26092    for(i=1; i<nArg; i++){
26093      const char *z = azArg[i];
26094      if( optionMatch(z,"wrap") && i+1<nArg ){
26095        cmOpts.iWrap = integerValue(azArg[++i]);
26096      }else if( optionMatch(z,"ww") ){
26097        cmOpts.bWordWrap = 1;
26098      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
26099        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
26100      }else if( optionMatch(z,"quote") ){
26101        cmOpts.bQuote = 1;
26102      }else if( optionMatch(z,"noquote") ){
26103        cmOpts.bQuote = 0;
26104      }else if( zMode==0 ){
26105        zMode = z;
26106        /* Apply defaults for qbox pseudo-mode.  If that
26107         * overwrites already-set values, user was informed of this.
26108         */
26109        if( cli_strcmp(z, "qbox")==0 ){
26110          ColModeOpts cmo = ColModeOpts_default_qbox;
26111          zMode = "box";
26112          cmOpts = cmo;
26113        }
26114      }else if( zTabname==0 ){
26115        zTabname = z;
26116      }else if( z[0]=='-' ){
26117        eputf("unknown option: %s\n", z);
26118        eputz("options:\n"
26119              "  --noquote\n"
26120              "  --quote\n"
26121              "  --wordwrap on/off\n"
26122              "  --wrap N\n"
26123              "  --ww\n");
26124        rc = 1;
26125        goto meta_command_exit;
26126      }else{
26127        eputf("extra argument: \"%s\"\n", z);
26128        rc = 1;
26129        goto meta_command_exit;
26130      }
26131    }
26132    if( zMode==0 ){
26133      if( p->mode==MODE_Column
26134       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
26135      ){
26136        oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
26137              modeDescr[p->mode], p->cmOpts.iWrap,
26138              p->cmOpts.bWordWrap ? "on" : "off",
26139              p->cmOpts.bQuote ? "" : "no");
26140      }else{
26141        oputf("current output mode: %s\n", modeDescr[p->mode]);
26142      }
26143      zMode = modeDescr[p->mode];
26144    }
26145    n2 = strlen30(zMode);
26146    if( cli_strncmp(zMode,"lines",n2)==0 ){
26147      p->mode = MODE_Line;
26148      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26149    }else if( cli_strncmp(zMode,"columns",n2)==0 ){
26150      p->mode = MODE_Column;
26151      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
26152        p->showHeader = 1;
26153      }
26154      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26155      p->cmOpts = cmOpts;
26156    }else if( cli_strncmp(zMode,"list",n2)==0 ){
26157      p->mode = MODE_List;
26158      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
26159      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26160    }else if( cli_strncmp(zMode,"html",n2)==0 ){
26161      p->mode = MODE_Html;
26162    }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
26163      p->mode = MODE_Tcl;
26164      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
26165      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26166    }else if( cli_strncmp(zMode,"csv",n2)==0 ){
26167      p->mode = MODE_Csv;
26168      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26169      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
26170    }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
26171      p->mode = MODE_List;
26172      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
26173    }else if( cli_strncmp(zMode,"insert",n2)==0 ){
26174      p->mode = MODE_Insert;
26175      set_table_name(p, zTabname ? zTabname : "table");
26176    }else if( cli_strncmp(zMode,"quote",n2)==0 ){
26177      p->mode = MODE_Quote;
26178      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26179      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26180    }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
26181      p->mode = MODE_Ascii;
26182      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
26183      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
26184    }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
26185      p->mode = MODE_Markdown;
26186      p->cmOpts = cmOpts;
26187    }else if( cli_strncmp(zMode,"table",n2)==0 ){
26188      p->mode = MODE_Table;
26189      p->cmOpts = cmOpts;
26190    }else if( cli_strncmp(zMode,"box",n2)==0 ){
26191      p->mode = MODE_Box;
26192      p->cmOpts = cmOpts;
26193    }else if( cli_strncmp(zMode,"count",n2)==0 ){
26194      p->mode = MODE_Count;
26195    }else if( cli_strncmp(zMode,"off",n2)==0 ){
26196      p->mode = MODE_Off;
26197    }else if( cli_strncmp(zMode,"json",n2)==0 ){
26198      p->mode = MODE_Json;
26199    }else{
26200      eputz("Error: mode should be one of: "
26201            "ascii box column csv html insert json line list markdown "
26202            "qbox quote table tabs tcl\n");
26203      rc = 1;
26204    }
26205    p->cMode = p->mode;
26206  }else
26207
26208#ifndef SQLITE_SHELL_FIDDLE
26209  if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
26210    if( nArg!=2 ){
26211      eputz("Usage: .nonce NONCE\n");
26212      rc = 1;
26213    }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
26214      eputf("line %d: incorrect nonce: \"%s\"\n",
26215            p->lineno, azArg[1]);
26216      exit(1);
26217    }else{
26218      p->bSafeMode = 0;
26219      return 0;  /* Return immediately to bypass the safe mode reset
26220                 ** at the end of this procedure */
26221    }
26222  }else
26223#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26224
26225  if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
26226    if( nArg==2 ){
26227      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
26228                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
26229    }else{
26230      eputz("Usage: .nullvalue STRING\n");
26231      rc = 1;
26232    }
26233  }else
26234
26235  if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
26236    const char *zFN = 0;     /* Pointer to constant filename */
26237    char *zNewFilename = 0;  /* Name of the database file to open */
26238    int iName = 1;           /* Index in azArg[] of the filename */
26239    int newFlag = 0;         /* True to delete file before opening */
26240    int openMode = SHELL_OPEN_UNSPEC;
26241
26242    /* Check for command-line arguments */
26243    for(iName=1; iName<nArg; iName++){
26244      const char *z = azArg[iName];
26245#ifndef SQLITE_SHELL_FIDDLE
26246      if( optionMatch(z,"new") ){
26247        newFlag = 1;
26248#ifdef SQLITE_HAVE_ZLIB
26249      }else if( optionMatch(z, "zip") ){
26250        openMode = SHELL_OPEN_ZIPFILE;
26251#endif
26252      }else if( optionMatch(z, "append") ){
26253        openMode = SHELL_OPEN_APPENDVFS;
26254      }else if( optionMatch(z, "readonly") ){
26255        openMode = SHELL_OPEN_READONLY;
26256      }else if( optionMatch(z, "nofollow") ){
26257        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
26258#ifndef SQLITE_OMIT_DESERIALIZE
26259      }else if( optionMatch(z, "deserialize") ){
26260        openMode = SHELL_OPEN_DESERIALIZE;
26261      }else if( optionMatch(z, "hexdb") ){
26262        openMode = SHELL_OPEN_HEXDB;
26263      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
26264        p->szMax = integerValue(azArg[++iName]);
26265#endif /* SQLITE_OMIT_DESERIALIZE */
26266      }else
26267#endif /* !SQLITE_SHELL_FIDDLE */
26268      if( z[0]=='-' ){
26269        eputf("unknown option: %s\n", z);
26270        rc = 1;
26271        goto meta_command_exit;
26272      }else if( zFN ){
26273        eputf("extra argument: \"%s\"\n", z);
26274        rc = 1;
26275        goto meta_command_exit;
26276      }else{
26277        zFN = z;
26278      }
26279    }
26280
26281    /* Close the existing database */
26282    session_close_all(p, -1);
26283    close_db(p->db);
26284    p->db = 0;
26285    p->pAuxDb->zDbFilename = 0;
26286    sqlite3_free(p->pAuxDb->zFreeOnClose);
26287    p->pAuxDb->zFreeOnClose = 0;
26288    p->openMode = openMode;
26289    p->openFlags = 0;
26290    p->szMax = 0;
26291
26292    /* If a filename is specified, try to open it first */
26293    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
26294      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
26295#ifndef SQLITE_SHELL_FIDDLE
26296      if( p->bSafeMode
26297       && p->openMode!=SHELL_OPEN_HEXDB
26298       && zFN
26299       && cli_strcmp(zFN,":memory:")!=0
26300      ){
26301        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
26302      }
26303#else
26304      /* WASM mode has its own sandboxed pseudo-filesystem. */
26305#endif
26306      if( zFN ){
26307        zNewFilename = sqlite3_mprintf("%s", zFN);
26308        shell_check_oom(zNewFilename);
26309      }else{
26310        zNewFilename = 0;
26311      }
26312      p->pAuxDb->zDbFilename = zNewFilename;
26313      open_db(p, OPEN_DB_KEEPALIVE);
26314      if( p->db==0 ){
26315        eputf("Error: cannot open '%s'\n", zNewFilename);
26316        sqlite3_free(zNewFilename);
26317      }else{
26318        p->pAuxDb->zFreeOnClose = zNewFilename;
26319      }
26320    }
26321    if( p->db==0 ){
26322      /* As a fall-back open a TEMP database */
26323      p->pAuxDb->zDbFilename = 0;
26324      open_db(p, 0);
26325    }
26326  }else
26327
26328#ifndef SQLITE_SHELL_FIDDLE
26329  if( (c=='o'
26330        && (cli_strncmp(azArg[0], "output", n)==0
26331            || cli_strncmp(azArg[0], "once", n)==0))
26332   || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
26333  ){
26334    char *zFile = 0;
26335    int bTxtMode = 0;
26336    int i;
26337    int eMode = 0;
26338    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
26339    static const char *zBomUtf8 = "\xef\xbb\xbf���";
26340    const char *zBom = 0;
26341
26342    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
26343    if( c=='e' ){
26344      eMode = 'x';
26345      bOnce = 2;
26346    }else if( cli_strncmp(azArg[0],"once",n)==0 ){
26347      bOnce = 1;
26348    }
26349    for(i=1; i<nArg; i++){
26350      char *z = azArg[i];
26351      if( z[0]=='-' ){
26352        if( z[1]=='-' ) z++;
26353        if( cli_strcmp(z,"-bom")==0 ){
26354          zBom = zBomUtf8;
26355        }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
26356          eMode = 'x';  /* spreadsheet */
26357        }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
26358          eMode = 'e';  /* text editor */
26359        }else{
26360          oputf("ERROR: unknown option: \"%s\".  Usage:\n", azArg[i]);
26361          showHelp(p->out, azArg[0]);
26362          rc = 1;
26363          goto meta_command_exit;
26364        }
26365      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
26366        zFile = sqlite3_mprintf("%s", z);
26367        if( zFile && zFile[0]=='|' ){
26368          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
26369          break;
26370        }
26371      }else{
26372        oputf("ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
26373        showHelp(p->out, azArg[0]);
26374        rc = 1;
26375        sqlite3_free(zFile);
26376        goto meta_command_exit;
26377      }
26378    }
26379    if( zFile==0 ){
26380      zFile = sqlite3_mprintf("stdout");
26381    }
26382    if( bOnce ){
26383      p->outCount = 2;
26384    }else{
26385      p->outCount = 0;
26386    }
26387    output_reset(p);
26388#ifndef SQLITE_NOHAVE_SYSTEM
26389    if( eMode=='e' || eMode=='x' ){
26390      p->doXdgOpen = 1;
26391      outputModePush(p);
26392      if( eMode=='x' ){
26393        /* spreadsheet mode.  Output as CSV. */
26394        newTempFile(p, "csv");
26395        ShellClearFlag(p, SHFLG_Echo);
26396        p->mode = MODE_Csv;
26397        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
26398        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
26399      }else{
26400        /* text editor mode */
26401        newTempFile(p, "txt");
26402        bTxtMode = 1;
26403      }
26404      sqlite3_free(zFile);
26405      zFile = sqlite3_mprintf("%s", p->zTempFile);
26406    }
26407#endif /* SQLITE_NOHAVE_SYSTEM */
26408    shell_check_oom(zFile);
26409    if( zFile[0]=='|' ){
26410#ifdef SQLITE_OMIT_POPEN
26411      eputz("Error: pipes are not supported in this OS\n");
26412      rc = 1;
26413      output_redir(p, stdout);
26414#else
26415      FILE *pfPipe = popen(zFile + 1, "w");
26416      if( pfPipe==0 ){
26417        eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
26418        rc = 1;
26419      }else{
26420        output_redir(p, pfPipe);
26421        if( zBom ) oputz(zBom);
26422        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
26423      }
26424#endif
26425    }else{
26426      FILE *pfFile = output_file_open(zFile, bTxtMode);
26427      if( pfFile==0 ){
26428        if( cli_strcmp(zFile,"off")!=0 ){
26429          eputf("Error: cannot write to \"%s\"\n", zFile);
26430        }
26431        rc = 1;
26432      } else {
26433        output_redir(p, pfFile);
26434        if( zBom ) oputz(zBom);
26435        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
26436      }
26437    }
26438    sqlite3_free(zFile);
26439  }else
26440#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26441
26442  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
26443    open_db(p,0);
26444    if( nArg<=1 ) goto parameter_syntax_error;
26445
26446    /* .parameter clear
26447    ** Clear all bind parameters by dropping the TEMP table that holds them.
26448    */
26449    if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
26450      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
26451                   0, 0, 0);
26452    }else
26453
26454    /* .parameter list
26455    ** List all bind parameters.
26456    */
26457    if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
26458      sqlite3_stmt *pStmt = 0;
26459      int rx;
26460      int len = 0;
26461      rx = sqlite3_prepare_v2(p->db,
26462             "SELECT max(length(key)) "
26463             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
26464      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26465        len = sqlite3_column_int(pStmt, 0);
26466        if( len>40 ) len = 40;
26467      }
26468      sqlite3_finalize(pStmt);
26469      pStmt = 0;
26470      if( len ){
26471        rx = sqlite3_prepare_v2(p->db,
26472             "SELECT key, quote(value) "
26473             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
26474        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26475          oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
26476                sqlite3_column_text(pStmt,1));
26477        }
26478        sqlite3_finalize(pStmt);
26479      }
26480    }else
26481
26482    /* .parameter init
26483    ** Make sure the TEMP table used to hold bind parameters exists.
26484    ** Create it if necessary.
26485    */
26486    if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
26487      bind_table_init(p);
26488    }else
26489
26490    /* .parameter set NAME VALUE
26491    ** Set or reset a bind parameter.  NAME should be the full parameter
26492    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
26493    ** VALUE can be in either SQL literal notation, or if not it will be
26494    ** understood to be a text string.
26495    */
26496    if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
26497      int rx;
26498      char *zSql;
26499      sqlite3_stmt *pStmt;
26500      const char *zKey = azArg[2];
26501      const char *zValue = azArg[3];
26502      bind_table_init(p);
26503      zSql = sqlite3_mprintf(
26504                  "REPLACE INTO temp.sqlite_parameters(key,value)"
26505                  "VALUES(%Q,%s);", zKey, zValue);
26506      shell_check_oom(zSql);
26507      pStmt = 0;
26508      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
26509      sqlite3_free(zSql);
26510      if( rx!=SQLITE_OK ){
26511        sqlite3_finalize(pStmt);
26512        pStmt = 0;
26513        zSql = sqlite3_mprintf(
26514                   "REPLACE INTO temp.sqlite_parameters(key,value)"
26515                   "VALUES(%Q,%Q);", zKey, zValue);
26516        shell_check_oom(zSql);
26517        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
26518        sqlite3_free(zSql);
26519        if( rx!=SQLITE_OK ){
26520          oputf("Error: %s\n", sqlite3_errmsg(p->db));
26521          sqlite3_finalize(pStmt);
26522          pStmt = 0;
26523          rc = 1;
26524        }
26525      }
26526      sqlite3_step(pStmt);
26527      sqlite3_finalize(pStmt);
26528    }else
26529
26530    /* .parameter unset NAME
26531    ** Remove the NAME binding from the parameter binding table, if it
26532    ** exists.
26533    */
26534    if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
26535      char *zSql = sqlite3_mprintf(
26536          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
26537      shell_check_oom(zSql);
26538      sqlite3_exec(p->db, zSql, 0, 0, 0);
26539      sqlite3_free(zSql);
26540    }else
26541    /* If no command name matches, show a syntax error */
26542    parameter_syntax_error:
26543    showHelp(p->out, "parameter");
26544  }else
26545
26546  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
26547    int i;
26548    for(i=1; i<nArg; i++){
26549      if( i>1 ) oputz(" ");
26550      oputz(azArg[i]);
26551    }
26552    oputz("\n");
26553  }else
26554
26555#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
26556  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
26557    int i;
26558    int nn = 0;
26559    p->flgProgress = 0;
26560    p->mxProgress = 0;
26561    p->nProgress = 0;
26562    for(i=1; i<nArg; i++){
26563      const char *z = azArg[i];
26564      if( z[0]=='-' ){
26565        z++;
26566        if( z[0]=='-' ) z++;
26567        if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
26568          p->flgProgress |= SHELL_PROGRESS_QUIET;
26569          continue;
26570        }
26571        if( cli_strcmp(z,"reset")==0 ){
26572          p->flgProgress |= SHELL_PROGRESS_RESET;
26573          continue;
26574        }
26575        if( cli_strcmp(z,"once")==0 ){
26576          p->flgProgress |= SHELL_PROGRESS_ONCE;
26577          continue;
26578        }
26579        if( cli_strcmp(z,"limit")==0 ){
26580          if( i+1>=nArg ){
26581            eputz("Error: missing argument on --limit\n");
26582            rc = 1;
26583            goto meta_command_exit;
26584          }else{
26585            p->mxProgress = (int)integerValue(azArg[++i]);
26586          }
26587          continue;
26588        }
26589        eputf("Error: unknown option: \"%s\"\n", azArg[i]);
26590        rc = 1;
26591        goto meta_command_exit;
26592      }else{
26593        nn = (int)integerValue(z);
26594      }
26595    }
26596    open_db(p, 0);
26597    sqlite3_progress_handler(p->db, nn, progress_handler, p);
26598  }else
26599#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
26600
26601  if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
26602    if( nArg >= 2) {
26603      shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
26604    }
26605    if( nArg >= 3) {
26606      shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
26607    }
26608  }else
26609
26610#ifndef SQLITE_SHELL_FIDDLE
26611  if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
26612    rc = 2;
26613  }else
26614#endif
26615
26616#ifndef SQLITE_SHELL_FIDDLE
26617  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
26618    FILE *inSaved = p->in;
26619    int savedLineno = p->lineno;
26620    failIfSafeMode(p, "cannot run .read in safe mode");
26621    if( nArg!=2 ){
26622      eputz("Usage: .read FILE\n");
26623      rc = 1;
26624      goto meta_command_exit;
26625    }
26626    if( azArg[1][0]=='|' ){
26627#ifdef SQLITE_OMIT_POPEN
26628      eputz("Error: pipes are not supported in this OS\n");
26629      rc = 1;
26630      p->out = stdout;
26631#else
26632      p->in = popen(azArg[1]+1, "r");
26633      if( p->in==0 ){
26634        eputf("Error: cannot open \"%s\"\n", azArg[1]);
26635        rc = 1;
26636      }else{
26637        rc = process_input(p);
26638        pclose(p->in);
26639      }
26640#endif
26641    }else if( (p->in = openChrSource(azArg[1]))==0 ){
26642      eputf("Error: cannot open \"%s\"\n", azArg[1]);
26643      rc = 1;
26644    }else{
26645      rc = process_input(p);
26646      fclose(p->in);
26647    }
26648    p->in = inSaved;
26649    p->lineno = savedLineno;
26650  }else
26651#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26652
26653#ifndef SQLITE_SHELL_FIDDLE
26654  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
26655    const char *zSrcFile;
26656    const char *zDb;
26657    sqlite3 *pSrc;
26658    sqlite3_backup *pBackup;
26659    int nTimeout = 0;
26660
26661    failIfSafeMode(p, "cannot run .restore in safe mode");
26662    if( nArg==2 ){
26663      zSrcFile = azArg[1];
26664      zDb = "main";
26665    }else if( nArg==3 ){
26666      zSrcFile = azArg[2];
26667      zDb = azArg[1];
26668    }else{
26669      eputz("Usage: .restore ?DB? FILE\n");
26670      rc = 1;
26671      goto meta_command_exit;
26672    }
26673    rc = sqlite3_open(zSrcFile, &pSrc);
26674    if( rc!=SQLITE_OK ){
26675      eputf("Error: cannot open \"%s\"\n", zSrcFile);
26676      close_db(pSrc);
26677      return 1;
26678    }
26679    open_db(p, 0);
26680    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
26681    if( pBackup==0 ){
26682      eputf("Error: %s\n", sqlite3_errmsg(p->db));
26683      close_db(pSrc);
26684      return 1;
26685    }
26686    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
26687          || rc==SQLITE_BUSY  ){
26688      if( rc==SQLITE_BUSY ){
26689        if( nTimeout++ >= 3 ) break;
26690        sqlite3_sleep(100);
26691      }
26692    }
26693    sqlite3_backup_finish(pBackup);
26694    if( rc==SQLITE_DONE ){
26695      rc = 0;
26696    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
26697      eputz("Error: source database is busy\n");
26698      rc = 1;
26699    }else{
26700      eputf("Error: %s\n", sqlite3_errmsg(p->db));
26701      rc = 1;
26702    }
26703    close_db(pSrc);
26704  }else
26705#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26706
26707  if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
26708    if( nArg==2 ){
26709      if( cli_strcmp(azArg[1], "vm")==0 ){
26710        p->scanstatsOn = 3;
26711      }else
26712      if( cli_strcmp(azArg[1], "est")==0 ){
26713        p->scanstatsOn = 2;
26714      }else{
26715        p->scanstatsOn = (u8)booleanValue(azArg[1]);
26716      }
26717      open_db(p, 0);
26718      sqlite3_db_config(
26719          p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
26720      );
26721#if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
26722      eputz("Warning: .scanstats not available in this build.\n");
26723#elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
26724      if( p->scanstatsOn==3 ){
26725        eputz("Warning: \".scanstats vm\" not available in this build.\n");
26726      }
26727#endif
26728    }else{
26729      eputz("Usage: .scanstats on|off|est\n");
26730      rc = 1;
26731    }
26732  }else
26733
26734  if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
26735    ShellText sSelect;
26736    ShellState data;
26737    char *zErrMsg = 0;
26738    const char *zDiv = "(";
26739    const char *zName = 0;
26740    int iSchema = 0;
26741    int bDebug = 0;
26742    int bNoSystemTabs = 0;
26743    int ii;
26744
26745    open_db(p, 0);
26746    memcpy(&data, p, sizeof(data));
26747    data.showHeader = 0;
26748    data.cMode = data.mode = MODE_Semi;
26749    initText(&sSelect);
26750    for(ii=1; ii<nArg; ii++){
26751      if( optionMatch(azArg[ii],"indent") ){
26752        data.cMode = data.mode = MODE_Pretty;
26753      }else if( optionMatch(azArg[ii],"debug") ){
26754        bDebug = 1;
26755      }else if( optionMatch(azArg[ii],"nosys") ){
26756        bNoSystemTabs = 1;
26757      }else if( azArg[ii][0]=='-' ){
26758        eputf("Unknown option: \"%s\"\n", azArg[ii]);
26759        rc = 1;
26760        goto meta_command_exit;
26761      }else if( zName==0 ){
26762        zName = azArg[ii];
26763      }else{
26764        eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
26765        rc = 1;
26766        goto meta_command_exit;
26767      }
26768    }
26769    if( zName!=0 ){
26770      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
26771                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
26772                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
26773                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
26774      if( isSchema ){
26775        char *new_argv[2], *new_colv[2];
26776        new_argv[0] = sqlite3_mprintf(
26777                      "CREATE TABLE %s (\n"
26778                      "  type text,\n"
26779                      "  name text,\n"
26780                      "  tbl_name text,\n"
26781                      "  rootpage integer,\n"
26782                      "  sql text\n"
26783                      ")", zName);
26784        shell_check_oom(new_argv[0]);
26785        new_argv[1] = 0;
26786        new_colv[0] = "sql";
26787        new_colv[1] = 0;
26788        callback(&data, 1, new_argv, new_colv);
26789        sqlite3_free(new_argv[0]);
26790      }
26791    }
26792    if( zDiv ){
26793      sqlite3_stmt *pStmt = 0;
26794      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
26795                              -1, &pStmt, 0);
26796      if( rc ){
26797        eputf("Error: %s\n", sqlite3_errmsg(p->db));
26798        sqlite3_finalize(pStmt);
26799        rc = 1;
26800        goto meta_command_exit;
26801      }
26802      appendText(&sSelect, "SELECT sql FROM", 0);
26803      iSchema = 0;
26804      while( sqlite3_step(pStmt)==SQLITE_ROW ){
26805        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
26806        char zScNum[30];
26807        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
26808        appendText(&sSelect, zDiv, 0);
26809        zDiv = " UNION ALL ";
26810        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
26811        if( sqlite3_stricmp(zDb, "main")!=0 ){
26812          appendText(&sSelect, zDb, '\'');
26813        }else{
26814          appendText(&sSelect, "NULL", 0);
26815        }
26816        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
26817        appendText(&sSelect, zScNum, 0);
26818        appendText(&sSelect, " AS snum, ", 0);
26819        appendText(&sSelect, zDb, '\'');
26820        appendText(&sSelect, " AS sname FROM ", 0);
26821        appendText(&sSelect, zDb, quoteChar(zDb));
26822        appendText(&sSelect, ".sqlite_schema", 0);
26823      }
26824      sqlite3_finalize(pStmt);
26825#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
26826      if( zName ){
26827        appendText(&sSelect,
26828           " UNION ALL SELECT shell_module_schema(name),"
26829           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
26830        0);
26831      }
26832#endif
26833      appendText(&sSelect, ") WHERE ", 0);
26834      if( zName ){
26835        char *zQarg = sqlite3_mprintf("%Q", zName);
26836        int bGlob;
26837        shell_check_oom(zQarg);
26838        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
26839                strchr(zName, '[') != 0;
26840        if( strchr(zName, '.') ){
26841          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
26842        }else{
26843          appendText(&sSelect, "lower(tbl_name)", 0);
26844        }
26845        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
26846        appendText(&sSelect, zQarg, 0);
26847        if( !bGlob ){
26848          appendText(&sSelect, " ESCAPE '\\' ", 0);
26849        }
26850        appendText(&sSelect, " AND ", 0);
26851        sqlite3_free(zQarg);
26852      }
26853      if( bNoSystemTabs ){
26854        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
26855      }
26856      appendText(&sSelect, "sql IS NOT NULL"
26857                           " ORDER BY snum, rowid", 0);
26858      if( bDebug ){
26859        oputf("SQL: %s;\n", sSelect.z);
26860      }else{
26861        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
26862      }
26863      freeText(&sSelect);
26864    }
26865    if( zErrMsg ){
26866      eputf("Error: %s\n", zErrMsg);
26867      sqlite3_free(zErrMsg);
26868      rc = 1;
26869    }else if( rc != SQLITE_OK ){
26870      eputz("Error: querying schema information\n");
26871      rc = 1;
26872    }else{
26873      rc = 0;
26874    }
26875  }else
26876
26877  if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
26878   || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
26879  ){
26880    unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
26881    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
26882  }else
26883
26884#if defined(SQLITE_ENABLE_SESSION)
26885  if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
26886    struct AuxDb *pAuxDb = p->pAuxDb;
26887    OpenSession *pSession = &pAuxDb->aSession[0];
26888    char **azCmd = &azArg[1];
26889    int iSes = 0;
26890    int nCmd = nArg - 1;
26891    int i;
26892    if( nArg<=1 ) goto session_syntax_error;
26893    open_db(p, 0);
26894    if( nArg>=3 ){
26895      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
26896        if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
26897      }
26898      if( iSes<pAuxDb->nSession ){
26899        pSession = &pAuxDb->aSession[iSes];
26900        azCmd++;
26901        nCmd--;
26902      }else{
26903        pSession = &pAuxDb->aSession[0];
26904        iSes = 0;
26905      }
26906    }
26907
26908    /* .session attach TABLE
26909    ** Invoke the sqlite3session_attach() interface to attach a particular
26910    ** table so that it is never filtered.
26911    */
26912    if( cli_strcmp(azCmd[0],"attach")==0 ){
26913      if( nCmd!=2 ) goto session_syntax_error;
26914      if( pSession->p==0 ){
26915        session_not_open:
26916        eputz("ERROR: No sessions are open\n");
26917      }else{
26918        rc = sqlite3session_attach(pSession->p, azCmd[1]);
26919        if( rc ){
26920          eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
26921          rc = 0;
26922        }
26923      }
26924    }else
26925
26926    /* .session changeset FILE
26927    ** .session patchset FILE
26928    ** Write a changeset or patchset into a file.  The file is overwritten.
26929    */
26930    if( cli_strcmp(azCmd[0],"changeset")==0
26931     || cli_strcmp(azCmd[0],"patchset")==0
26932    ){
26933      FILE *out = 0;
26934      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
26935      if( nCmd!=2 ) goto session_syntax_error;
26936      if( pSession->p==0 ) goto session_not_open;
26937      out = fopen(azCmd[1], "wb");
26938      if( out==0 ){
26939        eputf("ERROR: cannot open \"%s\" for writing\n",
26940              azCmd[1]);
26941      }else{
26942        int szChng;
26943        void *pChng;
26944        if( azCmd[0][0]=='c' ){
26945          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
26946        }else{
26947          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
26948        }
26949        if( rc ){
26950          sputf(stdout, "Error: error code %d\n", rc);
26951          rc = 0;
26952        }
26953        if( pChng
26954          && fwrite(pChng, szChng, 1, out)!=1 ){
26955          eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
26956        }
26957        sqlite3_free(pChng);
26958        fclose(out);
26959      }
26960    }else
26961
26962    /* .session close
26963    ** Close the identified session
26964    */
26965    if( cli_strcmp(azCmd[0], "close")==0 ){
26966      if( nCmd!=1 ) goto session_syntax_error;
26967      if( pAuxDb->nSession ){
26968        session_close(pSession);
26969        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
26970      }
26971    }else
26972
26973    /* .session enable ?BOOLEAN?
26974    ** Query or set the enable flag
26975    */
26976    if( cli_strcmp(azCmd[0], "enable")==0 ){
26977      int ii;
26978      if( nCmd>2 ) goto session_syntax_error;
26979      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
26980      if( pAuxDb->nSession ){
26981        ii = sqlite3session_enable(pSession->p, ii);
26982        oputf("session %s enable flag = %d\n", pSession->zName, ii);
26983      }
26984    }else
26985
26986    /* .session filter GLOB ....
26987    ** Set a list of GLOB patterns of table names to be excluded.
26988    */
26989    if( cli_strcmp(azCmd[0], "filter")==0 ){
26990      int ii, nByte;
26991      if( nCmd<2 ) goto session_syntax_error;
26992      if( pAuxDb->nSession ){
26993        for(ii=0; ii<pSession->nFilter; ii++){
26994          sqlite3_free(pSession->azFilter[ii]);
26995        }
26996        sqlite3_free(pSession->azFilter);
26997        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
26998        pSession->azFilter = sqlite3_malloc( nByte );
26999        shell_check_oom( pSession->azFilter );
27000        for(ii=1; ii<nCmd; ii++){
27001          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
27002          shell_check_oom(x);
27003        }
27004        pSession->nFilter = ii-1;
27005      }
27006    }else
27007
27008    /* .session indirect ?BOOLEAN?
27009    ** Query or set the indirect flag
27010    */
27011    if( cli_strcmp(azCmd[0], "indirect")==0 ){
27012      int ii;
27013      if( nCmd>2 ) goto session_syntax_error;
27014      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
27015      if( pAuxDb->nSession ){
27016        ii = sqlite3session_indirect(pSession->p, ii);
27017        oputf("session %s indirect flag = %d\n", pSession->zName, ii);
27018      }
27019    }else
27020
27021    /* .session isempty
27022    ** Determine if the session is empty
27023    */
27024    if( cli_strcmp(azCmd[0], "isempty")==0 ){
27025      int ii;
27026      if( nCmd!=1 ) goto session_syntax_error;
27027      if( pAuxDb->nSession ){
27028        ii = sqlite3session_isempty(pSession->p);
27029        oputf("session %s isempty flag = %d\n", pSession->zName, ii);
27030      }
27031    }else
27032
27033    /* .session list
27034    ** List all currently open sessions
27035    */
27036    if( cli_strcmp(azCmd[0],"list")==0 ){
27037      for(i=0; i<pAuxDb->nSession; i++){
27038        oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
27039      }
27040    }else
27041
27042    /* .session open DB NAME
27043    ** Open a new session called NAME on the attached database DB.
27044    ** DB is normally "main".
27045    */
27046    if( cli_strcmp(azCmd[0],"open")==0 ){
27047      char *zName;
27048      if( nCmd!=3 ) goto session_syntax_error;
27049      zName = azCmd[2];
27050      if( zName[0]==0 ) goto session_syntax_error;
27051      for(i=0; i<pAuxDb->nSession; i++){
27052        if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
27053          eputf("Session \"%s\" already exists\n", zName);
27054          goto meta_command_exit;
27055        }
27056      }
27057      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
27058        eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
27059        goto meta_command_exit;
27060      }
27061      pSession = &pAuxDb->aSession[pAuxDb->nSession];
27062      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
27063      if( rc ){
27064        eputf("Cannot open session: error code=%d\n", rc);
27065        rc = 0;
27066        goto meta_command_exit;
27067      }
27068      pSession->nFilter = 0;
27069      sqlite3session_table_filter(pSession->p, session_filter, pSession);
27070      pAuxDb->nSession++;
27071      pSession->zName = sqlite3_mprintf("%s", zName);
27072      shell_check_oom(pSession->zName);
27073    }else
27074    /* If no command name matches, show a syntax error */
27075    session_syntax_error:
27076    showHelp(p->out, "session");
27077  }else
27078#endif
27079
27080#ifdef SQLITE_DEBUG
27081  /* Undocumented commands for internal testing.  Subject to change
27082  ** without notice. */
27083  if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
27084    if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
27085      int i, v;
27086      for(i=1; i<nArg; i++){
27087        v = booleanValue(azArg[i]);
27088        oputf("%s: %d 0x%x\n", azArg[i], v, v);
27089      }
27090    }
27091    if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
27092      int i; sqlite3_int64 v;
27093      for(i=1; i<nArg; i++){
27094        char zBuf[200];
27095        v = integerValue(azArg[i]);
27096        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
27097        oputz(zBuf);
27098      }
27099    }
27100  }else
27101#endif
27102
27103  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
27104    int bIsInit = 0;         /* True to initialize the SELFTEST table */
27105    int bVerbose = 0;        /* Verbose output */
27106    int bSelftestExists;     /* True if SELFTEST already exists */
27107    int i, k;                /* Loop counters */
27108    int nTest = 0;           /* Number of tests runs */
27109    int nErr = 0;            /* Number of errors seen */
27110    ShellText str;           /* Answer for a query */
27111    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
27112
27113    open_db(p,0);
27114    for(i=1; i<nArg; i++){
27115      const char *z = azArg[i];
27116      if( z[0]=='-' && z[1]=='-' ) z++;
27117      if( cli_strcmp(z,"-init")==0 ){
27118        bIsInit = 1;
27119      }else
27120      if( cli_strcmp(z,"-v")==0 ){
27121        bVerbose++;
27122      }else
27123      {
27124        eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
27125        eputz("Should be one of: --init -v\n");
27126        rc = 1;
27127        goto meta_command_exit;
27128      }
27129    }
27130    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
27131           != SQLITE_OK ){
27132      bSelftestExists = 0;
27133    }else{
27134      bSelftestExists = 1;
27135    }
27136    if( bIsInit ){
27137      createSelftestTable(p);
27138      bSelftestExists = 1;
27139    }
27140    initText(&str);
27141    appendText(&str, "x", 0);
27142    for(k=bSelftestExists; k>=0; k--){
27143      if( k==1 ){
27144        rc = sqlite3_prepare_v2(p->db,
27145            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
27146            -1, &pStmt, 0);
27147      }else{
27148        rc = sqlite3_prepare_v2(p->db,
27149          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
27150          "      (1,'run','PRAGMA integrity_check','ok')",
27151          -1, &pStmt, 0);
27152      }
27153      if( rc ){
27154        eputz("Error querying the selftest table\n");
27155        rc = 1;
27156        sqlite3_finalize(pStmt);
27157        goto meta_command_exit;
27158      }
27159      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
27160        int tno = sqlite3_column_int(pStmt, 0);
27161        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
27162        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
27163        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
27164
27165        if( zOp==0 ) continue;
27166        if( zSql==0 ) continue;
27167        if( zAns==0 ) continue;
27168        k = 0;
27169        if( bVerbose>0 ){
27170          sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
27171        }
27172        if( cli_strcmp(zOp,"memo")==0 ){
27173          oputf("%s\n", zSql);
27174        }else
27175        if( cli_strcmp(zOp,"run")==0 ){
27176          char *zErrMsg = 0;
27177          str.n = 0;
27178          str.z[0] = 0;
27179          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
27180          nTest++;
27181          if( bVerbose ){
27182            oputf("Result: %s\n", str.z);
27183          }
27184          if( rc || zErrMsg ){
27185            nErr++;
27186            rc = 1;
27187            oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
27188            sqlite3_free(zErrMsg);
27189          }else if( cli_strcmp(zAns,str.z)!=0 ){
27190            nErr++;
27191            rc = 1;
27192            oputf("%d: Expected: [%s]\n", tno, zAns);
27193            oputf("%d:      Got: [%s]\n", tno, str.z);
27194          }
27195        }
27196        else{
27197          eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
27198          rc = 1;
27199          break;
27200        }
27201      } /* End loop over rows of content from SELFTEST */
27202      sqlite3_finalize(pStmt);
27203    } /* End loop over k */
27204    freeText(&str);
27205    oputf("%d errors out of %d tests\n", nErr, nTest);
27206  }else
27207
27208  if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
27209    if( nArg<2 || nArg>3 ){
27210      eputz("Usage: .separator COL ?ROW?\n");
27211      rc = 1;
27212    }
27213    if( nArg>=2 ){
27214      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
27215                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
27216    }
27217    if( nArg>=3 ){
27218      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
27219                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
27220    }
27221  }else
27222
27223  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
27224    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
27225    int i;                   /* Loop counter */
27226    int bSchema = 0;         /* Also hash the schema */
27227    int bSeparate = 0;       /* Hash each table separately */
27228    int iSize = 224;         /* Hash algorithm to use */
27229    int bDebug = 0;          /* Only show the query that would have run */
27230    sqlite3_stmt *pStmt;     /* For querying tables names */
27231    char *zSql;              /* SQL to be run */
27232    char *zSep;              /* Separator */
27233    ShellText sSql;          /* Complete SQL for the query to run the hash */
27234    ShellText sQuery;        /* Set of queries used to read all content */
27235    open_db(p, 0);
27236    for(i=1; i<nArg; i++){
27237      const char *z = azArg[i];
27238      if( z[0]=='-' ){
27239        z++;
27240        if( z[0]=='-' ) z++;
27241        if( cli_strcmp(z,"schema")==0 ){
27242          bSchema = 1;
27243        }else
27244        if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
27245         || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
27246        ){
27247          iSize = atoi(&z[5]);
27248        }else
27249        if( cli_strcmp(z,"debug")==0 ){
27250          bDebug = 1;
27251        }else
27252        {
27253          eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
27254          showHelp(p->out, azArg[0]);
27255          rc = 1;
27256          goto meta_command_exit;
27257        }
27258      }else if( zLike ){
27259        eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
27260        rc = 1;
27261        goto meta_command_exit;
27262      }else{
27263        zLike = z;
27264        bSeparate = 1;
27265        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
27266      }
27267    }
27268    if( bSchema ){
27269      zSql = "SELECT lower(name) as tname FROM sqlite_schema"
27270             " WHERE type='table' AND coalesce(rootpage,0)>1"
27271             " UNION ALL SELECT 'sqlite_schema'"
27272             " ORDER BY 1 collate nocase";
27273    }else{
27274      zSql = "SELECT lower(name) as tname FROM sqlite_schema"
27275             " WHERE type='table' AND coalesce(rootpage,0)>1"
27276             " AND name NOT LIKE 'sqlite_%'"
27277             " ORDER BY 1 collate nocase";
27278    }
27279    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27280    initText(&sQuery);
27281    initText(&sSql);
27282    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
27283    zSep = "VALUES(";
27284    while( SQLITE_ROW==sqlite3_step(pStmt) ){
27285      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
27286      if( zTab==0 ) continue;
27287      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
27288      if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
27289        appendText(&sQuery,"SELECT * FROM ", 0);
27290        appendText(&sQuery,zTab,'"');
27291        appendText(&sQuery," NOT INDEXED;", 0);
27292      }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
27293        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
27294                           " ORDER BY name;", 0);
27295      }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
27296        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
27297                           " ORDER BY name;", 0);
27298      }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
27299        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
27300                           " ORDER BY tbl,idx;", 0);
27301      }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
27302        appendText(&sQuery, "SELECT * FROM ", 0);
27303        appendText(&sQuery, zTab, 0);
27304        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
27305      }
27306      appendText(&sSql, zSep, 0);
27307      appendText(&sSql, sQuery.z, '\'');
27308      sQuery.n = 0;
27309      appendText(&sSql, ",", 0);
27310      appendText(&sSql, zTab, '\'');
27311      zSep = "),(";
27312    }
27313    sqlite3_finalize(pStmt);
27314    if( bSeparate ){
27315      zSql = sqlite3_mprintf(
27316          "%s))"
27317          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
27318          "   FROM [sha3sum$query]",
27319          sSql.z, iSize);
27320    }else{
27321      zSql = sqlite3_mprintf(
27322          "%s))"
27323          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
27324          "   FROM [sha3sum$query]",
27325          sSql.z, iSize);
27326    }
27327    shell_check_oom(zSql);
27328    freeText(&sQuery);
27329    freeText(&sSql);
27330    if( bDebug ){
27331      oputf("%s\n", zSql);
27332    }else{
27333      shell_exec(p, zSql, 0);
27334    }
27335#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27336    {
27337      int lrc;
27338      char *zRevText = /* Query for reversible to-blob-to-text check */
27339        "SELECT lower(name) as tname FROM sqlite_schema\n"
27340        "WHERE type='table' AND coalesce(rootpage,0)>1\n"
27341        "AND name NOT LIKE 'sqlite_%%'%s\n"
27342        "ORDER BY 1 collate nocase";
27343      zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
27344      zRevText = sqlite3_mprintf(
27345          /* lower-case query is first run, producing upper-case query. */
27346          "with tabcols as materialized(\n"
27347          "select tname, cname\n"
27348          "from ("
27349          " select printf('\"%%w\"',ss.tname) as tname,"
27350          " printf('\"%%w\"',ti.name) as cname\n"
27351          " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
27352          "select 'SELECT total(bad_text_count) AS bad_text_count\n"
27353          "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
27354          " from (select 'SELECT COUNT(*) AS bad_text_count\n"
27355          "FROM '||tname||' WHERE '\n"
27356          "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
27357          "|| ' AND typeof('||cname||')=''text'' ',\n"
27358          "' OR ') as query, tname from tabcols group by tname)"
27359          , zRevText);
27360      shell_check_oom(zRevText);
27361      if( bDebug ) oputf("%s\n", zRevText);
27362      lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
27363      if( lrc!=SQLITE_OK ){
27364        /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
27365        ** user does cruel and unnatural things like ".limit expr_depth 0". */
27366        rc = 1;
27367      }else{
27368        if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
27369        lrc = SQLITE_ROW==sqlite3_step(pStmt);
27370        if( lrc ){
27371          const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
27372          sqlite3_stmt *pCheckStmt;
27373          lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
27374          if( bDebug ) oputf("%s\n", zGenQuery);
27375          if( lrc!=SQLITE_OK ){
27376            rc = 1;
27377          }else{
27378            if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
27379              double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
27380              if( countIrreversible>0 ){
27381                int sz = (int)(countIrreversible + 0.5);
27382                eputf("Digest includes %d invalidly encoded text field%s.\n",
27383                      sz, (sz>1)? "s": "");
27384              }
27385            }
27386            sqlite3_finalize(pCheckStmt);
27387          }
27388          sqlite3_finalize(pStmt);
27389        }
27390      }
27391      if( rc ) eputz(".sha3sum failed.\n");
27392      sqlite3_free(zRevText);
27393    }
27394#endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
27395    sqlite3_free(zSql);
27396  }else
27397
27398#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
27399  if( c=='s'
27400   && (cli_strncmp(azArg[0], "shell", n)==0
27401       || cli_strncmp(azArg[0],"system",n)==0)
27402  ){
27403    char *zCmd;
27404    int i, x;
27405    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
27406    if( nArg<2 ){
27407      eputz("Usage: .system COMMAND\n");
27408      rc = 1;
27409      goto meta_command_exit;
27410    }
27411    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
27412    for(i=2; i<nArg && zCmd!=0; i++){
27413      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
27414                             zCmd, azArg[i]);
27415    }
27416    consoleRestore();
27417    x = zCmd!=0 ? system(zCmd) : 1;
27418    consoleRenewSetup();
27419    sqlite3_free(zCmd);
27420    if( x ) eputf("System command returns %d\n", x);
27421  }else
27422#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
27423
27424  if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
27425    static const char *azBool[] = { "off", "on", "trigger", "full"};
27426    const char *zOut;
27427    int i;
27428    if( nArg!=1 ){
27429      eputz("Usage: .show\n");
27430      rc = 1;
27431      goto meta_command_exit;
27432    }
27433    oputf("%12.12s: %s\n","echo",
27434          azBool[ShellHasFlag(p, SHFLG_Echo)]);
27435    oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
27436    oputf("%12.12s: %s\n","explain",
27437          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
27438    oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
27439    if( p->mode==MODE_Column
27440     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
27441    ){
27442      oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
27443            modeDescr[p->mode], p->cmOpts.iWrap,
27444            p->cmOpts.bWordWrap ? "on" : "off",
27445            p->cmOpts.bQuote ? "" : "no");
27446    }else{
27447      oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
27448    }
27449    oputf("%12.12s: ", "nullvalue");
27450    output_c_string(p->nullValue);
27451    oputz("\n");
27452    oputf("%12.12s: %s\n","output",
27453          strlen30(p->outfile) ? p->outfile : "stdout");
27454    oputf("%12.12s: ", "colseparator");
27455     output_c_string(p->colSeparator);
27456     oputz("\n");
27457    oputf("%12.12s: ", "rowseparator");
27458     output_c_string(p->rowSeparator);
27459     oputz("\n");
27460    switch( p->statsOn ){
27461      case 0:  zOut = "off";     break;
27462      default: zOut = "on";      break;
27463      case 2:  zOut = "stmt";    break;
27464      case 3:  zOut = "vmstep";  break;
27465    }
27466    oputf("%12.12s: %s\n","stats", zOut);
27467    oputf("%12.12s: ", "width");
27468    for (i=0;i<p->nWidth;i++) {
27469      oputf("%d ", p->colWidth[i]);
27470    }
27471    oputz("\n");
27472    oputf("%12.12s: %s\n", "filename",
27473          p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
27474  }else
27475
27476  if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
27477    if( nArg==2 ){
27478      if( cli_strcmp(azArg[1],"stmt")==0 ){
27479        p->statsOn = 2;
27480      }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
27481        p->statsOn = 3;
27482      }else{
27483        p->statsOn = (u8)booleanValue(azArg[1]);
27484      }
27485    }else if( nArg==1 ){
27486      display_stats(p->db, p, 0);
27487    }else{
27488      eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
27489      rc = 1;
27490    }
27491  }else
27492
27493  if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
27494   || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
27495                 || cli_strncmp(azArg[0], "indexes", n)==0) )
27496  ){
27497    sqlite3_stmt *pStmt;
27498    char **azResult;
27499    int nRow, nAlloc;
27500    int ii;
27501    ShellText s;
27502    initText(&s);
27503    open_db(p, 0);
27504    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
27505    if( rc ){
27506      sqlite3_finalize(pStmt);
27507      return shellDatabaseError(p->db);
27508    }
27509
27510    if( nArg>2 && c=='i' ){
27511      /* It is an historical accident that the .indexes command shows an error
27512      ** when called with the wrong number of arguments whereas the .tables
27513      ** command does not. */
27514      eputz("Usage: .indexes ?LIKE-PATTERN?\n");
27515      rc = 1;
27516      sqlite3_finalize(pStmt);
27517      goto meta_command_exit;
27518    }
27519    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
27520      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
27521      if( zDbName==0 ) continue;
27522      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
27523      if( sqlite3_stricmp(zDbName, "main")==0 ){
27524        appendText(&s, "SELECT name FROM ", 0);
27525      }else{
27526        appendText(&s, "SELECT ", 0);
27527        appendText(&s, zDbName, '\'');
27528        appendText(&s, "||'.'||name FROM ", 0);
27529      }
27530      appendText(&s, zDbName, '"');
27531      appendText(&s, ".sqlite_schema ", 0);
27532      if( c=='t' ){
27533        appendText(&s," WHERE type IN ('table','view')"
27534                      "   AND name NOT LIKE 'sqlite_%'"
27535                      "   AND name LIKE ?1", 0);
27536      }else{
27537        appendText(&s," WHERE type='index'"
27538                      "   AND tbl_name LIKE ?1", 0);
27539      }
27540    }
27541    rc = sqlite3_finalize(pStmt);
27542    if( rc==SQLITE_OK ){
27543      appendText(&s, " ORDER BY 1", 0);
27544      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
27545    }
27546    freeText(&s);
27547    if( rc ) return shellDatabaseError(p->db);
27548
27549    /* Run the SQL statement prepared by the above block. Store the results
27550    ** as an array of nul-terminated strings in azResult[].  */
27551    nRow = nAlloc = 0;
27552    azResult = 0;
27553    if( nArg>1 ){
27554      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
27555    }else{
27556      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
27557    }
27558    while( sqlite3_step(pStmt)==SQLITE_ROW ){
27559      if( nRow>=nAlloc ){
27560        char **azNew;
27561        int n2 = nAlloc*2 + 10;
27562        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
27563        shell_check_oom(azNew);
27564        nAlloc = n2;
27565        azResult = azNew;
27566      }
27567      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
27568      shell_check_oom(azResult[nRow]);
27569      nRow++;
27570    }
27571    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
27572      rc = shellDatabaseError(p->db);
27573    }
27574
27575    /* Pretty-print the contents of array azResult[] to the output */
27576    if( rc==0 && nRow>0 ){
27577      int len, maxlen = 0;
27578      int i, j;
27579      int nPrintCol, nPrintRow;
27580      for(i=0; i<nRow; i++){
27581        len = strlen30(azResult[i]);
27582        if( len>maxlen ) maxlen = len;
27583      }
27584      nPrintCol = 80/(maxlen+2);
27585      if( nPrintCol<1 ) nPrintCol = 1;
27586      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
27587      for(i=0; i<nPrintRow; i++){
27588        for(j=i; j<nRow; j+=nPrintRow){
27589          char *zSp = j<nPrintRow ? "" : "  ";
27590          oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
27591        }
27592        oputz("\n");
27593      }
27594    }
27595
27596    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
27597    sqlite3_free(azResult);
27598  }else
27599
27600#ifndef SQLITE_SHELL_FIDDLE
27601  /* Begin redirecting output to the file "testcase-out.txt" */
27602  if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
27603    output_reset(p);
27604    p->out = output_file_open("testcase-out.txt", 0);
27605    if( p->out==0 ){
27606      eputz("Error: cannot open 'testcase-out.txt'\n");
27607    }
27608    if( nArg>=2 ){
27609      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
27610    }else{
27611      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
27612    }
27613  }else
27614#endif /* !defined(SQLITE_SHELL_FIDDLE) */
27615
27616#ifndef SQLITE_UNTESTABLE
27617  if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
27618    static const struct {
27619       const char *zCtrlName;   /* Name of a test-control option */
27620       int ctrlCode;            /* Integer code for that option */
27621       int unSafe;              /* Not valid unless --unsafe-testing */
27622       const char *zUsage;      /* Usage notes */
27623    } aCtrl[] = {
27624    {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
27625    {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
27626  /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
27627  /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
27628    {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
27629    {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
27630  /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
27631    {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
27632    {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
27633    {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
27634    {"json_selfcheck",     SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN"      },
27635    {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
27636    {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
27637    {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
27638#ifdef YYCOVERAGE
27639    {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
27640#endif
27641    {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
27642    {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
27643    {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
27644    {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
27645    {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
27646    {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
27647    {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
27648    {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
27649    };
27650    int testctrl = -1;
27651    int iCtrl = -1;
27652    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
27653    int isOk = 0;
27654    int i, n2;
27655    const char *zCmd = 0;
27656
27657    open_db(p, 0);
27658    zCmd = nArg>=2 ? azArg[1] : "help";
27659
27660    /* The argument can optionally begin with "-" or "--" */
27661    if( zCmd[0]=='-' && zCmd[1] ){
27662      zCmd++;
27663      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
27664    }
27665
27666    /* --help lists all test-controls */
27667    if( cli_strcmp(zCmd,"help")==0 ){
27668      oputz("Available test-controls:\n");
27669      for(i=0; i<ArraySize(aCtrl); i++){
27670        if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
27671        oputf("  .testctrl %s %s\n",
27672              aCtrl[i].zCtrlName, aCtrl[i].zUsage);
27673      }
27674      rc = 1;
27675      goto meta_command_exit;
27676    }
27677
27678    /* convert testctrl text option to value. allow any unique prefix
27679    ** of the option name, or a numerical value. */
27680    n2 = strlen30(zCmd);
27681    for(i=0; i<ArraySize(aCtrl); i++){
27682      if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
27683      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
27684        if( testctrl<0 ){
27685          testctrl = aCtrl[i].ctrlCode;
27686          iCtrl = i;
27687        }else{
27688          eputf("Error: ambiguous test-control: \"%s\"\n"
27689                "Use \".testctrl --help\" for help\n", zCmd);
27690          rc = 1;
27691          goto meta_command_exit;
27692        }
27693      }
27694    }
27695    if( testctrl<0 ){
27696      eputf("Error: unknown test-control: %s\n"
27697            "Use \".testctrl --help\" for help\n", zCmd);
27698    }else{
27699      switch(testctrl){
27700
27701        /* sqlite3_test_control(int, db, int) */
27702        case SQLITE_TESTCTRL_OPTIMIZATIONS:
27703        case SQLITE_TESTCTRL_FK_NO_ACTION:
27704          if( nArg==3 ){
27705            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
27706            rc2 = sqlite3_test_control(testctrl, p->db, opt);
27707            isOk = 3;
27708          }
27709          break;
27710
27711        /* sqlite3_test_control(int) */
27712        case SQLITE_TESTCTRL_PRNG_SAVE:
27713        case SQLITE_TESTCTRL_PRNG_RESTORE:
27714        case SQLITE_TESTCTRL_BYTEORDER:
27715          if( nArg==2 ){
27716            rc2 = sqlite3_test_control(testctrl);
27717            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
27718          }
27719          break;
27720
27721        /* sqlite3_test_control(int, uint) */
27722        case SQLITE_TESTCTRL_PENDING_BYTE:
27723          if( nArg==3 ){
27724            unsigned int opt = (unsigned int)integerValue(azArg[2]);
27725            rc2 = sqlite3_test_control(testctrl, opt);
27726            isOk = 3;
27727          }
27728          break;
27729
27730        /* sqlite3_test_control(int, int, sqlite3*) */
27731        case SQLITE_TESTCTRL_PRNG_SEED:
27732          if( nArg==3 || nArg==4 ){
27733            int ii = (int)integerValue(azArg[2]);
27734            sqlite3 *db;
27735            if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
27736              sqlite3_randomness(sizeof(ii),&ii);
27737              sputf(stdout, "-- random seed: %d\n", ii);
27738            }
27739            if( nArg==3 ){
27740              db = 0;
27741            }else{
27742              db = p->db;
27743              /* Make sure the schema has been loaded */
27744              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
27745            }
27746            rc2 = sqlite3_test_control(testctrl, ii, db);
27747            isOk = 3;
27748          }
27749          break;
27750
27751        /* sqlite3_test_control(int, int) */
27752        case SQLITE_TESTCTRL_ASSERT:
27753        case SQLITE_TESTCTRL_ALWAYS:
27754          if( nArg==3 ){
27755            int opt = booleanValue(azArg[2]);
27756            rc2 = sqlite3_test_control(testctrl, opt);
27757            isOk = 1;
27758          }
27759          break;
27760
27761        /* sqlite3_test_control(int, int) */
27762        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
27763        case SQLITE_TESTCTRL_NEVER_CORRUPT:
27764          if( nArg==3 ){
27765            int opt = booleanValue(azArg[2]);
27766            rc2 = sqlite3_test_control(testctrl, opt);
27767            isOk = 3;
27768          }
27769          break;
27770
27771        /* sqlite3_test_control(int, int) */
27772        case SQLITE_TESTCTRL_USELONGDOUBLE: {
27773          int opt = -1;
27774          if( nArg==3 ){
27775            if( cli_strcmp(azArg[2],"default")==0 ){
27776              opt = 2;
27777            }else{
27778              opt = booleanValue(azArg[2]);
27779            }
27780          }
27781          rc2 = sqlite3_test_control(testctrl, opt);
27782          isOk = 1;
27783          break;
27784        }
27785
27786        /* sqlite3_test_control(sqlite3*) */
27787        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
27788          rc2 = sqlite3_test_control(testctrl, p->db);
27789          isOk = 3;
27790          break;
27791
27792        case SQLITE_TESTCTRL_IMPOSTER:
27793          if( nArg==5 ){
27794            rc2 = sqlite3_test_control(testctrl, p->db,
27795                          azArg[2],
27796                          integerValue(azArg[3]),
27797                          integerValue(azArg[4]));
27798            isOk = 3;
27799          }
27800          break;
27801
27802        case SQLITE_TESTCTRL_SEEK_COUNT: {
27803          u64 x = 0;
27804          rc2 = sqlite3_test_control(testctrl, p->db, &x);
27805          oputf("%llu\n", x);
27806          isOk = 3;
27807          break;
27808        }
27809
27810#ifdef YYCOVERAGE
27811        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
27812          if( nArg==2 ){
27813            sqlite3_test_control(testctrl, p->out);
27814            isOk = 3;
27815          }
27816          break;
27817        }
27818#endif
27819#ifdef SQLITE_DEBUG
27820        case SQLITE_TESTCTRL_TUNE: {
27821          if( nArg==4 ){
27822            int id = (int)integerValue(azArg[2]);
27823            int val = (int)integerValue(azArg[3]);
27824            sqlite3_test_control(testctrl, id, &val);
27825            isOk = 3;
27826          }else if( nArg==3 ){
27827            int id = (int)integerValue(azArg[2]);
27828            sqlite3_test_control(testctrl, -id, &rc2);
27829            isOk = 1;
27830          }else if( nArg==2 ){
27831            int id = 1;
27832            while(1){
27833              int val = 0;
27834              rc2 = sqlite3_test_control(testctrl, -id, &val);
27835              if( rc2!=SQLITE_OK ) break;
27836              if( id>1 ) oputz("  ");
27837              oputf("%d: %d", id, val);
27838              id++;
27839            }
27840            if( id>1 ) oputz("\n");
27841            isOk = 3;
27842          }
27843          break;
27844        }
27845#endif
27846        case SQLITE_TESTCTRL_SORTER_MMAP:
27847          if( nArg==3 ){
27848            int opt = (unsigned int)integerValue(azArg[2]);
27849            rc2 = sqlite3_test_control(testctrl, p->db, opt);
27850            isOk = 3;
27851          }
27852          break;
27853        case SQLITE_TESTCTRL_JSON_SELFCHECK:
27854          if( nArg==2 ){
27855            rc2 = -1;
27856            isOk = 1;
27857          }else{
27858            rc2 = booleanValue(azArg[2]);
27859            isOk = 3;
27860          }
27861          sqlite3_test_control(testctrl, &rc2);
27862          break;
27863      }
27864    }
27865    if( isOk==0 && iCtrl>=0 ){
27866      oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
27867      rc = 1;
27868    }else if( isOk==1 ){
27869      oputf("%d\n", rc2);
27870    }else if( isOk==2 ){
27871      oputf("0x%08x\n", rc2);
27872    }
27873  }else
27874#endif /* !defined(SQLITE_UNTESTABLE) */
27875
27876  if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
27877    open_db(p, 0);
27878    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
27879  }else
27880
27881  if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
27882    if( nArg==2 ){
27883      enableTimer = booleanValue(azArg[1]);
27884      if( enableTimer && !HAS_TIMER ){
27885        eputz("Error: timer not available on this system.\n");
27886        enableTimer = 0;
27887      }
27888    }else{
27889      eputz("Usage: .timer on|off\n");
27890      rc = 1;
27891    }
27892  }else
27893
27894#ifndef SQLITE_OMIT_TRACE
27895  if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
27896    int mType = 0;
27897    int jj;
27898    open_db(p, 0);
27899    for(jj=1; jj<nArg; jj++){
27900      const char *z = azArg[jj];
27901      if( z[0]=='-' ){
27902        if( optionMatch(z, "expanded") ){
27903          p->eTraceType = SHELL_TRACE_EXPANDED;
27904        }
27905#ifdef SQLITE_ENABLE_NORMALIZE
27906        else if( optionMatch(z, "normalized") ){
27907          p->eTraceType = SHELL_TRACE_NORMALIZED;
27908        }
27909#endif
27910        else if( optionMatch(z, "plain") ){
27911          p->eTraceType = SHELL_TRACE_PLAIN;
27912        }
27913        else if( optionMatch(z, "profile") ){
27914          mType |= SQLITE_TRACE_PROFILE;
27915        }
27916        else if( optionMatch(z, "row") ){
27917          mType |= SQLITE_TRACE_ROW;
27918        }
27919        else if( optionMatch(z, "stmt") ){
27920          mType |= SQLITE_TRACE_STMT;
27921        }
27922        else if( optionMatch(z, "close") ){
27923          mType |= SQLITE_TRACE_CLOSE;
27924        }
27925        else {
27926          eputf("Unknown option \"%s\" on \".trace\"\n", z);
27927          rc = 1;
27928          goto meta_command_exit;
27929        }
27930      }else{
27931        output_file_close(p->traceOut);
27932        p->traceOut = output_file_open(z, 0);
27933      }
27934    }
27935    if( p->traceOut==0 ){
27936      sqlite3_trace_v2(p->db, 0, 0, 0);
27937    }else{
27938      if( mType==0 ) mType = SQLITE_TRACE_STMT;
27939      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
27940    }
27941  }else
27942#endif /* !defined(SQLITE_OMIT_TRACE) */
27943
27944#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27945  if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
27946    int ii;
27947    int lenOpt;
27948    char *zOpt;
27949    if( nArg<2 ){
27950      eputz("Usage: .unmodule [--allexcept] NAME ...\n");
27951      rc = 1;
27952      goto meta_command_exit;
27953    }
27954    open_db(p, 0);
27955    zOpt = azArg[1];
27956    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
27957    lenOpt = (int)strlen(zOpt);
27958    if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
27959      assert( azArg[nArg]==0 );
27960      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
27961    }else{
27962      for(ii=1; ii<nArg; ii++){
27963        sqlite3_create_module(p->db, azArg[ii], 0, 0);
27964      }
27965    }
27966  }else
27967#endif
27968
27969#if SQLITE_USER_AUTHENTICATION
27970  if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
27971    if( nArg<2 ){
27972      eputz("Usage: .user SUBCOMMAND ...\n");
27973      rc = 1;
27974      goto meta_command_exit;
27975    }
27976    open_db(p, 0);
27977    if( cli_strcmp(azArg[1],"login")==0 ){
27978      if( nArg!=4 ){
27979        eputz("Usage: .user login USER PASSWORD\n");
27980        rc = 1;
27981        goto meta_command_exit;
27982      }
27983      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
27984                                     strlen30(azArg[3]));
27985      if( rc ){
27986        eputf("Authentication failed for user %s\n", azArg[2]);
27987        rc = 1;
27988      }
27989    }else if( cli_strcmp(azArg[1],"add")==0 ){
27990      if( nArg!=5 ){
27991        eputz("Usage: .user add USER PASSWORD ISADMIN\n");
27992        rc = 1;
27993        goto meta_command_exit;
27994      }
27995      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
27996                            booleanValue(azArg[4]));
27997      if( rc ){
27998        eputf("User-Add failed: %d\n", rc);
27999        rc = 1;
28000      }
28001    }else if( cli_strcmp(azArg[1],"edit")==0 ){
28002      if( nArg!=5 ){
28003        eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
28004        rc = 1;
28005        goto meta_command_exit;
28006      }
28007      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
28008                              booleanValue(azArg[4]));
28009      if( rc ){
28010        eputf("User-Edit failed: %d\n", rc);
28011        rc = 1;
28012      }
28013    }else if( cli_strcmp(azArg[1],"delete")==0 ){
28014      if( nArg!=3 ){
28015        eputz("Usage: .user delete USER\n");
28016        rc = 1;
28017        goto meta_command_exit;
28018      }
28019      rc = sqlite3_user_delete(p->db, azArg[2]);
28020      if( rc ){
28021        eputf("User-Delete failed: %d\n", rc);
28022        rc = 1;
28023      }
28024    }else{
28025      eputz("Usage: .user login|add|edit|delete ...\n");
28026      rc = 1;
28027      goto meta_command_exit;
28028    }
28029  }else
28030#endif /* SQLITE_USER_AUTHENTICATION */
28031
28032  if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
28033    char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
28034    oputf("SQLite %s %s\n" /*extra-version-info*/,
28035          sqlite3_libversion(), sqlite3_sourceid());
28036#if SQLITE_HAVE_ZLIB
28037    oputf("zlib version %s\n", zlibVersion());
28038#endif
28039#define CTIMEOPT_VAL_(opt) #opt
28040#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
28041#if defined(__clang__) && defined(__clang_major__)
28042    oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
28043          CTIMEOPT_VAL(__clang_minor__) "."
28044          CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
28045#elif defined(_MSC_VER)
28046    oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
28047#elif defined(__GNUC__) && defined(__VERSION__)
28048    oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
28049#endif
28050  }else
28051
28052  if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
28053    const char *zDbName = nArg==2 ? azArg[1] : "main";
28054    sqlite3_vfs *pVfs = 0;
28055    if( p->db ){
28056      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
28057      if( pVfs ){
28058        oputf("vfs.zName      = \"%s\"\n", pVfs->zName);
28059        oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
28060        oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
28061        oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
28062      }
28063    }
28064  }else
28065
28066  if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
28067    sqlite3_vfs *pVfs;
28068    sqlite3_vfs *pCurrent = 0;
28069    if( p->db ){
28070      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
28071    }
28072    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
28073      oputf("vfs.zName      = \"%s\"%s\n", pVfs->zName,
28074            pVfs==pCurrent ? "  <--- CURRENT" : "");
28075      oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
28076      oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
28077      oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
28078      if( pVfs->pNext ){
28079        oputz("-----------------------------------\n");
28080      }
28081    }
28082  }else
28083
28084  if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
28085    const char *zDbName = nArg==2 ? azArg[1] : "main";
28086    char *zVfsName = 0;
28087    if( p->db ){
28088      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
28089      if( zVfsName ){
28090        oputf("%s\n", zVfsName);
28091        sqlite3_free(zVfsName);
28092      }
28093    }
28094  }else
28095
28096  if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
28097    unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
28098    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
28099  }else
28100
28101  if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
28102    int j;
28103    assert( nArg<=ArraySize(azArg) );
28104    p->nWidth = nArg-1;
28105    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
28106    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
28107    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
28108    for(j=1; j<nArg; j++){
28109      p->colWidth[j-1] = (int)integerValue(azArg[j]);
28110    }
28111  }else
28112
28113  {
28114    eputf("Error: unknown command or invalid arguments: "
28115          " \"%s\". Enter \".help\" for help\n", azArg[0]);
28116    rc = 1;
28117  }
28118
28119meta_command_exit:
28120  if( p->outCount ){
28121    p->outCount--;
28122    if( p->outCount==0 ) output_reset(p);
28123  }
28124  p->bSafeMode = p->bSafeModePersist;
28125  return rc;
28126}
28127
28128/* Line scan result and intermediate states (supporting scan resumption)
28129*/
28130#ifndef CHAR_BIT
28131# define CHAR_BIT 8
28132#endif
28133typedef enum {
28134  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
28135  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
28136  QSS_Start = 0
28137} QuickScanState;
28138#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
28139#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
28140#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
28141#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
28142#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
28143
28144/*
28145** Scan line for classification to guide shell's handling.
28146** The scan is resumable for subsequent lines when prior
28147** return values are passed as the 2nd argument.
28148*/
28149static QuickScanState quickscan(char *zLine, QuickScanState qss,
28150                                SCAN_TRACKER_REFTYPE pst){
28151  char cin;
28152  char cWait = (char)qss; /* intentional narrowing loss */
28153  if( cWait==0 ){
28154  PlainScan:
28155    assert( cWait==0 );
28156    while( (cin = *zLine++)!=0 ){
28157      if( IsSpace(cin) )
28158        continue;
28159      switch (cin){
28160      case '-':
28161        if( *zLine!='-' )
28162          break;
28163        while((cin = *++zLine)!=0 )
28164          if( cin=='\n')
28165            goto PlainScan;
28166        return qss;
28167      case ';':
28168        qss |= QSS_EndingSemi;
28169        continue;
28170      case '/':
28171        if( *zLine=='*' ){
28172          ++zLine;
28173          cWait = '*';
28174          CONTINUE_PROMPT_AWAITS(pst, "/*");
28175          qss = QSS_SETV(qss, cWait);
28176          goto TermScan;
28177        }
28178        break;
28179      case '[':
28180        cin = ']';
28181        deliberate_fall_through;
28182      case '`': case '\'': case '"':
28183        cWait = cin;
28184        qss = QSS_HasDark | cWait;
28185        CONTINUE_PROMPT_AWAITC(pst, cin);
28186        goto TermScan;
28187      case '(':
28188        CONTINUE_PAREN_INCR(pst, 1);
28189        break;
28190      case ')':
28191        CONTINUE_PAREN_INCR(pst, -1);
28192        break;
28193      default:
28194        break;
28195      }
28196      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
28197    }
28198  }else{
28199  TermScan:
28200    while( (cin = *zLine++)!=0 ){
28201      if( cin==cWait ){
28202        switch( cWait ){
28203        case '*':
28204          if( *zLine != '/' )
28205            continue;
28206          ++zLine;
28207          cWait = 0;
28208          CONTINUE_PROMPT_AWAITC(pst, 0);
28209          qss = QSS_SETV(qss, 0);
28210          goto PlainScan;
28211        case '`': case '\'': case '"':
28212          if(*zLine==cWait){
28213            /* Swallow doubled end-delimiter.*/
28214            ++zLine;
28215            continue;
28216          }
28217          deliberate_fall_through;
28218        case ']':
28219          cWait = 0;
28220          CONTINUE_PROMPT_AWAITC(pst, 0);
28221          qss = QSS_SETV(qss, 0);
28222          goto PlainScan;
28223        default: assert(0);
28224        }
28225      }
28226    }
28227  }
28228  return qss;
28229}
28230
28231/*
28232** Return TRUE if the line typed in is an SQL command terminator other
28233** than a semi-colon.  The SQL Server style "go" command is understood
28234** as is the Oracle "/".
28235*/
28236static int line_is_command_terminator(char *zLine){
28237  while( IsSpace(zLine[0]) ){ zLine++; };
28238  if( zLine[0]=='/' )
28239    zLine += 1; /* Oracle */
28240  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
28241    zLine += 2; /* SQL Server */
28242  else
28243    return 0;
28244  return quickscan(zLine, QSS_Start, 0)==QSS_Start;
28245}
28246
28247/*
28248** The CLI needs a working sqlite3_complete() to work properly.  So error
28249** out of the build if compiling with SQLITE_OMIT_COMPLETE.
28250*/
28251#ifdef SQLITE_OMIT_COMPLETE
28252# error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
28253#endif
28254
28255/*
28256** Return true if zSql is a complete SQL statement.  Return false if it
28257** ends in the middle of a string literal or C-style comment.
28258*/
28259static int line_is_complete(char *zSql, int nSql){
28260  int rc;
28261  if( zSql==0 ) return 1;
28262  zSql[nSql] = ';';
28263  zSql[nSql+1] = 0;
28264  rc = sqlite3_complete(zSql);
28265  zSql[nSql] = 0;
28266  return rc;
28267}
28268
28269/*
28270** This function is called after processing each line of SQL in the
28271** runOneSqlLine() function. Its purpose is to detect scenarios where
28272** defensive mode should be automatically turned off. Specifically, when
28273**
28274**   1. The first line of input is "PRAGMA foreign_keys=OFF;",
28275**   2. The second line of input is "BEGIN TRANSACTION;",
28276**   3. The database is empty, and
28277**   4. The shell is not running in --safe mode.
28278**
28279** The implementation uses the ShellState.eRestoreState to maintain state:
28280**
28281**    0: Have not seen any SQL.
28282**    1: Have seen "PRAGMA foreign_keys=OFF;".
28283**    2-6: Currently running .dump transaction. If the "2" bit is set,
28284**         disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
28285**    7: Nothing left to do. This function becomes a no-op.
28286*/
28287static int doAutoDetectRestore(ShellState *p, const char *zSql){
28288  int rc = SQLITE_OK;
28289
28290  if( p->eRestoreState<7 ){
28291    switch( p->eRestoreState ){
28292      case 0: {
28293        const char *zExpect = "PRAGMA foreign_keys=OFF;";
28294        assert( strlen(zExpect)==24 );
28295        if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
28296          p->eRestoreState = 1;
28297        }else{
28298          p->eRestoreState = 7;
28299        }
28300        break;
28301      };
28302
28303      case 1: {
28304        int bIsDump = 0;
28305        const char *zExpect = "BEGIN TRANSACTION;";
28306        assert( strlen(zExpect)==18 );
28307        if( memcmp(zSql, zExpect, 19)==0 ){
28308          /* Now check if the database is empty. */
28309          const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
28310          sqlite3_stmt *pStmt = 0;
28311
28312          bIsDump = 1;
28313          shellPrepare(p->db, &rc, zQuery, &pStmt);
28314          if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
28315            bIsDump = 0;
28316          }
28317          shellFinalize(&rc, pStmt);
28318        }
28319        if( bIsDump && rc==SQLITE_OK ){
28320          int bDefense = 0;
28321          int bDqsDdl = 0;
28322          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
28323          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
28324          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
28325          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
28326          p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
28327        }else{
28328          p->eRestoreState = 7;
28329        }
28330        break;
28331      }
28332
28333      default: {
28334        if( sqlite3_get_autocommit(p->db) ){
28335          if( (p->eRestoreState & 2) ){
28336            sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
28337          }
28338          if( (p->eRestoreState & 4) ){
28339            sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
28340          }
28341          p->eRestoreState = 7;
28342        }
28343        break;
28344      }
28345    }
28346  }
28347
28348  return rc;
28349}
28350
28351/*
28352** Run a single line of SQL.  Return the number of errors.
28353*/
28354static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
28355  int rc;
28356  char *zErrMsg = 0;
28357
28358  open_db(p, 0);
28359  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
28360  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
28361  BEGIN_TIMER;
28362  rc = shell_exec(p, zSql, &zErrMsg);
28363  END_TIMER;
28364  if( rc || zErrMsg ){
28365    char zPrefix[100];
28366    const char *zErrorTail;
28367    const char *zErrorType;
28368    if( zErrMsg==0 ){
28369      zErrorType = "Error";
28370      zErrorTail = sqlite3_errmsg(p->db);
28371    }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
28372      zErrorType = "Parse error";
28373      zErrorTail = &zErrMsg[12];
28374    }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
28375      zErrorType = "Runtime error";
28376      zErrorTail = &zErrMsg[10];
28377    }else{
28378      zErrorType = "Error";
28379      zErrorTail = zErrMsg;
28380    }
28381    if( in!=0 || !stdin_is_interactive ){
28382      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
28383                       "%s near line %d:", zErrorType, startline);
28384    }else{
28385      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
28386    }
28387    eputf("%s %s\n", zPrefix, zErrorTail);
28388    sqlite3_free(zErrMsg);
28389    zErrMsg = 0;
28390    return 1;
28391  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
28392    char zLineBuf[2000];
28393    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
28394            "changes: %lld   total_changes: %lld",
28395            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
28396    oputf("%s\n", zLineBuf);
28397  }
28398
28399  if( doAutoDetectRestore(p, zSql) ) return 1;
28400  return 0;
28401}
28402
28403static void echo_group_input(ShellState *p, const char *zDo){
28404  if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
28405}
28406
28407#ifdef SQLITE_SHELL_FIDDLE
28408/*
28409** Alternate one_input_line() impl for wasm mode. This is not in the primary
28410** impl because we need the global shellState and cannot access it from that
28411** function without moving lots of code around (creating a larger/messier diff).
28412*/
28413static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
28414  /* Parse the next line from shellState.wasm.zInput. */
28415  const char *zBegin = shellState.wasm.zPos;
28416  const char *z = zBegin;
28417  char *zLine = 0;
28418  i64 nZ = 0;
28419
28420  UNUSED_PARAMETER(in);
28421  UNUSED_PARAMETER(isContinuation);
28422  if(!z || !*z){
28423    return 0;
28424  }
28425  while(*z && isspace(*z)) ++z;
28426  zBegin = z;
28427  for(; *z && '\n'!=*z; ++nZ, ++z){}
28428  if(nZ>0 && '\r'==zBegin[nZ-1]){
28429    --nZ;
28430  }
28431  shellState.wasm.zPos = z;
28432  zLine = realloc(zPrior, nZ+1);
28433  shell_check_oom(zLine);
28434  memcpy(zLine, zBegin, nZ);
28435  zLine[nZ] = 0;
28436  return zLine;
28437}
28438#endif /* SQLITE_SHELL_FIDDLE */
28439
28440/*
28441** Read input from *in and process it.  If *in==0 then input
28442** is interactive - the user is typing it it.  Otherwise, input
28443** is coming from a file or device.  A prompt is issued and history
28444** is saved only if input is interactive.  An interrupt signal will
28445** cause this routine to exit immediately, unless input is interactive.
28446**
28447** Return the number of errors.
28448*/
28449static int process_input(ShellState *p){
28450  char *zLine = 0;          /* A single input line */
28451  char *zSql = 0;           /* Accumulated SQL text */
28452  i64 nLine;                /* Length of current line */
28453  i64 nSql = 0;             /* Bytes of zSql[] used */
28454  i64 nAlloc = 0;           /* Allocated zSql[] space */
28455  int rc;                   /* Error code */
28456  int errCnt = 0;           /* Number of errors seen */
28457  i64 startline = 0;        /* Line number for start of current input */
28458  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
28459
28460  if( p->inputNesting==MAX_INPUT_NESTING ){
28461    /* This will be more informative in a later version. */
28462    eputf("Input nesting limit (%d) reached at line %d."
28463          " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
28464    return 1;
28465  }
28466  ++p->inputNesting;
28467  p->lineno = 0;
28468  CONTINUE_PROMPT_RESET;
28469  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
28470    fflush(p->out);
28471    zLine = one_input_line(p->in, zLine, nSql>0);
28472    if( zLine==0 ){
28473      /* End of input */
28474      if( p->in==0 && stdin_is_interactive ) oputz("\n");
28475      break;
28476    }
28477    if( seenInterrupt ){
28478      if( p->in!=0 ) break;
28479      seenInterrupt = 0;
28480    }
28481    p->lineno++;
28482    if( QSS_INPLAIN(qss)
28483        && line_is_command_terminator(zLine)
28484        && line_is_complete(zSql, nSql) ){
28485      memcpy(zLine,";",2);
28486    }
28487    qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
28488    if( QSS_PLAINWHITE(qss) && nSql==0 ){
28489      /* Just swallow single-line whitespace */
28490      echo_group_input(p, zLine);
28491      qss = QSS_Start;
28492      continue;
28493    }
28494    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
28495      CONTINUE_PROMPT_RESET;
28496      echo_group_input(p, zLine);
28497      if( zLine[0]=='.' ){
28498        rc = do_meta_command(zLine, p);
28499        if( rc==2 ){ /* exit requested */
28500          break;
28501        }else if( rc ){
28502          errCnt++;
28503        }
28504      }
28505      qss = QSS_Start;
28506      continue;
28507    }
28508    /* No single-line dispositions remain; accumulate line(s). */
28509    nLine = strlen(zLine);
28510    if( nSql+nLine+2>=nAlloc ){
28511      /* Grow buffer by half-again increments when big. */
28512      nAlloc = nSql+(nSql>>1)+nLine+100;
28513      zSql = realloc(zSql, nAlloc);
28514      shell_check_oom(zSql);
28515    }
28516    if( nSql==0 ){
28517      i64 i;
28518      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
28519      assert( nAlloc>0 && zSql!=0 );
28520      memcpy(zSql, zLine+i, nLine+1-i);
28521      startline = p->lineno;
28522      nSql = nLine-i;
28523    }else{
28524      zSql[nSql++] = '\n';
28525      memcpy(zSql+nSql, zLine, nLine+1);
28526      nSql += nLine;
28527    }
28528    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
28529      echo_group_input(p, zSql);
28530      errCnt += runOneSqlLine(p, zSql, p->in, startline);
28531      CONTINUE_PROMPT_RESET;
28532      nSql = 0;
28533      if( p->outCount ){
28534        output_reset(p);
28535        p->outCount = 0;
28536      }else{
28537        clearTempFile(p);
28538      }
28539      p->bSafeMode = p->bSafeModePersist;
28540      qss = QSS_Start;
28541    }else if( nSql && QSS_PLAINWHITE(qss) ){
28542      echo_group_input(p, zSql);
28543      nSql = 0;
28544      qss = QSS_Start;
28545    }
28546  }
28547  if( nSql ){
28548    /* This may be incomplete. Let the SQL parser deal with that. */
28549    echo_group_input(p, zSql);
28550    errCnt += runOneSqlLine(p, zSql, p->in, startline);
28551    CONTINUE_PROMPT_RESET;
28552  }
28553  free(zSql);
28554  free(zLine);
28555  --p->inputNesting;
28556  return errCnt>0;
28557}
28558
28559/*
28560** Return a pathname which is the user's home directory.  A
28561** 0 return indicates an error of some kind.
28562*/
28563static char *find_home_dir(int clearFlag){
28564  static char *home_dir = NULL;
28565  if( clearFlag ){
28566    free(home_dir);
28567    home_dir = 0;
28568    return 0;
28569  }
28570  if( home_dir ) return home_dir;
28571
28572#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
28573     && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
28574  {
28575    struct passwd *pwent;
28576    uid_t uid = getuid();
28577    if( (pwent=getpwuid(uid)) != NULL) {
28578      home_dir = pwent->pw_dir;
28579    }
28580  }
28581#endif
28582
28583#if defined(_WIN32_WCE)
28584  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
28585   */
28586  home_dir = "/";
28587#else
28588
28589#if defined(_WIN32) || defined(WIN32)
28590  if (!home_dir) {
28591    home_dir = getenv("USERPROFILE");
28592  }
28593#endif
28594
28595  if (!home_dir) {
28596    home_dir = getenv("HOME");
28597  }
28598
28599#if defined(_WIN32) || defined(WIN32)
28600  if (!home_dir) {
28601    char *zDrive, *zPath;
28602    int n;
28603    zDrive = getenv("HOMEDRIVE");
28604    zPath = getenv("HOMEPATH");
28605    if( zDrive && zPath ){
28606      n = strlen30(zDrive) + strlen30(zPath) + 1;
28607      home_dir = malloc( n );
28608      if( home_dir==0 ) return 0;
28609      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
28610      return home_dir;
28611    }
28612    home_dir = "c:\\";
28613  }
28614#endif
28615
28616#endif /* !_WIN32_WCE */
28617
28618  if( home_dir ){
28619    i64 n = strlen(home_dir) + 1;
28620    char *z = malloc( n );
28621    if( z ) memcpy(z, home_dir, n);
28622    home_dir = z;
28623  }
28624
28625  return home_dir;
28626}
28627
28628/*
28629** On non-Windows platforms, look for $XDG_CONFIG_HOME.
28630** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
28631** the path to it, else return 0. The result is cached for
28632** subsequent calls.
28633*/
28634static const char *find_xdg_config(void){
28635#if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
28636     || defined(__RTP__) || defined(_WRS_KERNEL)
28637  return 0;
28638#else
28639  static int alreadyTried = 0;
28640  static char *zConfig = 0;
28641  const char *zXdgHome;
28642
28643  if( alreadyTried!=0 ){
28644    return zConfig;
28645  }
28646  alreadyTried = 1;
28647  zXdgHome = getenv("XDG_CONFIG_HOME");
28648  if( zXdgHome==0 ){
28649    return 0;
28650  }
28651  zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
28652  shell_check_oom(zConfig);
28653  if( access(zConfig,0)!=0 ){
28654    sqlite3_free(zConfig);
28655    zConfig = 0;
28656  }
28657  return zConfig;
28658#endif
28659}
28660
28661/*
28662** Read input from the file given by sqliterc_override.  Or if that
28663** parameter is NULL, take input from the first of find_xdg_config()
28664** or ~/.sqliterc which is found.
28665**
28666** Returns the number of errors.
28667*/
28668static void process_sqliterc(
28669  ShellState *p,                  /* Configuration data */
28670  const char *sqliterc_override   /* Name of config file. NULL to use default */
28671){
28672  char *home_dir = NULL;
28673  const char *sqliterc = sqliterc_override;
28674  char *zBuf = 0;
28675  FILE *inSaved = p->in;
28676  int savedLineno = p->lineno;
28677
28678  if( sqliterc == NULL ){
28679    sqliterc = find_xdg_config();
28680  }
28681  if( sqliterc == NULL ){
28682    home_dir = find_home_dir(0);
28683    if( home_dir==0 ){
28684      eputz("-- warning: cannot find home directory;"
28685            " cannot read ~/.sqliterc\n");
28686      return;
28687    }
28688    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
28689    shell_check_oom(zBuf);
28690    sqliterc = zBuf;
28691  }
28692  p->in = fopen(sqliterc,"rb");
28693  if( p->in ){
28694    if( stdin_is_interactive ){
28695      eputf("-- Loading resources from %s\n", sqliterc);
28696    }
28697    if( process_input(p) && bail_on_error ) exit(1);
28698    fclose(p->in);
28699  }else if( sqliterc_override!=0 ){
28700    eputf("cannot open: \"%s\"\n", sqliterc);
28701    if( bail_on_error ) exit(1);
28702  }
28703  p->in = inSaved;
28704  p->lineno = savedLineno;
28705  sqlite3_free(zBuf);
28706}
28707
28708/*
28709** Show available command line options
28710*/
28711static const char zOptions[] =
28712  "   --                   treat no subsequent arguments as options\n"
28713#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
28714  "   -A ARGS...           run \".archive ARGS\" and exit\n"
28715#endif
28716  "   -append              append the database to the end of the file\n"
28717  "   -ascii               set output mode to 'ascii'\n"
28718  "   -bail                stop after hitting an error\n"
28719  "   -batch               force batch I/O\n"
28720  "   -box                 set output mode to 'box'\n"
28721  "   -column              set output mode to 'column'\n"
28722  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
28723  "   -csv                 set output mode to 'csv'\n"
28724#if !defined(SQLITE_OMIT_DESERIALIZE)
28725  "   -deserialize         open the database using sqlite3_deserialize()\n"
28726#endif
28727  "   -echo                print inputs before execution\n"
28728  "   -init FILENAME       read/process named file\n"
28729  "   -[no]header          turn headers on or off\n"
28730#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
28731  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
28732#endif
28733  "   -help                show this message\n"
28734  "   -html                set output mode to HTML\n"
28735  "   -interactive         force interactive I/O\n"
28736  "   -json                set output mode to 'json'\n"
28737  "   -line                set output mode to 'line'\n"
28738  "   -list                set output mode to 'list'\n"
28739  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
28740  "   -markdown            set output mode to 'markdown'\n"
28741#if !defined(SQLITE_OMIT_DESERIALIZE)
28742  "   -maxsize N           maximum size for a --deserialize database\n"
28743#endif
28744  "   -memtrace            trace all memory allocations and deallocations\n"
28745  "   -mmap N              default mmap size set to N\n"
28746#ifdef SQLITE_ENABLE_MULTIPLEX
28747  "   -multiplex           enable the multiplexor VFS\n"
28748#endif
28749  "   -newline SEP         set output row separator. Default: '\\n'\n"
28750  "   -nofollow            refuse to open symbolic links to database files\n"
28751  "   -nonce STRING        set the safe-mode escape nonce\n"
28752  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
28753  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
28754  "   -pcachetrace         trace all page cache operations\n"
28755  "   -quote               set output mode to 'quote'\n"
28756  "   -readonly            open the database read-only\n"
28757  "   -safe                enable safe-mode\n"
28758  "   -separator SEP       set output column separator. Default: '|'\n"
28759#ifdef SQLITE_ENABLE_SORTER_REFERENCES
28760  "   -sorterref SIZE      sorter references threshold size\n"
28761#endif
28762  "   -stats               print memory stats before each finalize\n"
28763  "   -table               set output mode to 'table'\n"
28764  "   -tabs                set output mode to 'tabs'\n"
28765  "   -unsafe-testing      allow unsafe commands and modes for testing\n"
28766  "   -version             show SQLite version\n"
28767  "   -vfs NAME            use NAME as the default VFS\n"
28768#ifdef SQLITE_ENABLE_VFSTRACE
28769  "   -vfstrace            enable tracing of all VFS calls\n"
28770#endif
28771#ifdef SQLITE_HAVE_ZLIB
28772  "   -zip                 open the file as a ZIP Archive\n"
28773#endif
28774;
28775static void usage(int showDetail){
28776  eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
28777       "FILENAME is the name of an SQLite database. A new database is created\n"
28778       "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
28779  if( showDetail ){
28780    eputf("OPTIONS include:\n%s", zOptions);
28781  }else{
28782    eputz("Use the -help option for additional information\n");
28783  }
28784  exit(1);
28785}
28786
28787/*
28788** Internal check:  Verify that the SQLite is uninitialized.  Print a
28789** error message if it is initialized.
28790*/
28791static void verify_uninitialized(void){
28792  if( sqlite3_config(-1)==SQLITE_MISUSE ){
28793    sputz(stdout, "WARNING: attempt to configure SQLite after"
28794          " initialization.\n");
28795  }
28796}
28797
28798/*
28799** Initialize the state information in data
28800*/
28801static void main_init(ShellState *data) {
28802  memset(data, 0, sizeof(*data));
28803  data->normalMode = data->cMode = data->mode = MODE_List;
28804  data->autoExplain = 1;
28805  data->pAuxDb = &data->aAuxDb[0];
28806  memcpy(data->colSeparator,SEP_Column, 2);
28807  memcpy(data->rowSeparator,SEP_Row, 2);
28808  data->showHeader = 0;
28809  data->shellFlgs = SHFLG_Lookaside;
28810  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
28811#if !defined(SQLITE_SHELL_FIDDLE)
28812  verify_uninitialized();
28813#endif
28814  sqlite3_config(SQLITE_CONFIG_URI, 1);
28815  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
28816  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
28817  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
28818}
28819
28820/*
28821** Output text to the console in a font that attracts extra attention.
28822*/
28823#if defined(_WIN32) || defined(WIN32)
28824static void printBold(const char *zText){
28825#if !SQLITE_OS_WINRT
28826  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
28827  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
28828  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
28829  SetConsoleTextAttribute(out,
28830         FOREGROUND_RED|FOREGROUND_INTENSITY
28831  );
28832#endif
28833  sputz(stdout, zText);
28834#if !SQLITE_OS_WINRT
28835  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
28836#endif
28837}
28838#else
28839static void printBold(const char *zText){
28840  sputf(stdout, "\033[1m%s\033[0m", zText);
28841}
28842#endif
28843
28844/*
28845** Get the argument to an --option.  Throw an error and die if no argument
28846** is available.
28847*/
28848static char *cmdline_option_value(int argc, char **argv, int i){
28849  if( i==argc ){
28850    eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
28851    exit(1);
28852  }
28853  return argv[i];
28854}
28855
28856static void sayAbnormalExit(void){
28857  if( seenInterrupt ) eputz("Program interrupted.\n");
28858}
28859
28860#ifndef SQLITE_SHELL_IS_UTF8
28861#  if (defined(_WIN32) || defined(WIN32)) \
28862   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
28863#    define SQLITE_SHELL_IS_UTF8          (0)
28864#  else
28865#    define SQLITE_SHELL_IS_UTF8          (1)
28866#  endif
28867#endif
28868
28869#ifdef SQLITE_SHELL_FIDDLE
28870#  define main fiddle_main
28871#endif
28872
28873#if SQLITE_SHELL_IS_UTF8
28874int SQLITE_CDECL main(int argc, char **argv){
28875#else
28876int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
28877  char **argv;
28878#endif
28879#ifdef SQLITE_DEBUG
28880  sqlite3_int64 mem_main_enter = 0;
28881#endif
28882  char *zErrMsg = 0;
28883#ifdef SQLITE_SHELL_FIDDLE
28884#  define data shellState
28885#else
28886  ShellState data;
28887  StreamsAreConsole consStreams = SAC_NoConsole;
28888#endif
28889  const char *zInitFile = 0;
28890  int i;
28891  int rc = 0;
28892  int warnInmemoryDb = 0;
28893  int readStdin = 1;
28894  int nCmd = 0;
28895  int nOptsEnd = argc;
28896  char **azCmd = 0;
28897  const char *zVfs = 0;           /* Value of -vfs command-line option */
28898#if !SQLITE_SHELL_IS_UTF8
28899  char **argvToFree = 0;
28900  int argcToFree = 0;
28901#endif
28902  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
28903
28904#ifdef SQLITE_SHELL_FIDDLE
28905  stdin_is_interactive = 0;
28906  stdout_is_console = 1;
28907  data.wasm.zDefaultDbName = "/fiddle.sqlite3";
28908#else
28909  consStreams = consoleClassifySetup(stdin, stdout, stderr);
28910  stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
28911  stdout_is_console = (consStreams & SAC_OutConsole)!=0;
28912  atexit(consoleRestore);
28913#endif
28914  atexit(sayAbnormalExit);
28915#ifdef SQLITE_DEBUG
28916  mem_main_enter = sqlite3_memory_used();
28917#endif
28918#if !defined(_WIN32_WCE)
28919  if( getenv("SQLITE_DEBUG_BREAK") ){
28920    if( isatty(0) && isatty(2) ){
28921      eputf("attach debugger to process %d and press any key to continue.\n",
28922            GETPID());
28923      fgetc(stdin);
28924    }else{
28925#if defined(_WIN32) || defined(WIN32)
28926#if SQLITE_OS_WINRT
28927      __debugbreak();
28928#else
28929      DebugBreak();
28930#endif
28931#elif defined(SIGTRAP)
28932      raise(SIGTRAP);
28933#endif
28934    }
28935  }
28936#endif
28937  /* Register a valid signal handler early, before much else is done. */
28938#ifdef SIGINT
28939  signal(SIGINT, interrupt_handler);
28940#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
28941  if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
28942    eputz("No ^C handler.\n");
28943  }
28944#endif
28945
28946#if USE_SYSTEM_SQLITE+0!=1
28947  if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
28948    eputf("SQLite header and source version mismatch\n%s\n%s\n",
28949          sqlite3_sourceid(), SQLITE_SOURCE_ID);
28950    exit(1);
28951  }
28952#endif
28953  main_init(&data);
28954
28955  /* On Windows, we must translate command-line arguments into UTF-8.
28956  ** The SQLite memory allocator subsystem has to be enabled in order to
28957  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
28958  ** subsequent sqlite3_config() calls will work.  So copy all results into
28959  ** memory that does not come from the SQLite memory allocator.
28960  */
28961#if !SQLITE_SHELL_IS_UTF8
28962  sqlite3_initialize();
28963  argvToFree = malloc(sizeof(argv[0])*argc*2);
28964  shell_check_oom(argvToFree);
28965  argcToFree = argc;
28966  argv = argvToFree + argc;
28967  for(i=0; i<argc; i++){
28968    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
28969    i64 n;
28970    shell_check_oom(z);
28971    n = strlen(z);
28972    argv[i] = malloc( n+1 );
28973    shell_check_oom(argv[i]);
28974    memcpy(argv[i], z, n+1);
28975    argvToFree[i] = argv[i];
28976    sqlite3_free(z);
28977  }
28978  sqlite3_shutdown();
28979#endif
28980
28981  assert( argc>=1 && argv && argv[0] );
28982  Argv0 = argv[0];
28983
28984#ifdef SQLITE_SHELL_DBNAME_PROC
28985  {
28986    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
28987    ** of a C-function that will provide the name of the database file.  Use
28988    ** this compile-time option to embed this shell program in larger
28989    ** applications. */
28990    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
28991    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
28992    warnInmemoryDb = 0;
28993  }
28994#endif
28995
28996  /* Do an initial pass through the command-line argument to locate
28997  ** the name of the database file, the name of the initialization file,
28998  ** the size of the alternative malloc heap, options affecting commands
28999  ** or SQL run from the command line, and the first command to execute.
29000  */
29001#ifndef SQLITE_SHELL_FIDDLE
29002  verify_uninitialized();
29003#endif
29004  for(i=1; i<argc; i++){
29005    char *z;
29006    z = argv[i];
29007    if( z[0]!='-' || i>nOptsEnd ){
29008      if( data.aAuxDb->zDbFilename==0 ){
29009        data.aAuxDb->zDbFilename = z;
29010      }else{
29011        /* Excess arguments are interpreted as SQL (or dot-commands) and
29012        ** mean that nothing is read from stdin */
29013        readStdin = 0;
29014        nCmd++;
29015        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
29016        shell_check_oom(azCmd);
29017        azCmd[nCmd-1] = z;
29018      }
29019      continue;
29020    }
29021    if( z[1]=='-' ) z++;
29022    if( cli_strcmp(z, "-")==0 ){
29023      nOptsEnd = i;
29024      continue;
29025    }else if( cli_strcmp(z,"-separator")==0
29026     || cli_strcmp(z,"-nullvalue")==0
29027     || cli_strcmp(z,"-newline")==0
29028     || cli_strcmp(z,"-cmd")==0
29029    ){
29030      (void)cmdline_option_value(argc, argv, ++i);
29031    }else if( cli_strcmp(z,"-init")==0 ){
29032      zInitFile = cmdline_option_value(argc, argv, ++i);
29033    }else if( cli_strcmp(z,"-interactive")==0 ){
29034    }else if( cli_strcmp(z,"-batch")==0 ){
29035      /* Need to check for batch mode here to so we can avoid printing
29036      ** informational messages (like from process_sqliterc) before
29037      ** we do the actual processing of arguments later in a second pass.
29038      */
29039      stdin_is_interactive = 0;
29040    }else if( cli_strcmp(z,"-utf8")==0 ){
29041    }else if( cli_strcmp(z,"-no-utf8")==0 ){
29042    }else if( cli_strcmp(z,"-heap")==0 ){
29043#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
29044      const char *zSize;
29045      sqlite3_int64 szHeap;
29046
29047      zSize = cmdline_option_value(argc, argv, ++i);
29048      szHeap = integerValue(zSize);
29049      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
29050      verify_uninitialized();
29051      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
29052#else
29053      (void)cmdline_option_value(argc, argv, ++i);
29054#endif
29055    }else if( cli_strcmp(z,"-pagecache")==0 ){
29056      sqlite3_int64 n, sz;
29057      sz = integerValue(cmdline_option_value(argc,argv,++i));
29058      if( sz>70000 ) sz = 70000;
29059      if( sz<0 ) sz = 0;
29060      n = integerValue(cmdline_option_value(argc,argv,++i));
29061      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
29062        n = 0xffffffffffffLL/sz;
29063      }
29064      verify_uninitialized();
29065      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
29066                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
29067      data.shellFlgs |= SHFLG_Pagecache;
29068    }else if( cli_strcmp(z,"-lookaside")==0 ){
29069      int n, sz;
29070      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
29071      if( sz<0 ) sz = 0;
29072      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
29073      if( n<0 ) n = 0;
29074      verify_uninitialized();
29075      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
29076      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
29077    }else if( cli_strcmp(z,"-threadsafe")==0 ){
29078      int n;
29079      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
29080      verify_uninitialized();
29081      switch( n ){
29082         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
29083         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
29084         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
29085      }
29086#ifdef SQLITE_ENABLE_VFSTRACE
29087    }else if( cli_strcmp(z,"-vfstrace")==0 ){
29088      extern int vfstrace_register(
29089         const char *zTraceName,
29090         const char *zOldVfsName,
29091         int (*xOut)(const char*,void*),
29092         void *pOutArg,
29093         int makeDefault
29094      );
29095      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
29096#endif
29097#ifdef SQLITE_ENABLE_MULTIPLEX
29098    }else if( cli_strcmp(z,"-multiplex")==0 ){
29099      extern int sqlite3_multiplex_initialize(const char*,int);
29100      sqlite3_multiplex_initialize(0, 1);
29101#endif
29102    }else if( cli_strcmp(z,"-mmap")==0 ){
29103      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
29104      verify_uninitialized();
29105      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
29106#if defined(SQLITE_ENABLE_SORTER_REFERENCES)
29107    }else if( cli_strcmp(z,"-sorterref")==0 ){
29108      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
29109      verify_uninitialized();
29110      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
29111#endif
29112    }else if( cli_strcmp(z,"-vfs")==0 ){
29113      zVfs = cmdline_option_value(argc, argv, ++i);
29114#ifdef SQLITE_HAVE_ZLIB
29115    }else if( cli_strcmp(z,"-zip")==0 ){
29116      data.openMode = SHELL_OPEN_ZIPFILE;
29117#endif
29118    }else if( cli_strcmp(z,"-append")==0 ){
29119      data.openMode = SHELL_OPEN_APPENDVFS;
29120#ifndef SQLITE_OMIT_DESERIALIZE
29121    }else if( cli_strcmp(z,"-deserialize")==0 ){
29122      data.openMode = SHELL_OPEN_DESERIALIZE;
29123    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29124      data.szMax = integerValue(argv[++i]);
29125#endif
29126    }else if( cli_strcmp(z,"-readonly")==0 ){
29127      data.openMode = SHELL_OPEN_READONLY;
29128    }else if( cli_strcmp(z,"-nofollow")==0 ){
29129      data.openFlags = SQLITE_OPEN_NOFOLLOW;
29130#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
29131    }else if( cli_strncmp(z, "-A",2)==0 ){
29132      /* All remaining command-line arguments are passed to the ".archive"
29133      ** command, so ignore them */
29134      break;
29135#endif
29136    }else if( cli_strcmp(z, "-memtrace")==0 ){
29137      sqlite3MemTraceActivate(stderr);
29138    }else if( cli_strcmp(z, "-pcachetrace")==0 ){
29139      sqlite3PcacheTraceActivate(stderr);
29140    }else if( cli_strcmp(z,"-bail")==0 ){
29141      bail_on_error = 1;
29142    }else if( cli_strcmp(z,"-nonce")==0 ){
29143      free(data.zNonce);
29144      data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
29145    }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29146      ShellSetFlag(&data,SHFLG_TestingMode);
29147    }else if( cli_strcmp(z,"-safe")==0 ){
29148      /* no-op - catch this on the second pass */
29149    }
29150  }
29151#ifndef SQLITE_SHELL_FIDDLE
29152  verify_uninitialized();
29153#endif
29154
29155
29156#ifdef SQLITE_SHELL_INIT_PROC
29157  {
29158    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
29159    ** of a C-function that will perform initialization actions on SQLite that
29160    ** occur just before or after sqlite3_initialize(). Use this compile-time
29161    ** option to embed this shell program in larger applications. */
29162    extern void SQLITE_SHELL_INIT_PROC(void);
29163    SQLITE_SHELL_INIT_PROC();
29164  }
29165#else
29166  /* All the sqlite3_config() calls have now been made. So it is safe
29167  ** to call sqlite3_initialize() and process any command line -vfs option. */
29168  sqlite3_initialize();
29169#endif
29170
29171  if( zVfs ){
29172    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
29173    if( pVfs ){
29174      sqlite3_vfs_register(pVfs, 1);
29175    }else{
29176      eputf("no such VFS: \"%s\"\n", zVfs);
29177      exit(1);
29178    }
29179  }
29180
29181  if( data.pAuxDb->zDbFilename==0 ){
29182#ifndef SQLITE_OMIT_MEMORYDB
29183    data.pAuxDb->zDbFilename = ":memory:";
29184    warnInmemoryDb = argc==1;
29185#else
29186    eputf("%s: Error: no database filename specified\n", Argv0);
29187    return 1;
29188#endif
29189  }
29190  data.out = stdout;
29191#ifndef SQLITE_SHELL_FIDDLE
29192  sqlite3_appendvfs_init(0,0,0);
29193#endif
29194
29195  /* Go ahead and open the database file if it already exists.  If the
29196  ** file does not exist, delay opening it.  This prevents empty database
29197  ** files from being created if a user mistypes the database name argument
29198  ** to the sqlite command-line tool.
29199  */
29200  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
29201    open_db(&data, 0);
29202  }
29203
29204  /* Process the initialization file if there is one.  If no -init option
29205  ** is given on the command line, look for a file named ~/.sqliterc and
29206  ** try to process it.
29207  */
29208  process_sqliterc(&data,zInitFile);
29209
29210  /* Make a second pass through the command-line argument and set
29211  ** options.  This second pass is delayed until after the initialization
29212  ** file is processed so that the command-line arguments will override
29213  ** settings in the initialization file.
29214  */
29215  for(i=1; i<argc; i++){
29216    char *z = argv[i];
29217    if( z[0]!='-' || i>=nOptsEnd ) continue;
29218    if( z[1]=='-' ){ z++; }
29219    if( cli_strcmp(z,"-init")==0 ){
29220      i++;
29221    }else if( cli_strcmp(z,"-html")==0 ){
29222      data.mode = MODE_Html;
29223    }else if( cli_strcmp(z,"-list")==0 ){
29224      data.mode = MODE_List;
29225    }else if( cli_strcmp(z,"-quote")==0 ){
29226      data.mode = MODE_Quote;
29227      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
29228      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
29229    }else if( cli_strcmp(z,"-line")==0 ){
29230      data.mode = MODE_Line;
29231    }else if( cli_strcmp(z,"-column")==0 ){
29232      data.mode = MODE_Column;
29233    }else if( cli_strcmp(z,"-json")==0 ){
29234      data.mode = MODE_Json;
29235    }else if( cli_strcmp(z,"-markdown")==0 ){
29236      data.mode = MODE_Markdown;
29237    }else if( cli_strcmp(z,"-table")==0 ){
29238      data.mode = MODE_Table;
29239    }else if( cli_strcmp(z,"-box")==0 ){
29240      data.mode = MODE_Box;
29241    }else if( cli_strcmp(z,"-csv")==0 ){
29242      data.mode = MODE_Csv;
29243      memcpy(data.colSeparator,",",2);
29244#ifdef SQLITE_HAVE_ZLIB
29245    }else if( cli_strcmp(z,"-zip")==0 ){
29246      data.openMode = SHELL_OPEN_ZIPFILE;
29247#endif
29248    }else if( cli_strcmp(z,"-append")==0 ){
29249      data.openMode = SHELL_OPEN_APPENDVFS;
29250#ifndef SQLITE_OMIT_DESERIALIZE
29251    }else if( cli_strcmp(z,"-deserialize")==0 ){
29252      data.openMode = SHELL_OPEN_DESERIALIZE;
29253    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
29254      data.szMax = integerValue(argv[++i]);
29255#endif
29256    }else if( cli_strcmp(z,"-readonly")==0 ){
29257      data.openMode = SHELL_OPEN_READONLY;
29258    }else if( cli_strcmp(z,"-nofollow")==0 ){
29259      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
29260    }else if( cli_strcmp(z,"-ascii")==0 ){
29261      data.mode = MODE_Ascii;
29262      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
29263      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
29264    }else if( cli_strcmp(z,"-tabs")==0 ){
29265      data.mode = MODE_List;
29266      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
29267      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
29268    }else if( cli_strcmp(z,"-separator")==0 ){
29269      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
29270                       "%s",cmdline_option_value(argc,argv,++i));
29271    }else if( cli_strcmp(z,"-newline")==0 ){
29272      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
29273                       "%s",cmdline_option_value(argc,argv,++i));
29274    }else if( cli_strcmp(z,"-nullvalue")==0 ){
29275      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
29276                       "%s",cmdline_option_value(argc,argv,++i));
29277    }else if( cli_strcmp(z,"-header")==0 ){
29278      data.showHeader = 1;
29279      ShellSetFlag(&data, SHFLG_HeaderSet);
29280     }else if( cli_strcmp(z,"-noheader")==0 ){
29281      data.showHeader = 0;
29282      ShellSetFlag(&data, SHFLG_HeaderSet);
29283    }else if( cli_strcmp(z,"-echo")==0 ){
29284      ShellSetFlag(&data, SHFLG_Echo);
29285    }else if( cli_strcmp(z,"-eqp")==0 ){
29286      data.autoEQP = AUTOEQP_on;
29287    }else if( cli_strcmp(z,"-eqpfull")==0 ){
29288      data.autoEQP = AUTOEQP_full;
29289    }else if( cli_strcmp(z,"-stats")==0 ){
29290      data.statsOn = 1;
29291    }else if( cli_strcmp(z,"-scanstats")==0 ){
29292      data.scanstatsOn = 1;
29293    }else if( cli_strcmp(z,"-backslash")==0 ){
29294      /* Undocumented command-line option: -backslash
29295      ** Causes C-style backslash escapes to be evaluated in SQL statements
29296      ** prior to sending the SQL into SQLite.  Useful for injecting
29297      ** crazy bytes in the middle of SQL statements for testing and debugging.
29298      */
29299      ShellSetFlag(&data, SHFLG_Backslash);
29300    }else if( cli_strcmp(z,"-bail")==0 ){
29301      /* No-op.  The bail_on_error flag should already be set. */
29302    }else if( cli_strcmp(z,"-version")==0 ){
29303      sputf(stdout, "%s %s (%d-bit)\n",
29304            sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
29305      return 0;
29306    }else if( cli_strcmp(z,"-interactive")==0 ){
29307      /* Need to check for interactive override here to so that it can
29308      ** affect console setup (for Windows only) and testing thereof.
29309      */
29310      stdin_is_interactive = 1;
29311    }else if( cli_strcmp(z,"-batch")==0 ){
29312      /* already handled */
29313    }else if( cli_strcmp(z,"-utf8")==0 ){
29314      /* already handled */
29315    }else if( cli_strcmp(z,"-no-utf8")==0 ){
29316      /* already handled */
29317    }else if( cli_strcmp(z,"-heap")==0 ){
29318      i++;
29319    }else if( cli_strcmp(z,"-pagecache")==0 ){
29320      i+=2;
29321    }else if( cli_strcmp(z,"-lookaside")==0 ){
29322      i+=2;
29323    }else if( cli_strcmp(z,"-threadsafe")==0 ){
29324      i+=2;
29325    }else if( cli_strcmp(z,"-nonce")==0 ){
29326      i += 2;
29327    }else if( cli_strcmp(z,"-mmap")==0 ){
29328      i++;
29329    }else if( cli_strcmp(z,"-memtrace")==0 ){
29330      i++;
29331    }else if( cli_strcmp(z,"-pcachetrace")==0 ){
29332      i++;
29333#ifdef SQLITE_ENABLE_SORTER_REFERENCES
29334    }else if( cli_strcmp(z,"-sorterref")==0 ){
29335      i++;
29336#endif
29337    }else if( cli_strcmp(z,"-vfs")==0 ){
29338      i++;
29339#ifdef SQLITE_ENABLE_VFSTRACE
29340    }else if( cli_strcmp(z,"-vfstrace")==0 ){
29341      i++;
29342#endif
29343#ifdef SQLITE_ENABLE_MULTIPLEX
29344    }else if( cli_strcmp(z,"-multiplex")==0 ){
29345      i++;
29346#endif
29347    }else if( cli_strcmp(z,"-help")==0 ){
29348      usage(1);
29349    }else if( cli_strcmp(z,"-cmd")==0 ){
29350      /* Run commands that follow -cmd first and separately from commands
29351      ** that simply appear on the command-line.  This seems goofy.  It would
29352      ** be better if all commands ran in the order that they appear.  But
29353      ** we retain the goofy behavior for historical compatibility. */
29354      if( i==argc-1 ) break;
29355      z = cmdline_option_value(argc,argv,++i);
29356      if( z[0]=='.' ){
29357        rc = do_meta_command(z, &data);
29358        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
29359      }else{
29360        open_db(&data, 0);
29361        rc = shell_exec(&data, z, &zErrMsg);
29362        if( zErrMsg!=0 ){
29363          eputf("Error: %s\n", zErrMsg);
29364          if( bail_on_error ) return rc!=0 ? rc : 1;
29365        }else if( rc!=0 ){
29366          eputf("Error: unable to process SQL \"%s\"\n", z);
29367          if( bail_on_error ) return rc;
29368        }
29369      }
29370#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
29371    }else if( cli_strncmp(z, "-A", 2)==0 ){
29372      if( nCmd>0 ){
29373        eputf("Error: cannot mix regular SQL or dot-commands"
29374              " with \"%s\"\n", z);
29375        return 1;
29376      }
29377      open_db(&data, OPEN_DB_ZIPFILE);
29378      if( z[2] ){
29379        argv[i] = &z[2];
29380        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
29381      }else{
29382        arDotCommand(&data, 1, argv+i, argc-i);
29383      }
29384      readStdin = 0;
29385      break;
29386#endif
29387    }else if( cli_strcmp(z,"-safe")==0 ){
29388      data.bSafeMode = data.bSafeModePersist = 1;
29389    }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
29390      /* Acted upon in first pass. */
29391    }else{
29392      eputf("%s: Error: unknown option: %s\n", Argv0, z);
29393      eputz("Use -help for a list of options.\n");
29394      return 1;
29395    }
29396    data.cMode = data.mode;
29397  }
29398
29399  if( !readStdin ){
29400    /* Run all arguments that do not begin with '-' as if they were separate
29401    ** command-line inputs, except for the argToSkip argument which contains
29402    ** the database filename.
29403    */
29404    for(i=0; i<nCmd; i++){
29405      if( azCmd[i][0]=='.' ){
29406        rc = do_meta_command(azCmd[i], &data);
29407        if( rc ){
29408          free(azCmd);
29409          return rc==2 ? 0 : rc;
29410        }
29411      }else{
29412        open_db(&data, 0);
29413        echo_group_input(&data, azCmd[i]);
29414        rc = shell_exec(&data, azCmd[i], &zErrMsg);
29415        if( zErrMsg || rc ){
29416          if( zErrMsg!=0 ){
29417            eputf("Error: %s\n", zErrMsg);
29418          }else{
29419            eputf("Error: unable to process SQL: %s\n", azCmd[i]);
29420          }
29421          sqlite3_free(zErrMsg);
29422          free(azCmd);
29423          return rc!=0 ? rc : 1;
29424        }
29425      }
29426    }
29427  }else{
29428    /* Run commands received from standard input
29429    */
29430    if( stdin_is_interactive ){
29431      char *zHome;
29432      char *zHistory;
29433      int nHistory;
29434#if CIO_WIN_WC_XLATE
29435# define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
29436#else
29437# define SHELL_CIO_CHAR_SET ""
29438#endif
29439      sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
29440            "Enter \".help\" for usage hints.\n",
29441            sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
29442      if( warnInmemoryDb ){
29443        sputz(stdout, "Connected to a ");
29444        printBold("transient in-memory database");
29445        sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
29446              " persistent database.\n");
29447      }
29448      zHistory = getenv("SQLITE_HISTORY");
29449      if( zHistory ){
29450        zHistory = strdup(zHistory);
29451      }else if( (zHome = find_home_dir(0))!=0 ){
29452        nHistory = strlen30(zHome) + 20;
29453        if( (zHistory = malloc(nHistory))!=0 ){
29454          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
29455        }
29456      }
29457      if( zHistory ){ shell_read_history(zHistory); }
29458#if HAVE_READLINE || HAVE_EDITLINE
29459      rl_attempted_completion_function = readline_completion;
29460#elif HAVE_LINENOISE
29461      linenoiseSetCompletionCallback(linenoise_completion);
29462#endif
29463      data.in = 0;
29464      rc = process_input(&data);
29465      if( zHistory ){
29466        shell_stifle_history(2000);
29467        shell_write_history(zHistory);
29468        free(zHistory);
29469      }
29470    }else{
29471      data.in = stdin;
29472      rc = process_input(&data);
29473    }
29474  }
29475#ifndef SQLITE_SHELL_FIDDLE
29476  /* In WASM mode we have to leave the db state in place so that
29477  ** client code can "push" SQL into it after this call returns. */
29478  free(azCmd);
29479  set_table_name(&data, 0);
29480  if( data.db ){
29481    session_close_all(&data, -1);
29482    close_db(data.db);
29483  }
29484  for(i=0; i<ArraySize(data.aAuxDb); i++){
29485    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
29486    if( data.aAuxDb[i].db ){
29487      session_close_all(&data, i);
29488      close_db(data.aAuxDb[i].db);
29489    }
29490  }
29491  find_home_dir(1);
29492  output_reset(&data);
29493  data.doXdgOpen = 0;
29494  clearTempFile(&data);
29495#if !SQLITE_SHELL_IS_UTF8
29496  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
29497  free(argvToFree);
29498#endif
29499  free(data.colWidth);
29500  free(data.zNonce);
29501  /* Clear the global data structure so that valgrind will detect memory
29502  ** leaks */
29503  memset(&data, 0, sizeof(data));
29504#ifdef SQLITE_DEBUG
29505  if( sqlite3_memory_used()>mem_main_enter ){
29506    eputf("Memory leaked: %u bytes\n",
29507          (unsigned int)(sqlite3_memory_used()-mem_main_enter));
29508  }
29509#endif
29510#endif /* !SQLITE_SHELL_FIDDLE */
29511  return rc;
29512}
29513
29514
29515#ifdef SQLITE_SHELL_FIDDLE
29516/* Only for emcc experimentation purposes. */
29517int fiddle_experiment(int a,int b){
29518  return a + b;
29519}
29520
29521/*
29522** Returns a pointer to the current DB handle.
29523*/
29524sqlite3 * fiddle_db_handle(){
29525  return globalDb;
29526}
29527
29528/*
29529** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
29530** "main" is assumed. Returns 0 if no db with the given name is
29531** open.
29532*/
29533sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
29534  sqlite3_vfs * pVfs = 0;
29535  if(globalDb){
29536    sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
29537                         SQLITE_FCNTL_VFS_POINTER, &pVfs);
29538  }
29539  return pVfs;
29540}
29541
29542/* Only for emcc experimentation purposes. */
29543sqlite3 * fiddle_db_arg(sqlite3 *arg){
29544    printf("fiddle_db_arg(%p)\n", (const void*)arg);
29545    return arg;
29546}
29547
29548/*
29549** Intended to be called via a SharedWorker() while a separate
29550** SharedWorker() (which manages the wasm module) is performing work
29551** which should be interrupted. Unfortunately, SharedWorker is not
29552** portable enough to make real use of.
29553*/
29554void fiddle_interrupt(void){
29555  if( globalDb ) sqlite3_interrupt(globalDb);
29556}
29557
29558/*
29559** Returns the filename of the given db name, assuming "main" if
29560** zDbName is NULL. Returns NULL if globalDb is not opened.
29561*/
29562const char * fiddle_db_filename(const char * zDbName){
29563    return globalDb
29564      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
29565      : NULL;
29566}
29567
29568/*
29569** Completely wipes out the contents of the currently-opened database
29570** but leaves its storage intact for reuse.
29571*/
29572void fiddle_reset_db(void){
29573  if( globalDb ){
29574    int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
29575    if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
29576    sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
29577  }
29578}
29579
29580/*
29581** Uses the current database's VFS xRead to stream the db file's
29582** contents out to the given callback. The callback gets a single
29583** chunk of size n (its 2nd argument) on each call and must return 0
29584** on success, non-0 on error. This function returns 0 on success,
29585** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
29586** code from the callback. Note that this is not thread-friendly: it
29587** expects that it will be the only thread reading the db file and
29588** takes no measures to ensure that is the case.
29589*/
29590int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
29591  sqlite3_int64 nSize = 0;
29592  sqlite3_int64 nPos = 0;
29593  sqlite3_file * pFile = 0;
29594  unsigned char buf[1024 * 8];
29595  int nBuf = (int)sizeof(buf);
29596  int rc = shellState.db
29597    ? sqlite3_file_control(shellState.db, "main",
29598                           SQLITE_FCNTL_FILE_POINTER, &pFile)
29599    : SQLITE_NOTFOUND;
29600  if( rc ) return rc;
29601  rc = pFile->pMethods->xFileSize(pFile, &nSize);
29602  if( rc ) return rc;
29603  if(nSize % nBuf){
29604    /* DB size is not an even multiple of the buffer size. Reduce
29605    ** buffer size so that we do not unduly inflate the db size when
29606    ** exporting. */
29607    if(0 == nSize % 4096) nBuf = 4096;
29608    else if(0 == nSize % 2048) nBuf = 2048;
29609    else if(0 == nSize % 1024) nBuf = 1024;
29610    else nBuf = 512;
29611  }
29612  for( ; 0==rc && nPos<nSize; nPos += nBuf ){
29613    rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
29614    if(SQLITE_IOERR_SHORT_READ == rc){
29615      rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
29616    }
29617    if( 0==rc ) rc = xCallback(buf, nBuf);
29618  }
29619  return rc;
29620}
29621
29622/*
29623** Trivial exportable function for emscripten. It processes zSql as if
29624** it were input to the sqlite3 shell and redirects all output to the
29625** wasm binding. fiddle_main() must have been called before this
29626** is called, or results are undefined.
29627*/
29628void fiddle_exec(const char * zSql){
29629  if(zSql && *zSql){
29630    if('.'==*zSql) puts(zSql);
29631    shellState.wasm.zInput = zSql;
29632    shellState.wasm.zPos = zSql;
29633    process_input(&shellState);
29634    shellState.wasm.zInput = shellState.wasm.zPos = 0;
29635  }
29636}
29637#endif /* SQLITE_SHELL_FIDDLE */
29638